text:
<?php
namespace App\Model\Table;

use App\Model\Entity\NotasFiscaisEntradasIten;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * NotasFiscaisEntradasItens Model
 *
 * @property \Cake\ORM\Association\BelongsTo $NotasFiscaisEntradas
 * @property \Cake\ORM\Association\BelongsTo $Produtos
 */
class NotasFiscaisEntradasItensTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('notas_fiscais_entradas_itens');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('NotasFiscaisEntradas', [
            'foreignKey' => 'notas_fiscais_entrada_id'
        ]);
        $this->belongsTo('Produtos', [
            'foreignKey' => 'produto_id'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->numeric('qtde')
            ->allowEmpty('qtde');

        $validator
            ->numeric('compra')
            ->allowEmpty('compra');

        $validator
            ->numeric('total')
            ->allowEmpty('total');

        return $validator;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['notas_fiscais_entrada_id'], 'NotasFiscaisEntradas'));
        $rules->add($rules->existsIn(['produto_id'], 'Produtos'));
        return $rules;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <aws/resource-groups/model/ListGroupResourcesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::ResourceGroups::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws::Http;

ListGroupResourcesRequest::ListGroupResourcesRequest() :
    m_groupNameHasBeenSet(false),
    m_filtersHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false),
    m_nextTokenHasBeenSet(false)
{
}

Aws::String ListGroupResourcesRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_filtersHasBeenSet)
  {
   Array<JsonValue> filtersJsonList(m_filters.size());
   for(unsigned filtersIndex = 0; filtersIndex < filtersJsonList.GetLength(); ++filtersIndex)
   {
     filtersJsonList[filtersIndex].AsObject(m_filters[filtersIndex].Jsonize());
   }
   payload.WithArray("Filters", std::move(filtersJsonList));

  }

  return payload.View().WriteReadable();
}

void ListGroupResourcesRequest::AddQueryStringParameters(URI& uri) const
{
    Aws::StringStream ss;
    if(m_maxResultsHasBeenSet)
    {
      ss << m_maxResults;
      uri.AddQueryStringParameter("maxResults", ss.str());
      ss.str("");
    }

    if(m_nextTokenHasBeenSet)
    {
      ss << m_nextToken;
      uri.AddQueryStringParameter("nextToken", ss.str());
      ss.str("");
    }

}


text:
package org.arquillian.cube.q;

import org.arquillian.cube.docker.impl.client.CubeDockerConfiguration;
import org.arquillian.cube.docker.impl.client.config.DockerCompositions;
import org.arquillian.cube.q.core.InstallProxy;
import org.arquillian.cube.q.spi.Proxy;
import org.arquillian.cube.q.spi.ProxyManager;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.spi.ServiceLoader;
import org.jboss.arquillian.core.test.AbstractManagerTestBase;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(MockitoJUnitRunner.class)
public class InstallProxyTestCase extends AbstractManagerTestBase {

    private static final String CONTENT =
        "a:\n" +
            "  image: a/a\n" +
            "  portBindings: [8089/tcp]\n" +
            "  links:\n" +
            "    - b:b\n" +
            "b:\n" +
            "  image: b/b\n" +
            "  exposedPorts: [2112/tcp]\n";

    @Mock
    private ArquillianDescriptor descriptor;

    @Mock
    private ServiceLoader serviceLoader;

    @Mock
    private ProxyManager proxyManager;

    @Override
    protected void addExtensions(List<Class<?>> extensions) {
        extensions.add(InstallProxy.class);
    }

    @Before
    public void setup() {

        Proxy p = new Proxy.Builder().build();

        bind(ApplicationScoped.class, ArquillianDescriptor.class, descriptor);
        bind(ApplicationScoped.class, ServiceLoader.class, serviceLoader);

        Mockito.when(serviceLoader.onlyOne(ProxyManager.class)).thenReturn(proxyManager);
        Mockito.when(proxyManager.install(Mockito.any(DockerCompositions.class))).thenReturn(p);
    }

    @Test
    public void shouldInstallProxy() throws Exception {
        CubeDockerConfiguration config = createConfig(CONTENT);
        fire(config);

        DockerCompositions cubes = config.getDockerContainersContent();
        Assert.assertEquals(3, cubes.getContainerIds().size());

        System.out.println(config.toString());
    }

    private CubeDockerConfiguration createConfig(String content) {
        Map<String, String> parameters = new HashMap<>();

        parameters.put("serverVersion", "1.13");
        parameters.put("serverUri", "http://localhost:25123");
        parameters.put("dockerContainers", content);

        return CubeDockerConfiguration.fromMap(parameters, null);
    }
}


text:
/**
 * @fileoverview Blocks for ComputerCraft Textutils API
 * @author ellen.spertus@gmail.com (Ellen Spertus)
 */
'use strict';
goog.require('ComputerCraft.DependentInputBlock');
goog.require('ComputerCraft.ValueBlock');
goog.require('ComputerCraft.VarArgsBlock');

Blockly.ComputerCraft.TEXTUTILS_BLOCK_COLOUR_ = 190;

Blockly.ComputerCraft.TEXTUTILS_FUNCS_ = [
  {blockName: 'write',
   text: 'write string %1 %2 to screen at rate %3',
   args: [['TEXT', 'String'],
          ['MODE',
           new Blockly.FieldDropdown([['without newline', 'slowWrite'],
                                      ['with newline', 'slowPrint']])],
          ['RATE', 'Number']],
   ddFuncName: 'MODE',
   tooltip:
   'Write the given string to the screen (terminal or monitor)\n'+
   'at the current cursor position character-by-character.\n' +
   'The higher the rate, the faster the string is output.\n' +
   'A value of 1 outputs one character per second.\n' +
   'If a newline is used, the next output will be to a new line.'
  },
  {funcName: 'slowPrint',
   text: 'write line %1 to screen at rate %2',
   args: [['TEXT', 'String'], ['RATE', 'Number']],
   tooltip:
   'Write the given string to the screen (terminal or monitor)\n'+
   'at the current cursor position character-by-character.\n' +
   'The higher the rate, the faster the string is output.\n' +
   'A value of 1 outputs one character per second.' +
   'Unlike with the "write string" block, a newline is printed at the end.\n'
  },
  {funcName: 'pagedPrint',
   text: 'write string %1 paginated',
   args: [['TEXT', 'String']],
   tooltip:
   'Print the string to the screen (terminal or monitor),\n' +
   'waiting for confirmation before scrolling down.'},
  {funcName: 'serialize',
   text: 'convert table %1 to string',
   args: [['TABLE', 'Table']],
   output: 'String',
   tooltip:
   'Serialize the table into a string for\n' +
   'display, storage, or transmission.\n' +
   'The table can be recovered with the\n' +
   '"convert string to table" block.'
  },
  {funcName: 'unserialize',
   text: 'convert string %1 to table',
   args: [['TEXT', 'String']],
   output: 'Table',
   tooltip:
   'Unserialize a string representation of a table\n' +
   'created with the "convert table to string" block.'
  },
  {funcName: 'urlEncode',
   text: 'encode %1 for URL',
   args: [['TEXT', 'String']],
   tooltip:
   'Encode a string for transmission within a URL.\n' +
   'Spaces are replaced with "+s".  Unsafe characters,\n' +
   'such as quotation marks, are replaced by their ASCII\n' +
   'values and preceded with a percent sign (%).'
  }
];

Blockly.ComputerCraft.TEXTUTILS_FUNCS_.forEach(function(info) {
  Blockly.ComputerCraft.buildValueBlock(
    'textutils', Blockly.ComputerCraft.TEXTUTILS_BLOCK_COLOUR_, info);});

Blockly.ComputerCraft.buildDependentInputBlock(
  'textutils',
  Blockly.ComputerCraft.TEXTUTILS_BLOCK_COLOUR_,
  {funcName: 'formatTime',
   text: 'format %1 %2',
   args: [['CHOICE*',
           [['current time', 'current'],
            ['time...', 'time*']]],
          ['TIME^', 'Number']],
   addChild: Blockly.ComputerCraft.InputAddType.NEVER,
   tooltip: 'Format the current or given time as a printable string.'});

Blockly.ComputerCraft.buildVarArgsBlock(
  'textutils',
  Blockly.ComputerCraft.TEXTUTILS_BLOCK_COLOUR_,
  {blockName: 'tabulate',
   text: 'display tables %v %1',
   args: [['MODE', new Blockly.FieldDropdown(
           [['with pagination', 'pagedTabulate'],
            ['without pagination', 'tabulate']])]],
   ddFuncName: 'MODE',
   varArgName: 'table',
   varArgType: ['Table', 'List'],
   varArgTooltip: 'A table to display.',
   varArgCount: 1,
   varContainerName: 'tables',
   varContainerTooltip: 'Add, remove, or reorder the tables to display.',
   tooltip:
   'Print tables to the screen in an ordered form.\n' +
   'If pagination is used, this pauses for confirmation before scrolling.\n' +
   'Click on the star to add (or remove) tables.'});


text:
/**@file
 * Adhoc main program for testing contact behavior between two unreasonably
 * dense meshes.
 */

#include "SimTKsimbody.h"

#include <cstdio>
#include <exception>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <ctime>
using std::cout; using std::endl;

using namespace SimTK;

Array_<State> saveEm;

static const Real ReportInterval = 0.01;
static const Real ForceScale = 10;
static const Real MomentScale = 20;

class ForceArrowGenerator : public DecorationGenerator {
public:
    ForceArrowGenerator(const MultibodySystem& system,
                        const CompliantContactSubsystem& complCont)
    :   m_system(system), m_compliant(complCont) {}

    virtual void generateDecorations(const State& state, Array_<DecorativeGeometry>& geometry) {
        const Vec3 frcColors[] = {Red,Orange,Cyan};
        const Vec3 momColors[] = {Blue,Green,Purple};
        m_system.realize(state, Stage::Velocity);

        const int ncont = m_compliant.getNumContactForces(state);
        for (int i=0; i < ncont; ++i) {
            const ContactForce& force = m_compliant.getContactForce(state,i);
            const ContactId     id    = force.getContactId();
            printf("viz contact %d: id=%d\n", i, (int)id);
            const Vec3& frc = force.getForceOnSurface2()[1];
            const Vec3& mom = force.getForceOnSurface2()[0];
            Real  frcMag = frc.norm(), momMag=mom.norm();
            int frcThickness = 1, momThickness = 1;
            Real frcScale = ForceScale, momScale = ForceScale;
            while (frcMag > 10)
                frcThickness++, frcScale /= 10, frcMag /= 10;
            while (momMag > 10)
                momThickness++, momScale /= 10, momMag /= 10;
            DecorativeLine frcLine(force.getContactPoint(),
                force.getContactPoint() + frcScale*frc);
            DecorativeLine momLine(force.getContactPoint(),
                force.getContactPoint() + momScale*mom);
            frcLine.setColor(frcColors[id%3]);
            momLine.setColor(momColors[id%3]);
            frcLine.setLineThickness(2*frcThickness);
            momLine.setLineThickness(2*momThickness);
            geometry.push_back(frcLine);
            geometry.push_back(momLine);
        }
    }
private:
    const MultibodySystem&              m_system;
    const CompliantContactSubsystem&    m_compliant;
};

