text:
package org.vizzini.illyriad.robot.inventory;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.vizzini.ai.neuralnetwork.ApplianceExample;
import org.vizzini.ai.neuralnetwork.NeuralNetworkAppliance;
import org.vizzini.ai.neuralnetwork.NeuralNetworkApplianceTrainer;
import org.vizzini.ai.neuralnetwork.format.CSVNeuralNetworkApplianceFormat;
import org.vizzini.ai.neuralnetwork.format.CSVNeuralNetworkFormat;
import org.vizzini.ai.neuralnetwork.format.InputFilterFormat;
import org.vizzini.ai.neuralnetwork.format.NeuralNetworkApplianceFormat;
import org.vizzini.ai.neuralnetwork.format.NeuralNetworkFormat;
import org.vizzini.ai.neuralnetwork.format.OutputFilterFormat;
import org.vizzini.ai.neuralnetwork.format.io.NeuralNetworkApplianceIO;
import org.vizzini.ai.robot.RobotImage;
import org.vizzini.ai.robot.RobotImageIO;
import org.vizzini.illyriad.FileUtilities;
import org.vizzini.illyriad.robot.CSVNumericOutputFilterFormat;
import org.vizzini.illyriad.robot.CSVRobotImageInputFilterFormat;
import org.vizzini.illyriad.robot.Example;

/**
 * Provides a neural network trainer for inventory data.
 */
public final class NeuralNetworkTrainer
{
    /**
     * Application method.
     *
     * @param args Application arguments.
     * @throws AWTException if the robot cannot be constructed.
     */
    public static void main(final String args[]) throws AWTException
    {
        final File inputDirectory = Locations.DIGITS_DIR;
        final File outputFilepath = Locations.NEURAL_NETWORK_OUTPUT_FILEPATH;

        final NeuralNetworkTrainer trainer = new NeuralNetworkTrainer(inputDirectory, outputFilepath);

        trainer.train();

        Toolkit.getDefaultToolkit().beep();
    }

    /** Neural network. */
    private NeuralNetworkAppliance<RobotImage, String> appliance;

    /** Training examples. */
    private final List<Example> examples = new ArrayList<Example>();

    /** File utilities. */
    private final FileUtilities fileUtils = new FileUtilities();

    /** Input directory. */
    private final File inputDirectory;

    /** Output filepath. */
    private final File outputFilepath;

    /**
     * Construct this object.
     *
     * @param inputDirectory Input directory. (required)
     * @param outputFilepath Output filepath. (required)
     */
    @SuppressWarnings("hiding")
    public NeuralNetworkTrainer(final File inputDirectory, final File outputFilepath)
    {
        if (inputDirectory == null)
        {
            throw new IllegalArgumentException("inputDirectory is null");
        }

        if (outputFilepath == null)
        {
            throw new IllegalArgumentException("outputFilepath is null");
        }

        this.inputDirectory = inputDirectory;
        this.outputFilepath = outputFilepath;

        // Load digit images.
        final Map<URL, RobotImage> urlToImageMap = loadImages();

        // Determine maxWidth, maxHeight
        final Dimension maxDimension = determineMaxDimensions(urlToImageMap);

        // Create the examples.
        createExamples(urlToImageMap);

        // Create neural network.
        appliance = createNeuralNetworkAppliance(maxDimension);
    }

    /**
     * Train the neural network.
     */
    public void train()
    {
        System.out.println("train()");

        final List<ApplianceExample<RobotImage, String>> aExamples = createExamples();

        // Train it.
        final boolean isVerbose = true;
        final boolean isBatchUsed = true;

        final int exampleCount = aExamples.size();
        final double beta = 0.95 / exampleCount;
        final double alpha = 0.20 / exampleCount;

        System.out.println("beta = " + beta + " (" + (beta * exampleCount) + ") alpha = " + alpha + " ("
                + (alpha * exampleCount) + ") exampleCount = " + exampleCount);

        final NeuralNetworkApplianceTrainer<RobotImage, String> trainer = new NeuralNetworkApplianceTrainer<RobotImage, String>(
                appliance, aExamples, isBatchUsed, isVerbose, alpha, beta);

        final double maxError = 0.001;
        final int maxCount = 2000;
        final int printFrequency = maxCount / 50;

        trainer.runTrainingLoop(maxError, maxCount, printFrequency);

        // Save resulting neural network appliance.
        saveNeuralNetworkAppliance();

        testNetwork(appliance);
    }

    /**
     * @return a new URL to the test resources directory.
     */
    private URL createDirectoryUrl()
    {
        final String protocol = "file";
        final String host = "";
        final String file = inputDirectory.getAbsolutePath();

        URL answer;

        try
        {
            answer = new URL(protocol, host, file);
        }
        catch (final MalformedURLException e)
        {
            throw new RuntimeException(e);
        }

        return answer;
    }

    /**
     * @return a new list of appliance examples.
     */
    private List<ApplianceExample<RobotImage, String>> createExamples()
    {
        final List<ApplianceExample<RobotImage, String>> answer = new ArrayList<ApplianceExample<RobotImage, String>>(
                examples.size());

        for (int i = 0; i < examples.size(); i++)
        {
            final Example example = examples.get(i);
            final RobotImage input = example.getImage();
            final String output = example.getOutput();

            answer.add(new ApplianceExample<RobotImage, String>(input, output));
        }

        return answer;
    }

    /**
     * @param urlToImageMap Map of file URL to image.
     */
    private void createExamples(final Map<URL, RobotImage> urlToImageMap)
    {
        System.out.println("createExamples()");

        for (final Entry<URL, RobotImage> entry : urlToImageMap.entrySet())
        {
            final URL url = entry.getKey();
            final RobotImage image = entry.getValue();
            final String output = createOutputFromUrl(url);

            final Example example = new Example(url, image, output);
            examples.add(example);
        }

        System.out.println(" examples.size() = " + examples.size());
    }

    /**
     * @param maxDimension Maximum image dimension.
     *
     * @return a new neural network appliance.
     */
    private NeuralNetworkAppliance<RobotImage, String> createNeuralNetworkAppliance(final Dimension maxDimension)
    {
        final NeuralNetworkApplianceBuilder builder = new NeuralNetworkApplianceBuilder();
        final NeuralNetworkAppliance<RobotImage, String> answer = builder.buildNumericOcrNetwork(maxDimension);
        answer.getNeuralNetwork().randomizeWeights(0.1);

        return answer;
    }

    /**
     * @param url Image file URL.
     *
     * @return neural network outputs.
     */
    private String createOutputFromUrl(final URL url)
    {
        final String filename = getDirectoryName(url);

        String key;

        if (filename.startsWith("digit"))
        {
            key = filename.substring(filename.length() - 1, filename.length());
        }
        else if ("comma".equals(filename))
        {
            key = ",";
        }
        else
        {
            return null;
        }

        return key;
    }

    /**
     * @param urlToImageMap Map of file URL to image.
     *
     * @return the maximum image dimensions.
     */
    private Dimension determineMaxDimensions(final Map<URL, RobotImage> urlToImageMap)
    {
        System.out.println("determineMaxDimensions()");

        int maxWidth = -1;
        int maxHeight = -1;

        for (final RobotImage image : urlToImageMap.values())
        {
            maxWidth = Math.max(image.getWidth(), maxWidth);
            maxHeight = Math.max(image.getHeight(), maxHeight);
        }

        final Dimension answer = new Dimension(maxWidth, maxHeight);
        System.out.println(" maxWidth = " + maxWidth + " maxHeight = " + maxHeight);

        return answer;
    }

    /**
     * @param url URL.
     *
     * @return the parent directory of the given file parameter.
     */
    private String getDirectoryName(final URL url)
    {
        final File file = new File(url.toExternalForm());
        String answer = file.getAbsolutePath();

        final int index2 = answer.lastIndexOf("/");
        final int index = answer.lastIndexOf("/", index2 - 1);
        answer = answer.substring(index + 1, index2);

        return answer;
    }

    /**
     * @param directory Directory.
     *
     * @return map of file URL to image.
     */
    private Map<URL, RobotImage> loadCommaImages(final URL directory)
    {
        final Map<URL, RobotImage> answer = new HashMap<URL, RobotImage>();
        final URL[] imageFiles = fileUtils.listFiles(directory);
        final RobotImageIO imageIo = new RobotImageIO();

        for (final URL imageFile : imageFiles)
        {
            final File imageFile2 = new File(imageFile.getFile());

            if (".DS_Store".equals(imageFile2.getName()) || ".svn".equals(imageFile2.getName()))
            {
                continue;
            }

            final File imageFile3 = new File(inputDirectory, "comma/" + imageFile2.getName());

            try
            {
                final RobotImage image = imageIo.read(imageFile3);
                answer.put(imageFile, image);
            }
            catch (final IllegalArgumentException e)
            {
                throw new RuntimeException("Failed to load image for file " + imageFile3, e);
            }
        }

        return answer;
    }

