text:
package io.enmasse.systemtest.platform;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import io.enmasse.systemtest.bases.ITestBase;
import io.enmasse.systemtest.time.TimeoutBudget;
import io.enmasse.systemtest.utils.TestUtils;
import org.slf4j.Logger;

import io.enmasse.systemtest.Environment;
import io.enmasse.systemtest.executor.Exec;
import io.enmasse.systemtest.executor.ExecutionResultData;
import io.enmasse.systemtest.logs.CustomLogger;
import io.fabric8.kubernetes.api.model.Pod;

/**
 * Class represent abstract client which keeps common features of client
 */
public class KubeCMDClient {
    protected static final int DEFAULT_SYNC_TIMEOUT = 10000;
    protected static final int ONE_MINUTE_TIMEOUT = 60000;
    protected static final int FIVE_MINUTES_TIMEOUT = 300000;
    protected static final String CMD = getCMD();
    private static final Logger log = CustomLogger.getLogger();

    public static String getCMD() {
        return Kubernetes.getInstance().getCluster().getKubeCmd();
    }

    /**
     * Create Custom Resource Address or AddressSpace
     *
     * @param definition in yaml or json format
     * @return result of execution
     */
    public static ExecutionResultData createOrUpdateCR(String namespace, String definition, boolean replace, int timeout) throws IOException {
        final File defInFile = new File("crdefinition.file");
        try (FileWriter wr = new FileWriter(defInFile.getName())) {
            wr.write(definition);
            wr.flush();
            log.info("Resource '{}' created", defInFile.getAbsolutePath());
            return Exec.execute(Arrays.asList(CMD, replace ? "replace" : "apply", "-n", namespace, "-f", defInFile.getAbsolutePath()), timeout, true);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            Files.delete(Paths.get(defInFile.getAbsolutePath()));
        }
    }

    public static ExecutionResultData deleteCR(String namespace, String definition, int timeout) throws IOException {
        final File defInFile = new File("crdefinition.file");
        try (FileWriter wr = new FileWriter(defInFile.getName())) {
            wr.write(definition);
            wr.flush();
            return Exec.execute(Arrays.asList(CMD, "delete", "-n", namespace, "-f", defInFile.getAbsolutePath()), timeout, true);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            Files.delete(Paths.get(defInFile.getAbsolutePath()));
        }
    }

    public static ExecutionResultData createCR(String definition) throws IOException {
        return createCR(Environment.getInstance().namespace(), definition);
    }

    public static ExecutionResultData createCR(String namespace, String definition) throws IOException {
        return createCR(namespace, definition, DEFAULT_SYNC_TIMEOUT);
    }

    public static ExecutionResultData createCR(String namespace, String definition, int timeoutMillis) throws IOException {
        return createOrUpdateCR(namespace, definition, false, timeoutMillis);
    }

    public static ExecutionResultData updateCR(String definition) throws IOException {
        return updateCR(Environment.getInstance().namespace(), definition);
    }

    public static ExecutionResultData updateCR(String namespace, String definition) throws IOException {
        return createOrUpdateCR(namespace, definition, true, DEFAULT_SYNC_TIMEOUT);
    }

    public static ExecutionResultData patchCR(String kind, String name, String patchData) {
        log.info("Patching {} {} in {}", kind, name, Environment.getInstance().namespace());
        return Exec.execute(Arrays.asList(CMD, "patch", "--type=merge", "-n", Environment.getInstance().namespace(), kind, name, "-p", patchData), DEFAULT_SYNC_TIMEOUT, true);
    }

    public static String getOCUser() {
        List<String> command = Arrays.asList(CMD, "whoami");
        return Exec.execute(command, DEFAULT_SYNC_TIMEOUT, false).getStdOut().replace(System.getProperty("line.separator"), "");
    }

    public static void getCurrentProject() {
        List<String> command = Arrays.asList(CMD, "project");
        Exec.execute(command, DEFAULT_SYNC_TIMEOUT, true);
    }

