text:
<?php

require_once OW::getPluginManager()->getPlugin('ode')->getRootDir() . 'lib/httpful.phar';

use Httpful\Request;
use Httpful\Http;
use Httpful\Mime;

class ODE_CTRL_Admin extends ADMIN_CTRL_Abstract
{
    public function settings($params)
    {
        $settingsItem = new BASE_MenuItem();
        $settingsItem->setLabel('SETTINGS');
        $settingsItem->setUrl( OW::getRouter()->urlForRoute( 'ode-settings' ) );
        $settingsItem->setKey( 'settings' );
        $settingsItem->setIconClass( 'ow_ic_gear_wheel' );
        $settingsItem->setOrder( 0 );

        $providersItem = new BASE_MenuItem();
        $providersItem->setLabel('PROVIDERS');
        $providersItem->setUrl( OW::getRouter()->urlForRoute( 'ode-providers' ) );
        $providersItem->setKey( 'providers' );
//        $providersItem->setIconClass( 'ow_ic_help' );
        $providersItem->setOrder( 1 );

        $toolsItem = new BASE_MenuItem();
        $toolsItem->setLabel('TOOLS');
        $toolsItem->setUrl( OW::getRouter()->urlForRoute( 'ode-tools' ) );
        $toolsItem->setKey( 'tools' );
        $toolsItem->setOrder( 2 );

        $menu = new BASE_CMP_ContentMenu( array( $settingsItem, $providersItem, $toolsItem ) );
        $this->addComponent( 'menu', $menu );

        $this->setPageTitle('ODE SETTINGS');
        $this->setPageHeading('ODE SETTINGS');

        $form = new Form('settings');
        $this->addForm($form);

        /* DEEP ULR */
        $deepUrl = new TextField('deep_url');
        $preference = BOL_PreferenceService::getInstance()->findPreference('ode_deep_url');
        $ode_deep_url = empty($preference) ? "http://deep.routetopa.eu/DEEP/" : $preference->defaultValue;
        $deepUrl->setValue($ode_deep_url);
        $deepUrl->setRequired();
        $form->addElement($deepUrl);

        /* DEEP DATALET LIST */
        $deepDataletList = new TextField('deep_datalet_list');
        $preference = BOL_PreferenceService::getInstance()->findPreference('ode_deep_datalet_list');
        $ode_deep_datalet_list = empty($preference) ? "http://deep.routetopa.eu/DEEP/datalets-list" :  $preference->defaultValue;
        $deepDataletList->setValue($ode_deep_datalet_list);
        $deepDataletList->setRequired();
        $form->addElement($deepDataletList);

        /* DEEP CLIENT */
        $deepClient = new TextField('deep_client');
        $preference = BOL_PreferenceService::getInstance()->findPreference('ode_deep_client');
        $ode_deep_client = empty($preference) ? "http://deep.routetopa.eu/DEEPCLIENT/js/deepClient.js" : $preference->defaultValue;
        $deepClient->setValue($ode_deep_client);
        $deepClient->setRequired();
        $form->addElement($deepClient);

        /* DEEP COMPONENTS */
        $componentsUrl = new TextField('components_url');
        $preference = BOL_PreferenceService::getInstance()->findPreference('spodpr_components_url');
        $spodpr_components_url = empty($preference) ? "http://deep.routetopa.eu/COMPONENTS/" : $preference->defaultValue;
        $componentsUrl->setValue($spodpr_components_url);
        $componentsUrl->setRequired();
        $form->addElement($componentsUrl);

        /* WEBCOMPONENT JS */
        $webcomponents = new TextField('webcomponents_js');
        $preference = BOL_PreferenceService::getInstance()->findPreference('ode_webcomponents_js');
        $ode_webcomponents_js = empty($preference) ? "http://deep.routetopa.eu/COMPONENTS/bower_components/webcomponentsjs/webcomponents-lite.js" : $preference->defaultValue;
        $webcomponents->setValue($ode_webcomponents_js);
        $webcomponents->setRequired();
        $form->addElement($webcomponents);

        /* DATALET POLYFILL */
        $datalet_polyfill = new TextField('datalet_polyfill');
        $preference = BOL_PreferenceService::getInstance()->findPreference('ode_datalet_polyfill');
        $ode_datalet_polyfill = empty($preference) ? "http://deep.routetopa.eu/COMPONENTS/datalets/lib/js/vendors/webcomponents_polyfill_ff/webcomponents-hi-sd-ce.js" : $preference->defaultValue;
        $datalet_polyfill->setValue($ode_datalet_polyfill);
        //$datalet_polyfill->setRequired();
        $form->addElement($datalet_polyfill);

        /* ULTRACLARITY URL */
        $ultraClarityUrl = new TextField('ultra_clarity_url');
        $preference = BOL_PreferenceService::getInstance()->findPreference('ode_ultra_clarity_url');
        $ode_ultra_clarity_url = empty($preference) ? "" : $preference->defaultValue;
        $ultraClarityUrl->setValue($ode_ultra_clarity_url);
        $ultraClarityUrl->setRequired();
        $form->addElement($ultraClarityUrl);

        /* ELASTICMAIL APIKEY */
        $elasticMailAPIKey = new TextField('elastic_mail_api_key');
        $preference = BOL_PreferenceService::getInstance()->findPreference('elastic_mail_api_key');
        $elastic_mail_api_key = empty($preference) ? "" : $preference->defaultValue;
        $elasticMailAPIKey->setValue($elastic_mail_api_key);
        $elasticMailAPIKey->setRequired();
        $form->addElement($elasticMailAPIKey);

        $submit = new Submit('add');
        $submit->setValue('SUBMIT');
        $form->addElement($submit);

        if ( OW::getRequest()->isPost() && $form->isValid($_POST))
        {
            $data = $form->getValues();

            /* ode_deep_url */
            $preference = BOL_PreferenceService::getInstance()->findPreference('ode_deep_url');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'ode_deep_url';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['deep_url'];
            $preference->sortOrder = 1;
            BOL_PreferenceService::getInstance()->savePreference($preference);

            /* ode_deep_datalet_list */
            $preference = BOL_PreferenceService::getInstance()->findPreference('ode_deep_datalet_list');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'ode_deep_datalet_list';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['deep_datalet_list'];
            $preference->sortOrder = 2;
            BOL_PreferenceService::getInstance()->savePreference($preference);

            /* ode_deep_client */
            $preference = BOL_PreferenceService::getInstance()->findPreference('ode_deep_client');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'ode_deep_client';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['deep_client'];
            $preference->sortOrder = 3;
            BOL_PreferenceService::getInstance()->savePreference($preference);

            /* spodpr_components_url */
            $preference = BOL_PreferenceService::getInstance()->findPreference('spodpr_components_url');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'spodpr_components_url';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['components_url'];
            $preference->sortOrder = 1;
            BOL_PreferenceService::getInstance()->savePreference($preference);

            /* ode_webcomponents_js */
            $preference = BOL_PreferenceService::getInstance()->findPreference('ode_webcomponents_js');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'ode_webcomponents_js';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['webcomponents_js'];
            $preference->sortOrder = 4;
            BOL_PreferenceService::getInstance()->savePreference($preference);

            /* ode_datalet_polyfill */
            $preference = BOL_PreferenceService::getInstance()->findPreference('ode_datalet_polyfill');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'ode_datalet_polyfill';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['datalet_polyfill'];
            $preference->sortOrder = 5;
            BOL_PreferenceService::getInstance()->savePreference($preference);

            /* ode_ultra_clarity_url */
            $preference = BOL_PreferenceService::getInstance()->findPreference('ode_ultra_clarity_url');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'ode_ultra_clarity_url';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['ultra_clarity_url'];
            $preference->sortOrder = 6;
            BOL_PreferenceService::getInstance()->savePreference($preference);

            /* elastic_mail_api_key */
            $preference = BOL_PreferenceService::getInstance()->findPreference('elastic_mail_api_key');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'elastic_mail_api_key';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['elastic_mail_api_key'];
            $preference->sortOrder = 7;
            BOL_PreferenceService::getInstance()->savePreference($preference);

        }
    }

    public function providers()
    {
        $settingsItem = new BASE_MenuItem();
        $settingsItem->setLabel('SETTINGS');
        $settingsItem->setUrl( OW::getRouter()->urlForRoute( 'ode-settings' ) );
        $settingsItem->setKey( 'settings' );
        $settingsItem->setIconClass( 'ow_ic_gear_wheel' );
        $settingsItem->setOrder( 0 );

        $providersItem = new BASE_MenuItem();
        $providersItem->setLabel('PROVIDERS');
        $providersItem->setUrl( OW::getRouter()->urlForRoute( 'ode-providers' ) );
        $providersItem->setKey( 'providers' );
//        $providersItem->setIconClass( 'ow_ic_help' );
        $providersItem->setOrder( 1 );

        $toolsItem = new BASE_MenuItem();
        $toolsItem->setLabel('TOOLS');
        $toolsItem->setUrl( OW::getRouter()->urlForRoute( 'ode-tools' ) );
        $toolsItem->setKey( 'tools' );
        $toolsItem->setOrder( 2 );

        $menu = new BASE_CMP_ContentMenu( array( $settingsItem, $providersItem, $toolsItem ) );
        $this->addComponent( 'menu', $menu );

        $this->setPageTitle('ODE PROVIDERS');
        $this->setPageHeading('ODE PROVIDERS');

        $form = new Form('providers');
        $this->addForm($form);

        $name = new TextField('name');
        $name->setRequired();
        $form->addElement($name);

        $url = new TextField('url');
        $url->setRequired();
        $form->addElement($url);

        $submit = new Submit('addProvider');
        $submit->setValue('ADD');
        $form->addElement($submit);

        if ( OW::getRequest()->isPost() && $form->isValid($_POST))
        {
            $data = $form->getValues();

            ODE_BOL_Service::getInstance()->addProvider($data['name'], $data['url']);

            $this->redirect(OW::getRouter()->urlForRoute('ode-providers'));
        }

        $providersList = array();
        $deleteUrls = array();
        $providers = ODE_BOL_Service::getInstance()->getProviderList();
        foreach ( $providers as $provider )
        {
            /* @var $contact ODE_BOL_Provider */
            $providersList[$provider->id]['name'] = $provider->name;
            $providersList[$provider->id]['url'] = $provider->url;
            $deleteUrls[$provider->id] = OW::getRouter()->urlFor(__CLASS__, 'delete', array('id' => $provider->id));
        }
        $this->assign('providersList', $providersList);
        $this->assign('deleteUrls', $deleteUrls);
        $this->assign('createDatasetCache', OW::getRouter()->urlFor(__CLASS__, 'createDatasetCache'));
    }