class MyReporter : public PeriodicEventReporter {
public:
    MyReporter(const MultibodySystem& system,
               const CompliantContactSubsystem& complCont,
               Real reportInterval)
    :   PeriodicEventReporter(reportInterval), m_system(system),
        m_compliant(complCont)
    {}

    ~MyReporter() {}

    void handleEvent(const State& state) const {
        m_system.realize(state, Stage::Dynamics);
        cout << state.getTime() << ": E = " << m_system.calcEnergy(state)
             << " Ediss=" << m_compliant.getDissipatedEnergy(state)
             << " E+Ediss=" << m_system.calcEnergy(state)
                               +m_compliant.getDissipatedEnergy(state)
             << endl;
        const int ncont = m_compliant.getNumContactForces(state);
        cout << "Num contacts: " << m_compliant.getNumContactForces(state) << endl;
        for (int i=0; i < ncont; ++i) {
            const ContactForce& force = m_compliant.getContactForce(state,i);
            //cout << force;
        }

        saveEm.push_back(state);
    }
private:
    const MultibodySystem&           m_system;
    const CompliantContactSubsystem& m_compliant;
};

int main() {
  try
  { std::cout << "Current working directory: "
              << Pathname::getCurrentWorkingDirectory() << std::endl;

    // Create the system.

    MultibodySystem         system; system.setUseUniformBackground(true);
    SimbodyMatterSubsystem  matter(system);
    GeneralForceSubsystem   forces(system);
    Force::UniformGravity   gravity(forces, matter, 0*Vec3(2, -9.8, 0));

    ContactTrackerSubsystem  tracker(system);
    CompliantContactSubsystem contactForces(system, tracker);
    contactForces.setTrackDissipatedEnergy(true);

    GeneralContactSubsystem OLDcontact(system);
    const ContactSetIndex OLDcontactSet = OLDcontact.createContactSet();

    contactForces.setTransitionVelocity(1e-3);

    std::ifstream meshFile1, meshFile2;
    PolygonalMesh femurMesh;
    meshFile1.open("ContactBigMeshes_Femur.obj");
    femurMesh.loadObjFile(meshFile1); meshFile1.close();
    PolygonalMesh patellaMesh;
    meshFile2.open("ContactBigMeshes_Patella.obj");
    patellaMesh.loadObjFile(meshFile2); meshFile2.close();

    ContactGeometry::TriangleMesh femurTri(femurMesh);
    ContactGeometry::TriangleMesh patellaTri(patellaMesh);

    DecorativeMesh showFemur(femurTri.createPolygonalMesh());
    Array_<DecorativeLine> femurNormals;
    const Real NormalLength = .02;
    //for (int fx=0; fx < femurTri.getNumFaces(); ++fx)
    //    femurNormals.push_back(
    //    DecorativeLine(femurTri.findCentroid(fx),
    //                   femurTri.findCentroid(fx)
    //                       + NormalLength*femurTri.getFaceNormal(fx)));

    DecorativeMesh showPatella(patellaTri.createPolygonalMesh());
    Array_<DecorativeLine> patellaNormals;
    //for (int fx=0; fx < patellaTri.getNumFaces(); ++fx)
    //    patellaNormals.push_back(
    //    DecorativeLine(patellaTri.findCentroid(fx),
    //                   patellaTri.findCentroid(fx)
    //                       + NormalLength*patellaTri.getFaceNormal(fx)));

    // This transform has the meshes close enough that their OBBs overlap
    // but in the end none of the faces are touching.
    const Transform X_FP(
        Rotation(Mat33( 0.97107625831404454, 0.23876955530133021, 0,
                       -0.23876955530133021, 0.97107625831404454, 0,
                        0,                   0,                   1), true),
        Vec3(0.057400580865008571, 0.43859170879135373,
             -0.00016506240185135300)
        );

    const Real fFac =1; // to turn off friction
    const Real fDis = .5*0.2; // to turn off dissipation
    const Real fVis =  .1*.1; // to turn off viscous friction
    const Real fK = 100*1e6; // pascals

    // Put femur on ground at origin
    matter.Ground().updBody().addDecoration(Vec3(0,0,0),
        showFemur.setColor(Cyan).setOpacity(.2));
    matter.Ground().updBody().addContactSurface(Vec3(0,0,0),
        ContactSurface(femurTri,
            ContactMaterial(fK*.01,fDis*.9,fFac*.8,fFac*.7,fVis*10),
            .01 /*thickness*/));

    Body::Rigid patellaBody(MassProperties(1.0, Vec3(0), Inertia(1)));
    patellaBody.addDecoration(Transform(),
        showPatella.setColor(Red).setOpacity(.2));
    patellaBody.addContactSurface(Transform(),
        ContactSurface(patellaTri,
            ContactMaterial(fK*.001,fDis*.9,fFac*.8,fFac*.7,fVis*10),
            .01 /*thickness*/));

    MobilizedBody::Free patella(matter.Ground(), Transform(Vec3(0)),
                                patellaBody,    Transform(Vec3(0)));

    //// The old way ...
    //OLDcontact.addBody(OLDcontactSet, ball,
    //    pyramid, Transform());

    //OLDcontact.addBody(OLDcontactSet, matter.updGround(),
    //    ContactGeometry::HalfSpace(), Transform(R_xdown, Vec3(0,-3,0)));
    //ElasticFoundationForce ef(forces, OLDcontact, OLDcontactSet);
    //Real stiffness = 1e6, dissipation = 0.01, us = 0.1,
    //    ud = 0.05, uv = 0.01, vt = 0.01;
    ////Real stiffness = 1e6, dissipation = 0.1, us = 0.8,
    ////    ud = 0.7, uv = 0.01, vt = 0.01;

    //ef.setBodyParameters(ContactSurfaceIndex(0),
    //    stiffness, dissipation, us, ud, uv);
    //ef.setTransitionVelocity(vt);
    //// end of old way.

    Visualizer viz(system);
    Visualizer::Reporter& reporter = *new Visualizer::Reporter(viz, ReportInterval);
    viz.addDecorationGenerator(new ForceArrowGenerator(system,contactForces));
    MyReporter& myRep = *new MyReporter(system,contactForces,ReportInterval);

    system.addEventReporter(&myRep);
    system.addEventReporter(&reporter);

    // Initialize the system and state.

    system.realizeTopology();
    State state = system.getDefaultState();

    viz.report(state);
    printf("Reference state -- hit ENTER\n");
    cout << "t=" << state.getTime()
         << " q=" << patella.getQAsVector(state)
         << " u=" << patella.getUAsVector(state)
         << endl;
    char c=getchar();

    patella.setQToFitTransform(state, ~X_FP);
    viz.report(state);
    printf("Initial state -- hit ENTER\n");
    cout << "t=" << state.getTime()
         << " q=" << patella.getQAsVector(state)
         << " u=" << patella.getUAsVector(state)
         << endl;
    c=getchar();

    // Simulate it.
    const clock_t start = clock();

    RungeKutta3Integrator integ(system);
    TimeStepper ts(system, integ);
    ts.initialize(state);
    ts.stepTo(2.0);

    const double timeInSec = (double)(clock()-start)/CLOCKS_PER_SEC;
    const int evals = integ.getNumRealizations();
    cout << "Done -- took " << integ.getNumStepsTaken() << " steps in " <<
        timeInSec << "s for " << ts.getTime() << "s sim (avg step="
        << (1000*ts.getTime())/integ.getNumStepsTaken() << "ms) "
        << (1000*ts.getTime())/evals << "ms/eval\n";

    printf("Using Integrator %s at accuracy %g:\n",
        integ.getMethodName(), integ.getAccuracyInUse());
    printf("# STEPS/ATTEMPTS = %d/%d\n", integ.getNumStepsTaken(), integ.getNumStepsAttempted());
    printf("# ERR TEST FAILS = %d\n", integ.getNumErrorTestFailures());
    printf("# REALIZE/PROJECT = %d/%d\n", integ.getNumRealizations(), integ.getNumProjections());

    while(true) {
        for (int i=0; i < (int)saveEm.size(); ++i) {
            viz.report(saveEm[i]);
        }
        getchar();
    }

  } catch (const std::exception& e) {
    std::printf("EXCEPTION THROWN: %s\n", e.what());
    exit(1);

  } catch (...) {
    std::printf("UNKNOWN EXCEPTION THROWN\n");
    exit(1);
  }

    return 0;
}


text:
/**
 * Created by david on 8/5/16.
 */
let jobService;
let Kayz = require('../../core');
var Config = require('../../config/config');
function JobHandler(jobs) {
    jobService = jobs;
}

JobHandler.prototype.list = (req, res, next) => {
    let skip = 0;
    let limit = 10;
    let queryData = {};
    if (req.query.skip !== undefined){
        skip = parseInt(req.query.skip);
    }
    if (req.query.limit !== undefined){
        limit = parseInt(req.query.limit);
    }
    if (req.query.isActive !== undefined){
        queryData.isActive = req.query.isActive;
    }
    return jobService.find(queryData)
        .then(function(jobs){
            jobs = jobs.slice(skip, skip + limit);
            res.status(200).send(jobs)
        })
        .catch(function(err){
            res.status(500).send({
                'message': err.message
            })
        });
};

JobHandler.prototype.create = (req, res, next) => {
    if (req.body.configuration == undefined){
        res.status(500).send({
            'message': 'there is no configuration file'
        });
        return;
    }
    var conf = JSON.parse(req.body.configuration);
    let bus = new Kayz.Bus(Config.redis);
    bus.online()
        .then(function(){
            return bus.publishTo(Kayz.Channels.Console, {
                'type': 'run_job',
                'config': conf
            })
        })
        .then(function(){
            res.status(200).send()
        })
        .catch(function(err){
            res.status(500).send({
                'message': 'internal server error'
            })
        })
};

JobHandler.prototype.change_state = (req, res, next) => {
    jobService.findById(req.params.jobId)
        .then(function(job){
            if (job == undefined){
                res.status(404).send({
                    'message': 'there isn\'t job with that id'
                });
                return;
            }
            let bus = new Kayz.Bus(Config.redis);
            bus.online()
                .then(function(){
                    return bus.publishTo(Kayz.Channels.Console, {
                        'type': 'stop_job',
                        'name': job.name
                    })
                })
                .then(function(){
                    job.isActive = false;
                    return job.save();
                })
                .then(function(job){
                    res.status(200).send();
                })
                .catch(function(err){
                    res.status(500).send({
                        'message': 'internal server error'
                    })
                })
        })
};
module.exports = JobHandler;