    /**
     * Use CRD for get address by addressName in 'namespace'
     *
     * @param namespace   name of namespace where addresses exists
     * @param addressName name of address in appropriate format, use '-a' for all addresses
     * @param format      output format (yaml/json accepted)
     * @return result of execution
     */
    public static ExecutionResultData getAddress(String namespace, String addressName, Optional<String> format) {
        List<String> getCmd = getRessourcesCmd("get", "addresses", namespace, addressName, format);
        return Exec.execute(getCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static ExecutionResultData getAddress(String namespace, String addressName) {
        return getAddress(namespace, addressName, Optional.empty());
    }

    public static ExecutionResultData getAddress(String namespace) {
        List<String> getCmd = getRessourcesCmd("get", "addresses", namespace, Optional.of("wide"));
        return Exec.execute(getCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static void dumpPodLogs(final Pod pod) {
        // we cannot use --all-containers, since kubectl is too old
        for (var c : pod.getStatus().getContainerStatuses()) {
            Exec.execute(DEFAULT_SYNC_TIMEOUT, true, CMD, "logs", pod.getMetadata().getName(), "-c", c.getName());
        }
    }

    /**
     * Use CRD for delete address by addressName in 'namespace'
     *
     * @param namespace   name of namespace where addresses exists
     * @param addressName name of address in appropriate format; --all means remove all addresses
     * @return result of execution
     */
    public static ExecutionResultData deleteAddress(String namespace, String addressName) {
        List<String> deleteCmd = getRessourcesCmd("delete", "addresses", namespace, addressName, Optional.empty());
        return Exec.execute(deleteCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    /**
     * Use CRD for get addressspace by addressspace name in 'namespace'
     *
     * @param namespace        name of namespace where addresses exists
     * @param addressSpaceName name of address in appropriate format
     * @param format           output format (yaml/json accepted)
     * @return result of execution
     */
    public static ExecutionResultData getAddressSpace(String namespace, String addressSpaceName, Optional<String> format) {
        List<String> getCmd = getRessourcesCmd("get", "addressspaces", namespace, addressSpaceName, format);
        return Exec.execute(getCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static ExecutionResultData getAddressSpace(String namespace, String addressSpaceName) {
        return getAddressSpace(namespace, addressSpaceName, Optional.empty());
    }

    public static ExecutionResultData getAddressSpace(String namespace, Optional<String> format) {
        List<String> getCmd = getRessourcesCmd("get", "addressspaces", namespace, format);
        return Exec.execute(getCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    /**
     * Use CRD for delete addressspace by addressspace name in 'namespace'
     *
     * @param namespace        name of namespace where addresses exists
     * @param addressSpaceName name of address in appropriate format
     * @return result of execution
     */
    public static ExecutionResultData deleteAddressSpace(String namespace, String addressSpaceName) {
        List<String> ressourcesCmd = getRessourcesCmd("delete", "addressspaces", namespace, addressSpaceName, Optional.empty());
        return Exec.execute(ressourcesCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    private static List<String> getRessourcesCmd(String operation, String kind, String namespace, String resourceName, Optional<String> format) {
        List<String> cmd = new LinkedList<>(Arrays.asList(CMD, operation, kind, resourceName, "-n", namespace));
        format.ifPresent(s -> {
            cmd.add("-o");
            cmd.add(s);
        });
        return cmd;
    }

    private static List<String> getRessourcesCmd(String operation, String kind, String namespace, Optional<String> format) {
        List<String> cmd = new LinkedList<>(Arrays.asList(CMD, operation, kind, "-n", namespace));
        format.ifPresent(s -> {
            cmd.add("-o");
            cmd.add(s);
        });
        return cmd;
    }

    public static ExecutionResultData checkPermission(String operation, String kind, String namespace, String serviceaccount) {
        List<String> cmd = new LinkedList<>(Arrays.asList(CMD, "auth", "can-i", operation, kind, "-n", namespace, "--as", "system:serviceaccount:enmasse-monitoring:" + serviceaccount));
        return Exec.execute(cmd, DEFAULT_SYNC_TIMEOUT, false);
    }

    public static void loginUser(String apiToken) {
        List<String> cmd = Arrays.asList(CMD, "login", "--token=" + apiToken);
        Exec.execute(cmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static String loginUser(String username, String password) {
        List<String> cmd = Arrays.asList(CMD, "login", "-u", username, "-p", password);
        ExecutionResultData execute = Exec.execute(cmd, DEFAULT_SYNC_TIMEOUT, true);
        if (!execute.getRetCode()) {
            throw new IllegalStateException(String.format("Failed to login user : %s : %s", username, execute.getStdErr()));
        }
        cmd = Arrays.asList(CMD, "whoami", "-t");
        return Exec.execute(cmd, DEFAULT_SYNC_TIMEOUT, true)
                .getStdOut().replace(System.getProperty("line.separator"), "");
    }

    public static void createNamespace(String namespace) {
        List<String> cmd = Arrays.asList(CMD, "new-project", namespace);
        Exec.execute(cmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static void switchProject(String namespace) {
        List<String> cmd = Arrays.asList(CMD, "project", namespace);
        Exec.execute(cmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static ExecutionResultData getUser(String namespace) {
        List<String> getCmd = getRessourcesCmd("get", "messaginguser", namespace, Optional.empty());
        return Exec.execute(getCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static ExecutionResultData getUser(String namespace, String addressSpace, String username) {
        List<String> getCmd = getRessourcesCmd("get", "messaginguser", namespace, String.format("%s.%s", addressSpace, username), Optional.empty());
        return Exec.execute(getCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static ExecutionResultData deleteUser(String namespace, String addressSpace, String username) {
        List<String> deleteCmd = getRessourcesCmd("delete", "messaginguser", namespace, String.format("%s.%s", addressSpace, username), Optional.empty());
        return Exec.execute(deleteCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static ExecutionResultData deletePodByLabel(String labelName, String labelValue) {
        List<String> deleteCmd = Arrays.asList(CMD, "delete", "pod", "-n", Environment.getInstance().namespace(), "-l", String.format("%s=%s", labelName, labelValue));
        return Exec.execute(deleteCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static ExecutionResultData setResourceEnvVarByLabel(Optional<String> namespace, String resourceType, Optional<String> containers, String envVarName, String resourceName, String envVarValue) {
        ArrayList<String> setEnvCmd = new ArrayList<>();
        setEnvCmd.add(CMD);
        setEnvCmd.add("set");
        setEnvCmd.add("env");
        setEnvCmd.add(resourceType);
        setEnvCmd.add(resourceName);
        containers.ifPresent(s -> setEnvCmd.add("--containers=" + s));
        namespace.ifPresent(s -> setEnvCmd.add("--namespace=" + s));

        if (envVarValue == null) {
            setEnvCmd.add(envVarName + "-");
        } else {
            setEnvCmd.add(envVarName + "=" + envVarValue);
        }

        return Exec.execute(setEnvCmd, DEFAULT_SYNC_TIMEOUT, true);
    }

    public static ExecutionResultData runOnPod(String namespace, String podName, Optional<String> container, String... args) {
        List<String> runCmd = new ArrayList<>();
        String[] base = container.map(s -> new String[]{CMD, "exec", podName, "-n", namespace, "--container", s, "--"})
                .orElseGet(() -> new String[]{CMD, "exec", podName, "-n", namespace, "--"});
        Collections.addAll(runCmd, base);
        Collections.addAll(runCmd, args);
        return Exec.execute(runCmd, DEFAULT_SYNC_TIMEOUT, false);
    }

    public static ExecutionResultData runQDstat(String namespace, String podName, String... args) {
        List<String> runCmd = new ArrayList<>();
        String[] base = new String[]{CMD, "exec", podName, "-n", namespace, "--", "qdstat", "-t 20"};
        Collections.addAll(runCmd, base);
        Collections.addAll(runCmd, args);
        return Exec.execute(runCmd, ONE_MINUTE_TIMEOUT, true);
    }

    public static ExecutionResultData copyPodContent(String podName, String source, String destination) {
        log.info("Copying file {} from pod {}", source, podName);
        List<String> deleteCmd = Arrays.asList(CMD, "cp", String.format("%s:%s", podName, source), destination);
        return Exec.execute(deleteCmd, DEFAULT_SYNC_TIMEOUT, false);
    }

    public static String getOpenshiftUserId(String username) {
        List<String> command = Arrays.asList(CMD, "get", "users", username, "-o", "jsonpath={.metadata.uid}");
        return Exec.execute(command, DEFAULT_SYNC_TIMEOUT, true).getStdOut()
                .replaceAll(System.getProperty("line.separator"), "");
    }

    /**
     * Note: there are lots of kubernetes components creating events with "<nil>" timestamps, so I'm forced to remove the sorting by this values
     */
    public static ExecutionResultData getEvents(String namespace) {
        List<String> command = Arrays.asList(CMD, "get", "events",
                "--namespace", namespace,
                "--sort-by={.metadata.creationTimestamp}");

        return Exec.execute(command, ONE_MINUTE_TIMEOUT, false);
    }

    /**
     * Note: there are lots of kubernetes components creating events with "<nil>" timestamps, so I'm forced to remove the sorting by this values
     */
    public static ExecutionResultData getAllEvents() {
        List<String> command = Arrays.asList(CMD, "get", "events",
                "--all-namespaces=true",
                "--sort-by={.metadata.creationTimestamp}");

        ExecutionResultData data = Exec.execute(command, ONE_MINUTE_TIMEOUT, false);
        if (!data.getRetCode()) {
            log.info("Error returning events: {}", data.getStdErr());
        }
        return data;
    }

    public static ExecutionResultData describePods(String namespace) {
        return Exec.execute(DEFAULT_SYNC_TIMEOUT, false, CMD, "-n", namespace, "describe", "pods");
    }

    public static ExecutionResultData describeNodes() {
        return Exec.execute(DEFAULT_SYNC_TIMEOUT, false, CMD, "describe", "nodes");
    }

    public static ExecutionResultData createFromFile(String namespace, Path path) {
        Objects.requireNonNull(namespace);
        Objects.requireNonNull(path);
        return Exec.executeAndCheck(CMD, "-n", namespace, "create", "-f", path.toString());
    }

    public static ExecutionResultData applyFromFile(String namespace, Path path) {
        Objects.requireNonNull(namespace);
        Objects.requireNonNull(path);
        return Exec.executeAndCheck(CMD, "-n", namespace, "apply", "-f", path.toString());
    }

    public static ExecutionResultData deleteFromFile(String namespace, Path path) {
        Objects.requireNonNull(namespace);
        Objects.requireNonNull(path);
        return Exec.execute(Arrays.asList(CMD, "-n", namespace, "delete", "-f", path.toString()), ONE_MINUTE_TIMEOUT, false);
    }

    public static String getMessagingEndpoint(String namespace, String addressspace) {
        Objects.requireNonNull(namespace);
        Objects.requireNonNull(addressspace);
        return Exec.execute(Arrays.asList(CMD, "-n", namespace, "get", "addressspace", addressspace, "-o", "jsonpath={.status.endpointStatuses[?(@.name==\"messaging\")].externalHost}"), ONE_MINUTE_TIMEOUT, true, false).getStdOut();
    }

    public static ExecutionResultData deleteNamespace(String name) {
        return Exec.execute(Arrays.asList(CMD, "delete", "namespace", name), FIVE_MINUTES_TIMEOUT, true);
    }

    public static ExecutionResultData deleteResource(String namespace, String resource, String name) {
        List<String> ressourcesCmd = getRessourcesCmd("delete", resource, namespace, name, Optional.empty());
        return Exec.execute(ressourcesCmd, ONE_MINUTE_TIMEOUT, true);
    }

    public static ExecutionResultData createGroupAndAddUser(String groupName, String username) {
        return Exec.execute(Arrays.asList(CMD, "adm", "groups", "new", groupName, username), ONE_MINUTE_TIMEOUT, true);
    }

    public static ExecutionResultData getConfigmaps(String namespace) {
        List<String> command = Arrays.asList(CMD, "get", "configmaps",
                "--namespace", namespace,
                "--output", "yaml");
        return Exec.execute(command, ONE_MINUTE_TIMEOUT, false);
    }

    public static ExecutionResultData getSecrets(String namespace) {
        List<String> command = Arrays.asList(CMD, "get", "secrets",
                "--namespace", namespace,
                "--output", "yaml");
        return Exec.execute(command, ONE_MINUTE_TIMEOUT, false);
    }

    public static ExecutionResultData runOnCluster(String... args) {
        return runOnClusterWithTimeout(ONE_MINUTE_TIMEOUT, args);
    }

    public static ExecutionResultData runOnClusterWithTimeout(int timeoutMillis, String... args) {
        List<String> command = new LinkedList<>();
        command.add(CMD);
        command.addAll(Arrays.asList(args));
        return Exec.execute(command, timeoutMillis, true);
    }

    public static ExecutionResultData runOnClusterWithoutLogger(String... args) {
        List<String> command = new LinkedList<>();
        command.add(CMD);
        command.addAll(Arrays.asList(args));
        return Exec.execute(command, ONE_MINUTE_TIMEOUT, false);
    }

    public static void awaitRollout(TimeoutBudget budget, String namespace, String deploymentName) {
        TestUtils.waitUntilCondition(String.format("Wait for deployment %s in namespace %s rollout to complete", deploymentName, namespace), waitPhase -> {
            ExecutionResultData rollout = Exec.execute(Arrays.asList(ITestBase.kubernetes.getCluster().getKubeCmd(), "rollout",
                    "status", "deployment", deploymentName,
                    "--namespace", namespace), true);
            return rollout.getRetCode();
        }, budget);
    }

    public static void awaitCatalogSourceReady(TimeoutBudget budget, String namespace, String name) {
        TestUtils.waitUntilCondition(String.format("catalogsource %s in namespace %s to become ready", name, namespace), waitPhase -> {
            ExecutionResultData rollout = Exec.execute(Arrays.asList(ITestBase.kubernetes.getCluster().getKubeCmd(), "get", "catalogsource",
                    name,
                    "--namespace", namespace,
                    "--output",
                    "jsonpath={.status.connectionState.lastObservedState}"
            ), true);
            return rollout.getRetCode() && "READY".equals(String.valueOf(rollout.getStdOut()).trim());
        }, budget);
    }

    public static void awaitStatusCondition(TimeoutBudget budget, String namespace, String resource, String name, String forPredicate) {
        TestUtils.waitUntilCondition(String.format("%s %s in namespace %s to have condition matching %s", resource, name, namespace, forPredicate), waitPhase -> {
            ExecutionResultData rollout = Exec.execute(Arrays.asList(ITestBase.kubernetes.getCluster().getKubeCmd(), "wait", resource, name,
                    "--namespace", namespace,
                    "--timeout", "15s",
                    String.format("--for=condition=%s", forPredicate)
            ), true);
            return rollout.getRetCode();
        }, budget);
    }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * Database queries for BxDolQueue object.
 * @see BxDolQueue
 */
class BxDolQueueQuery extends BxDolDb
{
    protected $_sTable;

    public function __construct()
    {
        parent::__construct();
    }

    public function getItems($aParams = array())
    {
        if(empty($this->_sTable))
            return array();

    	$aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));

    	$sSelectClause = '*';
    	$sWhereClause = '';
    	$sLimitClause = isset($aParams['start']) && !empty($aParams['per_page']) ? "LIMIT " . $aParams['start'] . ", " . $aParams['per_page'] : "";

    	if(!empty($aParams['type']))
            switch($aParams['type']) {
                case 'to_send':
                    $aMethod['name'] = 'getAllWithKey';
                    $aMethod['params'][1] = 0;
                    $aMethod['params'][2] = array();
                    $aMethod['params'][3] = PDO::FETCH_NUM;
                    break;
            }

        $aMethod['params'][0] = "SELECT " . $sSelectClause . " FROM `" . $this->_sTable . "` WHERE 1 " . $sWhereClause . $sLimitClause;
        return call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
    }

    public function insertItem($aValues)
    {
        if(empty($this->_sTable))
            return false;

        if(empty($aValues) || !is_array($aValues))
            return false;

        return $this->query("INSERT INTO `" . $this->_sTable . "` SET " . $this->arrayToSQL($aValues));
    }

	public function updateItem($aValues, $aWhere)
    {
        if(empty($this->_sTable))
            return false;

        if(empty($aValues) || !is_array($aValues) || empty($aWhere) || !is_array($aWhere))
            return false;

        return (int)$this->query("UPDATE `" . $this->_sTable . "` SET " . $this->arrayToSQL($aValues) . " WHERE " . $this->arrayToSQL($aWhere, ' AND ')) > 0;
    }

    public function deleteItem($mixedId)
    {
        if(empty($this->_sTable))
            return false;

    	if(!is_array($mixedId))
    		$mixedId = array($mixedId);

        return (int)$this->query("DELETE FROM `" . $this->_sTable . "` WHERE `id` IN (" . $this->implode_escape($mixedId) . ")") > 0;
    }
}

/** @} */

redpajama_set_name: RedPajamaGithub


text:
template< typename T, bool = QtPrivate::IsPointerToTypeDerivedFromQObject<T>::Value >
struct dtkMetaTypeHandler {
    static bool canConvert(const QList<int>& types);
};

template<typename T> struct dtkMetaTypeHandler<T *, false> {
    static     bool  canConvert(const QList<int>& types);
    static QVariant  variantFromValue(T *t);
    static        T *clone(T *t);
    static     void  copy(T *source, T *target);
};

template<typename T> struct dtkMetaTypeHandler<T *, true> {
    static     bool  canConvert(const QList<int>& types);
    static QVariant  variantFromValue(T *t);
    static        T *clone(T *t);
    static     void  copy(T *source, T *target);
};

template< typename T, bool B> struct dtkMetaTypeHandlerHelper;

template< typename T> struct dtkMetaTypeHandlerHelper<T *, false> {
    static bool  canConvert(const QList<int>& types);
    static    T *clone(T *t);
    static void  copy(T *source, T *target);
};

template< typename T> struct dtkMetaTypeHandlerHelper<T *, true> {
    static bool  canConvert(const QList<int>& types);
    static    T *clone(T *);
    static void  copy(T *source, T *target);
};

// /////////////////////////////////////////////////////////////////
// dtkMetaType definition
// /////////////////////////////////////////////////////////////////

class dtkMetaType
{
public:
    template <typename T> static     bool canConvert(int type);
    template <typename T> static     bool canConvert(const QList<int>& types);
    template <typename T> static QVariant variantFromValue(const T& t);
    template <typename T> static QVariant variantFromValue(      T *t);
    template <typename T> static        T *clone(T *t);
    template <typename T> static     void copy(T *source, T *target);
    template <typename T> static     bool registerContainerPointerConverter(int id);

public:
    static DTKMETA_EXPORT  QString description(const QVariant& v);
    static DTKMETA_EXPORT QVariant cloneContent(const QVariant& v);
    static DTKMETA_EXPORT QVariant createEmptyContainer(const QVariant& v);
    static DTKMETA_EXPORT     bool destroyPointer(QVariant& v);
};

// /////////////////////////////////////////////////////////////////
// Stream operators redefinition
// /////////////////////////////////////////////////////////////////

template <typename T> QDataStream& operator << (QDataStream& s, T   *t);
template <typename T> QDataStream& operator >> (QDataStream& s, T *&t);

template<typename T> QDataStream& operator << (QDataStream& s, const QList<T *>& l);
template<typename T> QDataStream& operator >> (QDataStream& s,       QList<T *>& l);

template<typename T> QDataStream& operator << (QDataStream& s, const QVector<T *>& v);
template<typename T> QDataStream& operator >> (QDataStream& s,       QVector<T *>& v);

template<typename T> QDataStream& operator << (QDataStream& s, const std::list<T *>& l);
template<typename T> QDataStream& operator >> (QDataStream& s,       std::list<T *>& l);

template<typename T> QDataStream& operator << (QDataStream& s, const std::vector<T *>& v);
template<typename T> QDataStream& operator >> (QDataStream& s,       std::vector<T *>& v);

// /////////////////////////////////////////////////////////////////
// MACRO REGISTERING POINTERS OF CONTAINERS INTO METATYPE SYSTEM
// /////////////////////////////////////////////////////////////////

#define DTK_DECLARE_SEQUENTIAL_CONTAINER_POINTER(CONTAINER_ARG)                   \
template <typename T> struct QMetaTypeId< CONTAINER_ARG<T> *>                     \
{                                                                                \
    enum {                                                                        \
        Defined = QMetaTypeId2<T>::Defined                                        \
    };                                                                            \
    static int qt_metatype_id()                                                   \
    {                                                                             \
        static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0);       \
        if (const int id = metatype_id.load())                                    \
            return id;                                                            \
        const char *tName = QMetaType::typeName(qMetaTypeId<T>());                \
        Q_ASSERT(tName);                                                          \
        const int tNameLen = int(qstrlen(tName));                                 \
        QByteArray typeName;                                                      \
        typeName.reserve(int(sizeof(#CONTAINER_ARG)) + 1 + tNameLen + 1 + 1 + 1); \
        typeName.append(#CONTAINER_ARG, int(sizeof(#CONTAINER_ARG)) - 1)          \
            .append('<').append(tName, tNameLen).append('>');                     \
        typeName.append('*');                                                     \
        const int newId = qRegisterNormalizedMetaType< CONTAINER_ARG<T> *>(       \
                        typeName,                                                 \
                        reinterpret_cast< CONTAINER_ARG<T> **>(quintptr(-1)));    \
        metatype_id.storeRelease(newId);                                          \
        if (newId > 0) {                                                          \
            dtkMetaType::registerContainerPointerConverter< CONTAINER_ARG<T> * >(newId); \
        }                                                                         \
        return newId;                                                             \
    }                                                                             \
};                                                                                \
template<typename T> struct dtkMetaTypeIsSequentialContainerPointer< CONTAINER_ARG<T> *> : std::true_type {};

// /////////////////////////////////////////////////////////////////

#include "dtkMeta.tpp"

//
// dtkMeta.h ends here


text:
#ifdef USE_TI_DATABASE
@import JavaScriptCore;
@import TitaniumKit.ObjcProxy;

typedef enum {
  FieldTypeUnknown = -1,
  FieldTypeString,
  FieldTypeInt,
  FieldTypeFloat,
  FieldTypeDouble
} DatabaseFieldType;

@class TiDatabaseProxy; // forward declare

@protocol DatabaseModuleExports <JSExport>

// Constants
CONSTANT(DatabaseFieldType, FIELD_TYPE_DOUBLE);
CONSTANT(DatabaseFieldType, FIELD_TYPE_FLOAT);
CONSTANT(DatabaseFieldType, FIELD_TYPE_INT);
CONSTANT(DatabaseFieldType, FIELD_TYPE_STRING);

// Methods
JSExportAs(install,
           -(TiDatabaseProxy *)install
           : (NSString *)path withName
           : (NSString *)dbName);
- (TiDatabaseProxy *)open:(NSString *)dbName;

@end

@interface DatabaseModule : ObjcProxy <DatabaseModuleExports>
@end

#endif


text:
package kubectl

import (
	"os"
	"os/signal"

	"k8s.io/kubernetes/pkg/watch"
)

// WatchLoop loops, passing events in w to fn.
// If user sends interrupt signal, shut down cleanly. Otherwise, never return.
func WatchLoop(w watch.Interface, fn func(watch.Event) error) {
	signals := make(chan os.Signal, 1)
	signal.Notify(signals, os.Interrupt)
	defer signal.Stop(signals)
	for {
		select {
		case event, ok := <-w.ResultChan():
			if !ok {
				return
			}
			if err := fn(event); err != nil {
				w.Stop()
			}
		case <-signals:
			w.Stop()
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hirneola auricula-judae var. mauritiensis Henn.

### Remarks
null


text:
[![Backlog](https://badge.waffle.io/haronk/binarydigger.png?label=backlog&title=Backlog)](https://waffle.io/haronk/binarydigger)
[![Stories in Ready](https://badge.waffle.io/haronk/binarydigger.svg?label=ready&title=Ready)](http://waffle.io/haronk/binarydigger)
[![In Progress](https://badge.waffle.io/haronk/binarydigger.svg?label=in%20progress&title=In%20Progress)](http://waffle.io/haronk/binarydigger)
[![Done](https://badge.waffle.io/haronk/binarydigger.svg?label=done&title=Done)](http://waffle.io/haronk/binarydigger)

# Binary Digger

## Introduction

The idea of **BinaryDiger** (BD) is to help programmers inspecting unknown data formats and traversing quickly known ones.

BD uses plugin system for digging different data formats.
There are 2 different types of plugins: compiled and script based. Compiled plugin is a dynamic library that provides
specific interface for the main application to access hierarchical data.
Scripter (script based plugin) is also dynamic library which loads external scripts to parse data.

In current state Gui supports only view mode for data file.

## Screenshots

![Compiled plugin](images/BinaryDigger1.png "Compiled plugin")

![Lua scripter](images/BinaryDigger2.png "Lua scripter")

## Features

### Modularity

BD is built around interface implemented by plugins. Gui is a standalone application that loads plugins and uses their functionality to parse binary data into hierarchical structures.
Main requirement for the both parts of system (plugins and Gui) is supporting same interface.
In this case plugins and Gui are independent and could be developed separately.

### Compiled plugins

To add new compiled plugin just add new \*.cpp file into *BinaryDigger/plugins* folder and recompile project.
For examples look into existing plugin files.

#### Syntax

Plugin contains templates and plugin definition.

Template is defined by **TEMPL** and **TEMPL_END** macrosses.

```cpp
TEMPL(name, params...)

    // C++ code and template fields definitions
    ...
TEMPL_END
```

Where **name** is template name (without quotes) and **params** is parameters declaration similar to C-function parameters declaration.

To declare and use template elements several macrosses and methods could be used:

* **VAR** - simple element declaration.

```cpp
    VAR(WORD, size);
```

* **ARR** - array elemnt declaration.

```cpp
    ARR(CHAR, tag, 3);
```

* **VAL** - retrieve value of the POD element of the current template.

```cpp
    VAR(WORD,  entryNameLen);
    ARR(CHAR,  entryName, VAL(entryNameLen));
```

* To access subelement use following approach:

```cpp
TEMPL(T1)
    VAR(DWORD, len);
TEMPL_END

TEMPL(T2)
    VAR(T1, t1);
    DWORD_T = t1->item<DWORD>("len");
TEMPL_END
```

* To get or set file position use **getPosition** and **setPosition** methods:

```cpp
    bd_u64 pos = getPosition(); // retrieve current position
    setPosition(dataOffset);    // set new one
    ARR(UCHAR, data, 10);       // read data at those position
    setPosition(pos);           // return to the current position
```

There are several predefined templates for the POD types: **CHAR**, **UCHAR**, **WORD**, **DWORD**, **QWORD** and **DOUBLE**.

To make template available for using outside it should be registered:

```cpp
TEMPL(T1)
    VAR(DWORD, len);
TEMPL_END

PLUGIN(T1Plugin)
    TEMPL_REGISTER(T1);
PLUGIN_END
```

There should be at least one registered plugin.

### Scripters

Scripter (scripting plugin) doesn't provide any hardcoded templates. It uses script to generate parsed tree.

Gui application supports configurable highlighting in the script editor window.

> In current state Gui supports highlighting file only for Lua. This will be fixed in the future.

#### Syntax highlighting

Syntax highlighting subsytem uses Json format for configuration files. See example in [lua.json](gui/BinaryDigger/syntax/lua.json) file.

Configuration can contain several sections:

1. **regexps** - generic regular expression mappers. Each subelement contains:

2. **keywords** -

3. **comments** -

4. **formats** -

#### Lua scripter

To compile Lua scripter you should update as described
[here](http://stackoverflow.com/questions/23574323/why-cant-i-catch-a-luabinderror-exception-when-my-lua-code-throws-an-error).
Otherwise exceptions from Luabind will not be catched and program terminates.

## Development tools.

- GUI: Qt.
- Plugins: plain C interface. Macroses are used to specify data templates/structures.
- Scripting: Lua. Script has only read access to the hierarchy tree.
- Build system: CMake.

[Installation instructions](INSTALL.md).

## Versions features.

### Version 0.1.0

- HEX view and synchronization with tree navigation (http://qt-apps.org/content/show.php/?content=133189)
- GUI with tree view
- defining templates as C macroses
- support of the minimum template types: char, short, int, int64, array, templ
- minimal Lua scripting support (console only)

### Version 0.1.1

- minimal Lua scripting support (Gui)
- configurable script syntax highlighting

### Version 0.X.0

- large files support (using memory mapped files or other techniques)
- multiple templates support: apply different templates to the hierarchy elements data (blobs)

## TODO

* Full Lua scripting support.
* Array as tree node. DONE
* *"size"* property of the node to specify predefined hardcoded node size. For the POD types generate "size" automatically.
* Postponed nodes loading/generation using "size" property. Additional parameter to specify deepness of tree generation.
* Node properties (size, color, toString, endian, ...).


text:
import { Injectable } from 'angular2/core';
import { Router } from 'angular2/router';
import { AuthService } from './auth-service';

/**
 * This is an ugly workaround until `CanActivate` supports DI
 * @see https://github.com/angular/angular/issues/4112
 */

@Injectable()
export class AuthRouteHelper {
  static auth: AuthService;
  static router: Router;

  static requireAuth(): boolean {
    const { auth, router } = AuthRouteHelper;
    if (!auth.authenticated) router.navigate(['/SignIn']);
    return auth.authenticated;
  }

  static requireUnauth(): boolean {
    const { auth, router } = AuthRouteHelper;
    if (auth.authenticated) router.navigate(['/Station']);
    return !auth.authenticated;
  }

  constructor(auth: AuthService, router: Router) {
    AuthRouteHelper.auth = auth;
    AuthRouteHelper.router = router;
  }
}


text:
module ("getopt", package.seeall)

require "base"
require "string_ext"
require "object"
require "io_ext"

-- TODO: Sort out the packaging. getopt.Option is tedious to type, but
-- surely Option shouldn't be in the root namespace?
-- TODO: Wrap all messages; do all wrapping in processArgs, not
-- usageInfo; use sdoc-like library (see string.format todos)
-- TODO: Don't require name to be repeated in banner.
-- TODO: Store version separately (construct banner?).

-- Usage:

-- options = Options {Option {...} ...}
-- getopt.processArgs ()

-- Assumes prog = {name[, banner] [, purpose] [, notes] [, usage]}

-- options take a single dash, but may have a double dash
-- arguments may be given as -opt=arg or -opt arg
-- if an option taking an argument is given multiple times, only the
-- last value is returned; missing arguments are returned as 1

-- getOpt, usageInfo and dieWithUsage can be called directly (see
-- below, and the example at the end). Set _DEBUG.std to a non-nil
-- value to run the example.

-- @func getOpt: perform argument processing
--   @param argIn: list of command-line args
--   @param options: options table
-- @returns
--   @param argOut: table of remaining non-options
--   @param optOut: table of option key-value list pairs
--   @param errors: table of error messages
function getOpt (argIn, options)
  local noProcess = nil
  local argOut, optOut, errors = {[0] = argIn[0]}, {}, {}
  -- get an argument for option opt
  local function getArg (o, opt, arg, oldarg)
    if o.type == nil then
      if arg ~= nil then
        table.insert (errors, getopt.errNoArg (opt))
      end
    else
      if arg == nil and argIn[1] and
        string.sub (argIn[1], 1, 1) ~= "-" then
        arg = argIn[1]
        table.remove (argIn, 1)
      end
      if arg == nil and o.type == "Req" then
        table.insert (errors, getopt.errReqArg (opt, o.var))
        return nil
      end
    end
    if o.func then
      return o.func (arg, oldarg)
    end
    return arg or 1 -- make sure arg has a value
  end
  -- parse an option
  local function parseOpt (opt, arg)
    local o = options.name[opt]
    if o ~= nil then
      optOut[o.name[1]] = getArg (o, opt, arg, optOut[o.name[1]])
    else
      table.insert (errors, getopt.errUnrec (opt))
    end
  end
  while argIn[1] do
    local v = argIn[1]
    table.remove (argIn, 1)
    local _, _, dash, opt = string.find (v, "^(%-%-?)([^=-][^=]*)")
    local _, _, arg = string.find (v, "=(.*)$")
    if v == "--" then
      noProcess = 1
    elseif dash == nil or noProcess then -- non-option
      table.insert (argOut, v)
    else -- option
      parseOpt (opt, arg)
    end
  end
  return argOut, optOut, errors
end

-- Options table type

_G.Option = Object {_init = {
    "name", -- list of names
    "desc", -- description of this option
    "type", -- type of argument (if any): Req (uired), Opt (ional)
    "var",  -- descriptive name for the argument
    "func"  -- optional function (newarg, oldarg) to convert argument
    -- into actual argument, (if omitted, argument is left as it
    -- is)
}}

-- Options table constructor: adds lookup tables for the option names
function _G.Options (t)
  local name = {}
  for _, v in ipairs (t) do
    for j, s in pairs (v.name) do
      if name[s] then
        warn ("duplicate option '%s'", s)
      end
      name[s] = v
    end
  end
  t.name = name
  return t
end

-- Error and usage information formatting

-- @func errNoArg: argument when there shouldn't be one
--   @paramoptStr: option string
-- @returns
--   @param err: option error
function errNoArg (optStr)
  return "option `" .. optStr .. "' doesn't take an argument"
end

-- @func errReqArg: required argument missing
--   @param optStr: option string
--   @param desc: argument description
-- @returns
--   @param err: option error
function errReqArg (optStr, desc)
  return "option `" .. optStr .. "' requires an argument `" .. desc ..
    "'"
end

-- @func errUnrec: unrecognized option
--   @param optStr: option string
-- @returns
--   @param err: option error
function errUnrec (optStr)
  return "unrecognized option `-" .. optStr .. "'"
end

-- @func usageInfo: produce usage info for the given options
--   @param header: header string
--   @param optDesc: option descriptors
--   @param pageWidth: width to format to [78]
-- @returns
--   @param mess: formatted string
function usageInfo (header, optDesc, pageWidth)
  pageWidth = pageWidth or 78
  -- @func formatOpt: format the usage info for a single option
  --   @param opt: the Option table
  -- @returns
  --   @param opts: options
  --   @param desc: description
  local function fmtOpt (opt)
    local function fmtName (o)
      return "-" .. o
    end
    local function fmtArg ()
      if opt.type == nil then
        return ""
      elseif opt.type == "Req" then
        return "=" .. opt.var
      else
        return "[=" .. opt.var .. "]"
      end
    end
    local textName = list.map (fmtName, opt.name)
    textName[1] = textName[1] .. fmtArg ()
    return {table.concat ({table.concat (textName, ", ")}, ", "),
      opt.desc}
  end
  local function sameLen (xs)
    local n = math.max (unpack (list.map (string.len, xs)))
    for i, v in pairs (xs) do
      xs[i] = string.sub (v .. string.rep (" ", n), 1, n)
    end
    return xs, n
  end
  local function paste (x, y)
    return "  " .. x .. "  " .. y
  end
  local function wrapper (w, i)
    return function (s)
             return string.wrap (s, w, i, 0)
           end
  end
  local optText = ""
  if #optDesc > 0 then
    local cols = list.transpose (list.map (fmtOpt, optDesc))
    local width
    cols[1], width = sameLen (cols[1])
    cols[2] = list.map (wrapper (pageWidth, width + 4), cols[2])
    optText = "\n\n" ..
      table.concat (list.mapWith (paste,
                                  list.transpose ({sameLen (cols[1]),
                                                    cols[2]})),
                    "\n")
  end
  return header .. optText
end

-- @func dieWithUsage: die emitting a usage message
function dieWithUsage ()
  local name = prog.name
  prog.name = nil
  local usage, purpose, notes = "[OPTION...] FILE...", "", ""
  if prog.usage then
    usage = prog.usage
  end
  if prog.purpose then
    purpose = "\n" .. prog.purpose
  end
  if prog.notes then
    notes = "\n\n"
    if not string.find (prog.notes, "\n") then
      notes = notes .. string.wrap (prog.notes)
    else
      notes = notes .. prog.notes
    end
  end
  die (getopt.usageInfo ("Usage: " .. name .. " " .. usage .. purpose,
                         options)
         .. notes)
end

-- @func processArgs: simple getOpt wrapper
-- adds -version/-v and -help/-h/-? automatically; stops program
-- if there was an error or -help was used
function processArgs ()
  local totArgs = #arg
  options = Options (list.concat (options or {},
                                  {Option {{"version", "v"},
                                      "show program version"},
                                    Option {{"help", "h", "?"},
                                      "show this help"}}
                              ))
  local errors
  _G.arg, opt, errors = getopt.getOpt (arg, options)
  if (opt.version or opt.help) and prog.banner then
    io.stderr:write (prog.banner .. "\n")
  end
  if #errors > 0 or opt.help then
    local name = prog.name
    prog.name = nil
    if #errors > 0 then
      warn (table.concat (errors, "\n") .. "\n")
    end
    prog.name = name
    getopt.dieWithUsage ()
  elseif opt.version and #arg == 0 then
    os.exit ()
  end
end

-- A small and hopefully enlightening example:
if type (_DEBUG) == "table" and _DEBUG.std then

  function out (o)
    return o or io.stdout
  end

  options = Options {
    Option {{"verbose", "v"}, "verbosely list files"},
    Option {{"version", "release", "V", "?"}, "show version info"},
    Option {{"output", "o"}, "dump to FILE", "Opt", "FILE", out},
    Option {{"name", "n"}, "only dump USER's files", "Req", "USER"},
  }

  function test (cmdLine)
    local nonOpts, opts, errors = getopt.getOpt (cmdLine, options)
    if #errors == 0 then
      print ("options=" .. tostring (opts) ..
             "  args=" .. tostring (nonOpts) .. "\n")
    else
      print (table.concat (errors, "\n") .. "\n" ..
             getopt.usageInfo ("Usage: foobar [OPTION...] FILE...",
                               options))
    end
  end

  prog = {name = "foobar"} -- in case of errors
  -- example runs:
  test {"foo", "-v"}
  -- options={verbose=1}  args={1=foo,n=1}
  test {"foo", "--", "-v"}
  -- options={}  args={1=foo,2=-v,n=2}
  test {"-o", "-?", "-name", "bar", "--name=baz"}
  -- options={output=userdata(?): 0x????????,version=1,name=baz}  args={}
  test {"-foo"}
  -- unrecognized option `foo'
  -- Usage: foobar [OPTION...] FILE...
  --   -verbose, -v                verbosely list files
  --   -version, -release, -V, -?  show version info
  --   -output[=FILE], -o          dump to FILE
  --   -name=USER, -n              only dump USER's files

end


text:
extern "C" {
#endif

int plugin_init(void);
void *plugin_get_widget(void);
void plugin_cleanup(void);

#ifdef __cplusplus
}
#endif

#endif // PLUGIN_H


text:
title: What is UX?
title_long: What actually is UX?
subtitle: Thoughts on where user experience (UX) begins and ends
banner_image: what-is-ux-thoughts-on-where-user-experience-begins-and-ends.png
square_image: what-is-ux-thoughts-on-where-user-experience-begins-and-ends-square.png
date: 2015-07-3
featured: false
author: guest
category: UX & Design
description: >
    UX is much more than just wireframes. The user experience is affected by multitude of factors beyond the common 'UX' wrapper.
---

It doesn't take long in any tech related conversation before the acronyms begin to flow, because they're a convenient way to express complex phrases in fewer syllables. Sometimes the acronyms we adopt don't mean much when broken down ('wi-fi' anyone?), but that's OK if they've taken on a single, accepted definition.

Other times we adopt terms that evolve from their original context without taking on a single definition, and this is the case with 'UX' as a shorthand for 'user experience'.

Apart from issues with lay-person pronunciation ("You're what? An 'ucks' designer?"), the problem with 'UX' is that it has become a buzzword, a convenient catch-all for a set of issues that UX teams are commonly asked to deal with. I frequently hear 'UX' substituted for usability ("we need some UX testing"), user-centred design ("UX process"), wireframes("when can I see the UX?"). Replacing 'UX' with 'user experience' in these examples doesn't work. The idea that the experience of a product or service is affected by more than usability and wireframes is lost, and with it the opportunity to really understand and improve it.

                <ohs-about-callout class="ml0 lg-ml"></ohs-about-callout>

What should UX actually mean?

I was interested to discover that 'user experience' is defined within an ISO standard, which fits much better with my own understanding of the term. ISO 9241-210 Human-centred design processes for interactive systems defines user experience as 'a person's perceptions and responses that result from the use or anticipated use of a product, system or service'.

It goes on to add:

            <ohs-quote>
                User experience includes all the users' emotions, beliefs, preferences, perceptions, physical and psychological responses, behaviours and accomplishments that occur before, during and after use.
            </ohs-quote>

It's clear from this definition that user experience is affected by multitude of factors beyond the common 'UX' wrapper.

To illustrate just how broad that goes, let's consider a movie streaming service as an example.  Outside of design, influencing factors for the service's user experience might include:

Expectations

How does the service compare with the user's pre-conceptions set by internal forces like marketing, advertising, price and brand identity, but also external forces like word of mouth and experience of competitor services?

Technology

Can the technology deliver what's expected of the service? Is the streaming quality great on the user's 60" TV? Is their connection up to it? Is it even available on their platform? Do outages and bugs affect the service?

Content

Is the content what the user wants? Does it have the latest blockbusters and that 80s sci-fi B-movie they've been recommended? Or, is it hampered by licensing restrictions? What about the interface content - are the descriptions useful and the movie stills recognisable? Does advertising get in the way of accessing the service?

Customer service

Do they resolve the problem within minutes, outside office hours? Or, are reps over-stretched, under-trained and hard to contact?

Context of use

Is the user trying to use this service in difficult circumstances, or in a way it was never intended for? Maybe they want to use it to watch films on a smartphone with a cracked screen in bright light over a 3G connection.

User experience is everywhere

None of the factors listed above fall under the perceived 'UX' discipline, some of them are not even within the control of the business, but they are obviously part of the user experience. So, we have a discrepancy between what the UX team is expected to achieve (to define and manage user experience) and their actual remit (to define how users interact with the digital interface).

In order to achieve user experience greatness, every team needs to consider how their decisions affect the user's experience of the product. Not just the obvious, direct implications for the current screen or process, but subtle effects elsewhere. What expectations does this set? And how is this experience affected by the user expectations set elsewhere?

Going back to our fictional movie streaming service, let's say for example that the product team want to introduce HD streaming. The technology team choose a new streaming supplier in order to offer HD. The user experience team re-design the interface to allow users to filter for HD movies. The marketing team run a campaign to tell customers about this new addition to the service, and how much it will improve their movie experience. Every team has done their best to meet their objectives. Great!

One of our users, Maggie, sees the HD campaign. She's been happily using the service for a few months, but her expectations have now changed. As the HD service is new, not many titles are available and Maggie is a little disappointed. When she tries to play HD content she finds that it buffers a lot, her connection's not up to it. What's more, the media player looks different and doesn't have keyboard controls.

Maggie is clearly having a worse experience despite the service being improved in real terms. Several things caused this:

The marketing campaign met its objectives in attracting customers to the new HD service, but didn't manage expectations around bandwidth and content availability.

The UX team designed the search interface for anticipating a large catalogue of HD films, but it looks underwhelming with the small launch selection.

The additional technology needed to switch back to a low quality stream wasn't anticipated.

Maggie was reliant on a feature of the old player that the tech team didn't know was important when they chose a new supplier.

The role of UX

Decisions will always affect user experience in unexpected ways. UX designers are often the first to notice and raise potential user experience problems, and to suggest solutions - we are problem solvers at heart. However, this doesn't mean that bad user experiences are caused by bad design, nor that clever design is always the solution. User experience is something that every team should consider and take responsibility for.

In many ways it's impossible to be a user experience designer. UX teams commonly tackle interaction design, visual design, information architecture, usability and user research. They are only able to influence user experience as far as it relates to the digital interface.

'UX' (User Experience) as a term, is probably not going away (no matter how much I'd like it to), but it's good to remind ourselves now and again that it means more than 'wireframes'.


text:
package org.knowm.xchange.huobi.service;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.huobi.BitVcFutures;
import org.knowm.xchange.huobi.dto.trade.BitVcFuturesPositionByContract;

import si.mazi.rescu.RestProxyFactory;

public class BitVcFuturesServiceRaw {

  protected final BitVcFutures bitvc;
  protected final String accessKey;
  protected HuobiDigest digest;

  public BitVcFuturesServiceRaw(Exchange exchange) {
    this.bitvc = RestProxyFactory.createProxy(BitVcFutures.class, "https://api.bitvc.com/futures");
    this.accessKey = exchange.getExchangeSpecification().getApiKey();

    this.digest = new HuobiDigest(exchange.getExchangeSpecification().getSecretKey(), "secretKey");
  }

  public BitVcFuturesPositionByContract getFuturesPositions() {
    final BitVcFuturesPositionByContract positions = bitvc.positions(accessKey, 1, requestTimestamp(), digest);

    return positions;
  }

  protected long requestTimestamp() {
    return System.currentTimeMillis() / 1000;
  }
}


text:
@interface ATCSecretKeyManuallyInputViewController ()

@end // Private Interfaces

// ATCSecretKeyManuallyInputViewController class
@implementation ATCSecretKeyManuallyInputViewController

- ( void ) viewDidLoad
    {
    [ super viewDidLoad ];

    [ self.view configureForAutoLayout ];
    [ self.view autoSetDimensionsToSize: self.view.frame.size ];
    }

NSString* const kOKButton = @"ok-button";
NSString* const kCancelButton = @"cancel-button";

- ( void ) dismissController: ( id )_Sender
    {
    [ super dismissController: _Sender ];

    NSString* identifier = [ ( NSButton* )_Sender identifier ];
    if ( [ identifier isEqualToString: kOKButton ] )
        {
        ATCAuthVaultItem* newEntry =
            [ [ ATCAuthVaultItem alloc ] initWithIssuer: self.serviceNameField.stringValue
                                            accountName: self.accountNameField.stringValue
                                              secretKey: self.secretKeyField.stringValue ];
        [ [ NSNotificationCenter defaultCenter ]
            postNotificationName: ATCNewTotpEntryDidAddNotif object: self userInfo: @{ kTotpEntry : newEntry } ];
        }

    [ self.view.window close ];
    }

#pragma mark - Conforms to <NSTextFieldDelegate>

NSString* const kSecretKeyField = @"secret-key-field";
NSString* const kAccountNameField = @"account-name-field";
NSString* const kServiceNameField = @"service-name-field";

- ( void ) controlTextDidChange: ( NSNotification* )_Notif
    {
    NSText* fieldEditor = _Notif.userInfo[ @"NSFieldEditor" ];
    NSTextField* fieldEditorDel = ( NSTextField* )[ fieldEditor delegate ];
    NSString* identifier = [ fieldEditorDel identifier ];

    if ( [ identifier isEqualToString: kSecretKeyField ]
            || [ identifier isEqualToString: kAccountNameField ] )
        [ self.okButton setEnabled:
            ( self.secretKeyField.stringValue.length > 0 ) && ( self.accountNameField.stringValue.length > 0 ) ];
    }

@end // ATCSecretKeyManuallyInputViewController class


text:
require 'autoproj/stats'

module Autoproj
    module Ops
        # Computes per-package statistics
        class Stats
            attr_reader :sanitizer

            def initialize(sanitizer: Autoproj::Stats::Sanitizer.new)
                @sanitizer = sanitizer
            end

            def process(packages, parallel: 1)
                executor = Concurrent::FixedThreadPool.new(parallel, max_length: 0)
                result = Hash.new

                futures = packages.map do |pkg|
                    [pkg, Concurrent::Future.execute(executor: executor) { compute_package_stats(pkg) }]
                end
                futures.inject(Hash.new) do |h, (pkg, future)|
                    if stats = future.value
                        h[pkg] = stats
                    elsif future.reason.kind_of?(Exception)
                        raise future.reason
                    else
                        pkg.error "%s: failed, #{future.reason}"
                    end
                    h
                end

            ensure
                executor.shutdown
                executor.wait_for_termination
            end

            def compute_package_stats(pkg)
                if pkg.importer
                    if stats_generator = find_generator_for_importer(pkg.importer)
                        stats_generator.(pkg)
                    else
                        Autoproj.warn "no stats generator for #{pkg.name} (#{pkg.importer.class})"
                    end
                else
                    Autoproj.warn "no importer for #{pkg.name}"
                end
            end

            def find_generator_for_importer(importer)
                if importer.class == Autobuild::Git
                    return Autoproj::Stats::Git.new(sanitizer: sanitizer)
                end
            end
        end
    end
end


text:
import { SubscriberClient, InvalidJsonError, ApiError } from '../common';

export class RouterUtils {
  static checkCredentials(req, res, next): any {
    if (req.body.password && req.body.username) {
      next();
    } else {
      res.statusCode = 400;
      res.json(new InvalidJsonError().toJSON());
    }
  }

  static checkTenantID(req, res, next): any {
    if (req.headers['tenant-id']) {
      next();
    } else {
      res.statusCode = 400;
      res.json(new ApiError('Missing Tenant-ID header', 400, 'BAD_REQUEST'));
    }
  }

  static checkEndpointID(req, res, next): any {
    if (req.headers['endpoint-id']) {
      next();
    } else {
      res.statusCode = 400;
      res.json(new ApiError('Missing Endpoint-ID header', 400, 'BAD_REQUEST'));
    }
  }

  /**
   * Checks if the requested OpenStack service needs to fetch information from another service and composes the new request body
   * Todo - Breaks post requests
   * @static
   * @param {any} req
   * @param {any} res
   * @param {any} next
   *
   * @memberOf RouterUtils
   */
  static getInfoFromServices(req, res, next) {
    if (req.method === 'POST') {
      if ((SubscriberClient.registeredMessages.hasOwnProperty(req.originalUrl)) && (SubscriberClient.registeredMessages[req.originalUrl].length > 0)) {
        SubscriberClient['requestBody'] = req.body;
        Promise.all(SubscriberClient.registeredMessages[req.originalUrl].map(SubscriberClient.notifyPublisher, SubscriberClient))
          .then(results => {
            return Promise.resolve(results.forEach(result => {
              req.body[result['accessKey']] = result['body'];
            }));
          })
          .then(() => {
            next();
          });
      }
    }
    else {
      next();
    }
  }
}


text:
module Course::Assessment::SubmissionsHelper
  # Returns the count of student submissions in a course that are pending grading.
  #
  # @return [Integer] The required count
  def pending_submissions_count
    @pending_submissions_count ||= begin
      student_ids = current_course.course_users.students.select(:user_id)
      pending_submission_count_for(student_ids)
    end
  end

  # Returns the count of submissions of my students in a course that are pending grading
  #
  # @return [Integer] The required count
  def my_students_pending_submissions_count
    @my_student_pending_submissions ||= begin
      my_student_ids = current_course_user ? current_course_user.my_students.select(:user_id) : []
      pending_submission_count_for(my_student_ids)
    end
  end

  private

  # Returns the count of submissions given the student ids
  #
  # @param [Array<Integer>] student_ids The submissions for the given user_ids of student
  # @return [Integer] The required count
  def pending_submission_count_for(student_ids)
    return 0 if student_ids.blank?
    Course::Assessment::Submission.
      from_course(current_course).by_users(student_ids).pending_for_grading.count
  end
end


text:
package org.robovm.samples.datecell.ui;

import java.util.ArrayList;
import java.util.List;

import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.foundation.Foundation;
import org.robovm.apple.foundation.NSArray;
import org.robovm.apple.foundation.NSDate;
import org.robovm.apple.foundation.NSDateFormatter;
import org.robovm.apple.foundation.NSDateFormatterStyle;
import org.robovm.apple.foundation.NSIndexPath;
import org.robovm.apple.foundation.NSLocale;
import org.robovm.apple.foundation.NSNotificationCenter;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.uikit.UIBarButtonItem;
import org.robovm.apple.uikit.UIControl;
import org.robovm.apple.uikit.UIDatePicker;
import org.robovm.apple.uikit.UITableView;
import org.robovm.apple.uikit.UITableViewCell;
import org.robovm.apple.uikit.UITableViewCellSelectionStyle;
import org.robovm.apple.uikit.UITableViewController;
import org.robovm.apple.uikit.UITableViewRowAnimation;
import org.robovm.apple.uikit.UIView;
import org.robovm.objc.annotation.CustomClass;
import org.robovm.objc.annotation.IBAction;
import org.robovm.objc.annotation.IBOutlet;
import org.robovm.objc.block.VoidBooleanBlock;

@CustomClass("MyTableViewController")
public class MyTableViewController extends UITableViewController {
    /**
     * duration for the animation to slide the date picker into view
     */
    private static final double PICKER_ANIMATION_DURATION = 0.40;
    /**
     * view tag identifying the date picker view
     */
    private static final long DATE_PICKER_TAG = 99;

    // keep track of which rows have date cells
    private static final int DATE_START_ROW = 1;
    private static final int DATE_END_ROW = 2;

    /**
     * the cells with the start or end date
     */
    private static final String DATE_CELL_ID = "dateCell";
    /**
     * the cell containing the date picker
     */
    private static final String DATE_PICKER_ID = "datePicker";
    /**
     * the remaining cells at the end
     */
    private static final String OTHER_CELL_ID = "otherCell";

    public class CellData {
        String title;
        NSDate date;

        public CellData(String title, NSDate date) {
            this.title = title;
            this.date = date;
        }
    }

    private List<CellData> data;
    private NSDateFormatter dateFormatter;

    // keep track which indexPath points to the cell with UIDatePicker
    private NSIndexPath datePickerIndexPath;

    private double pickerCellRowHeight;

    @IBOutlet
    private UIDatePicker pickerView;

    // this button appears only when the date picker is shown (iOS 6.1.x or
    // earlier)
    @IBOutlet
    private UIBarButtonItem doneButton;

    private NSObject localeNotif;

    @Override
    public void viewDidLoad() {
        super.viewDidLoad();

        // setup our data source
        data = new ArrayList<>();
        data.add(new CellData("Tap a cell to change its date:", null));
        data.add(new CellData("Start Date", new NSDate()));
        data.add(new CellData("End Date", new NSDate()));
        data.add(new CellData("(other item1)", null));
        data.add(new CellData("(other item2)", null));

        dateFormatter = new NSDateFormatter();
        dateFormatter.setDateStyle(NSDateFormatterStyle.Short);
        dateFormatter.setTimeStyle(NSDateFormatterStyle.No);

        // obtain the picker view cell's height, works because the cell was
        // pre-defined in our storyboard
        UITableViewCell pickerViewCellToCheck = getTableView().dequeueReusableCell(DATE_PICKER_ID);
        pickerCellRowHeight = pickerViewCellToCheck.getFrame().getHeight();

        // if the locale changes while in the background, we need to be notified
        // so we can update the date format in the table view cells
        localeNotif = NSLocale.Notifications.observeCurrentLocaleDidChange(new Runnable() {
            @Override
            public void run() {
                // the user changed the locale (region format) in Settings, so
                // we are notified here to
                // update the date format in the table view cells
                getTableView().reloadData();
            }
        });
    }

    @Override
    protected void dispose(boolean finalizing) {
        NSNotificationCenter.getDefaultCenter().removeObserver(localeNotif);
        super.dispose(finalizing);
    }

    /**
     * Determines if the given indexPath has a cell below it with a
     * UIDatePicker.
     *
     * @param indexPath The indexPath to check if its cell has a UIDatePicker
     *            below it.
     */
    private boolean hasPickerForIndexPath(NSIndexPath indexPath) {
        boolean hasDatePicker = false;

        long targetedRow = indexPath.getRow();
        targetedRow++;

        UITableViewCell checkDatePickerCell = getTableView().getCellForRow(NSIndexPath.row(targetedRow, 0));
        UIDatePicker checkDatePicker = (UIDatePicker) checkDatePickerCell.getViewWithTag(DATE_PICKER_TAG);

        hasDatePicker = checkDatePicker != null;
        return hasDatePicker;
    }

    /**
     * Updates the UIDatePicker's value to match with the date of the cell above
     * it.
     */
    private void updateDatePicker() {
        if (datePickerIndexPath != null) {
            UITableViewCell associatedDatePickerCell = getTableView().getCellForRow(datePickerIndexPath);

            UIDatePicker targetedDatePicker = (UIDatePicker) associatedDatePickerCell.getViewWithTag(DATE_PICKER_TAG);
            if (targetedDatePicker != null) {
                // we found a UIDatePicker in this cell, so update it's date
                // value
                CellData itemData = data.get(datePickerIndexPath.getRow() - 1);
                targetedDatePicker.setDate(itemData.date, false);
            }
        }
    }

    /**
     * @return if the UITableViewController has a UIDatePicker in any of its
     *         cells.
     */
    private boolean hasInlineDatePicker() {
        return datePickerIndexPath != null;
    }

    /**
     * Determines if the given indexPath points to a cell that contains the
     * UIDatePicker.
     *
     * @param indexPath The indexPath to check if it represents a cell with the
     *            UIDatePicker.
     * @return
     */
    private boolean indexPathHasPicker(NSIndexPath indexPath) {
        return hasInlineDatePicker() && datePickerIndexPath.getRow() == indexPath.getRow();
    }

    /**
     * Determines if the given indexPath points to a cell that contains the
     * start/end dates.
     *
     * @param indexPath The indexPath to check if it represents start/end date
     *            cell.
     * @return
     */
    private boolean indexPathHasDate(NSIndexPath indexPath) {
        boolean hasDate = false;

        if ((indexPath.getRow() == DATE_START_ROW)
                || (indexPath.getRow() == DATE_END_ROW || (hasInlineDatePicker() && (indexPath.getRow() == DATE_END_ROW + 1)))) {
            hasDate = true;
        }

        return hasDate;
    }

    @Override
    public double getHeightForRow(UITableView tableView, NSIndexPath indexPath) {
        return indexPathHasPicker(indexPath) ? pickerCellRowHeight : tableView.getRowHeight();
    }

    @Override
    public long getNumberOfRowsInSection(UITableView tableView, long section) {
        if (hasInlineDatePicker()) {
            // we have a date picker, so allow for it in the number of rows in
            // this section
            int numRows = data.size();
            return ++numRows;
        }
        return data.size();
    }

    @Override
    public UITableViewCell getCellForRow(UITableView tableView, NSIndexPath indexPath) {
        UITableViewCell cell = null;

        String cellID = OTHER_CELL_ID;

        if (indexPathHasPicker(indexPath)) {
            // the indexPath is the one containing the inline date picker
            cellID = DATE_PICKER_ID; // the current/opened date picker cell
        } else if (indexPathHasDate(indexPath)) {
            // the indexPath is one that contains the date information
            cellID = DATE_CELL_ID; // the start/end date cells
        }

        cell = getTableView().dequeueReusableCell(cellID);

        if (indexPath.getRow() == 0) {
            // we decide here that first cell in the table is not selectable
            // (it's just an indicator)
            cell.setSelectionStyle(UITableViewCellSelectionStyle.None);
        }

        // if we have a date picker open whose cell is above the cell we want to
        // update,
        // then we have one more cell than the model allows
        int modelRow = indexPath.getRow();
        if (datePickerIndexPath != null && datePickerIndexPath.getRow() <= indexPath.getRow()) {
            modelRow--;
        }

        CellData itemData = data.get(modelRow);

        // proceed to configure our cell
        switch (cellID) {
        case DATE_CELL_ID:
            // we have either start or end date cells, populate their date field
            cell.getDetailTextLabel().setText(dateFormatter.format(itemData.date));
        case OTHER_CELL_ID:
            // this cell is a non-date cell, just assign it's text label
            cell.getTextLabel().setText(itemData.title);
            break;
        default:
            break;
        }

        return cell;
    }

    /**
     * Adds or removes a UIDatePicker cell below the given indexPath.
     *
     * @param indexPath The indexPath to reveal the UIDatePicker.
     */
    private void toggleDatePicker(NSIndexPath indexPath) {
        getTableView().beginUpdates();

        NSArray<NSIndexPath> indexPaths = new NSArray<>(NSIndexPath.row(indexPath.getRow() + 1, 0));

        // check if 'indexPath' has an attached date picker below it
        if (hasPickerForIndexPath(indexPath)) {
            // found a picker below it, so remove it
            getTableView().deleteRows(indexPaths, UITableViewRowAnimation.Fade);
        } else {
            // didn't find a picker below it, so we should insert it
            getTableView().insertRows(indexPaths, UITableViewRowAnimation.Fade);
        }

        getTableView().endUpdates();
    }

    /**
     * Reveals the date picker inline for the given indexPath, called by
     * "didSelectRowAtIndexPath".
     *
     * @param indexPath The indexPath to reveal the UIDatePicker.
     */
    private void displayInlineDatePickerForRow(NSIndexPath indexPath) {
        // display the date picker inline with the table content
        getTableView().beginUpdates();

        boolean before = false; // indicates if the date picker is below
                                // "indexPath", help us determine which row to
                                // reveal
        if (hasInlineDatePicker()) {
            before = datePickerIndexPath.getRow() < indexPath.getRow();
        }

        boolean sameCellClicked = datePickerIndexPath != null && datePickerIndexPath.getRow() - 1 == indexPath.getRow();

        // remove any date picker cell if it exists
        if (hasInlineDatePicker()) {
            getTableView().deleteRows(
                    new NSArray<NSIndexPath>(NSIndexPath.row(datePickerIndexPath.getRow(), 0)),
                    UITableViewRowAnimation.Fade);
            datePickerIndexPath = null;
        }

        if (!sameCellClicked) {
            // hide the old date picker and display the new one
            long rowToReveal = before ? indexPath.getRow() - 1 : indexPath.getRow();
            NSIndexPath indexPathToReveal = NSIndexPath.row(rowToReveal, 0);

            toggleDatePicker(indexPathToReveal);
            datePickerIndexPath = NSIndexPath.row(indexPathToReveal.getRow() + 1, 0);
        }

        // always deselect the row containing the start or end date
        getTableView().deselectRow(indexPath, true);

        getTableView().endUpdates();

        // inform our date picker of the current date to match the current cell
        updateDatePicker();
    }

    /**
     * Reveals the UIDatePicker as an external slide-in view, iOS 6.1.x and
     * earlier, called by "didSelectRow".
     *
     * @param indexPath The indexPath used to display the UIDatePicker.
     */
    private void displayExternalDatePickerForRow(NSIndexPath indexPath) {
        // first update the date picker's date value according to our model
        CellData itemData = data.get(indexPath.getRow());
        pickerView.setDate(itemData.date, true);

        // the date picker might already be showing, so don't add it to our view
        if (pickerView.getSuperview() == null) {
            CGRect startFrame = pickerView.getFrame();
            final CGRect endFrame = pickerView.getFrame();

            // the start position is below the bottom of the visible frame
            startFrame.getOrigin().setY(getView().getFrame().getHeight());

            // the end position is slid up by the height of the view
            endFrame.getOrigin().setY(startFrame.getOrigin().getY() - endFrame.getHeight());

            pickerView.setFrame(startFrame);

            getView().addSubview(pickerView);

            // animate the date picker into view
            UIView.animate(PICKER_ANIMATION_DURATION, new Runnable() {
                @Override
                public void run() {
                    pickerView.setFrame(endFrame);
                }
            }, new VoidBooleanBlock() {
                @Override
                public void invoke(boolean v) {
                    // add the "Done" button to the nav bar
                    getNavigationItem().setRightBarButtonItem(doneButton);
                }
            });
        }
    }

    @Override
    public void didSelectRow(UITableView tableView, NSIndexPath indexPath) {
        UITableViewCell cell = tableView.getCellForRow(indexPath);
        if (cell.getReuseIdentifier().equals(DATE_CELL_ID)) {
            if (Foundation.getMajorSystemVersion() >= 7) {
                displayInlineDatePickerForRow(indexPath);
            } else {
                displayExternalDatePickerForRow(indexPath);
            }
        } else {
            tableView.deselectRow(indexPath, true);
        }
    }

    /**
     * User chose to change the date by changing the values inside the
     * UIDatePicker.
     *
     * @param control
     */
    @IBAction
    private void dateAction(UIControl sender) {
        NSIndexPath targetedCellIndexPath = null;

        if (hasInlineDatePicker()) {
            // inline date picker: update the cell's date "above" the
            // date picker cell
            targetedCellIndexPath = NSIndexPath.row(datePickerIndexPath.getRow() - 1, 0);
        } else {
            // external date picker: update the current "selected"
            // cell's date
            targetedCellIndexPath = getTableView().getIndexPathForSelectedRow();
        }

        UITableViewCell cell = getTableView().getCellForRow(targetedCellIndexPath);
        UIDatePicker targetedDatePicker = (UIDatePicker) sender;

        // update our data model
        CellData itemData = data.get(targetedCellIndexPath.getRow());
        itemData.date = targetedDatePicker.getDate();

        // update the cell's date string
        cell.getDetailTextLabel().setText(dateFormatter.format(targetedDatePicker.getDate()));
    }

    /**
     * User chose to finish using the UIDatePicker by pressing the "Done" button
     * (used only for "non-inline" date picker, iOS 6.1.x or earlier)
     *
     * @param control
     */
    @IBAction
    private void doneAction(UIBarButtonItem sender) {
        final CGRect pickerFrame = pickerView.getFrame();
        pickerFrame.getOrigin().setY(getView().getFrame().getHeight());

        // animate the date picker out of view
        UIView.animate(PICKER_ANIMATION_DURATION, new Runnable() {
            @Override
            public void run() {
                pickerView.setFrame(pickerFrame);
            }
        }, new VoidBooleanBlock() {
            @Override
            public void invoke(boolean v) {
                pickerView.removeFromSuperview();
            }
        });

        // remove the "Done" button in the navigation bar
        getNavigationItem().setRightBarButtonItem(null);

        // deselect the current table cell
        NSIndexPath indexPath = getTableView().getIndexPathForSelectedRow();
        getTableView().deselectRow(indexPath, true);
    }
}


text:
<!DOCTYPE html>
<title>sessionStorage storage event not fired for this window</title>

FAIL - Script did not execute.


text:
using System;
using System.Linq;
using System.Data.Common;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.Generic;

using CoreSystem.Data;

using CrystalMapper;
using CrystalMapper.Linq;
using CrystalMapper.Context;
using CrystalMapper.Mapping;

namespace CrystalMapper.Test.Northwind
{
	[Table(TABLE_NAME)]
    public partial class Region : IRecord, INotifyPropertyChanging, INotifyPropertyChanged
    {
		#region Table Schema

        public const string TABLE_NAME = "dbo.Region";

		public const string COL_REGIONID = "RegionID";
		public const string COL_REGIONDESCRIPTION = "RegionDescription";

        public const string PARAM_REGIONID = "@RegionID";
        public const string PARAM_REGIONDESCRIPTION = "@RegionDescription";

        #endregion

		#region Queries

		private const string SQL_INSERT_REGION = "INSERT INTO dbo.Region ( [RegionID], [RegionDescription]) VALUES ( @RegionID, @RegionDescription);"  ;

		private const string SQL_UPDATE_REGION = "UPDATE dbo.Region SET [RegionDescription] = @RegionDescription WHERE [RegionID] = @RegionID";

		private const string SQL_DELETE_REGION = "DELETE FROM dbo.Region WHERE  [RegionID] = @RegionID ";

        #endregion

        #region Declarations

		protected int regionid = default(int);

		protected string regiondescription = default(string);

        private event PropertyChangingEventHandler propertyChanging;

        private event PropertyChangedEventHandler propertyChanged;
        #endregion

 		#region Properties

        event PropertyChangingEventHandler INotifyPropertyChanging.PropertyChanging
        {
            add { this.propertyChanging += value; }
            remove { this.propertyChanging -= value; }
        }

        event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
        {
            add { this.propertyChanged += value; }
            remove { this.propertyChanged -= value; }
        }

        IQueryProvider IRecord.Provider { get; set; }

        [Column(COL_REGIONID, PARAM_REGIONID, default(int))]
        public virtual int RegionID
        {
            get { return this.regionid; }
			set	{
                  if(this.regionid != value)
                    {
                        this.OnPropertyChanging("RegionID");
                        this.regionid = value;
                        this.OnPropertyChanged("RegionID");
                    }
                }
        }

        [Column(COL_REGIONDESCRIPTION, PARAM_REGIONDESCRIPTION )]
        public virtual string RegionDescription
        {
            get { return this.regiondescription; }
			set	{
                  if(this.regiondescription != value)
                    {
                        this.OnPropertyChanging("RegionDescription");
                        this.regiondescription = value;
                        this.OnPropertyChanged("RegionDescription");
                    }
                }
        }

        public IQueryable<Territory> Territories
        {
            get { return this.CreateQuery<Territory>().Where(r => r.RegionID == RegionID); }
        }

        #endregion

        #region Methods

        public override bool Equals(object obj)
        {
            Region record = obj as Region;

            return (object.ReferenceEquals(this, record)
                    || (record != null
                        && this.RegionID == record.RegionID
                        && this.RegionID != default(int)
                        )
                    );
        }

        public override int GetHashCode()
        {
            int hashCode = 7;

            hashCode = (11 * hashCode) + this.regionid.GetHashCode();

            return hashCode;
        }

		void IRecord.Read(DbDataReader reader)
		{
			this.regionid = (int)reader[COL_REGIONID];
			this.regiondescription = (string)reader[COL_REGIONDESCRIPTION];
		}

		bool IRecord.Create(DataContext dataContext)
        {
            using(DbCommand command  = dataContext.CreateCommand(SQL_INSERT_REGION))
            {
				command.Parameters.Add(dataContext.CreateParameter(PARAM_REGIONID, this.RegionID));
				command.Parameters.Add(dataContext.CreateParameter(PARAM_REGIONDESCRIPTION, this.RegionDescription));
                return (command.ExecuteNonQuery() == 1);
            }
        }

		bool IRecord.Update(DataContext dataContext)
        {
            using(DbCommand command  = dataContext.CreateCommand(SQL_UPDATE_REGION))
            {
				command.Parameters.Add(dataContext.CreateParameter(PARAM_REGIONID, this.RegionID));
				command.Parameters.Add(dataContext.CreateParameter(PARAM_REGIONDESCRIPTION, this.RegionDescription));

                return (command.ExecuteNonQuery() == 1);
            }
        }

		bool IRecord.Delete(DataContext dataContext)
        {
            using(DbCommand command  = dataContext.CreateCommand(SQL_DELETE_REGION))
            {
				command.Parameters.Add(dataContext.CreateParameter(PARAM_REGIONID, this.RegionID));
                return (command.ExecuteNonQuery() == 1);
            }
        }

        protected virtual void OnPropertyChanging(string propertyName)
        {
            if(this.propertyChanging != null)
                this.propertyChanging(this, new PropertyChangingEventArgs(propertyName));
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if(this.propertyChanged != null)
                this.propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}


text:
A Rails template app we use at Populate.

## Front-end gems

* Turbolinks
* Velocity http://julian.com/research/velocity/
* jQuery Dynatable http://www.dynatable.com/
* jQuery Sticky http://stickyjs.com/
* Tipsy http://onehackoranother.com/projects/jquery/tipsy/
* Quill (Rich Text editor) http://quilljs.com/
* Cookies_eu https://github.com/infinum/cookies_eu
* Pickadate http://amsul.ca/pickadate.js/
* Bourbon http://bourbon.io/
* Populities https://github.com/PopulateTools/populities


text:
package nyla.solutions.core.util;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

/**
 * Test for Digits
 * @author Gregory Green
 */
public class DigitsTest
{
	private Digits subject;

	@BeforeEach
	void setUp()
	{
		subject = new Digits();
	}

	@Test
	void generateDouble()
	{
		Double actual = 0.0;

		for (int i = 0; i < 3; i++) {
			actual = subject.generateDouble();
			System.out.println(actual);
			assertThat(actual).isGreaterThan(-1);
		}
	}

	@Test
	void generateDouble_WhenRangesProvided() throws InterruptedException
	{
		Double low = 8.21;
		Double high = 17.21;
		Double actual = subject.generateDouble(low,high);
		assertThat(actual).isBetween(low,high);

		for (int i = 0; i < 10; i++) {
//			Thread.sleep(100);
			actual = subject.generateDouble(low,high);
			assertThat(actual).isBetween(low,high);
			System.out.println("actual:"+actual);
		}

	}

	@Test
	void generateDouble_WhenBound_ThenLessThan()
	{
		Double bound = 34.00;
		Double actual = subject.generateDouble(bound);

		System.out.println(actual);
		assertTrue(actual >= 0 && actual <= bound,"actual:"+actual+" between 0 and "+bound);
	}

	@Test
	public void generateInteger_Start_to_End()
	{

		int id = subject.generateInteger(1,1);
		assertEquals(1,id);
		id = subject.generateInteger(2,2);
		assertEquals(2,id);
		id = subject.generateInteger(0,2);
		assertThat(id).isBetween(0,2);
	}

	@Test
	public void generateInteger()
	{
		long generatedId = subject.generateInteger();
		assertNotEquals(generatedId ,subject.generateInteger());
	    generatedId = subject.generateInteger();
		assertTrue( generatedId > 0);
	}

	public void generateLong()
	{
		assertNotEquals(subject.generateLong() ,subject.generateLong());
		assertTrue(subject.generateLong() > 0);
	}

}


text:
<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyPathInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Validator\Exception\MissingOptionsException;

/**
 * @Annotation
 * @Target({"PROPERTY", "METHOD", "ANNOTATION"})
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Range extends Constraint
{
    const INVALID_CHARACTERS_ERROR = 'ad9a9798-7a99-4df7-8ce9-46e416a1e60b';
    const NOT_IN_RANGE_ERROR = '04b91c99-a946-4221-afc5-e65ebac401eb';
    const TOO_HIGH_ERROR = '2d28afcb-e32e-45fb-a815-01c431a86a69';
    const TOO_LOW_ERROR = '76454e69-502c-46c5-9643-f447d837c4d5';

    protected static $errorNames = [
        self::INVALID_CHARACTERS_ERROR => 'INVALID_CHARACTERS_ERROR',
        self::NOT_IN_RANGE_ERROR => 'NOT_IN_RANGE_ERROR',
        self::TOO_HIGH_ERROR => 'TOO_HIGH_ERROR',
        self::TOO_LOW_ERROR => 'TOO_LOW_ERROR',
    ];

    public $notInRangeMessage = 'This value should be between {{ min }} and {{ max }}.';
    public $minMessage = 'This value should be {{ limit }} or more.';
    public $maxMessage = 'This value should be {{ limit }} or less.';
    public $invalidMessage = 'This value should be a valid number.';
    public $invalidDateTimeMessage = 'This value should be a valid datetime.';
    public $min;
    public $minPropertyPath;
    public $max;
    public $maxPropertyPath;

    /**
     * @internal
     */
    public $deprecatedMinMessageSet = false;

    /**
     * @internal
     */
    public $deprecatedMaxMessageSet = false;

    /**
     * {@inheritdoc}
     *
     * @param string|PropertyPathInterface|null $minPropertyPath
     * @param string|PropertyPathInterface|null $maxPropertyPath
     */
    public function __construct(
        array $options = null,
        string $notInRangeMessage = null,
        string $minMessage = null,
        string $maxMessage = null,
        string $invalidMessage = null,
        string $invalidDateTimeMessage = null,
        $min = null,
        $minPropertyPath = null,
        $max = null,
        $maxPropertyPath = null,
        array $groups = null,
        $payload = null
    ) {
        parent::__construct($options, $groups, $payload);

        $this->notInRangeMessage = $notInRangeMessage ?? $this->notInRangeMessage;
        $this->minMessage = $minMessage ?? $this->minMessage;
        $this->maxMessage = $maxMessage ?? $this->maxMessage;
        $this->invalidMessage = $invalidMessage ?? $this->invalidMessage;
        $this->invalidDateTimeMessage = $invalidDateTimeMessage ?? $this->invalidDateTimeMessage;
        $this->min = $min ?? $this->min;
        $this->minPropertyPath = $minPropertyPath ?? $this->minPropertyPath;
        $this->max = $max ?? $this->max;
        $this->maxPropertyPath = $maxPropertyPath ?? $this->maxPropertyPath;

        if (null === $this->min && null === $this->minPropertyPath && null === $this->max && null === $this->maxPropertyPath) {
            throw new MissingOptionsException(sprintf('Either option "min", "minPropertyPath", "max" or "maxPropertyPath" must be given for constraint "%s".', __CLASS__), ['min', 'minPropertyPath', 'max', 'maxPropertyPath']);
        }

        if (null !== $this->min && null !== $this->minPropertyPath) {
            throw new ConstraintDefinitionException(sprintf('The "%s" constraint requires only one of the "min" or "minPropertyPath" options to be set, not both.', static::class));
        }

        if (null !== $this->max && null !== $this->maxPropertyPath) {
            throw new ConstraintDefinitionException(sprintf('The "%s" constraint requires only one of the "max" or "maxPropertyPath" options to be set, not both.', static::class));
        }

        if ((null !== $this->minPropertyPath || null !== $this->maxPropertyPath) && !class_exists(PropertyAccess::class)) {
            throw new LogicException(sprintf('The "%s" constraint requires the Symfony PropertyAccess component to use the "minPropertyPath" or "maxPropertyPath" option.', static::class));
        }

        if (null !== $this->min && null !== $this->max) {
            $this->deprecatedMinMessageSet = isset($options['minMessage']) || null !== $minMessage;
            $this->deprecatedMaxMessageSet = isset($options['maxMessage']) || null !== $maxMessage;

            // BC layer, should throw a ConstraintDefinitionException in 6.0
            if ($this->deprecatedMinMessageSet || $this->deprecatedMaxMessageSet) {
                trigger_deprecation('symfony/validator', '4.4', '"minMessage" and "maxMessage" are deprecated when the "min" and "max" options are both set. Use "notInRangeMessage" instead.');
            }
        }
    }
}


text:
from kivy_soil.kb_system.canvas import FocusBehaviorCanvas
from kivy_soil.kb_system.canvas import FocusBehaviorCanvasScroller
from kivy.uix.textinput import TextInput

__all__ = ('CompatTextInput', 'CompatTextInputScroller')

class CompatTextInputBase(TextInput):
    ignored_keys = [9,]
    ignored_text = '`'

    def __init__(self, **kwargs):
        super(CompatTextInputBase, self).__init__(**kwargs)
        self.remove_focus_on_touch_move = False

    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        if keycode[0] in self.ignored_keys:
            return
        super(CompatTextInputBase, self).keyboard_on_key_down(
            window, keycode, text, modifiers)

    def keyboard_on_key_up(self, window, keycode):
        if keycode[0] in self.ignored_keys:
            return
        super(CompatTextInputBase, self).keyboard_on_key_up(
            window, keycode)

    def insert_text(self, s, from_undo=False):
        if s in self.ignored_text:
            return
        return super(
            CompatTextInputBase, self).insert_text(s, from_undo=from_undo)

class CompatTextInput(FocusBehaviorCanvas, CompatTextInputBase):
    '''TextInput widget which is compatible with kivy_soil focus behavior'''
    pass

class CompatTextInputScroller(FocusBehaviorCanvasScroller,
                              CompatTextInputBase):
    '''TextInput widget which is compatible with kivy_soil focus behavior.
    Inherits from FocusBehaviorCanvasScroller instead of FocusBehaviorCanvas
    '''
    pass


text:
%% Copyright (C) 2009-2011, Gostai S.A.S.
%%
%% This software is provided "as is" without warranty of any kind,
%% either expressed or implied, including but not limited to the
%% implied warranties of fitness for a particular purpose.
%%
%% See the LICENSE file for more information.

\section{Regexp}

A Regexp is an object which allow you to match strings with a regular
expression.

\subsection{Prototypes}
\begin{refObjects}
\item[Container]
\item[Object]
\end{refObjects}

\subsection{Construction}
\label{stdlib:regexp:ctor}

A \lstinline{Regexp} is created from a regular expression once and for all;
it can be used several times to match with other strings.

\begin{urbiscript}
Regexp.new(".");
[00000001] Regexp(".")

var num = Regexp.new("\\d+\\.\\d+");
[00000004] Regexp("\\d+\\.\\d+")
"1.3" in num;
[00019618] true
"1." in num;
[00023113] false
\end{urbiscript}

\us supports Perl regular expressions, see
\href{http://perldoc.perl.org/perlre.html}{the perlre man page}.

Expressions cannot be empty, and must be syntactically correct.

%% This is likely to fails on some other arch because the error messages
%% might be different.  This is to handle in neutralize, not here.
\begin{urbiscript}
Regexp.new("");
[00000001:error] !!! new: invalid regular expression: empty expression: `'

Regexp.new("(");
[00003237:error] !!! new: invalid regular expression:\
[:] unmatched marking parenthesis ( or \(: `(>>>HERE>>>'

Regexp.new("*");
[00004372:error] !!! new: invalid regular expression:\
[:] the repeat operator "*" cannot start a regular expression: `>>>HERE>>>*'
\end{urbiscript}

\subsection{Slots}
\begin{urbiscriptapi}
\item|'[]'|(<n>)%
  Same as \lstinline|this.matches[\var{n}]|.
\begin{urbiscript}
var d = Regexp.new("(1+)(2+)(3+)")|;
assert
{
  "01223334" in d;
  d[0] == "122333";
  d[1] == "1";
  d[2] == "22";
  d[3] == "333";
};
d[4];
[00000009:error] !!! []: out of bound index: 4
\end{urbiscript}

\item[asPrintable] A string that shows that \this is a Regexp, and its
  value.
\begin{urbiassert}
           Regexp.new("abc").asPrintable() == "Regexp(\"abc\")";
Regexp.new("\\d+(\\.\\d+)?").asPrintable() == "Regexp(\"\\\\d+(\\\\.\\\\d+)?\")";
\end{urbiassert}

\item[asString] The regular expression that was compiled.
\begin{urbiassert}
           Regexp.new("abc").asString() == "abc";
Regexp.new("\\d+(\\.\\d+)?").asString() == "\\d+(\\.\\d+)?";
\end{urbiassert}

\item[has](<str>)%
  An experimental alias to \refSlot{match}, so that the infix operators
  \lstinline|in| and \lstinline|not in| can be used (see
  \autoref{sec:lang:op:containers}).
\begin{urbiassert}
"23.03"     in Regexp.new("^\\d+\\.\\d+$");
"-3.14" not in Regexp.new("^\\d+\\.\\d+$");
\end{urbiassert}

\item[match](<str>)%
  Whether \this matches \var{str}.
\begin{urbiscript}
// Ordinary characters
var r = Regexp.new("oo")|
assert
{
  r.match("oo");
  r.match("foobar");
  !r.match("bazquux");
};

// ^, anchoring at the beginning of line.
r = Regexp.new("^oo")|
assert
{
  r.match("oops");
  !r.match("woot");
};

// $, anchoring at the end of line.
r = Regexp.new("oo$")|
assert
{
  r.match("foo");
  !r.match("mooh");
};

// *, greedy repetition, 0 or more.
r = Regexp.new("fo*bar")|
assert
{
  r.match("fbar");
  r.match("fooooobar");
  !r.match("far");
};

// (), grouping.
r = Regexp.new("f(oo)*bar")|
assert
{
  r.match("foooobar");
  !r.match("fooobar");
};
\end{urbiscript}

\item[matches]%
  If the latest \refSlot{match} was successful, the matched groups, as
  delimited by parentheses in the regular expression; the first element
  being the whole match.  Otherwise, the empty list.  See also
  \refSlot{'[]'}.

\begin{urbiscript}
var re = Regexp.new("([a-zA-Z0-9._]+)@([a-zA-Z0-9._]+)")|;
assert
{
  re.match("Someone <someone@somewhere.com>");
  re.matches == ["someone@somewhere.com", "someone", "somewhere.com"];

  "does not match" not in re;
  re.matches == [];
};
\end{urbiscript}
\end{urbiscriptapi}

%%% Local Variables:
%%% coding: utf-8
%%% mode: latex
%%% TeX-master: "../urbi-sdk"
%%% ispell-dictionary: "american"
%%% ispell-personal-dictionary: "../urbi.dict"
%%% fill-column: 76
%%% End:


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. mens. Soc. linn. Lyon 14: 92 (1945)

#### Original name
Lepiotophyllum heterosporum Locq.

### Remarks
null


text:
import { SagaIterator } from 'redux-saga';
import { select, put, takeEvery, call } from 'redux-saga/effects';
import { Authentication, LoginPayload } from '../actions';
import { getAccessTokenClaims, getRefreshTokenClaims, isLoggedIn } from '../state/Selectors';
import { ApiErrors, AuthenticationApi } from '../api';
import moment from 'moment-timezone';
import { ApplicationState } from '../state/ApplicationState';

function* attemptRefresh(): SagaIterator {
  const state: ApplicationState = yield select();

  console.log('Checking authentication token refresh status');

  if (!isLoggedIn(state)) {
    console.log('Not logged in');
    return;
  }

  const now = moment();

  // If the access token still has time left do nothing
  if (getAccessTokenClaims(state)!.expires.isAfter(now.add(5, 'minutes'))) {
    console.log('Authentication token not stale');
    return;
  }

  const refreshClaims = getRefreshTokenClaims(state);

  // If the refresh token has expired too just log the client out
  if (!refreshClaims || refreshClaims.expires.isBefore(now.subtract(5, 'minutes'))) {
    console.log('Authentication + Refresh token stale, logging out');
    yield put(Authentication.logout());
    return;
  }

  try {
    // refresh token mustn't be null here as refreshClaims worked
    const data: LoginPayload = yield call(
      AuthenticationApi.callRefreshTokens,
      state.authentication.refreshToken || 'ERROR NO REFRESH TOKEN IN STATE',
    );

    yield put(Authentication.login(data));

    console.log('Authentication tokens refreshed');
  } catch (err) {
    console.error(err, 'error refreshing tokens');

    // force log them out if refresh token is broken
    if (err instanceof ApiErrors.ForbiddenError || err instanceof ApiErrors.NotAuthenticatedError) {
      yield put(Authentication.logout());
    }
  }
}

export function* refreshAuthentication(): SagaIterator {
  yield takeEvery(Authentication.attemptRefresh, attemptRefresh);
}