    /**
     * @param directory Directory.
     * @param key Map key.
     *
     * @return map of file URL to image.
     */
    private Map<URL, RobotImage> loadDigitImages(final URL directory, final String key)
    {
        final Map<URL, RobotImage> answer = new HashMap<URL, RobotImage>();
        final URL[] imageFiles = fileUtils.listFiles(directory);
        final RobotImageIO imageIo = new RobotImageIO();

        for (final URL imageFile : imageFiles)
        {
            final File imageFile2 = new File(imageFile.getFile());

            if (".DS_Store".equals(imageFile2.getName()) || ".svn".equals(imageFile2.getName()))
            {
                continue;
            }

            final File file = new File(directory.getFile());
            final String filename = file.getName();
            final File imageFile3 = new File(inputDirectory, filename + "/" + imageFile2.getName());

            try
            {
                final RobotImage image = imageIo.read(imageFile3);
                answer.put(imageFile, image);
            }
            catch (final IllegalArgumentException e)
            {
                throw new RuntimeException("Failed to load image for file " + imageFile3, e);
            }
        }

        return answer;
    }

    /**
     * Load images.
     *
     * @return map of file URL to image.
     */
    private Map<URL, RobotImage> loadImages()
    {
        System.out.println("loadImages()");

        final Map<URL, RobotImage> answer = new HashMap<URL, RobotImage>();

        final URL url = createDirectoryUrl();
        System.out.println("url = " + url.toExternalForm());
        final URL[] directories = fileUtils.listFilesSorted(url);

        for (final URL directory : directories)
        {
            final File file = new File(directory.getFile());
            final String filename = file.getName();

            if (filename.startsWith("digit"))
            {
                final String key = filename.substring(filename.length() - 1, filename.length());
                final Map<URL, RobotImage> nameToImageMap = loadDigitImages(directory, key);
                answer.putAll(nameToImageMap);
            }
            else if ("comma".equals(filename))
            {
                final Map<URL, RobotImage> nameToImageMap = loadCommaImages(directory);
                answer.putAll(nameToImageMap);
            }
        }

        if (answer.isEmpty())
        {
            throw new RuntimeException("Failed to load images");
        }

        return answer;
    }