    public function tools()
    {
        $settingsItem = new BASE_MenuItem();
        $settingsItem->setLabel('SETTINGS');
        $settingsItem->setUrl( OW::getRouter()->urlForRoute( 'ode-settings' ) );
        $settingsItem->setKey( 'settings' );
        $settingsItem->setIconClass( 'ow_ic_gear_wheel' );
        $settingsItem->setOrder( 0 );

        $providersItem = new BASE_MenuItem();
        $providersItem->setLabel('PROVIDERS');
        $providersItem->setUrl( OW::getRouter()->urlForRoute( 'ode-providers' ) );
        $providersItem->setKey( 'tools' );
//        $providersItem->setIconClass( 'ow_ic_help' );
        $providersItem->setOrder( 1 );

        $toolsItem = new BASE_MenuItem();
        $toolsItem->setLabel('TOOLS');
        $toolsItem->setUrl( OW::getRouter()->urlForRoute( 'ode-tools' ) );
        $toolsItem->setKey( 'tools' );
        $toolsItem->setOrder( 2 );

        $menu = new BASE_CMP_ContentMenu( array( $settingsItem, $providersItem, $toolsItem ) );
        $this->addComponent( 'menu', $menu );

        $this->setPageTitle('ODE TOOLS');
        $this->setPageHeading('ODE TOOLS');

        $form = new Form('settings');
        $this->addForm($form);

        /* SPLOD IsVisible */
        $SPLOD_visible = new CheckboxField('SPLOD_visible');
        $preference = BOL_PreferenceService::getInstance()->findPreference('splod_is_visible_whatsnew');
        $splod_pref = empty($preference) ? "0" : $preference->defaultValue;
        $SPLOD_visible->setValue($splod_pref);
        $form->addElement($SPLOD_visible);

        /* MAPLET IsVisible */
        $Maplet_visible = new CheckboxField('Maplet_visible');
        $preference = BOL_PreferenceService::getInstance()->findPreference('maplet_is_visible_whatsnew');
        $maplet_pref = empty($preference) ? "0" : $preference->defaultValue;
        $Maplet_visible->setValue($maplet_pref);
        $form->addElement($Maplet_visible);

        $submit = new Submit('add');
        $submit->setValue('SAVE');
        $form->addElement($submit);

        if ( OW::getRequest()->isPost() && $form->isValid($_POST))
        {
            $data = $form->getValues();

            /* splod */
            $preference = BOL_PreferenceService::getInstance()->findPreference('splod_is_visible_whatsnew');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'splod_is_visible_whatsnew';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['SPLOD_visible'] ? $data['SPLOD_visible'] : 0;
            $preference->sortOrder = 1;
            BOL_PreferenceService::getInstance()->savePreference($preference);

            /* maplet */
            $preference = BOL_PreferenceService::getInstance()->findPreference('maplet_is_visible_whatsnew');

            if(empty($preference))
                $preference = new BOL_Preference();

            $preference->key = 'maplet_is_visible_whatsnew';
            $preference->sectionName = 'general';
            $preference->defaultValue = $data['Maplet_visible'] ? $data['Maplet_visible'] : 0;
            $preference->sortOrder = 1;
            BOL_PreferenceService::getInstance()->savePreference($preference);
        }

    }

    public function delete( $params )
    {
        if ( isset($params['id']) )
        {
            ODE_BOL_Service::getInstance()->deleteProvider((int) $params['id']);
        }
        $this->redirect(OW::getRouter()->urlForRoute('ode-providers'));
    }

    public function createDatasetCache()
    {
        ODE_BOL_Service::getInstance()->saveSetting('ode_datasets_list', $this->datasetsListBuilder());
        $this->redirect(OW::getRouter()->urlForRoute('ode-providers'));
    }

    /**** GET DATASETS LIST ****/

//    public function datasetTree()
//    {
//        header('content-type: application/json');
//        header("Access-Control-Allow-Origin: *");
//        echo $this->datasetTreeBuilder();
//        die();
//    }