text:
/*************************************************************************/
/*  gdscript_utility_functions.cpp                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "gdscript_utility_functions.h"

#include "core/io/resource_loader.h"
#include "core/object/class_db.h"
#include "core/object/method_bind.h"
#include "core/object/object.h"
#include "core/templates/oa_hash_map.h"
#include "core/templates/vector.h"
#include "gdscript.h"

#ifdef DEBUG_ENABLED

#define VALIDATE_ARG_COUNT(m_count)                                         \
	if (p_arg_count < m_count) {                                            \
		r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;  \
		r_error.argument = m_count;                                         \
		r_error.expected = m_count;                                         \
		*r_ret = Variant();                                                 \
		return;                                                             \
	}                                                                       \
	if (p_arg_count > m_count) {                                            \
		r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; \
		r_error.argument = m_count;                                         \
		r_error.expected = m_count;                                         \
		*r_ret = Variant();                                                 \
		return;                                                             \
	}

#define VALIDATE_ARG_INT(m_arg)                                           \
	if (p_args[m_arg]->get_type() != Variant::INT) {                      \
		r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; \
		r_error.argument = m_arg;                                         \
		r_error.expected = Variant::INT;                                  \
		*r_ret = Variant();                                               \
		return;                                                           \
	}

#define VALIDATE_ARG_NUM(m_arg)                                           \
	if (!p_args[m_arg]->is_num()) {                                       \
		r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; \
		r_error.argument = m_arg;                                         \
		r_error.expected = Variant::FLOAT;                                \
		*r_ret = Variant();                                               \
		return;                                                           \
	}

#else

#define VALIDATE_ARG_COUNT(m_count)
#define VALIDATE_ARG_INT(m_arg)
#define VALIDATE_ARG_NUM(m_arg)

#endif

struct GDScriptUtilityFunctionsDefinitions {
	static inline void convert(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(2);
		VALIDATE_ARG_INT(1);
		int type = *p_args[1];
		if (type < 0 || type >= Variant::VARIANT_MAX) {
			*r_ret = RTR("Invalid type argument to convert(), use TYPE_* constants.");
			r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
			r_error.argument = 0;
			r_error.expected = Variant::INT;
			return;

		} else {
			Variant::construct(Variant::Type(type), *r_ret, p_args, 1, r_error);
		}
	}

	static inline void type_exists(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(1);
		*r_ret = ClassDB::class_exists(*p_args[0]);
	}

	static inline void _char(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(1);
		VALIDATE_ARG_INT(0);
		char32_t result[2] = { *p_args[0], 0 };
		*r_ret = String(result);
	}

	static inline void str(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		if (p_arg_count < 1) {
			r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
			r_error.argument = 1;
			*r_ret = Variant();
			return;
		}

		String str;
		for (int i = 0; i < p_arg_count; i++) {
			String os = p_args[i]->operator String();

			if (i == 0) {
				str = os;
			} else {
				str += os;
			}
		}
		*r_ret = str;
	}

	static inline void range(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		switch (p_arg_count) {
			case 0: {
				r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
				r_error.argument = 1;
				r_error.expected = 1;
				*r_ret = Variant();
			} break;
			case 1: {
				VALIDATE_ARG_NUM(0);
				int count = *p_args[0];
				Array arr;
				if (count <= 0) {
					*r_ret = arr;
					return;
				}
				Error err = arr.resize(count);
				if (err != OK) {
					r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
					*r_ret = Variant();
					return;
				}

				for (int i = 0; i < count; i++) {
					arr[i] = i;
				}

				*r_ret = arr;
			} break;
			case 2: {
				VALIDATE_ARG_NUM(0);
				VALIDATE_ARG_NUM(1);

				int from = *p_args[0];
				int to = *p_args[1];

				Array arr;
				if (from >= to) {
					*r_ret = arr;
					return;
				}
				Error err = arr.resize(to - from);
				if (err != OK) {
					r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
					*r_ret = Variant();
					return;
				}
				for (int i = from; i < to; i++) {
					arr[i - from] = i;
				}
				*r_ret = arr;
			} break;
			case 3: {
				VALIDATE_ARG_NUM(0);
				VALIDATE_ARG_NUM(1);
				VALIDATE_ARG_NUM(2);

				int from = *p_args[0];
				int to = *p_args[1];
				int incr = *p_args[2];
				if (incr == 0) {
					*r_ret = RTR("Step argument is zero!");
					r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
					return;
				}

				Array arr;
				if (from >= to && incr > 0) {
					*r_ret = arr;
					return;
				}
				if (from <= to && incr < 0) {
					*r_ret = arr;
					return;
				}

				// Calculate how many.
				int count = 0;
				if (incr > 0) {
					count = ((to - from - 1) / incr) + 1;
				} else {
					count = ((from - to - 1) / -incr) + 1;
				}

				Error err = arr.resize(count);

				if (err != OK) {
					r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
					*r_ret = Variant();
					return;
				}

				if (incr > 0) {
					int idx = 0;
					for (int i = from; i < to; i += incr) {
						arr[idx++] = i;
					}
				} else {
					int idx = 0;
					for (int i = from; i > to; i += incr) {
						arr[idx++] = i;
					}
				}

				*r_ret = arr;
			} break;
			default: {
				r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
				r_error.argument = 3;
				r_error.expected = 3;
				*r_ret = Variant();

			} break;
		}
	}

	static inline void load(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(1);
		if (p_args[0]->get_type() != Variant::STRING) {
			r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
			r_error.argument = 0;
			r_error.expected = Variant::STRING;
			*r_ret = Variant();
		} else {
			*r_ret = ResourceLoader::load(*p_args[0]);
		}
	}

	static inline void inst2dict(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(1);

		if (p_args[0]->get_type() == Variant::NIL) {
			*r_ret = Variant();
		} else if (p_args[0]->get_type() != Variant::OBJECT) {
			r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
			r_error.argument = 0;
			*r_ret = Variant();
		} else {
			Object *obj = *p_args[0];
			if (!obj) {
				*r_ret = Variant();

			} else if (!obj->get_script_instance() || obj->get_script_instance()->get_language() != GDScriptLanguage::get_singleton()) {
				r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::DICTIONARY;
				*r_ret = RTR("Not a script with an instance");
				return;
			} else {
				GDScriptInstance *ins = static_cast<GDScriptInstance *>(obj->get_script_instance());
				Ref<GDScript> base = ins->get_script();
				if (base.is_null()) {
					r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
					r_error.argument = 0;
					r_error.expected = Variant::DICTIONARY;
					*r_ret = RTR("Not based on a script");
					return;
				}

				GDScript *p = base.ptr();
				Vector<StringName> sname;

				while (p->_owner) {
					sname.push_back(p->name);
					p = p->_owner;
				}
				sname.reverse();

				if (!p->path.is_resource_file()) {
					r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
					r_error.argument = 0;
					r_error.expected = Variant::DICTIONARY;
					*r_ret = Variant();

					*r_ret = RTR("Not based on a resource file");

					return;
				}

				NodePath cp(sname, Vector<StringName>(), false);

				Dictionary d;
				d["@subpath"] = cp;
				d["@path"] = p->get_path();

				for (const KeyValue<StringName, GDScript::MemberInfo> &E : base->member_indices) {
					if (!d.has(E.key)) {
						d[E.key] = ins->members[E.value.index];
					}
				}
				*r_ret = d;
			}
		}
	}

	static inline void dict2inst(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(1);

		if (p_args[0]->get_type() != Variant::DICTIONARY) {
			r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
			r_error.argument = 0;
			r_error.expected = Variant::DICTIONARY;
			*r_ret = Variant();

			return;
		}

		Dictionary d = *p_args[0];

		if (!d.has("@path")) {
			r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
			r_error.argument = 0;
			r_error.expected = Variant::OBJECT;
			*r_ret = RTR("Invalid instance dictionary format (missing @path)");

			return;
		}

		Ref<Script> scr = ResourceLoader::load(d["@path"]);
		if (!scr.is_valid()) {
			r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
			r_error.argument = 0;
			r_error.expected = Variant::OBJECT;
			*r_ret = RTR("Invalid instance dictionary format (can't load script at @path)");
			return;
		}

		Ref<GDScript> gdscr = scr;

		if (!gdscr.is_valid()) {
			r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
			r_error.argument = 0;
			r_error.expected = Variant::OBJECT;
			*r_ret = Variant();
			*r_ret = RTR("Invalid instance dictionary format (invalid script at @path)");
			return;
		}

		NodePath sub;
		if (d.has("@subpath")) {
			sub = d["@subpath"];
		}

		for (int i = 0; i < sub.get_name_count(); i++) {
			gdscr = gdscr->subclasses[sub.get_name(i)];
			if (!gdscr.is_valid()) {
				r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::OBJECT;
				*r_ret = Variant();
				*r_ret = RTR("Invalid instance dictionary (invalid subclasses)");
				return;
			}
		}
		*r_ret = gdscr->_new(nullptr, -1 /*skip initializer*/, r_error);

		if (r_error.error != Callable::CallError::CALL_OK) {
			*r_ret = Variant();
			return;
		}

		GDScriptInstance *ins = static_cast<GDScriptInstance *>(static_cast<Object *>(*r_ret)->get_script_instance());
		Ref<GDScript> gd_ref = ins->get_script();

		for (KeyValue<StringName, GDScript::MemberInfo> &E : gd_ref->member_indices) {
			if (d.has(E.key)) {
				ins->members.write[E.value.index] = d[E.key];
			}
		}
	}

	static inline void Color8(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		if (p_arg_count < 3) {
			r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
			r_error.argument = 3;
			*r_ret = Variant();
			return;
		}
		if (p_arg_count > 4) {
			r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
			r_error.argument = 4;
			*r_ret = Variant();
			return;
		}

		VALIDATE_ARG_INT(0);
		VALIDATE_ARG_INT(1);
		VALIDATE_ARG_INT(2);

		Color color((int64_t)*p_args[0] / 255.0f, (int64_t)*p_args[1] / 255.0f, (int64_t)*p_args[2] / 255.0f);

		if (p_arg_count == 4) {
			VALIDATE_ARG_INT(3);
			color.a = (int64_t)*p_args[3] / 255.0f;
		}

		*r_ret = color;
	}

	static inline void print_debug(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		String str;
		for (int i = 0; i < p_arg_count; i++) {
			str += p_args[i]->operator String();
		}

		if (Thread::get_caller_id() == Thread::get_main_id()) {
			ScriptLanguage *script = GDScriptLanguage::get_singleton();
			if (script->debug_get_stack_level_count() > 0) {
				str += "\n   At: " + script->debug_get_stack_level_source(0) + ":" + itos(script->debug_get_stack_level_line(0)) + ":" + script->debug_get_stack_level_function(0) + "()";
			}
		} else {
			str += "\n   At: Cannot retrieve debug info outside the main thread. Thread ID: " + itos(Thread::get_caller_id());
		}

		print_line(str);
		*r_ret = Variant();
	}

	static inline void print_stack(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(0);
		if (Thread::get_caller_id() != Thread::get_main_id()) {
			print_line("Cannot retrieve debug info outside the main thread. Thread ID: " + itos(Thread::get_caller_id()));
			return;
		}

		ScriptLanguage *script = GDScriptLanguage::get_singleton();
		for (int i = 0; i < script->debug_get_stack_level_count(); i++) {
			print_line("Frame " + itos(i) + " - " + script->debug_get_stack_level_source(i) + ":" + itos(script->debug_get_stack_level_line(i)) + " in function '" + script->debug_get_stack_level_function(i) + "'");
		};
		*r_ret = Variant();
	}

	static inline void get_stack(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(0);
		if (Thread::get_caller_id() != Thread::get_main_id()) {
			*r_ret = Array();
			return;
		}

		ScriptLanguage *script = GDScriptLanguage::get_singleton();
		Array ret;
		for (int i = 0; i < script->debug_get_stack_level_count(); i++) {
			Dictionary frame;
			frame["source"] = script->debug_get_stack_level_source(i);
			frame["function"] = script->debug_get_stack_level_function(i);
			frame["line"] = script->debug_get_stack_level_line(i);
			ret.push_back(frame);
		};
		*r_ret = ret;
	}

	static inline void len(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
		VALIDATE_ARG_COUNT(1);
		switch (p_args[0]->get_type()) {
			case Variant::STRING: {
				String d = *p_args[0];
				*r_ret = d.length();
			} break;
			case Variant::DICTIONARY: {
				Dictionary d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::ARRAY: {
				Array d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_BYTE_ARRAY: {
				Vector<uint8_t> d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_INT32_ARRAY: {
				Vector<int32_t> d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_INT64_ARRAY: {
				Vector<int64_t> d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_FLOAT32_ARRAY: {
				Vector<float> d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_FLOAT64_ARRAY: {
				Vector<double> d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_STRING_ARRAY: {
				Vector<String> d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_VECTOR2_ARRAY: {
				Vector<Vector2> d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_VECTOR3_ARRAY: {
				Vector<Vector3> d = *p_args[0];
				*r_ret = d.size();
			} break;
			case Variant::PACKED_COLOR_ARRAY: {
				Vector<Color> d = *p_args[0];
				*r_ret = d.size();
			} break;
			default: {
				r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
				r_error.argument = 0;
				r_error.expected = Variant::NIL;
				*r_ret = vformat(RTR("Value of type '%s' can't provide a length."), Variant::get_type_name(p_args[0]->get_type()));
			}
		}
	}
};

struct GDScriptUtilityFunctionInfo {
	GDScriptUtilityFunctions::FunctionPtr function;
	MethodInfo info;
	bool is_constant = false;
};

static OAHashMap<StringName, GDScriptUtilityFunctionInfo> utility_function_table;
static List<StringName> utility_function_name_table;

static void _register_function(const String &p_name, const MethodInfo &p_method_info, GDScriptUtilityFunctions::FunctionPtr p_function, bool p_is_const) {
	StringName sname(p_name);

	ERR_FAIL_COND(utility_function_table.has(sname));

	GDScriptUtilityFunctionInfo function;
	function.function = p_function;
	function.info = p_method_info;
	function.is_constant = p_is_const;

	utility_function_table.insert(sname, function);
	utility_function_name_table.push_back(sname);
}

#define REGISTER_FUNC(m_func, m_is_const, m_return_type, ...)                                    \
	{                                                                                \
		String name(#m_func);                                                                    \
		if (name.begins_with("_")) {                                                             \
			name = name.substr(1, name.length() - 1);                                            \
		}                                                                                \
		MethodInfo info = MethodInfo(name, __VA_ARGS__);                                         \
		info.return_val.type = m_return_type;                                                    \
		_register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
	}

#define REGISTER_FUNC_NO_ARGS(m_func, m_is_const, m_return_type)                                 \
	{                                                                                \
		String name(#m_func);                                                                    \
		if (name.begins_with("_")) {                                                             \
			name = name.substr(1, name.length() - 1);                                            \
		}                                                                                \
		MethodInfo info = MethodInfo(name);                                                      \
		info.return_val.type = m_return_type;                                                    \
		_register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
	}

#define REGISTER_VARARG_FUNC(m_func, m_is_const, m_return_type)                                  \
	{                                                                                \
		String name(#m_func);                                                                    \
		if (name.begins_with("_")) {                                                             \
			name = name.substr(1, name.length() - 1);                                            \
		}                                                                                \
		MethodInfo info = MethodInfo(name);                                                      \
		info.return_val.type = m_return_type;                                                    \
		info.flags |= METHOD_FLAG_VARARG;                                                        \
		_register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
	}

#define REGISTER_VARIANT_FUNC(m_func, m_is_const, ...)                                           \
	{                                                                                \
		String name(#m_func);                                                                    \
		if (name.begins_with("_")) {                                                             \
			name = name.substr(1, name.length() - 1);                                            \
		}                                                                                \
		MethodInfo info = MethodInfo(name, __VA_ARGS__);                                         \
		info.return_val.type = Variant::NIL;                                                     \
		info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;                                  \
		_register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
	}

#define REGISTER_CLASS_FUNC(m_func, m_is_const, m_return_type, ...)                              \
	{                                                                                \
		String name(#m_func);                                                                    \
		if (name.begins_with("_")) {                                                             \
			name = name.substr(1, name.length() - 1);                                            \
		}                                                                                \
		MethodInfo info = MethodInfo(name, __VA_ARGS__);                                         \
		info.return_val.type = Variant::OBJECT;                                                  \
		info.return_val.hint = PROPERTY_HINT_RESOURCE_TYPE;                                      \
		info.return_val.class_name = m_return_type;                                              \
		_register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
	}

#define REGISTER_FUNC_DEF(m_func, m_is_const, m_default, m_return_type, ...)                     \
	{                                                                                \
		String name(#m_func);                                                                    \
		if (name.begins_with("_")) {                                                             \
			name = name.substr(1, name.length() - 1);                                            \
		}                                                                                \
		MethodInfo info = MethodInfo(name, __VA_ARGS__);                                         \
		info.return_val.type = m_return_type;                                                    \
		info.default_arguments.push_back(m_default);                                             \
		_register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
	}

#define ARG(m_name, m_type) \
	PropertyInfo(m_type, m_name)

#define VARARG(m_name) \
	PropertyInfo(Variant::NIL, m_name, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT)

void GDScriptUtilityFunctions::register_functions() {
	REGISTER_VARIANT_FUNC(convert, true, VARARG("what"), ARG("type", Variant::INT));
	REGISTER_FUNC(type_exists, true, Variant::BOOL, ARG("type", Variant::STRING_NAME));
	REGISTER_FUNC(_char, true, Variant::STRING, ARG("char", Variant::INT));
	REGISTER_VARARG_FUNC(str, true, Variant::STRING);
	REGISTER_VARARG_FUNC(range, false, Variant::ARRAY);
	REGISTER_CLASS_FUNC(load, false, "Resource", ARG("path", Variant::STRING));
	REGISTER_FUNC(inst2dict, false, Variant::DICTIONARY, ARG("instance", Variant::OBJECT));
	REGISTER_FUNC(dict2inst, false, Variant::OBJECT, ARG("dictionary", Variant::DICTIONARY));
	REGISTER_FUNC_DEF(Color8, true, 255, Variant::COLOR, ARG("r8", Variant::INT), ARG("g8", Variant::INT), ARG("b8", Variant::INT), ARG("a8", Variant::INT));
	REGISTER_VARARG_FUNC(print_debug, false, Variant::NIL);
	REGISTER_FUNC_NO_ARGS(print_stack, false, Variant::NIL);
	REGISTER_FUNC_NO_ARGS(get_stack, false, Variant::ARRAY);
	REGISTER_FUNC(len, true, Variant::INT, VARARG("var"));
}

void GDScriptUtilityFunctions::unregister_functions() {
	utility_function_name_table.clear();
	utility_function_table.clear();
}

GDScriptUtilityFunctions::FunctionPtr GDScriptUtilityFunctions::get_function(const StringName &p_function) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, nullptr);
	return info->function;
}

bool GDScriptUtilityFunctions::has_function_return_value(const StringName &p_function) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, false);
	return info->info.return_val.type != Variant::NIL || bool(info->info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT);
}

Variant::Type GDScriptUtilityFunctions::get_function_return_type(const StringName &p_function) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, Variant::NIL);
	return info->info.return_val.type;
}

StringName GDScriptUtilityFunctions::get_function_return_class(const StringName &p_function) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, StringName());
	return info->info.return_val.class_name;
}

Variant::Type GDScriptUtilityFunctions::get_function_argument_type(const StringName &p_function, int p_arg) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, Variant::NIL);
	ERR_FAIL_COND_V(p_arg >= info->info.arguments.size(), Variant::NIL);
	return info->info.arguments[p_arg].type;
}

int GDScriptUtilityFunctions::get_function_argument_count(const StringName &p_function, int p_arg) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, 0);
	return info->info.arguments.size();
}

bool GDScriptUtilityFunctions::is_function_vararg(const StringName &p_function) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, false);
	return (bool)(info->info.flags & METHOD_FLAG_VARARG);
}