    /**
     * Save the neural network to a file.
     */
    private void saveNeuralNetworkAppliance()
    {
        final InputFilterFormat<RobotImage> inputFilterFormatter = new CSVRobotImageInputFilterFormat();
        final NeuralNetworkFormat neuralNetworkFormatter = new CSVNeuralNetworkFormat();
        final OutputFilterFormat<String> outputFilterFormatter = new CSVNumericOutputFilterFormat();

        final NeuralNetworkApplianceFormat<RobotImage, String> formatter = new CSVNeuralNetworkApplianceFormat<RobotImage, String>(
                inputFilterFormatter, neuralNetworkFormatter, outputFilterFormatter);
        final NeuralNetworkApplianceIO<RobotImage, String> nnio = new NeuralNetworkApplianceIO<RobotImage, String>(
                formatter);

        outputFilepath.getParentFile().mkdirs();

        Writer writer = null;

        try
        {
            writer = new FileWriter(outputFilepath);
            nnio.write(appliance, writer);
        }
        catch (final IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * Test the network.
     *
     * @param appliance Neural network appliance.
     */
    @SuppressWarnings("hiding")
    private void testNetwork(final NeuralNetworkAppliance<RobotImage, String> appliance)
    {
        // Test the network.
        final int exampleCount = examples.size();
        int failCount = 0;

        System.out.println(String.format("%3s %10s %7s %8s %7s", "Ex", "Inputs", "Output", "Desired", "Error?"));

        for (int i = 0; i < exampleCount; i++)
        {
            final Example example = examples.get(i);
            final String tOutputs = appliance.evaluate(example.getImage());

            final String inputsString = "[too long]";
            final String outputsString = example.getOutput();
            String errorString = "";

            if (!tOutputs.equals(outputsString))
            {
                failCount++;
                errorString = "error: " + example.getFilename();

                System.out.println(String.format("%3d %10s %7s %8s %7s", i, inputsString, tOutputs, outputsString,
                        errorString));
            }
        }

        System.out.println("\nfailures: " + failCount + " of " + exampleCount + " ("
                + Math.round((100.0 * failCount) / exampleCount) + "%)");
    }
}


text:
package com.softwaremill.reactive.step3

import akka.actor.ActorSystem
import akka.stream.ActorFlowMaterializer
import akka.stream.scaladsl._
import akka.util.ByteString
import com.softwaremill.reactive._

import scala.concurrent.duration._

/**
 * - no changes
 */
object SenderStep3 extends App with Logging {
  implicit val system = ActorSystem()
  val serverConnection = Tcp().outgoingConnection("localhost", 9181)

  val getLines = () => scala.io.Source.fromFile("/Users/adamw/projects/reactive-akka-pres/data/2008.csv").getLines()

  val linesSource = Source(getLines).map { line => ByteString(line + "\n") }
  val logCompleteSink = Sink.onComplete(r => logger.info("Completed with: " + r))

  val graph = FlowGraph.closed() { implicit b =>
    import FlowGraph.Implicits._

    val broadcast = b.add(Broadcast[ByteString](2))

    val logWindowFlow = Flow[ByteString]
      .groupedWithin(10000, 1.seconds)
      .map(group => group.map(_.size).foldLeft(0)(_ + _))
      .map(groupSize => logger.info(s"Sent $groupSize bytes"))

    linesSource ~> broadcast ~> serverConnection ~> logCompleteSink
                   broadcast ~> logWindowFlow    ~> Sink.ignore
  }

  implicit val mat = ActorFlowMaterializer()
  graph.run()
}

redpajama_set_name: RedPajamaGithub


text:
package packet

import (
	"encoding/binary"
	"fmt"
)

// Returns the byte length of an identified packet.
func identifiedPacketLen() int {
	return headerLen(2) + 2
}

// Decodes an identified packet.
func identifiedPacketDecode(src []byte, t Type) (int, uint16, error) {
	total := 0

	// decode header
	hl, _, rl, err := headerDecode(src, t)
	total += hl
	if err != nil {
		return total, 0, err
	}

	// check remaining length
	if rl != 2 {
		return total, 0, fmt.Errorf("[%s] expected remaining length to be 2", t)
	}

	// read packet id
	packetID := binary.BigEndian.Uint16(src[total:])
	total += 2

	// check packet id
	if packetID == 0 {
		return total, 0, fmt.Errorf("[%s] packet id must be grater than zero", t)
	}

	return total, packetID, nil
}

// Encodes an identified packet.
func identifiedPacketEncode(dst []byte, packetID uint16, t Type) (int, error) {
	total := 0

	// check packet id
	if packetID == 0 {
		return total, fmt.Errorf("[%s] packet id must be grater than zero", t)
	}

	// encode header
	n, err := headerEncode(dst[total:], 0, 2, identifiedPacketLen(), t)
	total += n
	if err != nil {
		return total, err
	}

	// write packet id
	binary.BigEndian.PutUint16(dst[total:], packetID)
	total += 2

	return total, nil
}

// A PubackPacket is the response to a PublishPacket with QOS level 1.
type PubackPacket struct {
	// The packet identifier.
	PacketID uint16
}

// NewPubackPacket creates a new PubackPacket.
func NewPubackPacket() *PubackPacket {
	return &PubackPacket{}
}

// Type returns the packets type.
func (pp *PubackPacket) Type() Type {
	return PUBACK
}

// Len returns the byte length of the encoded packet.
func (pp *PubackPacket) Len() int {
	return identifiedPacketLen()
}

// Decode reads from the byte slice argument. It returns the total number of
// bytes decoded, and whether there have been any errors during the process.
func (pp *PubackPacket) Decode(src []byte) (int, error) {
	n, pid, err := identifiedPacketDecode(src, PUBACK)
	pp.PacketID = pid
	return n, err
}

// Encode writes the packet bytes into the byte slice from the argument. It
// returns the number of bytes encoded and whether there's any errors along
// the way. If there is an error, the byte slice should be considered invalid.
func (pp *PubackPacket) Encode(dst []byte) (int, error) {
	return identifiedPacketEncode(dst, pp.PacketID, PUBACK)
}

// String returns a string representation of the packet.
func (pp *PubackPacket) String() string {
	return fmt.Sprintf("<PubackPacket PacketID=%d>", pp.PacketID)
}

// A PubcompPacket is the response to a PubrelPacket. It is the fourth and
// final packet of the QOS 2 protocol exchange.
type PubcompPacket struct {
	// The packet identifier.
	PacketID uint16
}

var _ Packet = (*PubcompPacket)(nil)

// NewPubcompPacket creates a new PubcompPacket.
func NewPubcompPacket() *PubcompPacket {
	return &PubcompPacket{}
}

// Type returns the packets type.
func (pp *PubcompPacket) Type() Type {
	return PUBCOMP
}

// Len returns the byte length of the encoded packet.
func (pp *PubcompPacket) Len() int {
	return identifiedPacketLen()
}

// Decode reads from the byte slice argument. It returns the total number of
// bytes decoded, and whether there have been any errors during the process.
func (pp *PubcompPacket) Decode(src []byte) (int, error) {
	n, pid, err := identifiedPacketDecode(src, PUBCOMP)
	pp.PacketID = pid
	return n, err
}

// Encode writes the packet bytes into the byte slice from the argument. It
// returns the number of bytes encoded and whether there's any errors along
// the way. If there is an error, the byte slice should be considered invalid.
func (pp *PubcompPacket) Encode(dst []byte) (int, error) {
	return identifiedPacketEncode(dst, pp.PacketID, PUBCOMP)
}

// String returns a string representation of the packet.
func (pp *PubcompPacket) String() string {
	return fmt.Sprintf("<PubcompPacket PacketID=%d>", pp.PacketID)
}

// A PubrecPacket is the response to a PublishPacket with QOS 2. It is the
// second packet of the QOS 2 protocol exchange.
type PubrecPacket struct {
	// Shared packet identifier.
	PacketID uint16
}

// NewPubrecPacket creates a new PubrecPacket.
func NewPubrecPacket() *PubrecPacket {
	return &PubrecPacket{}
}

// Type returns the packets type.
func (pp *PubrecPacket) Type() Type {
	return PUBREC
}

// Len returns the byte length of the encoded packet.
func (pp *PubrecPacket) Len() int {
	return identifiedPacketLen()
}

// Decode reads from the byte slice argument. It returns the total number of
// bytes decoded, and whether there have been any errors during the process.
func (pp *PubrecPacket) Decode(src []byte) (int, error) {
	n, pid, err := identifiedPacketDecode(src, PUBREC)
	pp.PacketID = pid
	return n, err
}

// Encode writes the packet bytes into the byte slice from the argument. It
// returns the number of bytes encoded and whether there's any errors along
// the way. If there is an error, the byte slice should be considered invalid.
func (pp *PubrecPacket) Encode(dst []byte) (int, error) {
	return identifiedPacketEncode(dst, pp.PacketID, PUBREC)
}

// String returns a string representation of the packet.
func (pp *PubrecPacket) String() string {
	return fmt.Sprintf("<PubrecPacket PacketID=%d>", pp.PacketID)
}

// A PubrelPacket is the response to a PubrecPacket. It is the third packet of
// the QOS 2 protocol exchange.
type PubrelPacket struct {
	// Shared packet identifier.
	PacketID uint16
}

var _ Packet = (*PubrelPacket)(nil)

// NewPubrelPacket creates a new PubrelPacket.
func NewPubrelPacket() *PubrelPacket {
	return &PubrelPacket{}
}

// Type returns the packets type.
func (pp *PubrelPacket) Type() Type {
	return PUBREL
}

// Len returns the byte length of the encoded packet.
func (pp *PubrelPacket) Len() int {
	return identifiedPacketLen()
}

// Decode reads from the byte slice argument. It returns the total number of
// bytes decoded, and whether there have been any errors during the process.
func (pp *PubrelPacket) Decode(src []byte) (int, error) {
	n, pid, err := identifiedPacketDecode(src, PUBREL)
	pp.PacketID = pid
	return n, err
}

// Encode writes the packet bytes into the byte slice from the argument. It
// returns the number of bytes encoded and whether there's any errors along
// the way. If there is an error, the byte slice should be considered invalid.
func (pp *PubrelPacket) Encode(dst []byte) (int, error) {
	return identifiedPacketEncode(dst, pp.PacketID, PUBREL)
}

// String returns a string representation of the packet.
func (pp *PubrelPacket) String() string {
	return fmt.Sprintf("<PubrelPacket PacketID=%d>", pp.PacketID)
}

// An UnsubackPacket is sent by the server to the client to confirm receipt of
// an UnsubscribePacket.
type UnsubackPacket struct {
	// Shared packet identifier.
	PacketID uint16
}

// NewUnsubackPacket creates a new UnsubackPacket.
func NewUnsubackPacket() *UnsubackPacket {
	return &UnsubackPacket{}
}

// Type returns the packets type.
func (up *UnsubackPacket) Type() Type {
	return UNSUBACK
}

// Len returns the byte length of the encoded packet.
func (up *UnsubackPacket) Len() int {
	return identifiedPacketLen()
}

// Decode reads from the byte slice argument. It returns the total number of
// bytes decoded, and whether there have been any errors during the process.
func (up *UnsubackPacket) Decode(src []byte) (int, error) {
	n, pid, err := identifiedPacketDecode(src, UNSUBACK)
	up.PacketID = pid
	return n, err
}

// Encode writes the packet bytes into the byte slice from the argument. It
// returns the number of bytes encoded and whether there's any errors along
// the way. If there is an error, the byte slice should be considered invalid.
func (up *UnsubackPacket) Encode(dst []byte) (int, error) {
	return identifiedPacketEncode(dst, up.PacketID, UNSUBACK)
}

// String returns a string representation of the packet.
func (up *UnsubackPacket) String() string {
	return fmt.Sprintf("<UnsubackPacket PacketID=%d>", up.PacketID)
}


text:
package com.strider.datadefender.database;

import java.sql.Connection;

import com.strider.datadefender.DatabaseDiscoveryException;

/**
 * Interface for all classes implementing database connection
 * @author Armenak Grigoryan
 */
public interface IDBConnection {
    Connection connect() throws DatabaseDiscoveryException;
}

//~ Formatted by Jindent --- http://www.jindent.com


text:
from django import template
from django.db.models import Model
from django.db.models.query import QuerySet
from django.core.urlresolvers import reverse
from frontendadmin.views import check_permission

register = template.Library()

@register.inclusion_tag('frontendadmin/link_add.html', takes_context=True)
def frontendadmin_add(context, queryset_object, label=None):

    # Check if `queryset_object` is a queryset
    if not isinstance(queryset_object, QuerySet):
        raise template.TemplateSyntaxError("'%s' argument must be a queryset" % queryset_object)

    app_label = queryset_object.model._meta.app_label
    model_name = queryset_object.model._meta.module_name

    template_context = {
        'add_link': reverse('frontendadmin_add', kwargs={
            'app_label': app_label,
            'model_name': model_name,
        }),
        'next_link': context['request'].META['PATH_INFO'],
        'label': label,
    }

    # Check for permission
    if check_permission(request=context['request'], mode_name='add',
                                                    app_label=app_label,
                                                    model_name=model_name):
        template_context['has_permission'] = True
    else:
        template_context['has_permission'] = False
    context.update(template_context)
    return context

@register.inclusion_tag('frontendadmin/link_edit.html', takes_context=True)
def frontendadmin_change(context, model_object, label=None):

    # Check if `model_object` is a model-instance
    if not isinstance(model_object, Model):
        raise template.TemplateSyntaxError("'%s' argument must be a model-instance" % model_object)

    app_label = model_object._meta.app_label
    model_name = model_object._meta.module_name

    template_context = {
        'edit_link': reverse('frontendadmin_change', kwargs={
            'app_label': app_label,
            'model_name': model_name,
            'instance_id': model_object.pk,
        }),
        'next_link': context['request'].META['PATH_INFO'],
        'label': label,
    }

    # Check for permission
    if check_permission(request=context['request'], mode_name='change',
                                                    app_label=app_label,
                                                    model_name=model_name):
        template_context['has_permission'] = True
    else:
        template_context['has_permission'] = False
    context.update(template_context)
    return context

@register.inclusion_tag('frontendadmin/link_delete.html', takes_context=True)
def frontendadmin_delete(context, model_object, label=None):

    # Check if `model_object` is a model-instance
    if not isinstance(model_object, Model):
        raise template.TemplateSyntaxError("'%s' argument must be a model-instance" % model_object)

    app_label = model_object._meta.app_label
    model_name = model_object._meta.module_name

    template_context = {
        'delete_link': reverse('frontendadmin_delete', kwargs={
            'app_label': app_label,
            'model_name': model_name,
            'instance_id': model_object.pk,
        }),
        'next_link': context['request'].META['PATH_INFO'],
        'label': label,
    }

    # Check for permission
    if check_permission(request=context['request'], mode_name='delete',
                                                    app_label=app_label,
                                                    model_name=model_name):
        template_context['has_permission'] = True
    else:
        template_context['has_permission'] = False
    context.update(template_context)
    return context

@register.inclusion_tag('frontendadmin/common.css')
def frontendadmin_common_css():
    return {}

@register.inclusion_tag('frontendadmin/common.js')
def frontendadmin_common_js():
    return {}


text:
<?php

namespace Concrete\Tests\Package;

use Database;
use Package;
use PHPUnit_Framework_TestCase;

class DbXmlTest extends PHPUnit_Framework_TestCase
{
    /**
     * Tests that the table is properly updated according to the updated
     * database schema XML file when the database table already exists.
     */
    public function testTableUpdates()
    {
        // The easiest way to test that the DB is updated properly is to make
        // two consecutive calls to Package::installDB(). This is actually what
        // the package also internally does during the install() and upgrade()
        // calls and also what the block types do when the refresh() method is
        // called on them. So, this should cover the actual scenarios we want
        // to cover here.
        $db = Database::get();

        // Make sure the DB is in the initial state
        $schema = $db->getSchemaManager()->createSchema();
        $this->assertFalse($schema->hasTable('TestPackageTable'));

        // Create the table initially.
        Package::installDB(DIR_TESTS . '/assets/Package/db-1.xml');

        // Make sure the table was properly created and it contains the column
        // we are about to remove does NOT contain the column we are about to
        // add.
        $schema = $db->getSchemaManager()->createSchema();
        $this->assertTrue($schema->hasTable('TestPackageTable'));

        $tbl = $schema->getTable('TestPackageTable');
        $this->assertFalse($tbl->hasColumn('newColumn'));
        $this->assertTrue($tbl->hasColumn('testColumn'));

        // db-2.xml modifies the already existing table.
        Package::installDB(DIR_TESTS . '/assets/Package/db-2.xml');

        // Make sure the column exists in the updated database that is added in
        // db-2.xml. Also make sure that the column we drop in db-2.xml no
        // longer exists in the table. This is what we actually want to test
        // here.
        $schema = $db->getSchemaManager()->createSchema();

        $tbl = $schema->getTable('TestPackageTable');
        $this->assertTrue($tbl->hasColumn('newColumn'));
        $this->assertFalse($tbl->hasColumn('testColumn'));
    }
}


text:
package com.intellij.codeInsight.daemon.quickFix;

/**
 * @author ven
 */
public class CreateConstructorMatchingSuperTest extends LightQuickFixParameterizedTestCase {

  public void test() throws Exception { doAllTests(); }

  @Override
  protected String getBasePath() {
    return "/codeInsight/daemonCodeAnalyzer/quickFix/createConstructorMatchingSuper";
  }

}


text:
import fn from "../../secondsToHours/index.js";
import convertToFP from "../_lib/convertToFP/index.js";
export default convertToFP(fn, 1);


text:
layout: page
title: About
permalink: /about/
---

Post-doctor at [Uni Research Health](http://uni.no/en/uni-health/) currently studying socioeconomic mental health inequalities in children and adolescents.

### More Information

See my work [profile](http://uni.no/en/staff/directory/tormod-be/) and [publications and talks](http://www.cristin.no/as/WebObjects/cristin.woa/wa/fres?sort=ar&pnr=47019&la=no&action=sok).

### Blog
I blog about R using Rstudio and keep my md source while compiling for publications here.

### Contact me

[tormod.boe@uni.no](mailto:tormod.boe@uni.no)


text:
namespace net {

TEST(HttpAuthChallengeTokenizerTest, Basic) {
  std::string challenge_str = "Basic realm=\"foobar\"";
  HttpAuthChallengeTokenizer challenge(challenge_str.begin(),
                                       challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("basic"), challenge.auth_scheme());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("realm"), parameters.name());
  EXPECT_EQ(std::string("foobar"), parameters.value());
  EXPECT_FALSE(parameters.GetNext());
}

// Use a name=value property with no quote marks.
TEST(HttpAuthChallengeTokenizerTest, NoQuotes) {
  std::string challenge_str = "Basic realm=foobar@baz.com";
  HttpAuthChallengeTokenizer challenge(challenge_str.begin(),
                                       challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("basic"), challenge.auth_scheme());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("realm"), parameters.name());
  EXPECT_EQ(std::string("foobar@baz.com"), parameters.value());
  EXPECT_FALSE(parameters.GetNext());
}

// Use a name=value property with mismatching quote marks.
TEST(HttpAuthChallengeTokenizerTest, MismatchedQuotes) {
  std::string challenge_str = "Basic realm=\"foobar@baz.com";
  HttpAuthChallengeTokenizer challenge(challenge_str.begin(),
                                       challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("basic"), challenge.auth_scheme());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("realm"), parameters.name());
  EXPECT_EQ(std::string("foobar@baz.com"), parameters.value());
  EXPECT_FALSE(parameters.GetNext());
}

// Use a name= property without a value and with mismatching quote marks.
TEST(HttpAuthChallengeTokenizerTest, MismatchedQuotesNoValue) {
  std::string challenge_str = "Basic realm=\"";
  HttpAuthChallengeTokenizer challenge(challenge_str.begin(),
                                       challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("basic"), challenge.auth_scheme());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("realm"), parameters.name());
  EXPECT_EQ(std::string(), parameters.value());
  EXPECT_FALSE(parameters.GetNext());
}

// Use a name=value property with mismatching quote marks and spaces in the
// value.
TEST(HttpAuthChallengeTokenizerTest, MismatchedQuotesSpaces) {
  std::string challenge_str = "Basic realm=\"foo bar";
  HttpAuthChallengeTokenizer challenge(challenge_str.begin(),
                                       challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("basic"), challenge.auth_scheme());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("realm"), parameters.name());
  EXPECT_EQ(std::string("foo bar"), parameters.value());
  EXPECT_FALSE(parameters.GetNext());
}