    public function datasetsListBuilder()
    {
        $step = 100;
        $maxDatasetPerProvider = isset($_REQUEST['maxDataset']) ? $_REQUEST['maxDataset'] : 1;

        $providersDatasets = [];
        $providers = ODE_BOL_Service::getInstance()->getProviderList();

        foreach ($providers as $p) {

            $providerDatasetCounter = 0;
            $start = 0;

            // Build providers
            $providersDatasets[$p->id] = ['p_name' => $p->name, 'p_url' => $p->url, 'p_datasets' => []];

            // Try CKAN
            while($providerDatasetCounter < $maxDatasetPerProvider) {
                $ch = curl_init($p->url . "/api/3/action/package_search?start=" . $start . "&rows=" . $step);//1000 limit!
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                $res = curl_exec($ch);
                $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                if (200 == $retcode)
                {
                    $data = json_decode($res, true);

                    if(count($data["result"]["results"]))
                    {
//                        $providersDatasets[$p->id]['p_datasets'] = array_merge($providersDatasets[$p->id]['p_datasets'], $this->getCkanDatasets($data, $p->id));

                        $a = $this->getCkanDatasets($data, $p->id);
                        $l_a = count($a);
                        for($j = 0; $j < $l_a; $j++) {
                            $providersDatasets[$p->id]['p_datasets'][] = $a[$j];
                        }

                        $start += $step;
                        $providerDatasetCounter += count($data["result"]["results"]);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }

            // Try ODS
            $ch = curl_init($p->url . "/api/datasets/1.0/search/?rows=-1");
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            $res = curl_exec($ch);
            $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if (200 == $retcode) {
                $data = json_decode( $res, true );
//                $providersDatasets[$p->id]['p_datasets'] = array_merge($providersDatasets[$p->id]['p_datasets'], $this->getOpenDataSoftDatasets($data, $p->id));

                $a = $this->getOpenDataSoftDatasets($data, $p->id);
                $l_a = count($a);
                for($j = 0; $j < $l_a; $j++) {
                    $providersDatasets[$p->id]['p_datasets'][] = $a[$j];
                }
                continue;
            }

            // Try DKAN
            $ch = curl_init($p->url . "/?q=api/3/action/current_package_list_with_resources");
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $res = curl_exec($ch);
            $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if (200 == $retcode) {
                $data = json_decode( $res, true );

                $a = $this->getDKANDatasets($data, $p->id);
                $l_a = count($a);
                for($j = 0; $j < $l_a; $j++) {
                    $providersDatasets[$p->id]['p_datasets'][] = $a[$j];
                }
                continue;
            }

        }

        return json_encode($providersDatasets);
    }

//    private function getCkanDatasets($data, $provider_id) {
//        $treemapdata = array();
//        $datasets = $data['result']['results'];
//        $datasetsCnt = count( $datasets );
//        for ($i = 0; $i < $datasetsCnt; $i++) {
//            $ds = $datasets[$i];
//            $resourcesCnt = count($ds['resources']);
//            if($resourcesCnt > 1) {
//                $resources = array();
//                for ($j = 0; $j < $resourcesCnt; $j++)
//                    $resources[] = $ds['resources'][$j]['name'];
//                $treemapdata[] = array(
//                    'name' => $ds['name'],
//                    'id' => $ds['id'],
//                    'p' => 'CKAN_' . $provider_id,
//                    'resources' => $resources
//                );
//            }
//            else
//                $treemapdata[] = array(
//                    'name' => $ds['name'],
//                    'id' => $ds['id'],
//                    'p' => 'CKAN_' . $provider_id
//                );
//        }
//        return $treemapdata;
//    }

    private function getCkanDatasets($data, $provider_id) {
        $filter = ['csv', 'ods', 'xls', 'xlsx'];

        $treemapdata = array();
        $datasets = $data['result']['results'];
        $datasetsCnt = count( $datasets );
        for ($i = 0; $i < $datasetsCnt; $i++) {
            $ds = $datasets[$i];
            $resourcesCnt = count($ds['resources']);
            $resources = array();
            for ($j = 0; $j < $resourcesCnt; $j++)
//                if (strcasecmp($ds['resources'][$j]['format'], 'csv') == 0)

                if (in_array(strtolower($ds['resources'][$j]['format']), $filter))
                    $resources[] = $ds['resources'][$j]['name'];
                else
                    $resources[] = [$ds['resources'][$j]['name'], 'disabled'];

//                $resources[] =  $this->sanitizeInput($ds['resources'][$j]['name']);

                if (count($resources) == 1)
                    $treemapdata[] = array(
                        'name' => $ds['title'] ? $this->sanitizeInput($ds['title']) : $this->sanitizeInput($ds['name']),
                        'id' => $ds['id'],
                        'p' => 'CKAN_' . $provider_id
                    );
                else if(count($resources) > 1)
                    $treemapdata[] = array(
                        'name' => $ds['title'] ? $this->sanitizeInput($ds['title']) : $this->sanitizeInput($ds['name']),
                        'id' => $ds['id'],
                        'p' => 'CKAN_' . $provider_id,
                        'resources' => $resources
                    );
        }
        return $treemapdata;
    }

    private function getOpenDataSoftDatasets($data, $provider_id) {
        $treemapdata = array();
        $datasets = $data['datasets'];
        $datasetsCnt = count( $datasets );
        for ($i = 0; $i < $datasetsCnt; $i++) {
            $ds = $datasets[$i];

            @$treemapdata[] = array(
                'name' => $this->sanitizeInput($ds['metas']['title']),
                'id' => $this->sanitizeInput($ds['datasetid']),
                'p' => 'ODS_' . $provider_id
            );
        }
        return $treemapdata;
    }

    private function getDKANDatasets($data, $provider_id)
    {
        $treemapdata = array();
        $datasets = $data['result'];
        $datasetsCnt = count( $datasets );

        for ($i = 0; $i < $datasetsCnt; $i++)
        {
            $ds = $datasets[$i];
            $resourcesCnt = count($ds['resources']);
            $resources = array();

            for ($j = 0; $j < $resourcesCnt; $j++)
                $resources[] =  $this->sanitizeInput($ds['resources'][$j]['title']);

            if (count($resources) == 1)
                $treemapdata[] = array(
                    'name' => $this->sanitizeInput($ds['title']),
                    'id' => $ds['id'],
                    'p' => 'DKAN_' . $provider_id
                );
            else if(count($resources) > 1)
                $treemapdata[] = array(
                    'name' => $this->sanitizeInput($ds['title']),
                    'id' => $ds['id'],
                    'p' => 'DKAN_' . $provider_id,
                    'resources' => $resources
                );
        }

        return $treemapdata;

    }

    protected function sanitizeInput($str)
    {
//        return str_replace("'", "'", !empty($str) ? $str : "");
        return $str;
    }

}


text:
<!DOCTYPE html>
    <?php
    require_once ('../model/connect.php');
    require_once ('upOrder.php');

    if (isset($_POST['product_id']) && (!empty($_POST['product_id'])))  {
      uploadSold();
     // header("Refresh:0");
    }
    ?>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>About - Business Casual - Start Bootstrap Theme</title>

        <link href="css/bootstrap.min.css" rel="stylesheet">

        <link href="css/business-casual.css" rel="stylesheet">

        <link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
        <link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

Zoo Shop

 | give us your money |

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>

                    Business Casual

                            Home

                            Products

                            Promotion

                            Sold History

                            Order

                        Sold History

                       <?php

          require_once ('../model/connect.php');

          if ($conn) {
            $sql = "SELECT s.RUNNINGNO,s.PRODUCTNO,s.AMOUNT,p.PRICE*s.AMOUNT,s.PRICE
                    FROM EMM_ZOO.PRODUCT as p , EMM_ZOO.HISTORYSOLD as s
                    WHERE p.PRODUCTNO = s.PRODUCTNO;";

            $stmt = dbQuery($conn,$sql);

            if($stmt == FALSE) {
               die('Critical error: '. db2_stmt_error($stmt));
          }

          echo("

                                 #

                                Product ID

                                Amount

                                Price

                                Price afer Promotion

");
          echo("
");
          while ($row = dbFetchArray($conn,$stmt)) {
          echo "\t

            $row[0]
            $row[1]
            $row[2]
            $row[3]
            $row[4]

\n";
          }
          echo("
");
          echo "
\n";
          db2_free_stmt($stmt);
          db2_close($conn);
          }
          else {
          echo "Connection failed" .db2_conn_errormsg($conn);
          }
      ?>

                    <form role="form" method = "post">

                            ProductID
                            <input type="text" placeholder ="xxxx" name="product_id" class="form-control">

                            amount
                            <input type="text" name="amount"class="form-control">

                            Date
                            <input type="text" placrholder = "yyyy-mm-dd" name="date" class="form-control">

                                SHOP Location
                               <select name="location"  class="form-control" rows="5" style="width : 250px">
                                <option value="shop1">SHOP1</option>
                                <option value="shop2">SHOP2</option>
                                <option value="shop3">SHOP3</option>
                                <option value="shop4">SHOP4</option>
                        </select>

                            <button type="submit" class="btn btn-default">ADD</button>

                </form>

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path('../boot', __FILE__)

# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Orientation
  class Application < Rails::Application
    config.exceptions_app = self.routes

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/extras)

    # Configure sensitive parameters which will be filtered from the log file.
    config.filter_parameters += [:password]

    # Use SQL instead of Active Record's schema dumper when creating the database.
    # This is necessary if your schema can't be completely dumped by the schema dumper,
    # like if you have constraints or database-specific column types.
    config.active_record.schema_format = :sql

    # Enable the asset pipeline.
    config.assets.enabled = true

    # Version of your assets, change this if you want to expire all your assets.
    config.assets.version = '1.0'

    # Precompilation assets list
    config.assets.precompile += %w( vendor.js )

    # Asset paths list
    config.assets.paths << Rails.root.join('bower_components')

    # Prevent Rails from initializing during the precompile phase on Heroku
    config.assets.initialize_on_precompile = false

    # prefer indented sass syntax
    config.sass.preferred_syntax = :sass

    config.generators do |g|
      g.test_framework :rspec
      g.view_specs false
      g.helper_specs false
    end

    # Do not swallow errors in after_commit/after_rollback callbacks.
    config.active_record.raise_in_transactional_callbacks = true

    # https://robots.thoughtbot.com/content-compression-with-rack-deflater
    config.middleware.use Rack::Deflater
  end
end


text:
using System.Data.Entity;
using System.Web;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using WebApi.OAuth.Jwt.Core;

namespace WebApi.OAuth.Jwt
{
    public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configure(FilterConfig.Configure);

            Database.SetInitializer(new Initializer());

            var formatters = GlobalConfiguration.Configuration.Formatters;
            var jsonFormatter = formatters.JsonFormatter;
            var settings = jsonFormatter.SerializerSettings;
            settings.Formatting = Formatting.Indented;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }
}


text:
from stepic.discrete_math.gauss_method import gauss_method

__author__ = 'mlaptev'

def difference_between_vectors(minuend_vector, subtrahend_vector):
    """
    >>> difference_between_vectors([2, 3, 4], [1, 1, 1])
    [1, 2, 3]
    """
    return [minuend_vector[i] - subtrahend_vector[i] for i in range(len(minuend_vector))]

def multiply_vector_by_value(vector, value):
    """
    >>> multiply_vector_by_value([1, 2, 3], 5)
    [5, 10, 15]
    """
    return [vector[i] * value for i in range(len(vector))]

def scalar_multiplication(first_vector, second_vector):
    """
    >>> scalar_multiplication([2, 3, 4], [3, 4, 6])
    42
    """
    return sum([first_vector[i]*second_vector[i] for i in range(len(first_vector))])

def process_initial_data(list_of_vectors, result_vector):
    """
    >>> processed_matrix, processed_vector = process_initial_data([[2, 3, 4]], [3, 4, 6])
    >>> processed_matrix
    [[29]]
    >>> processed_vector
    [42]
    """
    processed_matrix = list()
    processed_vector = list()
    for equation_id in range(len(list_of_vectors)):
        # calculate value for processed vector
        processed_vector.append(scalar_multiplication(result_vector, list_of_vectors[equation_id]))
        # calculate value for equation
        processed_matrix.append([scalar_multiplication(list_of_vectors[equation_id], list_of_vectors[another_equation_id]) for another_equation_id in range(len(list_of_vectors))])

    return processed_matrix, processed_vector

def ordinary_least_squares(list_of_vectors, result_vector):
    """
    >>> ordinary_least_squares([[2, 3, 4]], [3, 4, 6])
    [1.4482758620689655]
    >>> ordinary_least_squares([[1, 1, 1], [-1, 0, 1]], [4, 5, 9])
    [6.0, 2.5]
    """
    processed_matrix, processed_vector = process_initial_data(list_of_vectors, result_vector)
    gauss_method(processed_matrix, processed_vector)
    return processed_vector

def calculate_minimum_of_discrepancy(list_of_vectors, result_vector):
    """
    >>> calculate_minimum_of_discrepancy([[1, 1, 1], [-1, 0, 1]], [4, 5, 9])
    1.5
    """
    discrepancy_vector = ordinary_least_squares(list_of_vectors, result_vector)
    difference = result_vector[:]
    for position in range(len(list_of_vectors)):
        difference = difference_between_vectors(difference,
                                                multiply_vector_by_value(list_of_vectors[position],
                                                                         discrepancy_vector[position]))
    return scalar_multiplication(difference, difference)

if __name__ == "__main__":
    # data initialization
    data = list(map(lambda x: int(x), input().split()))
    amount_of_equations = data[0]
    amount_of_variables = data[1]
    list_of_vectors = [list() for dummy_i in range(amount_of_variables)]
    result_vector = list()
    for equation_id in range(amount_of_equations):
        equation = list(map(lambda x: float(x), input().split()))
        for position in range(amount_of_variables):
            list_of_vectors[position].append(equation[position])
        result_vector.append(equation[-1])

    discrepancy_vector = ordinary_least_squares(list_of_vectors, result_vector)
    print(" ".join([str(discrepancy) for discrepancy in discrepancy_vector]))


text:
#if cAlgo
using cAlgo.API;
using cAlgo.API.Internals;
#endif
using System.Diagnostics;

using LionFire.Trading.Bots;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LionFire.Trading
{

    public class BotPosition : IOnBar
    {

        #region Ontology

        public IBot Bot
        {
            get { return bot; }
        }
        IBot bot;
        public ISingleChartBot SingleChartBot { get { return bot as ISingleChartBot; } }
        public ISingleChartBotEx BotEx
        {
            get { return bot as ISingleChartBotEx; }
        }

        public Position Position
        {
            get { return position; }
        }
        Position position;

        public Symbol Symbol
        {
            get { return symbol; }
        }
        Symbol symbol;

        #endregion

        #region State

        public double? MinStopLoss
        {
            get { return minStopLoss; }
            set
            {
                if (minStopLoss == value)
                    return;
                minStopLoss = value;
                //    l.LogTrace("[MIN SL] " + value);
            }
        }
        private double? minStopLoss;
        public double? MaxStopLoss;
        public double? MinTakeProfit;
        public double? MaxTakeProfit;

        public int DefaultBarsSinceOpen = 0;
        public TimeFrame DefaultTimeFrame
        {
            get; set;
        }

        public double NewStopLoss = double.NaN;

        public double ClosePoints { get; set; }
        public double BarsSinceLastClosePointsIncrease { get; set; }

        #endregion

        #region State (Derived)

        public int BarsSinceOpen(TimeFrame timeFrame)
        {
            if (timeFrame == DefaultTimeFrame)
            {
                return DefaultBarsSinceOpen;
            }
            throw new NotImplementedException("timeFrame != DefaultTimeFrame");
        }

        #endregion

        public BotPosition(Position position, IBot bot, Symbol symbol, TradeType tradeType, double stopLossInPips, double takeProfitInPips, double volumeInUnits)
        {
            this.bot = bot;
            this.position = position;
            this.symbol = symbol;
#if !cAlgo
            if (position == null)
            {
                double sl = symbol.GetStopLossFromPips(tradeType, stopLossInPips);
                double tp = symbol.GetTakeProfitFromPips(tradeType, takeProfitInPips);
                position = new Position()
                {
                    TradeType = tradeType,
                    StopLoss = sl,
                    TakeProfit = tp,
                    Volume = volumeInUnits,
                };
                Debug.WriteLine($"[BOT POSITION] {this}");
            }
#endif
            this.DefaultTimeFrame = (bot as ISingleChartBot)?.TimeFrame;
            this.onBars = new List<IOnBar>();
            this.MinStopLoss = position.StopLoss;
            this.MinTakeProfit = position.TakeProfit;
        }

        /*public void OnTick(object sender)
        {
            Robot bot = (Robot)sender;
            TimeFrame timeFrame = bot.TimeFrame;

            CloseIfStopLossTriggered();
            CloseIfTakeProfitTriggered()
        }*/

        public void CloseIfStopLossTriggered()
        {
            //l.LogTrace("[sl close debug] SL: " + StopLoss + " Ask: " + symbol.Ask + " " + TradeMath.IsStopLossTriggered(StopLoss, position, symbol));
            if (TradeMath.IsStopLossTriggered(StopLoss, position, symbol))
            {
                /* if (position.TradeType == TradeType.Sell)
                {
                    l.LogTrace("[SL CLOSE] Ask: " + symbol.Ask + " SL:" + StopLoss);
                }
                else
                {
                    l.LogTrace("[SL CLOSE] Bid: " + symbol.Bid + " SL:" + StopLoss);
                }*/
                bot.ClosePosition(position);
                return;
            }
        }
        public void CloseIfTakeProfitTriggered()
        {
            if (TradeMath.IsTakeProfitTriggered(TakeProfit, position, symbol))
            {
                //l.LogTrace("[TP CLOSE]");
                bot.ClosePosition(position);
                return;
            }
        }

        public double? StopLoss;
        public double? TakeProfit;

        public double? StopLoss_
        {
            get
            {
                var val = TradeMath.Constrain(position.StopLoss, MinStopLoss, MaxStopLoss, position.TradeType);

                if (val.HasValue && double.IsNaN(val.Value))
                {
                    // If Min & Max conflict, take the most aggressive to close the position
                    l.LogTrace("SL: Min " + MinStopLoss + " > Max* " + MaxStopLoss);
                    val = MaxStopLoss;
                }
#if TRACE_SL
                else
                {
                    l.LogTrace("SL=" + val);
                }
#endif
                return val;
            }
        }
        public double? TakeProfit_
        {
            get
            {
                var val = TradeMath.Constrain(position.TakeProfit, MinTakeProfit, MaxTakeProfit, position.TradeType);
                if (val.HasValue && double.IsNaN(val.Value))
                {
                    if (MinTakeProfit.HasValue && !double.IsNaN(MinTakeProfit.Value))
                    {
                        // If Min & Max conflict, take the most aggressive to close the position
                        l.LogTrace("TP: Min* " + MinTakeProfit + " > Max " + MaxTakeProfit);
                        val = MinTakeProfit;
                    }
                    else
                    {
                        if (MaxTakeProfit.HasValue && !double.IsNaN(MaxTakeProfit.Value))
                        {
                            val = MaxTakeProfit.Value;
                        }
                        else
                        {
                            val = null;
                        }
                    }
                }
                return val;
            }
        }

        public List<IOnBar> onBars { get; set; }

        public void OnBar(object sender, TimeFrame timeFrame)
        {
            double lastClosePoints = ClosePoints;

            DefaultBarsSinceOpen++;

            foreach (var hasOnBar in onBars)
            {
                hasOnBar.OnBar(sender, timeFrame);
            }

            TakeProfit = TakeProfit_;
            StopLoss = StopLoss_;

            CloseIfStopLossTriggered();
            CloseIfTakeProfitTriggered();

            var botEx = bot as ISingleChartBotEx;
            if (botEx != null)
            {

                if ((position.TradeType == TradeType.Buy && (StopLoss <= Symbol.Bid && StopLoss - position.StopLoss >= Symbol.TickSize || TakeProfit >= Symbol.Bid && TakeProfit - position.TakeProfit >= Symbol.TickSize)) || (position.TradeType == TradeType.Sell && (StopLoss >= Symbol.Ask && position.StopLoss - StopLoss >= Symbol.TickSize || TakeProfit <= Symbol.Ask && position.TakeProfit - TakeProfit >= Symbol.TickSize)))            /*if (!TakeProfit.AboutEquals(position.TakeProfit, Symbol.PipSize / 10.0)
             || !StopLoss.AboutEquals(position.StopLoss, Symbol.PipSize / 10.0))*/
                {
                    //l.LogTrace("[MOD] Modifying position: SL:" + StopLoss + " (was " + position.StopLoss + ") TP:" + TakeProfit + " (was: " + position.TakeProfit + ")");
                    bot.ModifyPosition(position, StopLoss, botEx.UseTakeProfit ? TakeProfit : double.NaN);
                }
                else if (StopLoss.HasValue && position.StopLoss.HasValue && StopLoss != position.StopLoss)
                {
                    //                l.LogTrace("[mod sl debug] (Not modifying SL) StopLoss (" + StopLoss.Value + ") != position.StopLoss (" + position.StopLoss.Value + ")  pip: " + Symbol.PipSize + " diff:" + (StopLoss.Value - position.StopLoss.Value) + " abs(diff)-pip: " + (Math.Abs(StopLoss.Value - position.StopLoss.Value) - Convert.ToDouble(Symbol.PipSize)));

                }

                if (lastClosePoints == ClosePoints)
                {
                    if (ClosePoints > 0 && ++BarsSinceLastClosePointsIncrease >= botEx.ClosePointsBackoffFreezeBars)
                    {
                        ClosePoints -= botEx.ClosePointsBackoff;

#if TRACE_ClosePoints
                    l.LogTrace("[closepoints backoff] " + ClosePoints);
#endif
                    }
                }
            }
        }

        #region Misc

        public Microsoft.Extensions.Logging.ILogger Logger { get { return l; } }
        private Microsoft.Extensions.Logging.ILogger l { get { return bot?.Logger; } }

        #endregion
    }
    /*
            if(sl.HasValue && (position.TradeType sl.Value > bot.Symbol.Ask)
            var tp = TradeMath.Constrain(position.TakeProfit, MinTakeProfit, MaxTakeProfit, position.TradeType);
            if(TradeMath.GreaterOrEqual(MinStopLoss, position.StopLoss, position.TradeType))
            {
            }
            */

}


text:
package com.orgsync.api.model.timesheets;

import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.reflect.TypeToken;
import com.orgsync.api.model.IdAndName;

/**
 * A model for a timesheet.
 *
 * @author steffyj
 *
 */
public class Timesheet {

    public static final Type TYPE = new TypeToken<Timesheet>() {
    }.getType();

    public static final Type LIST_TYPE = new TypeToken<List<Timesheet>>() {
    }.getType();

    private int id;
    private String startDate;
    private String endDate;
    private String alternateOrgName;
    private TimesheetAccount account;
    private IdAndName org;
    private IdAndName event;
    private String description;
    private float hours;
    private String status;
    private String attendanceStatus;

    public final int getId() {
        return id;
    }

    public final String getStartDate() {
        return startDate;
    }

    public final String getAlternateOrgName() {
        return alternateOrgName;
    }

    public final TimesheetAccount getAccount() {
        return account;
    }

    public final IdAndName getOrg() {
        return org;
    }

    public final IdAndName getEvent() {
        return event;
    }

    public final String getDescription() {
        return description;
    }

    public final float getHours() {
        return hours;
    }

    public final String getEndDate() {
        return endDate;
    }

    public final String getStatus() {
        return status;
    }

    public final String getAttendanceStatus() {
        return attendanceStatus;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Timesheet)) return false;

        Timesheet timesheet = (Timesheet) o;

        if (Float.compare(timesheet.hours, hours) != 0) return false;
        if (id != timesheet.id) return false;
        if (account != null ? !account.equals(timesheet.account) : timesheet.account != null) return false;
        if (alternateOrgName != null ? !alternateOrgName.equals(timesheet.alternateOrgName) : timesheet.alternateOrgName != null)
            return false;
        if (attendanceStatus != null ? !attendanceStatus.equals(timesheet.attendanceStatus) : timesheet.attendanceStatus != null)
            return false;
        if (description != null ? !description.equals(timesheet.description) : timesheet.description != null)
            return false;
        if (endDate != null ? !endDate.equals(timesheet.endDate) : timesheet.endDate != null) return false;
        if (event != null ? !event.equals(timesheet.event) : timesheet.event != null) return false;
        if (org != null ? !org.equals(timesheet.org) : timesheet.org != null) return false;
        if (startDate != null ? !startDate.equals(timesheet.startDate) : timesheet.startDate != null) return false;
        if (status != null ? !status.equals(timesheet.status) : timesheet.status != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (startDate != null ? startDate.hashCode() : 0);
        result = 31 * result + (endDate != null ? endDate.hashCode() : 0);
        result = 31 * result + (alternateOrgName != null ? alternateOrgName.hashCode() : 0);
        result = 31 * result + (account != null ? account.hashCode() : 0);
        result = 31 * result + (org != null ? org.hashCode() : 0);
        result = 31 * result + (event != null ? event.hashCode() : 0);
        result = 31 * result + (description != null ? description.hashCode() : 0);
        result = 31 * result + (hours != +0.0f ? Float.floatToIntBits(hours) : 0);
        result = 31 * result + (status != null ? status.hashCode() : 0);
        result = 31 * result + (attendanceStatus != null ? attendanceStatus.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Timesheet{");
        sb.append("id=").append(id);
        sb.append(", startDate='").append(startDate).append('\'');
        sb.append(", endDate='").append(endDate).append('\'');
        sb.append(", alternateOrgName='").append(alternateOrgName).append('\'');
        sb.append(", account=").append(account);
        sb.append(", org=").append(org);
        sb.append(", event=").append(event);
        sb.append(", description='").append(description).append('\'');
        sb.append(", hours=").append(hours);
        sb.append(", status='").append(status).append('\'');
        sb.append(", attendanceStatus='").append(attendanceStatus).append('\'');
        sb.append(", super=").append(super.toString());
        sb.append('}');
        return sb.toString();
    }
}


text:
![Travis CI Build Status](https://travis-ci.org/BuckeyeHackers/rateathon.svg?branch=master)

This is a site where hackathon attendees can rate hackathons they have attended in hopes of making them better!


text:
from .base import *

SITE_NAME = "Live"
DEBUG = False
SECURE_SSL_REDIRECT = True

env_path = os.path.join(BASE_DIR, ".env")
environ.Env.read_env(env_path)

INSTALLED_APPS += ["raven.contrib.django.raven_compat"]

DATABASES = {"default": env.db_url("DATABASE_URL")}

ALLOWED_HOSTS = ["www.coombewoodltc.com", "www.coombewoodltc.co.uk"]

TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG

STATIC_ROOT = os.path.join(BASE_DIR, "static_files/")
SECRET_KEY = env.str("SECRET_KEY")

BEE_FREE_ID = env.str("BEE_FREE_ID")
BEE_FREE_SECRET = env.str("BEE_FREE_SECRET")

POS_COOKIE = env.str("POS_COOKIE")

EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
ANYMAIL = env.dict("ANYMAIL")

CARDLESS_ACCESS_TOKEN = env.str("CARDLESS_PRODUCTION_TOKEN")
CARDLESS_ENVIRONMENT = "live"
CARDLESS_WEBHOOK_SECRET = env.str("CARDLESS_WEBHOOK_SECRET")

RAVEN_CONFIG = {"dsn": env.str("RAVEN")}

# https://www.webforefront.com/django/setupdjangologging.html
LOGGING = {
    "version": 1,
    "disable_existing_loggers": True,
    "filters": {
        "require_debug_false": {"()": "django.utils.log.RequireDebugFalse"},
        "require_debug_true": {"()": "django.utils.log.RequireDebugTrue"},
    },
    "formatters": {
        "simple": {"format": "[%(asctime)s] %(levelname)s %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S"},
        "verbose": {
            "format": "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S",
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "filters": ["require_debug_true"],
            "class": "logging.StreamHandler",
            "formatter": "simple",
        },
        "production_logfile": {
            "level": "INFO",
            "filters": ["require_debug_false"],
            "class": "logging.handlers.RotatingFileHandler",
            "filename": "./logs/django.log",
            "maxBytes": 1024 * 1024 * 10,  # 10MB
            "backupCount": 5,
            "formatter": "simple",
        },
        "sentry": {
            "level": "ERROR",  # To capture more than ERROR, change to WARNING, INFO, etc.
            "filters": ["require_debug_false"],
            "class": "raven.contrib.django.raven_compat.handlers.SentryHandler",
            "tags": {"custom-tag": SITE_NAME},
        },
    },
    "root": {"level": "DEBUG", "handlers": ["console"]},
    "loggers": {
        "members": {"handlers": ["production_logfile", "sentry"]},
        "django": {"handlers": ["console", "sentry"], "propagate": True},
        # stop sentry logging disallowed host
        "django.security.DisallowedHost": {"handlers": ["console"], "propagate": False},
        "django.request": {  # debug logging of things that break requests
            "handlers": ["production_logfile", "sentry"],
            "level": "DEBUG",
            "propagate": True,
        },
    },
    "py.warnings": {"handlers": ["console"]},
}

WAGTAIL_CACHE = True
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
        "LOCATION": os.path.join(BASE_DIR, "cache"),
        "KEY_PREFIX": "coderedcms",
        "TIMEOUT": 14400,  # in seconds
    }
}
# todo cache and template loaders


text:
require 'test_helper'

class TestStrictTypes < ConfigurationsTest
  setup_with :strict_types
  shares_tests :properties, :properties_outside_block, :kernel_methods

  def test_configure_with_wrong_type
    assert_raises Configurations::ConfigurationError do
      @configuration.p1 = :symbol
    end
  end

  def test_configure_nested_with_wrong_type
    assert_raises Configurations::ConfigurationError do
      @configuration.p3.p5.p6 = 'STRING'
    end
  end
end


text:
All requests are processed through Watson's pre-routing handler, if it has been assigned.  The pre-routing handler indicates whether or not the request should be permitted to to continue.

Beyond the pre-routing handler, Watson includes following types of routing:

- **Content routes** - specifically for serving objects (GET) or verifying existence (HEAD)
- **Static routes** - routes with specific URLs
- **Parameter routes** - routes with URLs that contain variables, for instance, ```/customer/{id}```
- **Dynamic routes** - routes with more complex URLs defined by regular expression
- **Default route** - any request not matching a content, static, parameter, or dynamic route is processed using the default route

## Pre-Routing Handler

All requests are processed through Watson's pre-routing handler, if it has been assigned.

### Assigning the Pre-Routing Handler
```csharp
using WatsonWebserver;

Server server = new Server("localhost", 8000, false, DefaultRoute);
server.Routes.PreRouting = PreRoutingHandler;

static async Task<bool> PreRoutingHandler(HttpContext ctx)
{
  return false;  // allow the connection
}

static async Task DefaultRoute(HttpContext ctx)
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("Hello from the default route!");
}
```

The ```HttpContext``` is passed into the pre-routing handler, giving you visibility into everything you may want to know about the request.  If you ```return true```, this indicates that Watson should terminate the connection, i.e. it should not be allowed to continue through to other routes.  If you ```return false```, this indicates that Watson should allow the connection through to other routes.

The pre-routing handler is commonly used for tasks such as authentication, access control, and logging.

## Content Routes

Content routes are used to serve files from Watson (i.e. HTTP GET requests) and verify existence of files (i.e. HTTP HEAD requests).

### Set the Base Directory

You should not need to set the base directory unless it is different than the directory from which your server is running.

```csharp
server.Routes.Content.BaseDirectory = "./";
```

### Specify Content Routes
```csharp
server.Routes.Content.Add("/html/", true);            // the entire directory
server.Routes.Content.Add("/large/", true);           // the entire directory
server.Routes.Content.Add("/img/watson.jpg", false);  // individual files work too!
```

Content routes only work for HTTP GET and HEAD requests.

## Static Routes

Static routes are specific URL endpoints and specific HTTP methods without variables.  For example, ```POST /login``` may be a static route.

Static routes can be defined multiple ways.  All three are functionally equivalent.

1) Using the ```StaticRoute``` attribute
2) Adding a method to the ```StaticRouteManager```
3) Adding an inline function to the ```StaticRouteManager```