bool GDScriptUtilityFunctions::is_function_constant(const StringName &p_function) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, false);
	return info->is_constant;
}

bool GDScriptUtilityFunctions::function_exists(const StringName &p_function) {
	return utility_function_table.has(p_function);
}

void GDScriptUtilityFunctions::get_function_list(List<StringName> *r_functions) {
	for (const StringName &E : utility_function_name_table) {
		r_functions->push_back(E);
	}
}

MethodInfo GDScriptUtilityFunctions::get_function_info(const StringName &p_function) {
	GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
	ERR_FAIL_COND_V(!info, MethodInfo());
	return info->info;
}


text:
#include <Windows.h>
#include <tchar.h>
#include <commctrl.h>
#include <string>
#include <list>
#include <stdarg.h>
#include <shlwapi.h>

typedef std::basic_string<TCHAR> TSTRING, *PTSTRING;
typedef const TSTRING CTSTRING, *PCTSTRING;

typedef std::list<TSTRING> TSTRINGLIST, *PTSTRINGLIST;
typedef TSTRINGLIST::iterator TSTRINGLISTIT, *PTSTRINGLISTIT;

#endif // _WLIB_STDAFX_H


text:
Example to illustrate the usage of bittools
-------------------------------------------

``BinPyBits`` is a class inheriting from the ``bitstring.BitArray`` class. It will be used for efficient manipulation / handling of Bit vectors.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code:: python

    from BinPy import *

    # Initializing a BinPyBits object

    bit_vector = BinPyBits(5)
.. code:: python

    # By default all BinPyBits objects are not signed

    bit_vector.signed

.. parsed-literal::

    False

.. code:: python

    # Getting the decimal value

    bit_vector.uint

.. parsed-literal::

    5

.. code:: python

    # Getting the binary string

    bit_vector.bin

.. parsed-literal::

    '101'

.. code:: python

    # Do not use int with unsigned BinPyBits objects

    bit_vector.int

.. parsed-literal::

    -3