// Use multiple name=value properties with mismatching quote marks in the last
// value.
TEST(HttpAuthChallengeTokenizerTest, MismatchedQuotesMultiple) {
  std::string challenge_str = "Digest qop=auth-int, algorithm=md5, realm=\"foo";
  HttpAuthChallengeTokenizer challenge(challenge_str.begin(),
                                       challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("digest"), challenge.auth_scheme());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("qop"), parameters.name());
  EXPECT_EQ(std::string("auth-int"), parameters.value());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("algorithm"), parameters.name());
  EXPECT_EQ(std::string("md5"), parameters.value());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("realm"), parameters.name());
  EXPECT_EQ(std::string("foo"), parameters.value());
  EXPECT_FALSE(parameters.GetNext());
}

// Use a name= property which has no value.
TEST(HttpAuthChallengeTokenizerTest, NoValue) {
  std::string challenge_str = "Digest qop=";
  HttpAuthChallengeTokenizer challenge(
      challenge_str.begin(), challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("digest"), challenge.auth_scheme());
  EXPECT_FALSE(parameters.GetNext());
  EXPECT_FALSE(parameters.valid());
}

// Specify multiple properties, comma separated.
TEST(HttpAuthChallengeTokenizerTest, Multiple) {
  std::string challenge_str =
      "Digest algorithm=md5, realm=\"Oblivion\", qop=auth-int";
  HttpAuthChallengeTokenizer challenge(challenge_str.begin(),
                                       challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("digest"), challenge.auth_scheme());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("algorithm"), parameters.name());
  EXPECT_EQ(std::string("md5"), parameters.value());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("realm"), parameters.name());
  EXPECT_EQ(std::string("Oblivion"), parameters.value());
  EXPECT_TRUE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("qop"), parameters.name());
  EXPECT_EQ(std::string("auth-int"), parameters.value());
  EXPECT_FALSE(parameters.GetNext());
  EXPECT_TRUE(parameters.valid());
}

// Use a challenge which has no property.
TEST(HttpAuthChallengeTokenizerTest, NoProperty) {
  std::string challenge_str = "NTLM";
  HttpAuthChallengeTokenizer challenge(
      challenge_str.begin(), challenge_str.end());
  HttpUtil::NameValuePairsIterator parameters = challenge.param_pairs();

  EXPECT_TRUE(parameters.valid());
  EXPECT_EQ(std::string("ntlm"), challenge.auth_scheme());
  EXPECT_FALSE(parameters.GetNext());
}

// Use a challenge with Base64 encoded token.
TEST(HttpAuthChallengeTokenizerTest, Base64) {
  std::string challenge_str = "NTLM  SGVsbG8sIFdvcmxkCg===";
  HttpAuthChallengeTokenizer challenge(challenge_str.begin(),
                                       challenge_str.end());

  EXPECT_EQ(std::string("ntlm"), challenge.auth_scheme());
  // Notice the two equal statements below due to padding removal.
  EXPECT_EQ(std::string("SGVsbG8sIFdvcmxkCg=="), challenge.base64_param());
}

}  // namespace net


text:
require 'rl2/thread'
require 'uri'
require 'net/http'
require 'zlib'
require 'stringio'
require 'logger'
require 'time'