### Using the StaticRoute Attribute

The ```StaticRoute``` attribute can be applied to a method.  This will automatically include the static route in Watson without any additional configuration.
```csharp
[StaticRoute(HttpMethod.GET, "/login")]
public static async Task LoginRoute(HttpContext ctx)
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("You're in!");
}
```

### Adding a Method to StaticRouteManager
```csharp
public static async Task LoginRoute(HttpContext ctx)
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("You're in!");
}

server.Routes.Static.Add(HttpMethod.POST, "/login", LoginRoute);
```

### Adding Inline Function to StaticRouteManager
```csharp
server.Routes.Static.Add(HttpMethod.POST, "/login", async (ctx) =>
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("You're in!");
  return;
});
```

## Parameter Routes

Parameter routes are specific URL endpoints and specific HTTP methods **with** variables.  For example, ```GET /order/{id}``` may be a parameter route, because ```{id}``` is a variable that is needed for processing the request.

Parameters, if matched within the URL, appear in ```HttpContext.Request.Url.Parameters```.  For instance, in the case of a parameter route ```GET /order/{id}``` and an incoming request of ```GET /order/123```, the ID (of ```123```) could be accessed using ```HttpContext.Request.Url.Parameters["id"]```.

Like static routes, parameter routes can be added using the ```ParameterRoute``` attribute, by adding a method to the ```ParameterRouteManager```, or by adding an inline function to the ```ParameterRouteManager```.