.. code:: python

    # This returns -3 since '101' ==> -3 ( 2's Complement representation )

    # You could use :

    int_value = bit_vector.int if bit_vector.signed else bit_vector.uint

    print int_value

.. parsed-literal::

    5

.. code:: python

    # Creating a BinPyBits object using binary string

    bit_vector = BinPyBits('1111', signed=False)

    # Converting to decimal

    int_value = bit_vector.int if bit_vector.signed else bit_vector.uint

    print int_value

.. parsed-literal::

    15

.. code:: python

    # Creating a signed BinPyBits

    bit_vector = BinPyBits('1111', signed=True)

    # Converting to decimal

    int_value = bit_vector.int if bit_vector.signed else bit_vector.uint

    print int_value

.. parsed-literal::

    -1

.. code:: python

    # Converting to hex

    bit_vector.hex

.. parsed-literal::

    'f'

Refer `the documentation of
bittstring <https://pypi.python.org/pypi/bitstring/3.1.3>`__ to discover
additional functionality.

.. code:: python

    # The speciality of BinPyBits lies in the fact that it can be initialized from various types of inputs
    # Except for the initialization, the rest of the functionalities remain similar to that of the bitstring.BitArray

    # Initializing a signed value using - sign

    bit_vector = BinPyBits('-1111', signed=True)

    print bit_vector.int

.. parsed-literal::

    -15