class Rl2::Thread::Downloader
  attr_reader :logger

  def initialize options={}
    @logger = options[:logger] || Logger.new(STDOUT)
  end

  def dat_download dat_url, path
    Net::HTTP.version_1_2
    uri = URI.parse( dat_url )

    Net::HTTP.start( uri.host, uri.port ) do |http|
      if File.exists?( path )
        dat_download_second_or_later http, uri.path, path
      else
        dat_download_first_time http, uri.path, path
      end
    end
  end

  def dat_download_first_time http, dat_path, path
    logger.debug( 'download dat at first time.' )
    response = http.get( dat_path, { 'Accept-Encoding' => 'gzip', 'User-Agent' => Rl2::USER_AGENT } )
    raise 'DAT can not download.' if response.code.to_i >= 300

    modified_time = Time.httpdate(response['Last-Modified']) if response['Last-Modified']

    open( path, 'w' ) do |cache|
      if response['Content-Encoding'] == 'gzip'
        StringIO.open( response.body ) do |io|
          Zlib::GzipReader.wrap(io) do |gz|
            cache.write( gz.read.chop )
          end
        end
      else
        cache.write( response.body.chop )
      end
    end
    File.utime( modified_time, modified_time, path ) if modified_time
  end

  def dat_download_second_or_later http, dat_path, path
    logger.debug( 'download dat at second or later time.' )
    stat = File.stat( path )
    last_modified_time = File.mtime( path )

    response = http.get( dat_path, {
      'If-Modified-Since' => last_modified_time.httpdate,
      'Range' => "bytes= #{stat.size}-",
      'User-Agent' => Rl2::USER_AGENT
    } )
    modified_time = Time.httpdate(response['Last-Modified']) if response['Last-Modified']

    logger.debug( "response.code: #{response.code}" )
    return unless response.code.to_i == 206
    logger.debug( "check abon: #{response.body[0]}" )
    if ( response.body[0] == 10 )
      open( path, 'a' ) do |cache|
        logger.debug( "append body:\n#{response.body}" )
        cache.write( response.body.chop )
      end
    else
      logger.debug( "abon is detected." )
      dat_download_first_time http, dat_path, path
    end
    File.utime( modified_time, modified_time, path ) if modified_time
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AdminLTE 2 | Dashboard</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

  <link rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap.min.css') ?>">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css') ?>">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('dist/css/AdminLTE.min.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('dist/css/skins/_all-skins.min.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/iCheck/flat/blue.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/morris/morris.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/jvectormap/jquery-jvectormap-1.2.2.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/datepicker/datepicker3.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/daterangepicker/daterangepicker.css') ?>">

  <link rel="stylesheet" href="<?php echo base_url('plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css') ?>') ?>">
   <link href="<?php echo base_url('assets/css/bootstrap.min.css') ?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/font-awesome.min.css') ?>" rel="stylesheet">

      D

      Dashboards

        Toggle navigation

<?php echo $this->session->userdata('username')?>

           Online

MAIN NAVIGATION

            Dashboards

              4

          <a href="<?php echo base_url();?>index.php/home_cont/connectdatabase">
             Create Dashboards

          <a href="<?php echo base_url();?>index.php/home_cont/connectdatabase">
             Connect Database

            Your Databases

             <?php
        $dbs = $this->session->flashdata('dbs');
        foreach ($dbs as $row)
         {
            echo "
id.">".$row->host.'/'.$row->data_base."
";
          }
          ?>

          <a href="<?php echo base_url();?>index.php/home_cont/logout">
             Logout

        Dashboard
        Control panel

 Home

Dashboard

            <?php
            $i=1;
          $dbs=$this->session->flashdata('dbs');
          foreach($dbs as $row)
          {
            echo "

";?>

<?php echo $i++ ;?>

<?php echo $row->data_base; ?>

            <a href="<?php echo base_url().'index.php/home_cont/displaydb/'.$row->id."/".$row->data_base;?>" class="small-box-footer">View dashboard

            <?php
            //echo "<button type=\"button\" class=\"btn\">id.">".$row->data_base."</button>";
          }?>


text:
require 'spec_helper'

describe BurnPlan::DistributionStrategy::NoDistributionStrategy do
  let(:portfolio) do
    double('portfolio', {
        :assets => {
            'asset1' => BurnPlan::Asset.new('asset1', 10),
            'asset2' => BurnPlan::Asset.new('asset2', 0),
        }
    })
  end

  subject { described_class.new.create_distribution(portfolio) }

  it 'always returns zero' do
    portfolio.assets.values.each do |asset|
      subject.for_asset(asset).amount.should eq 0
    end
  end
end