### Using the ParameterRoute Attribute

The ```ParameterRoute``` attribute can be applied to a method.  This will automatically include the parameter route in Watson without any additional configuration.
```csharp
[ParameterRoute(HttpMethod.GET, "/order/{id}")]
public static async Task GetOrderRoute(HttpContext ctx)
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("Here are details for order ID " + ctx.Request.Url.Parameters["id"] + "!");
}
```

### Adding a Method to ParameterRouteManager
```csharp
public static async Task GetOrderRoute(HttpContext ctx)
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("Here are details for order ID " + ctx.Request.Url.Parameters["id"] + "!");
}

server.Routes.Parameter.Add(HttpMethod.GET, "/order/{id}", GetOrderRoute);
```

### Adding Inline Function to ParameterRouteManager
```csharp
server.Routes.Parameter.Add(HttpMethod.GET, "/order/{id}", async (ctx) =>
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("Here are details for order ID " + ctx.Request.Url.Parameters["id"] + "!");
});
```

## Dynamic Routes

Dynamic routes are URL endpoints defined by a regular expression and specific HTTP methods.  For example, ```GET ^/order/\\d+$``` would be a dynamic route, and would match ```/order/1``` and ```/order/abcd```, etc.

Like static and parameter routes, dynamic routes can be added using the ```DynamicRoute``` attribute, by adding a method to the ```DynamicRouteManager```, or by adding an inline function to the ```DynamicRouteManager```.

It is best to understand that URL elements can be accessed using ```HttpContext.Request.Url.Elements```.  For instance, in the case of ```GET /order/abcd```, ```order``` would be found in ```HttpContext.Request.Url.Elements[0]```, and ```abcd``` would be found in ```HttpContext.Request.Url.Elements[1]```.

### Using the DynamicRoute Attribute

The ```DynamicRoute``` attribute can be applied to a method.  This will automatically include the dynamic route in Watson without any additional configuration.
```csharp
[DynamicRoute(HttpMethod.GET, "^/order/\\d+$")]
public static async Task GetOrderRoute(HttpContext ctx)
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("Here are details for order ID " + ctx.Request.Url.Elements[1] + "!");
}
```