text:
This program aims to validate the correctness of [crossing numbers](http://en.wikipedia.org/wiki/Crossing_number_(graph_theory)).

[![Build Status](https://travis-ci.org/TiloW/ocm-validator.svg?branch=master)](https://travis-ci.org/TiloW/ocm-validator)
[![Coverage Status](https://coveralls.io/repos/TiloW/ocm-validator/badge.svg?branch=master)](https://coveralls.io/r/TiloW/ocm-validator?branch=master)
[![SonarQube](https://img.shields.io/badge/sonarqube-v5.1-brightgreen.svg?style=flat)](http://www.sonarqube.org/)
[![checkstyle](https://img.shields.io/badge/checkstyle-v6.6-brightgreen.svg?style=flat)](https://github.com/checkstyle/checkstyle)

## Purpose
Given a graph `G` and a set of [Kuratowski subdivisions](http://en.wikipedia.org/wiki/Kuratowski%27s_theorem) it can be shown that the crossing number of `G` exceeds some lower bound using linear programming.
Existing algorithms are able to identify a small subset of the exponentially large set of Kuratowski subdivisions, such that the bound grows tight.
However, all implementations lack the required readability to comprehend the supposed proof.

The validator will be used to track down bugs in the existing implementations and to validate generated proofs. Sufficient readability is a major objective.

## Requirements
You need one of the following linear program solvers available on your command line:
  * `gurobi_cl` (http://www.gurobi.com)
  * `scip` (http://scip.zib.de)
  * `cplex`

Java Runtime Environment 7 or higher is required to run the program.

## References
This program is part of a master thesis developed at [Osnabrück University](http://www.uni-osnabrueck.de/en/home.html) ([Algorithm Engineering group](http://www-lehre.informatik.uni-osnabrueck.de/theoinf/index/start)).
The [**O**pen **G**raph **D**rawing **F**ramework](http://ogdf.net) is utilized for extracting the set of Kuratowski subdivions.
My work is based on [Computing Crossing Numbers](http://www.ae.uni-jena.de/alenmedia/de/dokumente/ComputingCrossingNumbers_PhDthesis_Chimani_pdf.pdf) PhD Thesis by M. Chimani, Technical University Dortmund, 2008
and [A New Approach to Exact Crossing Minimization](http://ls11-www.cs.uni-dortmund.de/people/chimani/files/oocm-preprint.pdf) by M. Chimani, P. Mutzel, I. Bomze, 16th Annual European Symposium on Algorithms 2008, Karlsruhe (ESA08), LNCS 5193, pp. 284-296, Springer, 2008.

## License
Copyright (c) 2015 Tilo Wiedera

This program is released under the [MIT License](https://github.com/TiloW/ocm-validator/blob/master/LICENSE.txt).


text:
namespace Incoding.UnitTest.MvcContribGroup
{
    #region << Using >>

    using Incoding.Extensions;
    using Incoding.MvcContrib;
    using Machine.Specifications;

    #endregion

    [Subject(typeof(HtmlType))]
    public class When_web_enum_convert
    {
        It should_be_verify_ToStringHtmlContent = () =>
                                                      {
                                                          HtmlType.TextCss.ToLocalization().ShouldEqual("text/css");
                                                          HtmlType.TextHtml.ToLocalization().ShouldEqual("text/html");
                                                          HtmlType.TextXml.ToLocalization().ShouldEqual("text/xml");
                                                          HtmlType.TextJavaScript.ToLocalization().ShouldEqual("text/javascript");
                                                          HtmlType.TextTemplate.ToLocalization().ShouldEqual("text/template");
                                                      };
    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/****************************************************************************
 *  SSL client program that tests  a server for proper operation of SSL2,   *
 *  SSL3, and TLS. Test propder certificate installation.                   *
 *                                                                          *
 *  This code was modified from the SSLSample code also kept in the NSS     *
 *  directory.                                                              *
 ****************************************************************************/

#include <stdio.h>
#include <string.h>

#if defined(XP_UNIX)
#include <unistd.h>
#endif

#include "prerror.h"

#include "pk11func.h"
#include "secmod.h"
#include "secitem.h"

#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>

#include "nspr.h"
#include "plgetopt.h"
#include "prio.h"
#include "prnetdb.h"
#include "nss.h"
#include "secutil.h"
#include "ocsp.h"

#include "vfyserv.h"

#define RD_BUF_SIZE (60 * 1024)

extern int ssl2CipherSuites[];
extern int ssl3CipherSuites[];

GlobalThreadMgr threadMGR;
char *certNickname = NULL;
char *hostName = NULL;
secuPWData  pwdata          = { PW_NONE, 0 };
unsigned short port = 0;
PRBool dumpChain;

static void
Usage(const char *progName)
{
    PRFileDesc *pr_stderr;

    pr_stderr = PR_STDERR;

    PR_fprintf(pr_stderr, "Usage:\n"
               "   %s  [-c ] [-o] [-p port] [-d dbdir] [-w password] [-f pwfile]\n"
               "   \t\t[-C cipher(s)]  [-l <url> -t <nickname> ] hostname",
               progName);
    PR_fprintf (pr_stderr, "\nWhere:\n");
    PR_fprintf (pr_stderr,
                "  %-13s dump server cert chain into files\n",
                "-c");
    PR_fprintf (pr_stderr,
                "  %-13s perform server cert OCSP check\n",
                "-o");
    PR_fprintf (pr_stderr,
                "  %-13s server port to be used\n",
                "-p");
    PR_fprintf (pr_stderr,
                "  %-13s use security databases in \"dbdir\"\n",
                "-d dbdir");
    PR_fprintf (pr_stderr,
                "  %-13s key database password\n",
                "-w password");
    PR_fprintf (pr_stderr,
                "  %-13s token password file\n",
                "-f pwfile");
    PR_fprintf (pr_stderr,
                "  %-13s communication cipher list\n",
                "-C cipher(s)");
    PR_fprintf (pr_stderr,
                "  %-13s OCSP responder location. This location is used to\n"
                "  %-13s check  status  of a server  certificate.  If  not \n"
                "  %-13s specified, location  will  be taken  from the AIA\n"
                "  %-13s server certificate extension.\n",
                "-l url", "", "", "");
    PR_fprintf (pr_stderr,
                "  %-13s OCSP Trusted Responder Cert nickname\n\n",
                "-t nickname");

	exit(1);
}

PRFileDesc *
setupSSLSocket(PRNetAddr *addr)
{
	PRFileDesc         *tcpSocket;
	PRFileDesc         *sslSocket;
	PRSocketOptionData	socketOption;
	PRStatus            prStatus;
	SECStatus           secStatus;

	tcpSocket = PR_NewTCPSocket();
	if (tcpSocket == NULL) {
		errWarn("PR_NewTCPSocket");
	}

	/* Make the socket blocking. */
	socketOption.option	            = PR_SockOpt_Nonblocking;
	socketOption.value.non_blocking = PR_FALSE;

	prStatus = PR_SetSocketOption(tcpSocket, &socketOption);
	if (prStatus != PR_SUCCESS) {
		errWarn("PR_SetSocketOption");
		goto loser;
	}

	/* Import the socket into the SSL layer. */
	sslSocket = SSL_ImportFD(NULL, tcpSocket);
	if (!sslSocket) {
		errWarn("SSL_ImportFD");
		goto loser;
	}

	/* Set configuration options. */
	secStatus = SSL_OptionSet(sslSocket, SSL_SECURITY, PR_TRUE);
	if (secStatus != SECSuccess) {
		errWarn("SSL_OptionSet:SSL_SECURITY");
		goto loser;
	}

	secStatus = SSL_OptionSet(sslSocket, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
	if (secStatus != SECSuccess) {
		errWarn("SSL_OptionSet:SSL_HANDSHAKE_AS_CLIENT");
		goto loser;
	}

	/* Set SSL callback routines. */
	secStatus = SSL_GetClientAuthDataHook(sslSocket,
	                          (SSLGetClientAuthData)myGetClientAuthData,
	                          (void *)certNickname);
	if (secStatus != SECSuccess) {
		errWarn("SSL_GetClientAuthDataHook");
		goto loser;
	}

	secStatus = SSL_AuthCertificateHook(sslSocket,
	                                   (SSLAuthCertificate)myAuthCertificate,
                                       (void *)CERT_GetDefaultCertDB());
	if (secStatus != SECSuccess) {
		errWarn("SSL_AuthCertificateHook");
		goto loser;
	}

	secStatus = SSL_BadCertHook(sslSocket,
	                           (SSLBadCertHandler)myBadCertHandler, NULL);
	if (secStatus != SECSuccess) {
		errWarn("SSL_BadCertHook");
		goto loser;
	}

	secStatus = SSL_HandshakeCallback(sslSocket,
	                                  myHandshakeCallback,
	                                  NULL);
	if (secStatus != SECSuccess) {
		errWarn("SSL_HandshakeCallback");
		goto loser;
	}

	return sslSocket;

loser:

	PR_Close(tcpSocket);
	return NULL;
}

const char requestString[] = {"GET /testfile HTTP/1.0\r\n\r\n" };

SECStatus
handle_connection(PRFileDesc *sslSocket, int connection)
{
	int	countRead = 0;
	PRInt32  numBytes;
	char    *readBuffer;

	readBuffer = PORT_Alloc(RD_BUF_SIZE);
	if (!readBuffer) {
		exitErr("PORT_Alloc");
	}

	/* compose the http request here. */

	numBytes = PR_Write(sslSocket, requestString, strlen(requestString));
	if (numBytes <= 0) {
		errWarn("PR_Write");
		PR_Free(readBuffer);
		readBuffer = NULL;
		return SECFailure;
	}

	/* read until EOF */
	while (PR_TRUE) {
		numBytes = PR_Read(sslSocket, readBuffer, RD_BUF_SIZE);
		if (numBytes == 0) {
			break;	/* EOF */
		}
		if (numBytes < 0) {
			errWarn("PR_Read");
			break;
		}
		countRead += numBytes;
	}

	printSecurityInfo(stderr, sslSocket);

	PR_Free(readBuffer);
	readBuffer = NULL;

	/* Caller closes the socket. */

	fprintf(stderr,
	        "***** Connection %d read %d bytes total.\n",
	        connection, countRead);

	return SECSuccess;	/* success */
}

#define BYTE(n,i) (((i)>>((n)*8))&0xff)

/* one copy of this function is launched in a separate thread for each
** connection to be made.
*/
SECStatus
do_connects(void *a, int connection)
{
	PRNetAddr  *addr = (PRNetAddr *)a;
	PRFileDesc *sslSocket;
	PRHostEnt   hostEntry;
	char        buffer[PR_NETDB_BUF_SIZE];
	PRStatus    prStatus;
	PRIntn      hostenum;
	PRInt32    ip;
	SECStatus   secStatus;

	/* Set up SSL secure socket. */
	sslSocket = setupSSLSocket(addr);
	if (sslSocket == NULL) {
		errWarn("setupSSLSocket");
		return SECFailure;
	}

	secStatus = SSL_SetPKCS11PinArg(sslSocket, &pwdata);
	if (secStatus != SECSuccess) {
		errWarn("SSL_SetPKCS11PinArg");
		return secStatus;
	}

	secStatus = SSL_SetURL(sslSocket, hostName);
	if (secStatus != SECSuccess) {
		errWarn("SSL_SetURL");
		return secStatus;
	}

	/* Prepare and setup network connection. */
	prStatus = PR_GetHostByName(hostName, buffer, sizeof(buffer), &hostEntry);
	if (prStatus != PR_SUCCESS) {
		errWarn("PR_GetHostByName");
		return SECFailure;
	}

	hostenum = PR_EnumerateHostEnt(0, &hostEntry, port, addr);
	if (hostenum == -1) {
		errWarn("PR_EnumerateHostEnt");
		return SECFailure;
	}

 	ip = PR_ntohl(addr->inet.ip);
	fprintf(stderr,
	 	"Connecting to host %s (addr %d.%d.%d.%d) on port %d\n",
			hostName, BYTE(3,ip), BYTE(2,ip), BYTE(1,ip),
			BYTE(0,ip), PR_ntohs(addr->inet.port));

	prStatus = PR_Connect(sslSocket, addr, PR_INTERVAL_NO_TIMEOUT);
	if (prStatus != PR_SUCCESS) {
		errWarn("PR_Connect");
		return SECFailure;
	}

	/* Established SSL connection, ready to send data. */
#if 0
	secStatus = SSL_ForceHandshake(sslSocket);
	if (secStatus != SECSuccess) {
		errWarn("SSL_ForceHandshake");
		return secStatus;
	}
#endif

	secStatus = SSL_ResetHandshake(sslSocket, /* asServer */ PR_FALSE);
	if (secStatus != SECSuccess) {
		errWarn("SSL_ResetHandshake");
		prStatus = PR_Close(sslSocket);
		if (prStatus != PR_SUCCESS) {
			errWarn("PR_Close");
		}
		return secStatus;
	}

	secStatus = handle_connection(sslSocket, connection);
	if (secStatus != SECSuccess) {
		/* error already printed out in handle_connection */
		/* errWarn("handle_connection"); */
		prStatus = PR_Close(sslSocket);
		if (prStatus != PR_SUCCESS) {
			errWarn("PR_Close");
		}
		return secStatus;
	}

	PR_Close(sslSocket);
	return SECSuccess;
}

void
client_main(unsigned short      port,
            int	                connections,
            const char *        hostName)
{
	int			i;
	SECStatus	secStatus;
	PRStatus    prStatus;
	PRInt32     rv;
	PRNetAddr	addr;
	PRHostEnt   hostEntry;
	char        buffer[PR_NETDB_BUF_SIZE];

	/* Setup network connection. */
	prStatus = PR_GetHostByName(hostName, buffer, sizeof(buffer), &hostEntry);
	if (prStatus != PR_SUCCESS) {
		exitErr("PR_GetHostByName");
	}

	rv = PR_EnumerateHostEnt(0, &hostEntry, port, &addr);
	if (rv < 0) {
		exitErr("PR_EnumerateHostEnt");
	}

	secStatus = launch_thread(&threadMGR, do_connects, &addr, 1);
	if (secStatus != SECSuccess) {
		exitErr("launch_thread");
	}

	if (connections > 1) {
		/* wait for the first connection to terminate, then launch the rest. */
		reap_threads(&threadMGR);
		/* Start up the connections */
		for (i = 2; i <= connections; ++i) {
			secStatus = launch_thread(&threadMGR, do_connects, &addr, i);
			if (secStatus != SECSuccess) {
				errWarn("launch_thread");
			}
		}
	}

	reap_threads(&threadMGR);
	destroy_thread_data(&threadMGR);
}

#define HEXCHAR_TO_INT(c, i) \
    if (((c) >= '0') && ((c) <= '9')) { \
	i = (c) - '0'; \
    } else if (((c) >= 'a') && ((c) <= 'f')) { \
	i = (c) - 'a' + 10; \
    } else if (((c) >= 'A') && ((c) <= 'F')) { \
	i = (c) - 'A' + 10; \
    } else { \
	Usage(progName); \
    }

int
main(int argc, char **argv)
{
	char *               certDir = NULL;
	char *               progName     = NULL;
	int                  connections  = 1;
	char *               cipherString = NULL;
	char *               respUrl = NULL;
	char *               respCertName = NULL;
	SECStatus            secStatus;
	PLOptState *         optstate;
	PLOptStatus          status;
	PRBool               doOcspCheck = PR_FALSE;

	/* Call the NSPR initialization routines */
	PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);

	progName = PORT_Strdup(argv[0]);

	hostName = NULL;
	optstate = PL_CreateOptState(argc, argv, "C:cd:f:l:n:p:ot:w:");
	while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
		switch(optstate->option) {
		case 'C' : cipherString = PL_strdup(optstate->value); break;
 		case 'c' : dumpChain = PR_TRUE;                       break;
		case 'd' : certDir = PL_strdup(optstate->value);      break;
		case 'l' : respUrl = PL_strdup(optstate->value);      break;
		case 'p' : port = PORT_Atoi(optstate->value);         break;
		case 'o' : doOcspCheck = PR_TRUE;                     break;
		case 't' : respCertName = PL_strdup(optstate->value); break;
                case 'w':
                           pwdata.source = PW_PLAINTEXT;
                           pwdata.data = PORT_Strdup(optstate->value);
                           break;

                case 'f':
                           pwdata.source = PW_FROMFILE;
                           pwdata.data = PORT_Strdup(optstate->value);
                           break;
		case '\0': hostName = PL_strdup(optstate->value);     break;
		default  : Usage(progName);
		}
	}

	if (port == 0) {
		port = 443;
	}

	if (port == 0 || hostName == NULL)
		Usage(progName);

        if (doOcspCheck &&
            ((respCertName != NULL && respUrl == NULL) ||
             (respUrl != NULL && respCertName == NULL))) {
	    SECU_PrintError (progName, "options -l <url> and -t "
	                     "<responder> must be used together");
	    Usage(progName);
        }

	PK11_SetPasswordFunc(SECU_GetModulePassword);

	/* Initialize the NSS libraries. */
	if (certDir) {
	    secStatus = NSS_Init(certDir);
	} else {
	    secStatus = NSS_NoDB_Init(NULL);

	    /* load the builtins */
	    SECMOD_AddNewModule("Builtins",
				DLL_PREFIX"nssckbi."DLL_SUFFIX, 0, 0);
	}
	if (secStatus != SECSuccess) {
		exitErr("NSS_Init");
	}
	SECU_RegisterDynamicOids();

	if (doOcspCheck == PR_TRUE) {
            SECStatus rv;
            CERTCertDBHandle *handle = CERT_GetDefaultCertDB();
            if (handle == NULL) {
                SECU_PrintError (progName, "problem getting certdb handle");
                goto cleanup;
            }

            rv = CERT_EnableOCSPChecking (handle);
            if (rv != SECSuccess) {
                SECU_PrintError (progName, "error enabling OCSP checking");
                goto cleanup;
            }

            if (respUrl != NULL) {
                rv = CERT_SetOCSPDefaultResponder (handle, respUrl,
                                                   respCertName);
                if (rv != SECSuccess) {
                    SECU_PrintError (progName,
                                     "error setting default responder");
                    goto cleanup;
                }

                rv = CERT_EnableOCSPDefaultResponder (handle);
                if (rv != SECSuccess) {
                    SECU_PrintError (progName,
                                     "error enabling default responder");
                    goto cleanup;
                }
            }
	}

	/* All cipher suites except RSA_NULL_MD5 are enabled by
	 * Domestic Policy. */
	NSS_SetDomesticPolicy();
	SSL_CipherPrefSetDefault(SSL_RSA_WITH_NULL_MD5, PR_TRUE);

	/* all the SSL2 and SSL3 cipher suites are enabled by default. */
	if (cipherString) {
	    int ndx;

	    /* disable all the ciphers, then enable the ones we want. */
	    disableAllSSLCiphers();

	    while (0 != (ndx = *cipherString++)) {
		int  cipher;

		if (ndx == ':') {
		    int ctmp;

		    cipher = 0;
		    HEXCHAR_TO_INT(*cipherString, ctmp)
		    cipher |= (ctmp << 12);
		    cipherString++;
		    HEXCHAR_TO_INT(*cipherString, ctmp)
		    cipher |= (ctmp << 8);
		    cipherString++;
		    HEXCHAR_TO_INT(*cipherString, ctmp)
		    cipher |= (ctmp << 4);
		    cipherString++;
		    HEXCHAR_TO_INT(*cipherString, ctmp)
		    cipher |= ctmp;
		    cipherString++;
		} else {
		    const int *cptr;
		    if (! isalpha(ndx))
			Usage(progName);
		    cptr = islower(ndx) ? ssl3CipherSuites : ssl2CipherSuites;
		    for (ndx &= 0x1f; (cipher = *cptr++) != 0 && --ndx > 0; )
			/* do nothing */;
		}
		if (cipher > 0) {
		    SSL_CipherPrefSetDefault(cipher, PR_TRUE);
		} else {
		    Usage(progName);
		}
	    }
	}

	client_main(port, connections, hostName);

cleanup:
        if (doOcspCheck) {
            CERTCertDBHandle *handle = CERT_GetDefaultCertDB();
            CERT_DisableOCSPDefaultResponder(handle);
            CERT_DisableOCSPChecking (handle);
        }

        if (NSS_Shutdown() != SECSuccess) {
            exit(1);
        }

	PR_Cleanup();
	PORT_Free(progName);
	return 0;
}


text:
import pyRead, sys, coapSender, asyncio

# Check File
pyRead.checkArg(sys.argv)
# Read File
file = pyRead.readFile(sys.argv[1])

# Send each line to the server
for line in file:
    split = line.split()
    # Make sure we wait until msg is send to server
    asyncio.get_event_loop().run_until_complete(coapSender.send(split[0], split[1]))


text:
package com.b2international.commons.exceptions;

import java.util.Map;
import java.util.Map.Entry;

import com.b2international.commons.Pair;

/**
 * Generic syntax exception
 *
 * @since 5.4
 */
public final class SyntaxException extends BadRequestException {

	private static final long serialVersionUID = 1L;

	public SyntaxException(String language, Map<Pair<Integer, Integer>, String> errors) {
		super("One or more %s syntax errors", language);
		for (Entry<Pair<Integer, Integer>, String> entry : errors.entrySet()) {
			withAdditionalInfo(String.format("[%s,%s]", entry.getKey().getA(), entry.getKey().getB()), entry.getValue());
		}
	}

}


text:
from meine_stadt_transparent.settings.env import env

SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
X_FRAME_OPTIONS = "DENY"
SECURE_HSTS_SECONDS = 365 * 24 * 60 * 60
SECURE_HSTS_PRELOAD = True
# There might be deployments where a subdomain is still without https
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("SECURE_HSTS_INCLUDE_SUBDOMAINS", True)

CSP_DEFAULT_SRC = ("'self'",)

if env.bool("MINIO_REDIRECT", False):
    if env.str("MINIO_PUBLIC_HOST"):
        endpoint = env.str("MINIO_PUBLIC_HOST")
        secure = env.bool("MINIO_PUBLIC_SECURE", True)
    else:
        endpoint = env.str("MINIO_HOST")
        secure = env.bool("MINIO_SECURE", False)

    CSP_DEFAULT_SRC += (("https://" if secure else "http://") + endpoint,)

CSP_SCRIPT_SRC = ("'self'",) + env.tuple("CSP_EXTRA_SCRIPT", default=tuple())
CSP_IMG_SRC = ("'self'", "data:") + env.tuple("CSP_EXTRA_IMG", default=tuple())

if env.str("MAP_TILES_PROVIDER", "OSM") == "OSM":
    CSP_IMG_SRC = CSP_IMG_SRC + (
        "a.tile.openstreetmap.org",
        "b.tile.openstreetmap.org",
        "c.tile.openstreetmap.org",
    )
if env.str("MAP_TILES_PROVIDER", "OSM") == "Mapbox":
    CSP_IMG_SRC = CSP_IMG_SRC + ("api.tiles.mapbox.com", "api.mapbox.com")

SENTRY_HEADER_ENDPOINT = env.str("SENTRY_HEADER_ENDPOINT", None)

CSP_CONNECT_SRC = ("'self'", "sentry.io") + env.tuple(
    "CSP_CONNECT_SRC", default=tuple()
)

if SENTRY_HEADER_ENDPOINT:
    CSP_REPORT_URI = SENTRY_HEADER_ENDPOINT

# Those are not covered by default-src
CSP_FORM_ACTION = ("'self'",)
CSP_FRAME_SRC = ("'self'",) + env.tuple("CSP_FRAME", default=tuple())
CSP_FRAME_ANCESTORS = ("'self'",) + env.tuple("CSP_FRAME", default=tuple())

# Hack for Landshut, where the RIS has a broken ssl configuration (intermediate ceritificate missing)
SSL_NO_VERIFY = env.bool("SSL_NO_VERIFY", False)


text:
Overview
--------
The F5 Dashboard project is intended to to give administrators easier control
of their F5 LTM machines as well as provide a status dashboard to be viewed at
a glance. This dashboard is also a great tool to give to developers so that they
can have control of their own applications while at the same time restricting
their access to the F5 as a whole. This dashboard utilizes the F5 REST API so
requires Big-IP LTM version 11.5 at a minimum.

Installation Instructions
-------------------------
The F5 Dashboard comes bundled with a Python interpreter that has all the
necessary modules pre-installed. To start the application simply run the run.py
executable. This will start flask on port 5000 with the F5 Dashboard running. The
port can be changed in the run.py file.

If you want to use your own Python interpreter you will need the following modules:
- dns.resolver
- requests
- json

Configuration
-------------
Currently all the python code is contained in the __init__.py file. To configure
the dashboard you need to modify two sections of the code. First enter your api
credentials in the apiuser and apipassword variables. Next, enter the hostname/ip
address of your F5s in the dcdict dictionary, along with the syncgroup information
if applicable. Two entries, f5-1 and f5-2 have been provided as examples.


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

<TITLE>
com.googlecode.objectify.annotation Class Hierarchy (Objectify-AppEngine Javadoc)
</TITLE>

<META NAME="date" CONTENT="2012-01-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package com.googlecode.objectify.annotation

Package Hierarchies:
All Packages

Annotation Type Hierarchy

com.googlecode.objectify.annotation.AlsoLoad (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Cache (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.IgnoreSave (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Serialize (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Ignore (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Unindex (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.EntitySubclass (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Load (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Id (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.OnSave (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.OnLoad (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Mapify (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Index (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Translate (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Embed (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Entity (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.IgnoreLoad (implements java.lang.annotation.Annotation)

com.googlecode.objectify.annotation.Parent (implements java.lang.annotation.Annotation)

      Overview
      Package
      Class
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2012 Jeff Schnitzer and a gang of pirates. All Rights Reserved. Build version: 4.0a3


text:
<?xml version="1.0" encoding="utf-8"?>
 <!-- $Revision: 297078 $ -->
 <sect2 xml:id="internals2.ze1.zendapi.where-to-go" xmlns="http://docbook.org/ns/docbook">
  <title>Where to Go from Here</title>
  <para>
   You've learned a lot about PHP. You now know how to create
   dynamic loadable modules and statically linked extensions. You've
   learned how PHP and Zend deal with internal storage of variables and how you
   can create and access these variables. You know quite a set of tool functions
   that do a lot of routine tasks such as printing informational texts,
   automatically introducing variables to the symbol table, and so on.
  </para>
  <para>
   Even though this chapter often had a mostly "referential" character, we
   hope that it gave you insight on how to start writing your own extensions.
   For the sake of space, we had to leave out a lot; we suggest that you take the time to
   study the header files and some modules (especially the ones in the
   <filename>ext/standard</filename> directory and the MySQL module, as these
   implement commonly known functionality). This will give you an idea of how
   other people have used the API functions - particularly those that didn't make it into
   this chapter.
  </para>
 </sect2>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Creations</title>
  <meta property="og:title" content="Creations" />
  <meta property="og:image" content="https://www.simontiu.com/img/profilepic.jpg" />
  <meta name="description" content="Associate at Valia Ventures, Strategy at Google Cloud, Growth at Google Fiber, Consultant at Deloitte">
  <meta property="og:description" content="Associate at Valia Ventures, Strategy at Google Cloud, Growth at Google Fiber, Consultant at Deloitte" />
  <meta name="author" content="Simon Tiu">

  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">

  <link href="https://fonts.googleapis.com/css?family=Saira+Extra+Condensed:100,200,300,400,500,600,700,800,900" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href='https://cdnjs.cloudflare.com/ajax/libs/devicons/1.8.0/css/devicons.min.css' rel='stylesheet'>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">

  <link href="https://www.simontiu.com/css/resume.css" rel="stylesheet">
  <link href="https://www.simontiu.com/css/tweaks.css" rel="stylesheet">
  <meta name="generator" content="Hugo 0.37.1" />

    Simon Tiu

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        About

            Experience

            Education

            Skills

            Projects

            Photos + Vids

            Musings

  Simon

  Projects

  Creations

Creations

A collection of random projects. I like to tinker with new things in my spare time.

Encryption Folder

The Encryption Folder is a quick tool to protect a folder on your machine. It's a simple solution for multiple people using the same machine (local or remote).

Read more..

Cryptography

Encryption

MacOS

GMAT Timer

A quick web app to help you train on GMAT questions by tracking your timing.

Read more..

webapp

gmat

angular

bootstrap

Word Tower

A fun game to improve you typing speed by typing along with your favorite songs

Read more..

game

matlab

app


text:
Cottz subscache
=============================

subscache allows you to store all documents received by a collection on the client without deleting them when changing subscription.
unlike subsmanager I don't keep active subscriptions I keep documents

## Installation
```sh
$ meteor add cottz:subscache
```

## Quick Start
```js
import SubsCache from 'meteor/cottz:subscache';

APPCache = new SubsCache({
  expireIn: 10,
  inAll: false
});

// publish
Meteor.publish('users', function (skip) {
  return Meteor.users.find({}, {skip: skip});
});

// Router
FlowRouter.route('/users', {
  subscriptions (params, query) {
    this.register('my users', APPCache.subscribe('users', Number(query.skip) || 0));
  }
});

// template
Template.user.helpers({
  users () {
    return APPCache.find('users', Meteor.users);
  }
});
```
### subscache options
`expireIn` is the time in minutes before the stored documents begin to remove or null if you don't want to remove them
`inAll` if true the find() will bring all documents stored
```js
// the next values are the defaults
APPCache = new SubsCache({
  expireIn: 10,
  inAll: false
});
```
#### wait a moment... inAll is what ?
Suppose You have a collection with 100 documents, the user has a pagination in batches of 10 documents

when `inAll` is false (default) whenever the user changes the pagination always see 10 documents and documents of previous pages will be used to return the documents immediately if the user returns to a previous page
when `inAll` is true always get the documents that match your query, if the user changes the pagination 3 times he will see 30 documents unless the query limits them, by default a findOne() always use inAll as true

### subscribe
he subscription works exactly like the subscription in Meteor
```js
APPCache.subscribe('users', params);
```

### find() and findOne()
parameters (in order) are:

 - the name of the subscription
 - a mongo collection
 - cursor selector (not required)
 - cursor options (not required)
```js
APPCache = new SubsCache();

APPCache.find('users', Meteor.users, {}, {});
APPCache.findOne('users', Meteor.users, {}, {});
```

### subscache.ready
```js
APPCache = new SubsCache();
// is reactive
// true if the subscription users is ready
APPCache.ready('users');
// true if all subscriptions are ready
APPCache.ready();
```

### subscache.use
```js
APPCache = new SubsCache();

let users = APPCache.use('users', Meteor.users);
let usersSub = APPCache.use('users');

users.find({}, {});

usersSub.find(Meteor.users, {}, {});
usersSub.find(Profiles, {}, {});
```


text:
export default function prepareSpectrum(spectrum) {
  if (!spectrum.xFactor) spectrum.xFactor = 1;
  if (!spectrum.yFactor) spectrum.yFactor = 1;
}


text:
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { findIndex } from 'lodash';
import moment from 'moment';

import { requireUser, notAfterCheckIn } from '../imports/method-helpers.js';
import { emailTeamInvite } from '../imports/emails.js';

Invites = new Mongo.Collection('invites');

/*
Structure of a TeamInvite:

{
  _id: String,
  teamId: String,
  email: String,
  invitedBy: {
    _id: String,
    name: String,
  },
  accepted: Boolean,

}
*/

Meteor.methods({
  'teams.inviteMember'(team, email) {
    check(team, Object);
    try {
      check(email, ValidEmail);
    }
    catch (ex) {
      throw new Meteor.Error(400, 'You must enter a valid email address!');
    }

    requireUser();
    notAfterCheckIn();

    const user = Meteor.users.findOne({ _id: this.userId });
    if (!user.teamId) {
      throw new Meteor.Error(400, 'You must be on a team to invite people!');
    } else if (user.teamId !== team._id) {
      throw new Meteor.Error(400, 'You can only invite members to your team!');
    }

    // Only send and create invite on the server.
    if (!Meteor.isServer) return true;

    // Check team size limit
    const teamInvites = Invites.find({ teamId: user.teamId, accepted: false }).fetch();
    const existingIndex = findIndex(teamInvites, { email });

    if ((existingIndex === -1) && (teamInvites.length + team.members.length >= 6)) {
      throw new Meteor.Error(400, 'Teams can only have up to 6 members!');
    }

    const now = new Date();
    Invites.upsert({
      teamId: user.teamId,
      email,
    },
    {
      teamId: user.teamId,
      teamName: team.name,
      email,
      invitedBy: {
        _id: user._id,
        name: user.name,
      },
      updatedAt: now,
      accepted: false,
    });

    this.unblock();

    if (existingIndex === -1 || moment(teamInvites[existingIndex].updatedAt).isBefore(moment(now).subtract({ minutes: 5}))) {
      emailTeamInvite(team, user, email);
    }

  },

  'teams.deleteInvite'(team, email) {
    check(team, Object);
    check(email, String);

    requireUser();

    const user = Meteor.users.findOne({ _id: this.userId });
    if (!user.teamId) {
      throw new Meteor.Error(400, 'You must be on a team to invite people!');
    } else if (user.teamId !== team._id) {
      throw new Meteor.Error(400, 'You can only invite members to your team!');
    }

    return Invites.remove({ teamId: user.teamId, email, accepted: false });
  },

  'invites.accept'(invite) {
    check(invite, Object);

    requireUser();
    const user = Meteor.user();
    if (user.getEmail() !== invite.email) {
      throw new Meteor.Error(400, 'This invite does not belong to you!');
    }
    if (user.teamId) {
      throw new Meteor.Error(400, 'You are already on a team!');
    }

    if (!Meteor.isServer) return true;

    const team = Teams.findOne(invite.teamId);
    if (!team) {
      throw new Meteor.Error(400, 'Oops, this team no longer exists!');
    }
    if (team.members.length >= 6) {
      throw new Meteor.Error(400, 'Oops, this team is already full!');
    }
    if (team.checkinConfirmed) {
      throw new Meteor.Error(400, "Oops, this team has already been checked in!");
    }

    // Great join the team.
    Meteor.users.update({ _id: user._id }, { $set: { teamId: team._id }});
    Teams.update({ _id: team._id }, { $push: { members: user._id }});
    Invites.update({ _id: invite._id }, { $set: { accepted: true }});
  }

});


text:
package net.dv8tion.jda.api.managers.channel.concrete;

import net.dv8tion.jda.api.entities.channel.concrete.StageChannel;
import net.dv8tion.jda.api.managers.channel.middleman.AudioChannelManager;
import net.dv8tion.jda.api.managers.channel.middleman.StandardGuildChannelManager;

/**
 * Manager providing methods to modify a {@link StageChannel}.
 *
 *
Example
 *
{@code
 * manager.setName("School Presentations")
 *        .setBitrate(96000)
 *        .queue();
 * }

 */
public interface StageChannelManager extends
        AudioChannelManager<StageChannel, StageChannelManager>,
        StandardGuildChannelManager<StageChannel, StageChannelManager>
{
}


text:
Just for Fun do not use in the real world.  :)

Building

mvn clean compile assembly:single

Running

hadoop jar target/HBaseUtilMain.jar com.cloudera.sa.hbaseloadexamples.DataGenerator "/mvp/ingest/staging" 1000000 4

hadoop jar target/HBaseUtilMain.jar com.cloudera.sa.hbaseloadexamples.HBaseSinglePut "/mvp/ingest/staging" "christoph_gamer" "i"

hadoop jar target/HBaseUtilMain.jar com.cloudera.sa.hbaseloadexamples.HBasePutListMultiThreaded "/mvp/ingest/staging" "christoph_gamer" "i" 320 8


text:
<?php

namespace Orbitale\Bundle\EasyImpressBundle\DependencyInjection\Compiler;

use Orbitale\Bundle\EasyImpressBundle\Configuration\ConfigProcessor;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Finder\Finder;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

class PresentationsPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $finder = (new Finder())
            ->files()
            ->name('*.{yaml,yml}')
            ->in($container->getParameter('easy_impress.presentations_dir'))
        ;

        $configProcessor = new ConfigProcessor();

        $presentations = [];

        foreach ($finder as $file) {
            /** @var \SplFileInfo $file */
            $container->addResource(new FileResource($file->getRealPath()));
            $presentations[preg_replace('~\.ya?ml$~', '', $file->getBasename())] = $configProcessor->processConfigurationFile($file);
        }

        $container->setParameter('easy_impress.presentations', $presentations);
    }
}


text: require "mini_magick"


text:
import * as React from 'react';

import { SITE_CARD_BACKGROUND_URL, SITE_CARD_EMBLEM_IMAGE, SITE_NAME } from '../../constants';
import { ALL_RAIDS } from '../../constants/destiny';
import DestinyCard from '../../layouts/components/DestinyCard';
import RaidLayout from '../../layouts/components/RaidLayout';
import HomeCard from './components/HomeCard';

export const HomeContainer = () => {
    const raids = ALL_RAIDS.map((raid) => {
        return (

                <RaidLayout raid={raid}>
                    <HomeCard raid={raid.raid}>
                        {raid.homePageCard && <raid.homePageCard />}
                    </HomeCard>
                </RaidLayout>

        );
    });
    return (

            <DestinyCard emblemImage={SITE_CARD_EMBLEM_IMAGE} backgroundImage={SITE_CARD_BACKGROUND_URL}>
                {SITE_NAME}
            </DestinyCard>

                {raids}

    );
};

export default HomeContainer;


text:
package pubsub

import "google.golang.org/grpc/xds/internal/xdsclient/xdsresource"

// UpdateHandler receives and processes (by taking appropriate actions) xDS
// resource updates from an APIClient for a specific version.
//
// It's a subset of the APIs of a *Pubsub.
type UpdateHandler interface {
	// NewListeners handles updates to xDS listener resources.
	NewListeners(map[string]xdsresource.ListenerUpdateErrTuple, xdsresource.UpdateMetadata)
	// NewRouteConfigs handles updates to xDS RouteConfiguration resources.
	NewRouteConfigs(map[string]xdsresource.RouteConfigUpdateErrTuple, xdsresource.UpdateMetadata)
	// NewClusters handles updates to xDS Cluster resources.
	NewClusters(map[string]xdsresource.ClusterUpdateErrTuple, xdsresource.UpdateMetadata)
	// NewEndpoints handles updates to xDS ClusterLoadAssignment (or tersely
	// referred to as Endpoints) resources.
	NewEndpoints(map[string]xdsresource.EndpointsUpdateErrTuple, xdsresource.UpdateMetadata)
	// NewConnectionError handles connection errors from the xDS stream. The
	// error will be reported to all the resource watchers.
	NewConnectionError(err error)
}


text:
'use strict'

const Joi = require('joi')

const schema = Joi.object().keys({
  url: Joi.string().uri().required(),
  status_code: Joi.number().min(0).required()
})

module.exports = (data) => {
  return new Promise((resolve, reject) => {
    Joi.validate(data, schema, (error) => {
      if (!error) resolve()
      else reject(error)
    })
  })
}


text:
package org.fcrepo.client.messaging;

import javax.jms.Message;

/**
 * A MessagingListener is used to receive asynchronously
 * delivered notifications.
 *
 * @author Bill Branan
 */
public interface MessagingListener {

    /**
     * Processes a message.
     *
     * @param clientId - the identifier of the messaging client from
     *                   which the message came
     * @param message - the message to be processed
     */
    public void onMessage(String clientId, Message message);

}


text:
var mysql = require('../lib/mysql');
var exception = require('../lib/exception');

function* createTodo () {
	console.log("createTodo");

	var body = this.request.body;
	var todo = yield mysql.createTodo(this.session.id, body);
	var resBody = transformTodo(todo);

	this.response.body = resBody;

	this.status = 200;
}

function* getTodoInfo (todoUUID) {
	console.log("getTodoInfo");

	var todo = yield mysql.getTodoInfo(this.session.id, todoUUID);
	var resBody = transformTodo(todo);

	this.response.body = resBody;

	this.status = 200;
}

function* getTodoByLabel (labelUUID) {
	console.log("getTodoByLabel");

	var todos = yield mysql.fetchTodosBylabel(this.session.id, labelUUID);
	var body = [];
	for (var index in todos) {
		body.push(transformTodo(todos[index]));
	}
	this.response.body = body;
	this.status = 200;
}

function* getTodoByDate (date) {
	console.log("getTodoByDate");
	var todos = yield mysql.fetchTodosByDate(this.session.id, date);
	var body = [];
	for (var index in todos) {
		body.push(transformTodo(todos[index]));
	}
	this.response.body = body;
	this.status = 200;
}

function* deleteTodo (todoUUID) {
	console.log("deleteTodo");

	var success = yield mysql.deleteTodo(this.session.id, todoUUID);

	if (success) {
		this.status = 200;
	} else {
		throw exception('ServerError', '操作失败');
	}
}

function* updateTodo (todoUUID) {
	console.log("updateTodo");

	var body = this.request.body;
	var success = yield mysql.updateTodo(this.session.id, todoUUID, body);

	if (success) {
		this.status = 200;
	} else {
		throw exception('ServerError', '操作失败');
	}
}

function transformTodo(todo) {
	var resBody = {};
 	resBody.uuid = todo.uuid;
 	resBody.labelUUID = todo.labelUUID;
 	resBody.title = todo.title;
 	resBody.body = todo.body;
 	resBody.ownerUUID = todo.ownerUUID;
 	resBody.terminatorUUID = todo.terminatorUUID;
 	resBody.type = todo.type;
 	resBody.status = todo.status;
 	resBody.expiredAt = todo.expiredAt;

 	return resBody;
}

module.exports = {
	createTodo: createTodo,
	getTodoInfo: getTodoInfo,
	getTodoByLabel: getTodoByLabel,
	getTodoByDate: getTodoByDate,
	deleteTodo: deleteTodo,
	updateTodo: updateTodo
};