text:
<?php

	/**
	 * Functions related to patients
	 */
	class Patient_session extends CI_Model
	{
		/*
		 * Returns true if the specified session_id is in the database for a patient
		 */
		public function validateSession($session_id){
			try{
			  $this->load->database();
				$query = $this->db->query("SELECT * FROM tbl_patient_sessions
											WHERE session_id = '".$session_id."'");

				if($query->num_rows() > 0)
				return true;
				else
				return false;
			}catch(Exception $ex){
				return $ex;
			}
		}

		/*
		 * Retuns all details on the patient with the specified session id
		 */
		public function getPatientDetails($session_id){
			try{
				$this->load->database();
				$query = $this->db->query("SELECT HP.id AS param_id, HP.param, HPO.name AS value, HPO.points, PS.Name AS patient_name, PS.medical_record_no, PS.age, PS.platelets
											FROM tbl_patient_health_params PH
											JOIN tbl_health_params HP ON HP.id = PH.health_param_id
											JOIN tbl_health_params_options HPO ON HPO.id = PH.selected_health_param_option_id
											JOIN tbl_patient_sessions PS ON PS.session_id = PH.session_id
											WHERE PH.session_id = '".$session_id."'
											GROUP BY  HP.id
											");

				if($query->num_rows() > 0){
          $res = $query->result_array();
					return $res;
				}
				else{
					throw new Exception("No records found!");
				}
			}catch(Exception $ex){
				return $ex;
			}

		}

	/*
	 * Returns an array of data of all patients matching the searchString who would be on page $page
	 * if each page contained $records_per_page patients, ordered newest added patient first
	 */
    public function getMatchingPatients($searchString,$page,$records_per_page=10){
        $this->load->database();

        if($searchString == NULL)
        {
            $where = ' ';
        }
        else
        {
            $where = ' WHERE name LIKE \'%'.$searchString.'%\' OR medical_record_no LIKE \'%'.$searchString.'%\' ';
        }

        $query = $this->db->query("SELECT session_id,name,medical_record_no,survey_completed FROM tbl_patient_sessions"
        .$where.
        "ORDER BY created_at DESC LIMIT " . $records_per_page . " OFFSET ". $records_per_page*($page-1));

        if($query->num_rows() > 0){
          $res = $query->result_array();
          return $res;
        }
        else{
          return array();
        }
    }

	/*
	 * Returns the number of patients matching the searchString
	 */
    public function getMatchingPatientsCount($searchString)
    {
        $this->load->database();

        if($searchString == NULL)
        {
            $where = ' ';
        }
        else
        {
            $where = ' WHERE name LIKE \'%'.$searchString.'%\' OR medical_record_no LIKE \'%'.$searchString.'%\' ';
        }

        $res_params_cnt = $this->db->query("SELECT count(*) AS cnt FROM tbl_patient_sessions" . $where);
        $res_params_cnt = $res_params_cnt->row_array();
        $num_records = $res_params_cnt['cnt'];

        return $num_records;
    }

		/*
		 * Inserts a patient's info into the database and generates a corresponding session unique identifier for this patient.
		 */
		public function generateSession($patient_health_params){
			try{
			   $this->load->database();
				$res_params_cnt = $this->db->query("SELECT count(*) AS cnt FROM tbl_health_params");
				$res_params_cnt = $res_params_cnt->row_array();

				$validation_str = '';

				for($i=1;$i<=$res_params_cnt['cnt'];$i++){
					if(!isset($patient_health_params['health_param_'.$i]))
					throw new Exception("All fields are mandatory!".$i);
					if(!isset($patient_health_params['selected_health_param_option_'.$i]))
					throw new Exception("All fields are mandatory!".$i);
				}
				while(1){
					$session_id = rand(1000000000, 9999999999);
					$res_session_id = $this->db->query("SELECT * FROM tbl_patient_sessions
											WHERE session_id = '".$session_id."'");
					if($res_session_id->num_rows() == 0)
					break;
				}
				$res_create_session = $this->db->query("INSERT INTO tbl_patient_sessions (session_id, name, medical_record_no, age, platelets, created_at)  VALUES ('".$session_id."', '".$patient_health_params['patient_name']."', '".$patient_health_params['medical_record_no']."', '".$patient_health_params['age']."', '".$patient_health_params['platelets']."',NOW() )");
				for($i=1; $i<=$res_params_cnt['cnt'];$i++){
					$this->db->query("INSERT INTO tbl_patient_health_params (session_id, health_param_id, selected_health_param_option_id, created_at) VALUES ('".$session_id."', '".$patient_health_params['health_param_'.$i]."', '".$patient_health_params['selected_health_param_option_'.$i]."', NOW())");
				}
				return $session_id;
			}catch(Exception $ex){
				return $ex;
			}
		}

		/**
		 * Returns the percentages of life, death ect. for the patient with the corresponding session id
		 */
		public function getReport($session_id){
			 $this->load->database();
			 $points = array();
			$res_age_platelets = $this->db->query("SELECT age, platelets FROM tbl_patient_sessions WHERE session_id='".$session_id."'");

			if($res_age_platelets->num_rows() == 0)
			{
			  return null;
			}

			$row_age_platelets = $res_age_platelets->row_array();
			$points['age'] = $row_age_platelets['age'];
			$points['platelets'] = $row_age_platelets['platelets'];
			$res_points = $this->db->query("SELECT HPO.points,HP.id FROM tbl_patient_health_params PHP
							   JOIN tbl_health_params_options HPO ON HPO.id = PHP.selected_health_param_option_id
							   JOIN tbl_health_params HP ON HP.id = HPO.health_param_id
							   WHERE PHP.session_id = '".$session_id."' ");

			foreach($res_points->result_array() as $row_points){
				$points[$row_points['id']] = $row_points['points'];
			}
			$dead = exp(-2.5683+(0.0434*$points['age'])+(-0.00293*$points['platelets'])+(1.2497*$points[1])+(0.914*$points[2])+(0.6918*((2-$points[3])-1)))/(1+exp(-2.5683+(0.0434*$points['age'])+(-0.00293*$points['platelets'])+(1.2497*$points[1])+(0.914*$points[2])+(0.6918*((2-$points[3])-1))));
			$response = array("dead" => round(($dead*100),0), "nursing_home" => round(((((1-$dead)*0.15)/0.5)*100),0), "dependent_on_others" => round(((((1-$dead)*0.25)/0.5)*100),0), "independent" => round(((((1-$dead)*0.1)/0.5)*100),0));
			return $response;
		}

		/*
		 * Returns the health parameters from the DB
		 */
		public function getHealthParams(){
			try{
				$this->load->database();
				$res_health_params = $this->db->query("SELECT * FROM tbl_health_params");
				$health_params = array();
				if($res_health_params->num_rows() >0){
					foreach($res_health_params->result_array() as $row_health_params){
						$health_params[$row_health_params['id']]['health_params'] = $row_health_params;
						$res_hlth_prms_opts = $this->db->query("SELECT * FROM tbl_health_params_options WHERE health_param_id = '".$row_health_params['id']."'");
						$health_param_opts = array();
						foreach($res_hlth_prms_opts->result_array() as $row_hlth_prms_opts){
							$health_param_opts[] = $row_hlth_prms_opts;
						}
						$health_params[$row_health_params['id']]['health_param_options'] = $health_param_opts;
					}
					return $health_params;
				}else{
					throw new Exception("No records found!");
				}

			}catch(Exception $ex){
				return $ex;
			}
		}

		/**
		 * Returns session ids of matching patients
		 */
		public function getSessionIDs($search_str,$per_pg,$offset){
			try{
				$this->load->database();
				$search = "";
				if($search_str != ''){
					$search = " WHERE session_id LIKE '%{$search_str}%' OR medical_record_no LIKE '%{$search_str}%' OR name LIKE '%{$search_str}%'";
				}
				$res_ids = $this->db->query("SELECT SQL_CALC_FOUND_ROWS * FROM tbl_patient_sessions".$search." ORDER BY session_id DESC LIMIT $offset,$per_pg");
				$notemp = $this->db->query('SELECT found_rows() as count');
				$no = $notemp->row_array();

				$session_ids = array();
				if($res_ids->num_rows() > 0){
					foreach($res_ids->result_array() as $row_ids){
						$session_ids["data"][] = $row_ids;
					}
					$session_ids["total_results"] = $no['count'];
					return $session_ids;
				}else{
					throw new Exception("No records found!");
				}

			}catch(Exception $ex){
				return $ex;
			}
		}
	}

?>


text:
package egovframework.rte.itl.webservice.data.dao.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import egovframework.rte.itl.integration.metadata.ServiceDefinition;
import egovframework.rte.itl.webservice.data.WebServiceServerDefinition;
import egovframework.rte.itl.webservice.data.dao.WebServiceServerDefinitionDao;

/**
 * WebServiceServerDefinitionDao를 hibernate를 이용하여 구현한
 * DAO 클래스
 *

 * NOTE: WebServiceServerDefinitionDao를
 * hibernate를 이용하여 구현한 DAO class이다.
 * @author 실행환경 개발팀 심상호
 * @since 2009.06.01
 * @version 1.0
 * @see

 *  == 개정이력(Modification Information) ==
 *
 *   수정일      수정자           수정내용
 *  -------    --------    ---------------------------
 *   2009.06.01  심상호           최초 생성
 *
 *

 */
public class HibernateWebServiceServerDefinitionDao extends HibernateDaoSupport
        implements WebServiceServerDefinitionDao {
    private Log LOG = LogFactory.getLog(this.getClass());

    public WebServiceServerDefinition getWebServiceServerDefinition(
            ServiceDefinition serviceDefinition) {
        LOG.debug("get WebServiceServerDefinition(serviceDefinition = "
            + serviceDefinition + ")");

        WebServiceServerDefinition webServiceServerDefinition =
            getWebServiceServerDefinition(serviceDefinition.getKey());

        LOG.debug("get WebServiceServerDefinition(serviceDefinition = "
            + serviceDefinition + ") = " + webServiceServerDefinition);

        return webServiceServerDefinition;
    }

    public WebServiceServerDefinition getWebServiceServerDefinition(String key) {
        LOG.debug("get WebServiceServerDefinition(key = \"" + key + "\"");

        WebServiceServerDefinition webServiceServerDefinition =
            (WebServiceServerDefinition) getHibernateTemplate().get(
                WebServiceServerDefinition.class, key);

        LOG.debug("get WebServiceServerDefinition(key = \"" + key + "\") = "
            + webServiceServerDefinition);

        return webServiceServerDefinition;
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClient, QueryClientProvider } from 'react-query';

import './index.css';
import './components/charts/charts.scss';

import { App } from './components/App';
import * as errorHandler from './errors/errorHandler';

errorHandler.initialize();

const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            refetchOnWindowFocus: false,
        },
    },
});

ReactDOM.render(
    <React.StrictMode>
        <QueryClientProvider client={queryClient}>
            <App />
        </QueryClientProvider>
    </React.StrictMode>,
    document.getElementById('root')
);


text:
from copy import deepcopy

import pytest

from datadog_checks.dev import WaitFor, docker_run, run_command
from datadog_checks.dev.conditions import CheckDockerLogs
from datadog_checks.oracle import Oracle

from .common import (
    CHECK_NAME,
    CLIENT_LIB,
    COMPOSE_FILE,
    CONTAINER_NAME,
    ENABLE_TCPS,
    HERE,
    HOST,
    ORACLE_DATABASE_VERSION,
    PASSWORD,
    PORT,
    TCPS_PORT,
    USER,
)

E2E_METADATA_ORACLE_CLIENT = {
    'docker_volumes': [
        '{}/scripts/install_instant_client.sh:/tmp/install_instant_client.sh'.format(HERE),
        '{}/docker/client/client_wallet:/opt/oracle/instantclient_19_3/client_wallet'.format(HERE),
        '{}/docker/client/sqlnet.ora:/opt/oracle/instantclient_19_3/sqlnet.ora'.format(HERE),
        '{}/docker/client/tnsnames.ora:/opt/oracle/instantclient_19_3/tnsnames.ora'.format(HERE),
        '{}/docker/client/listener.ora:/opt/oracle/instantclient_19_3/listener.ora'.format(HERE),
    ],
    'start_commands': [
        'bash /tmp/install_instant_client.sh',
    ],
    'env_vars': {'LD_LIBRARY_PATH': '/opt/oracle/instantclient_19_3', 'TNS_ADMIN': '/opt/oracle/instantclient_19_3'},
}

E2E_METADATA_JDBC_CLIENT = {
    # Since we don't include Oracle instantclient to `LD_LIBRARY_PATH` env var,
    # the integration will fallback to JDBC client
    'use_jmx': True,  # Using jmx to have a ready to use java runtime
    'docker_volumes': [
        '{}/scripts/install_instant_client.sh:/tmp/install_instant_client.sh'.format(HERE),
        '{}/docker/client/client_wallet:/opt/oracle/instantclient_19_3/client_wallet'.format(HERE),
        '{}/docker/client/sqlnet.ora:/opt/oracle/instantclient_19_3/sqlnet.ora'.format(HERE),
        '{}/docker/client/tnsnames.ora:/opt/oracle/instantclient_19_3/tnsnames.ora'.format(HERE),
        '{}/docker/client/listener.ora:/opt/oracle/instantclient_19_3/listener.ora'.format(HERE),
        '{}/docker/client/oraclepki.jar:/opt/oracle/instantclient_19_3/oraclepki.jar'.format(HERE),
        '{}/docker/client/osdt_cert.jar:/opt/oracle/instantclient_19_3/osdt_cert.jar'.format(HERE),
        '{}/docker/client/osdt_core.jar:/opt/oracle/instantclient_19_3/osdt_core.jar'.format(HERE),
    ],
    'start_commands': [
        'bash /tmp/install_instant_client.sh',  # Still needed to set up the database
    ],
    'env_vars': {'TNS_ADMIN': '/opt/oracle/instantclient_19_3'},
}

@pytest.fixture
def check(instance):
    return Oracle(CHECK_NAME, {}, [instance])

@pytest.fixture
def tcps_check(tcps_instance):
    return Oracle(CHECK_NAME, {}, [tcps_instance])

@pytest.fixture
def instance():
    return deepcopy(
        {
            'server': 'localhost:1521',
            'username': 'system',
            'password': 'oracle',
            'service_name': 'xe',
            'protocol': 'TCP',
            'tags': ['optional:tag1'],
        }
    )

@pytest.fixture
def tcps_instance():
    return deepcopy(
        {
            'server': 'localhost:2484',
            'username': 'system',
            'password': 'oracle',
            'service_name': 'xe',
            'protocol': 'TCPS',
            'tags': ['optional:tag1'],
        }
    )

@pytest.fixture(scope='session')
def dd_environment():
    instance = {
        'server': '{}:{}'.format(HOST, PORT),
        'username': USER,
        'password': PASSWORD,
        'service_name': 'InfraDB.us.oracle.com',
        'protocol': 'TCP',
    }

    if CLIENT_LIB == 'jdbc':
        e2e_metadata = E2E_METADATA_JDBC_CLIENT
        instance['jdbc_driver_path'] = '/opt/oracle/instantclient_19_3/ojdbc8.jar'
    else:
        e2e_metadata = E2E_METADATA_ORACLE_CLIENT

    # Set additional config options for TCPS
    if ENABLE_TCPS:
        instance['server'] = '{}:{}'.format(HOST, TCPS_PORT)
        instance['protocol'] = 'TCPS'

        if CLIENT_LIB == 'jdbc':
            instance['jdbc_truststore_path'] = '/opt/oracle/instantclient_19_3/client_wallet/cwallet.sso'
            instance['jdbc_truststore_type'] = 'SSO'

    with docker_run(
        COMPOSE_FILE,
        conditions=[
            CheckDockerLogs(COMPOSE_FILE, ['The database is ready for use'], wait=5, attempts=120),
            WaitFor(create_user),
        ],
        env_vars={'ORACLE_DATABASE_VERSION': ORACLE_DATABASE_VERSION},
        attempts=20,
        attempts_wait=5,
    ):
        yield instance, e2e_metadata

@pytest.fixture
def bad_instance():
    return {
        "password": "badpassword",
        "protocol": "TCP",
        "server": "localhost:1521",
        "service_name": "InfraDB.us.oracle.com",
        "username": "datadog",
    }

def create_user():
    output = run_docker_command(
        [
            '/u01/app/oracle/product/12.2.0/dbhome_1/bin/sqlplus',
            'sys/Oradoc_db1@localhost:1521/InfraDB.us.oracle.com',
            'AS',
            'SYSDBA',
            '@/host/data/setup.sql',
        ]
    )

    return 'Grant succeeded.' in output.stdout

def run_docker_command(command):
    cmd = ['docker', 'exec', CONTAINER_NAME] + command
    return run_command(cmd, capture=True, check=True)


text:
package org.keycloak.forms.login.freemarker.model;

import org.keycloak.theme.Theme;
import org.keycloak.models.RealmModel;
import org.keycloak.services.Urls;

import java.net.URI;

/**
 * @author Stian Thorgersen
 */
public class UrlBean {

    private final URI actionuri;
    private URI baseURI;
    private Theme theme;
    private String realm;

    public UrlBean(RealmModel realm, Theme theme, URI baseURI, URI actionUri) {
        this.realm = realm.getName();
        this.theme = theme;
        this.baseURI = baseURI;
        this.actionuri = actionUri;
    }

    public String getLoginAction() {
        if (this.actionuri != null) {
            return this.actionuri.toString();
        }
        throw new RuntimeException("action URI not set");
    }

    public String getLoginUrl() {
        return Urls.realmLoginPage(baseURI, realm).toString();
    }

    public String getRegistrationAction() {
        if (this.actionuri != null) {
            return this.actionuri.toString();
        }
        return Urls.realmRegisterAction(baseURI, realm).toString();
    }

    public String getRegistrationUrl() {
        return Urls.realmRegisterPage(baseURI, realm).toString();
    }

    public String getLoginUpdatePasswordUrl() {
        return Urls.loginActionUpdatePassword(baseURI, realm).toString();
    }

    public String getLoginUpdateTotpUrl() {
        return Urls.loginActionUpdateTotp(baseURI, realm).toString();
    }

    public String getLoginUpdateProfileUrl() {
        return Urls.loginActionUpdateProfile(baseURI, realm).toString();
    }

    public String getLoginResetCredentialsUrl() {
        return Urls.loginResetCredentials(baseURI, realm).toString();
    }

    public String getLoginUsernameReminderUrl() {
        return Urls.loginUsernameReminder(baseURI, realm).toString();
    }

    public String getLoginEmailVerificationUrl() {
        return Urls.loginActionEmailVerification(baseURI, realm).toString();
    }

    public String getFirstBrokerLoginUrl() {
        return Urls.firstBrokerLoginProcessor(baseURI, realm).toString();
    }

    public String getOauthAction() {
        if (this.actionuri != null) {
            return this.actionuri.getPath();
        }

        return Urls.realmOauthAction(baseURI, realm).toString();
    }

    public String getResourcesPath() {
        URI uri = Urls.themeRoot(baseURI);
        return uri.getPath() + "/" + theme.getType().toString().toLowerCase() +"/" + theme.getName();
    }
}


text:
/// @author Владимир Керимов

#include <data/cast>
#include <data/text>
#include <data/decimal>
#include <cstddef>
#include <cstdio>
#include <string>

#ifdef _MSC_VER
#define snscanf   _snscanf
#define snprintf  _snprintf
#define snwscanf  _snwscanf
#define snwprintf _snwprintf
#endif

#define DATA_BYTE_FORMAT_INT64  "%lld"
#define DATA_BYTE_FORMAT_INT32  "%ld"
#define DATA_BYTE_FORMAT_INT16  "%hd"
#define DATA_BYTE_FORMAT_UINT64 "%llu"
#define DATA_BYTE_FORMAT_UINT32 "%lu"
#define DATA_BYTE_FORMAT_UINT16 "%hu"
#define DATA_BYTE_FORMAT_DOUBLE "%LG"
#define DATA_BYTE_FORMAT_FLOAT  "%G"

#define DATA_BYTE_STRING_NULL   "null"
#define DATA_BYTE_STRING_TRUE   "true"
#define DATA_BYTE_STRING_FALSE  "false"

#define DATA_WIDE( literal_constant ) L ## #literal_constant

#define DATA_WIDE_FORMAT_INT64  DATA_WIDE( DATA_BYTE_FORMAT_INT64 )
#define DATA_WIDE_FORMAT_INT32  DATA_WIDE( DATA_BYTE_FORMAT_INT32 )
#define DATA_WIDE_FORMAT_INT16  DATA_WIDE( DATA_BYTE_FORMAT_INT16 )
#define DATA_WIDE_FORMAT_UINT64 DATA_WIDE( DATA_BYTE_FORMAT_UINT64 )
#define DATA_WIDE_FORMAT_UINT32 DATA_WIDE( DATA_BYTE_FORMAT_UINT32 )
#define DATA_WIDE_FORMAT_UINT16 DATA_WIDE( DATA_BYTE_FORMAT_UINT16 )
#define DATA_WIDE_FORMAT_DOUBLE DATA_WIDE( DATA_BYTE_FORMAT_DOUBLE )
#define DATA_WIDE_FORMAT_FLOAT  DATA_WIDE( DATA_BYTE_FORMAT_FLOAT )

#define DATA_WIDE_STRING_NULL   DATA_WIDE( DATA_BYTE_STRING_NULL )
#define DATA_WIDE_STRING_TRUE   DATA_WIDE( DATA_BYTE_STRING_TRUE )
#define DATA_WIDE_STRING_FALSE  DATA_WIDE( DATA_BYTE_STRING_FALSE )

namespace data
{
    char const* const byte_string_null  = DATA_BYTE_STRING_NULL;
    char const* const byte_string_true  = DATA_BYTE_STRING_TRUE;
    char const* const byte_string_false = DATA_BYTE_STRING_FALSE;

    wchar_t const* const wide_string_null  = DATA_WIDE_STRING_NULL;
    wchar_t const* const wide_string_true  = DATA_WIDE_STRING_TRUE;
    wchar_t const* const wide_string_false = DATA_WIDE_STRING_FALSE;

    template <typename char_type>
    struct string_operations
    {
        typedef int (*const read_function)(char_type const*, size_t, char_type const*, ...);
        typedef int (*const write_function)(char_type*, size_t, char_type const*, ...);

        static read_function  reader;
        static write_function writer;
    };

    template <> string_operations<char>::read_function string_operations<char>::reader = snscanf;
    template <> string_operations<char>::write_function string_operations<char>::writer = snprintf;
    template <> string_operations<wchar_t>::read_function string_operations<wchar_t>::reader = snwscanf;
    template <> string_operations<wchar_t>::write_function string_operations<wchar_t>::writer = snwprintf;

    template <typename value_type>
    struct string_value
    {
        static size_t const max_length;
    };

    template <typename value_type, typename char_type>
    struct string_format
    {
        static char_type const* const format;
    };

    template <> size_t const string_value<int64_t >::max_length = 20;
    template <> size_t const string_value<int32_t >::max_length = 11;
    template <> size_t const string_value<int16_t >::max_length = 6;
    template <> size_t const string_value<int8_t  >::max_length = 4;
    template <> size_t const string_value<uint64_t>::max_length = 20;
    template <> size_t const string_value<uint32_t>::max_length = 10;
    template <> size_t const string_value<uint16_t>::max_length = 5;
    template <> size_t const string_value<uint8_t >::max_length = 3;
    template <> size_t const string_value<double  >::max_length = 15;
    template <> size_t const string_value<float   >::max_length = 15;

    template <> char const* const string_format<int64_t,  char>::format = DATA_BYTE_FORMAT_INT64;
    template <> char const* const string_format<int32_t,  char>::format = DATA_BYTE_FORMAT_INT32;
    template <> char const* const string_format<int16_t,  char>::format = DATA_BYTE_FORMAT_INT16;
    template <> char const* const string_format<int8_t,   char>::format = DATA_BYTE_FORMAT_INT16;
    template <> char const* const string_format<uint64_t, char>::format = DATA_BYTE_FORMAT_UINT64;
    template <> char const* const string_format<uint32_t, char>::format = DATA_BYTE_FORMAT_UINT32;
    template <> char const* const string_format<uint16_t, char>::format = DATA_BYTE_FORMAT_UINT16;
    template <> char const* const string_format<uint8_t,  char>::format = DATA_BYTE_FORMAT_UINT16;
    template <> char const* const string_format<double,   char>::format = DATA_BYTE_FORMAT_DOUBLE;
    template <> char const* const string_format<float,    char>::format = DATA_BYTE_FORMAT_FLOAT;

    template <> wchar_t const* const string_format<int64_t,  wchar_t>::format = DATA_WIDE_FORMAT_INT64;
    template <> wchar_t const* const string_format<int32_t,  wchar_t>::format = DATA_WIDE_FORMAT_INT32;
    template <> wchar_t const* const string_format<int16_t,  wchar_t>::format = DATA_WIDE_FORMAT_INT16;
    template <> wchar_t const* const string_format<uint64_t, wchar_t>::format = DATA_WIDE_FORMAT_UINT64;
    template <> wchar_t const* const string_format<uint32_t, wchar_t>::format = DATA_WIDE_FORMAT_UINT32;
    template <> wchar_t const* const string_format<uint16_t, wchar_t>::format = DATA_WIDE_FORMAT_UINT16;
    template <> wchar_t const* const string_format<double,   wchar_t>::format = DATA_WIDE_FORMAT_DOUBLE;
    template <> wchar_t const* const string_format<float,    wchar_t>::format = DATA_WIDE_FORMAT_FLOAT;

    template <typename value_type, typename char_type>
    bool cast_to_string(std::basic_string<char_type>& result, value_type const& value)
    {
        result.resize(string_value<value_type>::max_length);
        int length = string_operations<char_type>::writer(&result.at(0), result.size(),
                                              string_format<value_type, char_type>::format, value);
        result.resize(length);
        return true;
    }

    template <typename value_type, typename char_type>
    bool try_cast_from_string(value_type& result, std::basic_string<char_type> const& source)
    {
        int count = string_operations<char_type>::reader(source.c_str(), source.size(),
                                            string_format<value_type, char_type>::format, &result);
        return count == 1;
    }

    bool type_cast<std::string, std::nullptr_t>::try_cast(std::string& result, std::nullptr_t const& )
    {
        result = byte_string_null;
        return true;
    }

    bool type_cast<std::string, bool>::try_cast(std::string& result, bool const& value)
    {
        result = value ? byte_string_true : byte_string_false;
        return true;
    }

    bool type_cast<std::string, int64_t>::try_cast(std::string& result, int64_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::string, int32_t>::try_cast(std::string& result, int32_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::string, int16_t>::try_cast(std::string& result, int16_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::string, int8_t>::try_cast(std::string& result, int8_t const& value)
    {
        return cast_to_string(result, static_cast<int16_t>(value));
    }

    bool type_cast<std::string, uint64_t>::try_cast(std::string& result, uint64_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::string, uint32_t>::try_cast(std::string& result, uint32_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::string, uint16_t>::try_cast(std::string& result, uint16_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::string, uint8_t>::try_cast(std::string& result, uint8_t const& value)
    {
        return cast_to_string(result, static_cast<uint16_t>(value));
    }

    bool type_cast<std::string, double>::try_cast(std::string& result, double const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::string, float>::try_cast(std::string& result, float const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::string, decimal>::try_cast(std::string& result, decimal const& value)
    {
        result = value.as<std::string>();
        return true;
    }

    bool type_cast<bool, std::string>::try_cast(bool& result, std::string const& value)
    {
        result = !value.empty();
        return true;
    }

    bool type_cast<int64_t, std::string>::try_cast(int64_t& result, std::string const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<int32_t, std::string>::try_cast(int32_t& result, std::string const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<int16_t, std::string>::try_cast(int16_t& result, std::string const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<int8_t, std::string>::try_cast(int8_t& result, std::string const& value)
    {
        int16_t holder;
        if (!try_cast_from_string(holder, value))
            return false;
        result = cast<int8_t>(holder);
        return true;
    }

    bool type_cast<uint64_t, std::string>::try_cast(uint64_t& result, std::string const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<uint32_t, std::string>::try_cast(uint32_t& result, std::string const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<uint16_t, std::string>::try_cast(uint16_t& result, std::string const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<uint8_t, std::string>::try_cast(uint8_t& result, std::string const& value)
    {
        uint16_t holder;
        if (!try_cast_from_string(holder, value))
            return false;
        result = cast<uint8_t>(holder);
        return true;
    }

    bool type_cast<double, std::string>::try_cast(double& result, std::string const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<float, std::string>::try_cast(float& result, std::string const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<decimal, std::string>::try_cast(decimal& result, std::string const& value)
    {
        result = decimal(value);
        return true;
    }

    bool type_cast<std::wstring, std::nullptr_t>::try_cast(std::wstring& result, std::nullptr_t const& )
    {
        result = wide_string_null;
        return true;
    }

    bool type_cast<std::wstring, bool>::try_cast(std::wstring& result, bool const& value)
    {
        result = value ? wide_string_true : wide_string_false;
        return true;
    }

    bool type_cast<std::wstring, int64_t>::try_cast(std::wstring& result, int64_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::wstring, int32_t>::try_cast(std::wstring& result, int32_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::wstring, int16_t>::try_cast(std::wstring& result, int16_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::wstring, int8_t>::try_cast(std::wstring& result, int8_t const& value)
    {
        return cast_to_string(result, static_cast<int16_t>(value));
    }

    bool type_cast<std::wstring, uint64_t>::try_cast(std::wstring& result, uint64_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::wstring, uint32_t>::try_cast(std::wstring& result, uint32_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::wstring, uint16_t>::try_cast(std::wstring& result, uint16_t const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::wstring, uint8_t>::try_cast(std::wstring& result, uint8_t const& value)
    {
        return cast_to_string(result, static_cast<uint16_t>(value));
    }

    bool type_cast<std::wstring, double>::try_cast(std::wstring& result, double const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::wstring, float>::try_cast(std::wstring& result, float const& value)
    {
        return cast_to_string(result, value);
    }

    bool type_cast<std::wstring, decimal>::try_cast(std::wstring& result, decimal const& value)
    {
        result = value.as<std::wstring>();
        return true;
    }

    bool type_cast<bool, std::wstring>::try_cast(bool& result, std::wstring const& value)
    {
        result = !value.empty();
        return true;
    }

    bool type_cast<int64_t, std::wstring>::try_cast(int64_t& result, std::wstring const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<int32_t, std::wstring>::try_cast(int32_t& result, std::wstring const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<int16_t, std::wstring>::try_cast(int16_t& result, std::wstring const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<int8_t, std::wstring>::try_cast(int8_t& result, std::wstring const& value)
    {
        int16_t holder;
        if (!try_cast_from_string(holder, value))
            return false;
        result = cast<int8_t>(holder);
        return true;
    }

    bool type_cast<uint64_t, std::wstring>::try_cast(uint64_t& result, std::wstring const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<uint32_t, std::wstring>::try_cast(uint32_t& result, std::wstring const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<uint16_t, std::wstring>::try_cast(uint16_t& result, std::wstring const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<uint8_t, std::wstring>::try_cast(uint8_t& result, std::wstring const& value)
    {
        uint16_t holder;
        if (!try_cast_from_string(holder, value))
            return false;
        result = cast<uint8_t>(holder);
        return true;
    }

    bool type_cast<double, std::wstring>::try_cast(double& result, std::wstring const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<float, std::wstring>::try_cast(float& result, std::wstring const& value)
    {
        return try_cast_from_string(result, value);
    }

    bool type_cast<decimal, std::wstring>::try_cast(decimal& result, std::wstring const& value)
    {
        result = decimal(value);
        return true;
    }
}

// sine qua non