### Adding a Method to DynamicRouteManager
```csharp
public static async Task GetOrderRoute(HttpContext ctx)
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("Here are details for order ID " + ctx.Request.Url.Elements[1] + "!");
}

server.Routes.Dynamic.Add(HttpMethod.GET, "^/order/\\d+$", GetOrderRoute);
```

### Adding Inline Function to DynamicRouteManager
```csharp
server.Routes.Dynamic.Add(HttpMethod.GET, "^/order/\\d+$", async (ctx) =>
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("Here are details for order ID " + ctx.Request.Url.Elements[1] + "!");
});
```

## Default Route

The default route is also known as the ```route of last resort```.  i.e. if no other route could be matched, this is the route that gets the job of handling the request.  Don't get me wrong, you could literally build your entire set of APIs within the default route (and it would work just fine).  But, it's a best practice to use the default route as just that - the ```route of last resort```.

### Defining Default Route During Instantiation
```csharp
Server server = new Server("localhost", 8000, false, DefaultRoute);

static async Task DefaultRoute(HttpContext ctx)
{
  ctx.Response.StatusCode = 200;
  await ctx.Response.Send("Hello from the default route!");
}
```

### Defining Default Route in Settings
```csharp
server.Settings.Routes.Default = DefaultRoute;
```


text:
package com.mychess.mychess;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mychess.mychess.Chess.Chess;
import com.mychess.mychess.Chess.Ubicacion;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.ArrayList;
import java.util.zip.Inflater;

public class Juego extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    Servicio mService;
    boolean mBound = false;

    ImageView casillas[][] = new ImageView[8][8];
    ImageView origen;
    ImageView destino;
    TextView tiempo;
    Tiempo tiempoMovimiento;

    TextView nombreColumnas[] = new TextView[8];
    TextView numeroFila[] = new TextView[8];

    int cOrigen;
    int cDestino;
    int fOrigen;
    int fDestino;

    boolean enroqueBlanco = true;
    boolean enroqueNegro = true;

    boolean jugadaLocal;// sirve para difenciar entre una jugada local y una remota
    boolean juegoIniciado;
    Chess chess;
    TextView nombreUsuario;

    RecibirMovimientos movimientos;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_juego);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Tablero tab = new Tablero(casillas,nombreColumnas,numeroFila,this);
        jugadaLocal =  tab.inicializarCasillasNegro();
        Bundle bundle = getIntent().getExtras();
        if(bundle != null)
        {
            if(bundle.getBoolean("juegoIniciado")){
               new RecibirMovimientos().start();
            }
        }else{
            new SocketServidor().conectar();
            MainThread.iniciar();
        }
        setOnclickListener();
        setDefaultColor();
        juegoIniciado = true;
        handler  = new Handler();
        /**-------------------------**/
        nombreUsuario = (TextView) findViewById(R.id.nombreUsuario);
        nombreUsuario.setText(new Usuario(getApplicationContext()).getUsuario());
        /*--------------------------*/
        /********** inicializacion del tiempo *******/
        tiempo = (TextView) findViewById(R.id.textView18);
        tiempoMovimiento = new Tiempo();

        /* inicializcion del nuevo juego*/
        chess = new Chess();
        chess.newGame();
        /*---------------------*/

        RecibirInvitacion invitacion = new RecibirInvitacion();

        invitacion.start();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!juegoIniciado)
                    Toast.makeText(Juego.this, "No ha iniciado un juego todavía", Toast.LENGTH_SHORT).show();
                else if (jugadaLocal) {
                    SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Juego.this);
                    Speech speech = new Speech(Juego.this);
                    speechRecognizer.setRecognitionListener(speech);
                    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                    speechRecognizer.startListening(intent);
                } else
                    Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, Servicio.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Servicio.LocalBinder binder = (Servicio.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.juego, menu);
        if (juegoIniciado)
            return true;
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.jugar) {
            // Handle the camera action
        } else if (id == R.id.amigos) {

            Intent intent = new Intent(Juego.this, Amigos.class);

            startActivity(intent);

        } else if (id == R.id.logout) {
            DialogInterface.OnClickListener listenerOk = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    new Usuario(getApplicationContext()).clear();

                    Intent intent = new Intent(Juego.this, Acceso.class);
                    startActivity(intent);
                    finish();
                }
            };
            DialogInterface.OnClickListener listenerCanclar = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            };
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Mensaje");
            builder.setMessage("¿Está seguro que desea salir?");
            builder.setPositiveButton("Cerrar Sesión", listenerOk);
            builder.setNegativeButton("Cancelar", listenerCanclar);
            builder.create();
            builder.show();

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void setDefaultColor() {
        boolean dark = true;
        for (int i = 0; i < 8; ++i) {
            for (int j = 0; j < 8; ++j) {
                if (dark)
                    casillas[i][j].setBackgroundResource(R.color.casillablanca);
                else
                    casillas[i][j].setBackgroundResource(R.color.casillnegra);
                dark = !dark;
            }
            dark = !dark;
        }
    }

    private void setOnclickListener() {
        for (int i = 0; i < 8; ++i) {
            for (int j = 0; j < 8; ++j) {
                casillas[i][j].setOnClickListener(this);

            }

        }
    }

    private int[] getPosition(int id) {

        int position[] = {-1, -1};//inicialización del arreglo con valores negativos para indicar que el click no se realizó en una casilla

        for (int i = 0; i < 8; ++i) {
            for (int j = 0; j < 8; ++j) {
                if (id == casillas[i][j].getId()) {
                    position[0] = i;
                    position[1] = j;
                    return position;//si el click fue en una casilla se retorna la posicion
                }
            }

        }
        return position;//si el click no fue en una casilla se devuelven valores negativos en la posicion
    }

    private boolean validarCoordenadas(String coordenadas) {
        final String columnas = "abcdefgh";
        final String filas = "87654321";

        cOrigen = columnas.indexOf(coordenadas.charAt(0));
        cDestino = columnas.indexOf(coordenadas.charAt(2));
        fOrigen = filas.indexOf(coordenadas.charAt(1));
        fDestino = filas.indexOf(coordenadas.charAt(3));

        if (cOrigen == -1 || cDestino == -1 || fOrigen == -1 || fDestino == -1)
            return false;

        return true;

    }

    public void procesarResultados(ArrayList<String> listaCoordenadas) {
        String coordenadas;
        for (int i = 0; i < listaCoordenadas.size(); ++i) {
            coordenadas = listaCoordenadas.get(i).replace(" ", "").toLowerCase();
            if (coordenadas.length() == 4) {
                if (validarCoordenadas(coordenadas)) {

                    validarMovimiento(coordenadas);
                    break;

                }

            }

        }

    }

    private void enviarMovimiento(String coordendas) {
        DataOutputStream out;
        try {

            out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
            out.writeInt(3);
            out.writeUTF(coordendas);

            //tiempoMovimiento.reiniciar();
        } catch (IOException e) {
            Toast.makeText(Juego.this, "no hay conexion", Toast.LENGTH_SHORT).show();
        }

    }

    private void validarMovimiento(String coordenadas) {
        switch (chess.mover(coordenadas.substring(0, 2), coordenadas.substring(2, 4))) {

            case 2:
                Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                moverPieza(1, coordenadas);
                break;
            case 4:
                Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
                break;
            case 0:
                moverPieza(2, coordenadas);
                break;

        }
    }

    private void moverPieza(int n, String coordenada) {
        if (jugadaLocal) {
            enviarMovimiento(crearCoordenada());
            if (!enroque()) {
                casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
                casillas[cOrigen][fOrigen].setImageDrawable(null);
            }

        } else {
            validarCoordenadas(coordenada);
            if (!enroque()) {
                casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
                casillas[cOrigen][fOrigen].setImageDrawable(null);
            }

        }

        jugadaLocal = !jugadaLocal;

        if (n == 1) {
            Toast.makeText(Juego.this, "Jaque Mate", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean enroque() {

        if (enroqueBlanco)
            if (cOrigen == 4 && fOrigen == 7 && cDestino == 6 && fDestino == 7) {
                casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
                casillas[cOrigen][fOrigen].setImageDrawable(null);
                casillas[5][7].setImageDrawable(casillas[7][7].getDrawable());
                casillas[7][7].setImageDrawable(null);
                enroqueBlanco = !enroqueBlanco;
                return true;
            } else if (cOrigen == 4 && fOrigen == 7 && cDestino == 2 && fDestino == 7) {
                casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
                casillas[cOrigen][fOrigen].setImageDrawable(null);
                casillas[3][7].setImageDrawable(casillas[0][7].getDrawable());
                casillas[0][7].setImageDrawable(null);
                enroqueBlanco = !enroqueBlanco;
                return true;

            }
        if (enroqueNegro)
            if (cOrigen == 4 && fOrigen == 0 && cDestino == 6 && fDestino == 0) {
                casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
                casillas[cOrigen][fOrigen].setImageDrawable(null);
                casillas[5][0].setImageDrawable(casillas[7][0].getDrawable());
                casillas[7][0].setImageDrawable(null);
                enroqueNegro = !enroqueNegro;
                return true;
            } else if (cOrigen == 4 && fOrigen == 0 && cDestino == 2 && fDestino == 0) {
                casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
                casillas[cOrigen][fOrigen].setImageDrawable(null);
                casillas[3][0].setImageDrawable(casillas[0][0].getDrawable());
                casillas[0][0].setImageDrawable(null);
                enroqueNegro = !enroqueNegro;
                return true;

            }
        return false;
    }

    private String crearCoordenada() {
        String coordenada = "";
        final String columnas = "abcdefgh";
        final String filas = "87654321";
        coordenada += columnas.charAt(cOrigen);
        coordenada += filas.charAt(fOrigen);
        coordenada += columnas.charAt(cDestino);
        coordenada += filas.charAt(fDestino);

        return coordenada;
    }

    @Override
    public void onClick(View v) {
        if (!juegoIniciado)
            Toast.makeText(Juego.this, "No ha iniciado un juego todavía", Toast.LENGTH_SHORT).show();
        else if (jugadaLocal) {
            int position[] = getPosition(v.getId());
            if (position[0] != -1) {//si el valor es negativo indica que el click no se  realizo en una casilla
                if (origen == null) {
                    origen = casillas[position[0]][position[1]];
                    cOrigen = position[0];
                    fOrigen = position[1];
                    casillas[cOrigen][fOrigen].setBackgroundResource(R.color.origen);
                    for (Ubicacion u : chess.mostrarMovimientos(fOrigen, cOrigen)) {
                        casillas[u.getCol()][u.getFila()].setBackgroundResource(R.drawable.seleccion);
                    }
                } else {
                    cDestino = position[0];
                    fDestino = position[1];
                    destino = casillas[cDestino][fDestino];
                    if (!(destino == origen)) {
                        validarMovimiento(crearCoordenada());
                        setDefaultColor();
                    } else
                        setDefaultColor();
                    origen = null;
                }
            }
        } else {
            Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
        }

    }

    class Tiempo {
        CountDown countDown;

        public void iniciar() {
            countDown = new CountDown(60000, 1000);
            countDown.start();
        }

        public void detener() {
            countDown.cancel();

        }

        public void reiniciar() {
            tiempo.setText("60");
            tiempo.setTextColor(Color.WHITE);
            countDown.cancel();
        }

        class CountDown extends CountDownTimer {

            public CountDown(long millisInFuture, long countDownInterval) {
                super(millisInFuture, countDownInterval);
            }

            @Override
            public void onTick(long millisUntilFinished) {
                long time = millisUntilFinished / 1000;
                tiempo.setText(String.valueOf(time));
                if (time == 15)
                    tiempo.setTextColor(Color.RED);

            }

            @Override
            public void onFinish() {

            }
        }

    }

    class RecibirMovimientos extends Thread {

        @Override
        public void run() {
            super.run();
            boolean continuar = true;
            while (continuar) {
                try {
                    Thread.sleep(250);

                    if(ThreadsData.RECIBIR_MOVIMIENTO) {
                        ThreadsData.RECIBIR_MOVIMIENTO = false;
                        handler.post(run);

                    }
                } catch (Exception ex) {

                }

            }
        }
    Runnable run = new Runnable() {
          @Override
          public void run() {
              Toast.makeText(Juego.this, ThreadsData.MOVIMIENTO, Toast.LENGTH_SHORT).show();
              validarMovimiento(ThreadsData.MOVIMIENTO);
          }
      };
    }

   class RecibirInvitacion extends Thread {
       boolean continuar = true;

       @Override
       public void run() {
           super.run();
           while(continuar){
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               if(ThreadsData.RECIBIR_INVITACION){
                   ThreadsData.RECIBIR_INVITACION = false;
                   handler.post(run);
               }
           }
       }
       Runnable run = new Runnable() {
           @Override
           public void run() {
                mostrarDialogo();
           }
       };

        private void enviarRespuesta(int respuesta,String jugador){
            try {
                DataOutputStream out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
                out.writeInt(2);
                out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
                out.writeInt(respuesta);
                out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
                out.writeUTF(jugador);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

       private void mostrarDialogo(){
           DialogInterface.OnClickListener listenerOk = new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   enviarRespuesta(1,ThreadsData.INVITACION_USUARIO);
                   movimientos = new RecibirMovimientos();
                   movimientos.start();
               }
           };
           DialogInterface.OnClickListener listenerCanclar = new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   enviarRespuesta(0, ThreadsData.INVITACION_USUARIO);

                   dialog.cancel();
               }
           };
           AlertDialog.Builder builder = new AlertDialog.Builder(Juego.this);

           View v = getLayoutInflater().inflate(R.layout.invitacion,null);
           TextView retador = (TextView) v.findViewById(R.id.retador);
           retador.setText(ThreadsData.INVITACION_USUARIO);
           builder.setView(v);
           builder.setPositiveButton("Aceptar", listenerOk);
           builder.setNegativeButton("Rechazar", listenerCanclar);
           builder.create();
           builder.show();

       }

    }

}


text:
'use strict';

var objectKeys = require( '@stdlib/utils/keys' );
var chisquare = require( './../lib' );

console.log( objectKeys( chisquare ) );


text:
namespace json {

    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;

    template< typename Iter >
    struct json_grammar : qi::grammar< Iter, value(), ascii::space_type > {

        json_grammar() : json_grammar::base_type(start) {

            using qi::lexeme;
            using qi::double_;
            using qi::bool_;
            using ascii::char_;

            quoted_string = lexeme['"' >> +(char_ - '"') >> '"'];
            object_rule   = '{' >> pair_rule % ',' >> '}';
            pair_rule     = quoted_string >> ':' >> value_rule;
            array_rule    = '[' >> value_rule % ',' >> ']';
            value_rule    = object_rule | array_rule | quoted_string | double_ | bool_ ;
            start         = value_rule;
        }

        qi::rule< Iter, value(),        ascii::space_type > start;
        qi::rule< Iter, std::string(),  ascii::space_type > quoted_string;
        qi::rule< Iter, value(),        ascii::space_type > value_rule;
        qi::rule< Iter, object(),       ascii::space_type > object_rule;
        qi::rule< Iter, keyval(),       ascii::space_type > pair_rule;
        qi::rule< Iter, array(),        ascii::space_type > array_rule;

    };
}


text:
module Api
  module V1
    class BatchesController < ApplicationController
      before_filter :restrict_access
      respond_to :json

      def index
        respond_with Batch.all
      end

      def show
        respond_with Batch.find(params[:id])
      end

      def create
        batch = JSON.parse(params[:batch])
        respond_with Batch.create(batch)
      end

      def update
        respond_with Batch.update(params[:id], JSON.parse(params[:batch]))
      end

      def destroy
        respond_with Batch.destroy(params[:id])
      end

    private

      def restrict_access
        authenticate_or_request_with_http_token do |token, options|
          ApiKey.exists?(access_token: token)
        end
      end
    end
  end
end


text:
from __future__ import print_function
import json
import logging
import os
import re
import signal
import shutil
import subprocess
import sys
import tempfile
import time
import threading

# Uncomment to enable debug logging
#logging.basicConfig(level=logging.DEBUG)

minidump_dir=None

def cleanup_and_exit(status_code):
    """Remove any temporary files etc and exit with the given status code."""
    if minidump_dir:
        shutil.rmtree(minidump_dir)
    exit(status_code);

def print_stderrdata(stderrdata):
    print("=== stderr begin ===")
    for line in stderrdata.splitlines():
        print(line)
    print("=== stderr end ===")

def invoke_gdb(gdb_exe, program, core_file, commands=[]):
    """Invoke GDB on the specified program and core file, running the given
    commands. Returns a string of GDB's output.
    """
    args = [gdb_exe, memcached_exe,
            '--core=' + os.path.abspath(core_file.name),
            '--batch']
    for c in commands:
        args += ['--eval-command='+c]

    gdb = subprocess.Popen(args, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    gdb.wait()
    return gdb.stdout.read()

class Subprocess(object):
    """Simple wrapper around subprocess to add a timeout & core file limit
    to the child process.
    """

    def __init__(self, args):
        self.args = args
        self.process = None

    def run(self, timeout):
        def set_core_file_ulimit():
            try:
                import resource
                resource.setrlimit(resource.RLIMIT_CORE, (0,0))
            except ImportError:
                if os.name == 'nt':
                    # Not possible to set core on Windows.
                    pass
                else:
                    raise

        def target():
            self.process = subprocess.Popen(self.args, stderr=subprocess.PIPE,
                                            env = os.environ,
                                            preexec_fn=set_core_file_ulimit)
            (_, self.stderrdata) = self.process.communicate()

        thread = threading.Thread(target=target)
        thread.start()

        thread.join(timeout)
        if thread.is_alive():
            print("*** Timeout - terminating process " + self.args[0])
            self.process.terminate()
            thread.join()
        return (self.process.returncode, self.stderrdata)

if len(sys.argv) == 3:
    (memcached_exe, crash_mode, md2core_exe, gdb_exe) = sys.argv[1:3] + [None, None]
elif len(sys.argv) == 5:
    (memcached_exe, crash_mode, md2core_exe, gdb_exe) = sys.argv[1:]
else:
    print(("Usage: {0} <path/to/memcached> <segfault|std_exception|unknown_exception> [path/to/md2core] " +
          "[path/to/gdb]").format(os.path.basename(sys.argv[0])),
          file=sys.stderr)
    cleanup_and_exit(1)

# Given there are multiple breakpad tests which can run in parallel, give
# each one it's own minidump directory.
minidump_dir = tempfile.mkdtemp(prefix='breakpad_test_tmp.')
logging.debug("Using minidump_dir=" + minidump_dir)

rbac_data = {}
rbac_file = tempfile.NamedTemporaryFile(delete=False)
rbac_file.write(json.dumps(rbac_data))
rbac_file.close()

# 'verbosity' isn't functionally needed, but helpful to debug test issues.
config = {"interfaces": [{"port": 0,
                          "maxconn":  1000,
                          "backlog":  1024,
                          "host": "*"}],
          "breakpad": { "enabled": True,
                        "minidump_dir" : minidump_dir
                      },
          "verbosity" : 2,
          "rbac_file" : os.path.abspath(rbac_file.name)}
config_json = json.dumps(config)

# Need a temporary file which can be opened (a second time) by memcached,
# therefore use NamedTemporaryFile(delete=False) and manually unlink
# when no longer needed.
config_file = tempfile.NamedTemporaryFile(delete=False)
config_file.write(config_json)
config_file.close()

os.environ['MEMCACHED_UNIT_TESTS'] = "true"
os.environ['MEMCACHED_CRASH_TEST'] = crash_mode

args = [memcached_exe, "-C", os.path.abspath(config_file.name)]

# Spawn memcached from a child thread.
logging.debug('Spawning memcached as: "MEMCACHED_UNIT_TESTS=' +
              os.environ['MEMCACHED_UNIT_TESTS'] +
              ' MEMCACHED_CRASH_TEST=' +
              os.environ['MEMCACHED_CRASH_TEST'] + ' ' +
              (' '.join(args) + '"'))
memcached = Subprocess(args)

# Wait for memcached to initialise (and consequently crash due to loading
# crash_engine).
(status, stderrdata) = memcached.run(timeout=30)

# Cleanup config_file (no longer needed).
os.remove(config_file.name)
os.remove(rbac_file.name)

# Check a message was written to stderr
if 'Breakpad caught crash' not in stderrdata:
    print("FAIL - No message written to stderr on crash.")
    print_stderrdata(stderrdata)
    cleanup_and_exit(3)

# Check the message includes the exception what() message (std::exception crash)
if crash_mode == 'std_exception' and 'what():' not in stderrdata:
    print("FAIL - No exception what() message written to stderr on crash.")
    print_stderrdata(stderrdata)
    cleanup_and_exit(3)

# Check the message also included a stack backtrace - we just check
# for one known function.
if 'recursive_crash_function' not in stderrdata:
    print("FAIL - No stack backtrace written to stderr on crash.")
    print_stderrdata(stderrdata)
    cleanup_and_exit(3)

# Check there is a minidump path in the output.
m = re.search('Writing crash dump to ([\w\\\/\:\-.]+)', stderrdata)
if not m:
    print("FAIL - Unable to find crash filename in stderr.")
    print_stderrdata(stderrdata)
    cleanup_and_exit(4)

# Check the minidump file exists on disk.
minidump = m.group(1)
if not os.path.exists(minidump):
    print("FAIL - Minidump file '{0}' does not exist.".format(minidump))
    print_stderrdata(stderrdata)
    cleanup_and_exit(5)

# On Windows we don't have md2core or gdb; so skip these tests.
if md2core_exe and gdb_exe:
    with tempfile.NamedTemporaryFile() as core_file:
        # Convert minidump to core file.
        try:
            subprocess.check_call([md2core_exe, minidump], stdout=core_file)
        except subprocess.CalledProcessError as e:
            print("FAIL - minidump-2-core failed with return code {0}".format(
                  e.returncode))
            os.remove(minidump)
            cleanup_and_exit(7)

        # Check for shared library information, and symbols successfully ead
        # (needed for any useful backtraces).
        # Shared libraries may change over time, but we explicitly asked for
        # crash_engine.so in the config so we should have that.
        gdb_output = invoke_gdb(gdb_exe, memcached_exe, core_file,
                                ['info shared'])
        m = re.search("^0x[0-9a-f]+\s+0x[0-9a-f]+\s+(\w+)\s+([^\s]+crash_engine\.so$)",
                      gdb_output, re.MULTILINE)
        if not m:
            print("FAIL - GDB unable to show information for " +
                  "crash_engine.so shared library.")
            cleanup_and_exit(9)

        if not m.group(1).startswith('Yes'):
            print("FAIL - GDB unable to read symbols for crash_engine.so " +
                  "(tried path: '{0}').".format(m.group(2)))
            cleanup_and_exit(10)

        # Check for sensible backtrace. This is again tricky as we could have
        # received the SIGABRT pretty much anywhere so we can't check for a
        # particular trace. Instead we check that all frames but the first have
        # a useful-looking symbol (and not just a random address.)
        gdb_output = invoke_gdb(gdb_exe, memcached_exe, core_file,
                                ['backtrace'])
        lines = gdb_output.splitlines()

        # Discard all those lines before the stacktrace
        backtrace = [i for i in lines if re.match('#\d+', i)]

        # Discard the innermost frame, as it could be anywhere (and hence may
        # not have a valid symbol).
        backtrace.pop(-1)

        for i, frame in enumerate(backtrace):
            # GDB prints stack frames in a variety of formats, however for
            # these purposes we just care that we *don't* have with an unknown
            # symbol, i.e. of the format:
            #     #0 <hex-address> in ??
            m = re.match('#\d+\s+0x[0-9a-f]+ in \?\? \(\) from ([^\s]+)', frame)
            if m:
                # However allow unknown symbols if they are in system libraries.
                so_name = m.group(1)
                if not any(so_name.startswith(d) for d in ['/lib', '/usr/lib']):
                    print(("FAIL - GDB unable to identify the symbol of " +
                           "frame {0} - found '{1}'.").format(i, frame))
                    print("=== GDB begin ===")
                    for line in lines:
                        print(line)
                    print("=== GDB end ===")
                    cleanup_and_exit(11)

        # Check we can read stack memory. Another tricky one as again we have
        # no idea where we crashed. Just ensure that we get *something* back
        gdb_output = invoke_gdb(gdb_exe, memcached_exe, core_file,
                                ['x/x $sp'])
        m = re.search('(0x[0-9a-f]+):\s(0x[0-9a-f]+)?', gdb_output)
        if not m:
            print("FAIL - GDB failed to output memory disassembly when " +
                  "attempting to examine stack.")
            cleanup_and_exit(12)
        if not m.group(2):
            print("FAIL - GDB unable to examine stack memory " +
                  "(tried address {0}).".format(m.group(1)))
            cleanup_and_exit(13)
else:
    # Check the minidump file is non-zero in size.
    statinfo = os.stat(minidump)
    if statinfo.st_size == 0:
        print("FAIL - minidump file '{0}' is zero bytes in size.".format(
              minidump))
        cleanup_and_exit(14)

    # Done with the minidump
    os.remove(minidump)

# Got to the end - that's a pass
print("Pass")
cleanup_and_exit(0)


text:
echo " "
echo "RESTART SERVICES"
echo " "

systemctl restart nginx.service php7.2-fpm.service php7.4-fpm.service

echo ""
echo "------------------------------------------------------------------------"
echo "         **** HMS should now be running at http://hmsdev/ ****          "
echo ""
echo "Your hosts file needs to have a 'hmsdev' entry."
echo "Linux / MacOS: /etc/hosts"
echo "Windows: C:\Windows\System32\Drivers\etc\hosts"
echo ""
echo "192.168.25.35	hmsdev vimbadmin-api.hmsdev"
echo ""
echo "Info: https://github.com/NottingHack/hms2/blob/master/README.md"
echo ""
echo "phpMyAdmin: https://hmsdev/phpmyadmin/"
echo "mialhog: http://hmsdev:8025/"
echo "vimbadmin-api: http://vimbadmin-api.hmsdev/"
echo ""
echo "MySQL:  username = hmsdev,        password = hmsdev"
echo "kadmin: username = vagrant      password = vagrant"
echo "HMS:    username = admin        password = admin"
echo "------------------------------------------------------------------------"
echo ""


text:
class Dataset
{
public:
    enum class Dimension : unsigned char
    {
        _1D = 0x01,
        _2D
    };

    enum class ArrangeType : unsigned char
    {
        _Seperate = 0x01,
        _Compact
    };

    enum class ElemDataType : unsigned char
    {
        _ElemFloat64 = 0x01, // double
        _ElemFloat32,
        _ElemInt64,
        _ElemUInt64,
        _ElemInt32,
        _ElemUInt32,
        _ElemInt16, // short
        _ElemUInt16, // unsigned short
        _ElemInt8,
        _ElemUInt8
    };

    static unsigned char s_NbBytesOfElemDataType[11];

    Dataset(const Dimension &dim, const ArrangeType &arrangeType, const ElemDataType &elemtype, const void *srcDataBuffer, unsigned int dataLengthInBytes);

    Dataset(const Dataset &b) = delete;

    Dataset operator=(const Dataset& b) = delete;

    ~Dataset();

    unsigned int GetNbOfDataPoint() {
        return m_dataVec.size();
    }

    Dimension Dim();

    ArrangeType arrangeT();

    ElemDataType ElemType();

    float GetMinX() const { return minX; }

    float GetMinY() const { return minY; }

    float GetMaxX() const { return maxX; }

    float GetMaxY() const { return maxY; }

    void BeginRetrival() { m_currPointIndex = 0u; }

    Vec2dFloat *GetNextPoint() { if (m_currPointIndex < m_dataVec.size()) return &(m_dataVec.at(m_currPointIndex++)); else return nullptr; }

    unsigned int GetId() { return m_ID; }

    bool ShouldRendering() { return m_dataRendering.m_visible; }

    DataRendering::Shape GetShape() { return m_dataRendering.m_shape; }

    bool SetRenderAsShape(const unsigned char &shape) {
        if (shape > (unsigned char) DataRendering::Shape::NumbersOfShape) return false;
        m_dataRendering.m_shape = (DataRendering::Shape)shape;
        m_dataRendering.m_visible = true;
        return true;
    }

    static void ResetUnusedId() {
        s_DatasetId = 1u;
    }

private:

    unsigned int m_ID;

    Dimension m_dim;

    ArrangeType m_arrangeType;

    ElemDataType m_eleType;

    DataRendering m_dataRendering;

    // For Cartesian Chart
    std::vector<Vec2dFloat> m_dataVec;
    unsigned int m_currPointIndex;

    float minX, maxX, minY, maxY;

    static unsigned int s_DatasetId;
};


text:
module SQLiterate
  module Node
    module LiteralIdentifier
      def name
        text_value
      end
    end

    module QuotedIdentifier
      def name
        c.elements.map(&:char).join
      end
    end

    module IdentifierChar
      module Quote
        def char
          '"'
        end
      end
      module Text
        def char
          text_value
        end
      end
    end

    module QualifiedName
      def name
        [ schema_name.name, identifier.name ].join '.'
      end
    end

    module AllFields
      def name
        :all
      end
    end
  end
end


text:
<?php

namespace Symfony\Component\Validator\Tests;

use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\MetadataFactoryInterface;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Validator\AbstractLegacyApiTest;
use Symfony\Component\Validator\Validator as LegacyValidator;

class ValidatorTest extends AbstractLegacyApiTest
{
    protected function createValidator(MetadataFactoryInterface $metadataFactory)
    {
        return new LegacyValidator($metadataFactory, new ConstraintValidatorFactory(), new DefaultTranslator());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ValidatorException
     */
    public function testValidateValueRejectsValid()
    {
        $this->validator->validateValue(new Entity(), new Valid());
    }
}


text:
typedef enum {
    SCCalloutViewAnchorNone, // hidden the anchor
    SCCalloutViewAnchorBottom, // anchor down
} SCCalloutViewAnchorDirection;

@interface SCCalloutView : UIView
@property (nonatomic, assign) SCCalloutViewAnchorDirection anchorDirection;
@property (nonatomic, strong, readonly) UILabel *titleLabel, *subtitleLabel;
@property (nonatomic, assign) UIEdgeInsets titleLabelInsets, subtitleLabelInsets;
@property (nonatomic, assign) CGFloat maxWidth;
@property (nonatomic, assign) CGFloat minWidth;
@end