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

Blockly.ComputerCraft.TERM_BLOCK_COLOUR_ = 160;

Blockly.ComputerCraft.TERM_FUNCS_ = [
  {funcName: 'write',
   text: 'write %1 to screen',
   args: [['Text', 'String']],
   tooltip:
   'Write the given string to the screen (terminal or monitor).'
  },
  {funcName: 'clear',
   text: 'clear screen',
   tooltip: 'Clear the entire screen (terminal or monitor).'
  },
  {funcName: 'clearLine',
   text: 'clear line on screen',
   tooltip: 'Clear the line the cursor is on.'
  },
  {funcName: 'getCursorPos',
   text: 'get cursor position',
   output: 'Number',  // first output
   tooltip: 'Get the x and y coodinates of the cursor.',
   multipleOutputs: 2
  },
  {funcName: 'setCursorPos',
   text: 'set cursor position to (%1, %2)',
   args: [['X', 'Number'], ['Y', 'Number']],
   tooltip: 'Set the x and y coodinates, respecitvely, of the cursor.'
  },
  {funcName: 'isColor',
   text: 'computer supports colour?',
   output: 'Boolean',
   tooltip:
   'Return true if the computer supports colour, false otherwise.\n' +
   'This indicates whether an Advanced Computer is being used.'
  },
  {funcName: 'getSize',
   text: 'get width and height of screen',
   output: 'Number',  // first output
   multipleOutputs: 2,
   tooltip:
   'Get the maximum x-coordinate (width) and y-coordinate (height)\n' +
   'of the screen (terminal or monitor)'
  },
  {funcName: 'scroll',
   text: 'scroll the screen %1 line(s)',
   args: [['NUM', 'Number']],
   tooltip:
   'Scroll the screen (terminal or monitor)\n' +
   'the specified number of lines.'
  },
  {funcName: 'redirect',
   text: 'redirect display to %1',
   args: [['TERM', 'Peripheral']],
   tooltip:
   'Redirect terminal output to a monitor or other redirect target.\n' +
   'The input is usually the output of "wrap peripheral"\n' +
   'Display can be restored to the original with the "restore display" block.'
  },
  {funcName: 'restore',
   text: 'restore display',
   tooltip:
   'Restore the display to the previous target, \n' +
   'after changing it with the "redirect display" block.'
  },
  {funcName: 'setTextColor',
   text: 'set text colour to %1',
   args: [['COLOUR', ['Colour', 'Number']]],
   tooltip:
   'Set the text colour of the terminal.\n' +
   'This is only available for Advanced Computers\n' +
   'and Advanced Monitors.'
  },
  {funcName: 'setBackgroundColor',
   text: 'set background colour to %1',
   args: [['COLOUR', ['Colour', 'Number']]],
   tooltip:
   'Set the background colour of the screen.\n' +
   'This is only available for Advanced Computers\n' +
   'and Advanced Monitors.'
  },
  {funcName: 'setTextScale',
   text: 'scale text by %1',
   args: [['SCALE', 'Number']],
   tooltip:
   'Set the size of all text on the connected monitor.\n' +
   'The input must be a multiple of .5 between .5 and 5 (inclusive).\n' +
   'This is only available on monitors, not terminals.'
  }
];

Blockly.ComputerCraft.TERM_FUNCS_.forEach(function(info) {
  Blockly.ComputerCraft.buildValueBlock(
    'term', Blockly.ComputerCraft.TERM_BLOCK_COLOUR_, info);});

// Make sure that a numeric literal argument is in the range [.5, 5],
// and divisible by .5.
Blockly.Blocks['term_set_text_scale'].onchange = function() {
  if (!this.workspace) {
    // Block has been deleted.
    return;
  }
  // If there's no child block, no warning.
  if (!this.childBlocks_) {
    this.setWarningText(null);
    return;
  }
  // Don't display (or remove) a warning if the child
  // block is selected, since editing might be in progress.
  // Flaw: No warning is displayed if after typing (but not entering)
  // a bad value, user clicks on 'Lua'.
  if (Blockly.selected == this.childBlocks_[0]) {
    return;
  }
  // If the input is a constant, make sure it is divisible by .5
  // and in the range [.5, 5].
  var code = Blockly.Lua.valueToCode(this, 'SCALE', Blockly.Lua.ORDER_NONE);
  if (code) {
    var num = Number(code);
    if (num != NaN) {
      if (num * 2 != Math.floor(num * 2) || num < .5 || num > 5) {
        this.setWarningText(
          'The scale value must be a multiple of .5 in the range .5 to 5.');
        return;
      }
    }
  }
  this.setWarningText(null);
};

// TODO: Convert to ValueBlock.
Blockly.Blocks['term_set_cursor_blink'] = new Blockly.ComputerCraft.Block(
  'term', Blockly.ComputerCraft.TERM_BLOCK_COLOUR_, {
    funcName: 'setCursorBlink',
    helpUrlType: Blockly.ComputerCraft.HelpUrlType.PREFIX_NAME,
    tooltip:
    'Enable or disable blinking of the\n' +
    'cursor on a screen (terminal or monitor).'});

Blockly.Blocks['term_set_cursor_blink'].init = function() {
  Blockly.ComputerCraft.Block.prototype.init.call(this);
  this.appendDummyInput()
      .appendTitle(
        new Blockly.FieldDropdown(
          [['turn on cursor blinking', 'true'],
           ['turn off cursor blinking', 'false']]),
        'STATUS')
};

Blockly.Lua['term_set_cursor_blink'] = Blockly.ComputerCraft.generateLuaInner_;


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="footer_links">
            <block class="Magento\Framework\View\Element\Html\Link\Current" ifconfig="contact/contact/enabled" name="contact-us-link">
                <arguments>
                    <argument name="label" xsi:type="string" translate="true">Contact Us</argument>
                    <argument name="path" xsi:type="string">contact</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

redpajama_set_name: RedPajamaGithub


text:
#include "modules/audio_processing/aec3/clockdrift_detector.h"

#include "test/gtest.h"

namespace webrtc {
TEST(ClockdriftDetector, ClockdriftDetector) {
  ClockdriftDetector c;
  // No clockdrift at start.
  EXPECT_TRUE(c.ClockdriftLevel() == ClockdriftDetector::Level::kNone);

  // Monotonically increasing delay.
  for (int i = 0; i < 100; i++)
    c.Update(1000);
  EXPECT_TRUE(c.ClockdriftLevel() == ClockdriftDetector::Level::kNone);
  for (int i = 0; i < 100; i++)
    c.Update(1001);
  EXPECT_TRUE(c.ClockdriftLevel() == ClockdriftDetector::Level::kNone);
  for (int i = 0; i < 100; i++)
    c.Update(1002);
  // Probable clockdrift.
  EXPECT_TRUE(c.ClockdriftLevel() == ClockdriftDetector::Level::kProbable);
  for (int i = 0; i < 100; i++)
    c.Update(1003);
  // Verified clockdrift.
  EXPECT_TRUE(c.ClockdriftLevel() == ClockdriftDetector::Level::kVerified);

  // Stable delay.
  for (int i = 0; i < 10000; i++)
    c.Update(1003);
  // No clockdrift.
  EXPECT_TRUE(c.ClockdriftLevel() == ClockdriftDetector::Level::kNone);

  // Decreasing delay.
  for (int i = 0; i < 100; i++)
    c.Update(1001);
  for (int i = 0; i < 100; i++)
    c.Update(999);
  // Probable clockdrift.
  EXPECT_TRUE(c.ClockdriftLevel() == ClockdriftDetector::Level::kProbable);
  for (int i = 0; i < 100; i++)
    c.Update(1000);
  for (int i = 0; i < 100; i++)
    c.Update(998);
  // Verified clockdrift.
  EXPECT_TRUE(c.ClockdriftLevel() == ClockdriftDetector::Level::kVerified);
}
}  // namespace webrtc


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Provider\PageData;

use Oro\Bundle\ActionBundle\Provider\RouteProviderInterface;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowItem;
use Oro\Bundle\WorkflowBundle\Exception\InvalidTransitionException;
use Oro\Bundle\WorkflowBundle\Model\Transition;
use Oro\Bundle\WorkflowBundle\Model\WorkflowManager;
use Symfony\Component\Routing\RouterInterface;

class TransitionPageDataProvider
{
    /** @var WorkflowManager */
    private $workflowManager;

    /** @var RouteProviderInterface */
    private $routeProvider;

    /** @var RouterInterface */
    private $router;

    /**
     * @param WorkflowManager $workflowManager
     * @param RouteProviderInterface $routeProvider
     * @param RouterInterface $router
     */
    public function __construct(
        WorkflowManager $workflowManager,
        RouteProviderInterface $routeProvider,
        RouterInterface $router
    ) {
        $this->workflowManager = $workflowManager;
        $this->routeProvider = $routeProvider;
        $this->router = $router;
    }

    /**
     * @param string $transition
     * @param WorkflowItem $workflowItem
     *
     * @return array
     * @throws InvalidTransitionException
     */
    public function getData(string $transition, WorkflowItem $workflowItem): array
    {
        $workflow = $this->workflowManager->getWorkflow($workflowItem);
        $transition = $workflow->getTransitionManager()->getTransition($transition);

        if (!$transition instanceof Transition) {
            throw InvalidTransitionException::unknownTransition($transition);
        }

        $routeParams = [
            'transitionName' => $transition->getName(),
            'workflowItemId' => $workflowItem->getId(),
        ];

        return array_merge(
            [
                'transition' => $transition,
                'workflow' => $workflow
            ],
            $this->getUrls($routeParams)
        );
    }

    /**
     * @param array $parameters
     * @return array
     */
    protected function getUrls(array $parameters): array
    {
        return [
            'transitionUrl' => $this->router->generate($this->routeProvider->getExecutionRoute(), $parameters),
            'transitionFormUrl' => $this->router->generate($this->routeProvider->getFormDialogRoute(), $parameters)
        ];
    }
}


text:
Contributing

Fork and clone into your local environment

Implement changes you would like

Run JUnit tests - make sure all execute correctly

Run Karma - use CLI by typing "gulp karma"

Write JUnit and/or Jasmine test (if appropriate)

Run your unit tests

Run linters

gulp eslint

gulp scss-lint

Make merge request :)


text:
import React, {
  Component,
  Navigator,
  StyleSheet,
  Text,
  TextInput,
  CheckBox,
  SliderIOS,
  View,
  TouchableHighlight,
  TouchableOpacity
} from 'react-native';

const KeyPocket = require("./KeyPocket.js");

const Create = React.createClass({
    getInitialState() {
        return {
            name: "My Secret",
            secret: "",
            numberOfShares: 3,
            threshold: 2
        };
    },
    updateNumberOfShares(value) {
        this.setState({numberOfShares: value});
        if (value < this.state.threshold) {
            this.setState({threshold: value})
        }
    },
    complete() {
        this.props.navigator.pop();
        let callback = this.props.callback;
        if (callback) {
            let secretSharing = KeyPocket.createSecretSharing(
                this.state.name,
                this.state.secret,
                this.state.numberOfShares,
                this.state.threshold);
            callback(secretSharing);
        }
    },
    render() {
        return (
          <View style={styles.container}>
              <Text style={styles.label}>Name</Text>
              <TextInput
                style={styles.textInput}
                onChangeText={(text) => this.setState({name: text})}
                value={this.state.name} />
              <Text style={styles.label}>Secret</Text>
              <TextInput
                style={styles.textInputMultiline}
                multiline={true}
                onChangeText={(text) => this.setState({secret: text})}
                value={this.state.secret} />
              <View style={styles.labelValue}>
                <Text>Number of Shares</Text>
                <Text style={styles.value}>{this.state.numberOfShares}</Text>
              </View>
              <SliderIOS
                style={styles.slider}
                value={this.state.numberOfShares}
                onValueChange={(value) => this.updateNumberOfShares(value)}
                minimumValue={3} maximumValue={10} step={1} />
              <View style={styles.labelValue}>
                <Text>Shares to Recover Secret</Text>
                <Text style={styles.value}>{this.state.threshold}</Text>
              </View>
              <SliderIOS
                style={styles.slider}
                value={this.state.threshold}
                onValueChange={(value) => this.setState({threshold: value})}
                minimumValue={2} maximumValue={this.state.numberOfShares} step={1} />
              <TouchableOpacity style={styles.button} onPress={() => this.complete()}>
                <Text style={styles.buttonText}>Create</Text>
              </TouchableOpacity>
          </View>
        );
    }
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        flexDirection: "column",
        margin: 10,
    },
  label: {
    marginTop: 10,
  },
  labelValue: {
    marginTop: 10,
    alignSelf: "stretch",
    justifyContent: "space-between",
    flexDirection: "row",
  },
  textInput: {
    height: 32,
    marginTop: 10,
    padding: 4,
    borderRadius: 4,
    borderWidth: 1,
    borderColor: "#d6d7da",
    fontSize: 16,
  },
    textInputMultiline : {
        flex: 1,
        marginTop: 10,
        padding: 4,
        borderRadius: 4,
        borderWidth: 1,
        borderColor: "#d6d7da",
        fontSize: 16,
    },
  slider: {
    alignSelf: "stretch",
    height: 32,
    marginTop: 10,
  },
    button: {
        backgroundColor: "#00dcb0",
        borderRadius: 8,
        marginTop: 10,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        padding: 10,
    },
    buttonText: {
        color: "#fff",
        fontSize: 18,
    }
});

module.exports = Create;


text:
beamonsite
==========

Beamons hemsida


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @class Ext.data.ScriptTagProxy
 * @extends Ext.data.DataProxy
 * An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain
 * other than the originating domain of the running page.<br>
 * <p>
 * <b>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
 * of the running page, you must use this class, rather than HttpProxy.</b><br>
 * <p>
 * The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript
 * source code because it is used as the source inside a &lt;script> tag.<br>
 * <p>
 * In order for the browser to process the returned data, the server must wrap the data object
 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
 * depending on whether the callback name was passed:
 * <p>
 * <pre><code>
boolean scriptTag = false;
String cb = request.getParameter("callback");
if (cb != null) {
    scriptTag = true;
    response.setContentType("text/javascript");
} else {
    response.setContentType("application/x-json");
}
Writer out = response.getWriter();
if (scriptTag) {
    out.write(cb + "(");
}
out.print(dataBlock.toJsonString());
if (scriptTag) {
    out.write(");");
}
</code></pre>
 * <p>Below is a PHP example to do the same thing:</p><pre><code>
$callback = $_REQUEST['callback'];

// Create the output object.
$output = array('a' => 'Apple', 'b' => 'Banana');

//start output
if ($callback) {
    header('Content-Type: text/javascript');
    echo $callback . '(' . json_encode($output) . ');';
} else {
    header('Content-Type: application/x-json');
    echo json_encode($output);
}
</code></pre>
 * <p>Below is the ASP.Net code to do the same thing:</p><pre><code>
String jsonString = "{success: true}";
String cb = Request.Params.Get("callback");
String responseString = "";
if (!String.IsNullOrEmpty(cb)) {
    responseString = cb + "(" + jsonString + ")";
} else {
    responseString = jsonString;
}
Response.Write(responseString);
</code></pre>
 *
 * @constructor
 * @param {Object} config A configuration object.
 */
Ext.data.ScriptTagProxy = function(config){
    Ext.apply(this, config);

    Ext.data.ScriptTagProxy.superclass.constructor.call(this, config);

    this.head = document.getElementsByTagName("head")[0];

    /**
     * @event loadexception
     * <b>Deprecated</b> in favor of 'exception' event.
     * Fires if an exception occurs in the Proxy during data loading.  This event can be fired for one of two reasons:
     * <ul><li><b>The load call timed out.</b>  This means the load callback did not execute within the time limit
     * specified by {@link #timeout}.  In this case, this event will be raised and the
     * fourth parameter (read error) will be null.</li>
     * <li><b>The load succeeded but the reader could not read the response.</b>  This means the server returned
     * data, but the configured Reader threw an error while reading the data.  In this case, this event will be
     * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>
     * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly
     * on any Store instance.
     * @param {Object} this
     * @param {Object} options The loading options that were specified (see {@link #load} for details).  If the load
     * call timed out, this parameter will be null.
     * @param {Object} arg The callback's arg object passed to the {@link #load} function
     * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data.
     * If the remote request returns success: false, this parameter will be null.
     */
};

Ext.data.ScriptTagProxy.TRANS_ID = 1000;

Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {
    /**
     * @cfg {String} url The URL from which to request the data object.
     */
    /**
     * @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
     */
    timeout : 30000,
    /**
     * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
     * the server the name of the callback function set up by the load call to process the returned data object.
     * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
     * javascript output which calls this named function passing the data object as its only parameter.
     */
    callbackParam : "callback",
    /**
     *  @cfg {Boolean} nocache (optional) Defaults to true. Disable caching by adding a unique parameter
     * name to the request.
     */
    nocache : true,

    /**
     * HttpProxy implementation of DataProxy#doRequest
     * @param {String} action
     * @param {Ext.data.Record/Ext.data.Record[]} rs If action is <tt>read</tt>, rs will be null
     * @param {Object} params An object containing properties which are to be used as HTTP parameters
     * for the request to the remote server.
     * @param {Ext.data.DataReader} reader The Reader object which converts the data
     * object into a block of Ext.data.Records.
     * @param {Function} callback The function into which to pass the block of Ext.data.Records.
     * The function must be passed <ul>
     * <li>The Record block object</li>
     * <li>The "arg" argument from the load function</li>
     * <li>A boolean success indicator</li>
     * </ul>
     * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
     * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
     */
    doRequest : function(action, rs, params, reader, callback, scope, arg) {
        var p = Ext.urlEncode(Ext.apply(params, this.extraParams));

        var url = this.buildUrl(action, rs);
        if (!url) {
            throw new Ext.data.Api.Error('invalid-url', url);
        }
        url = Ext.urlAppend(url, p);

        if(this.nocache){
            url = Ext.urlAppend(url, '_dc=' + (new Date().getTime()));
        }
        var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
        var trans = {
            id : transId,
            action: action,
            cb : "stcCallback"+transId,
            scriptId : "stcScript"+transId,
            params : params,
            arg : arg,
            url : url,
            callback : callback,
            scope : scope,
            reader : reader
        };
        window[trans.cb] = this.createCallback(action, rs, trans);
        url += String.format("&{0}={1}", this.callbackParam, trans.cb);
        if(this.autoAbort !== false){
            this.abort();
        }

        trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);

        var script = document.createElement("script");
        script.setAttribute("src", url);
        script.setAttribute("type", "text/javascript");
        script.setAttribute("id", trans.scriptId);
        this.head.appendChild(script);

        this.trans = trans;
    },

    // @private createCallback
    createCallback : function(action, rs, trans) {
        var self = this;
        return function(res) {
            self.trans = false;
            self.destroyTrans(trans, true);
            if (action === Ext.data.Api.actions.read) {
                self.onRead.call(self, action, trans, res);
            } else {
                self.onWrite.call(self, action, trans, res, rs);
            }
        };
    },
    /**
     * Callback for read actions
     * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
     * @param {Object} trans The request transaction object
     * @param {Object} res The server response
     * @protected
     */
    onRead : function(action, trans, res) {
        var result;
        try {
            result = trans.reader.readRecords(res);
        }catch(e){
            // @deprecated: fire loadexception
            this.fireEvent("loadexception", this, trans, res, e);

            this.fireEvent('exception', this, 'response', action, trans, res, e);
            trans.callback.call(trans.scope||window, null, trans.arg, false);
            return;
        }
        if (result.success === false) {
            // @deprecated: fire old loadexception for backwards-compat.
            this.fireEvent('loadexception', this, trans, res);

            this.fireEvent('exception', this, 'remote', action, trans, res, null);
        } else {
            this.fireEvent("load", this, res, trans.arg);
        }
        trans.callback.call(trans.scope||window, result, trans.arg, result.success);
    },
    /**
     * Callback for write actions
     * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
     * @param {Object} trans The request transaction object
     * @param {Object} res The server response
     * @protected
     */
    onWrite : function(action, trans, response, rs) {
        var reader = trans.reader;
        try {
            // though we already have a response object here in STP, run through readResponse to catch any meta-data exceptions.
            var res = reader.readResponse(action, response);
        } catch (e) {
            this.fireEvent('exception', this, 'response', action, trans, res, e);
            trans.callback.call(trans.scope||window, null, res, false);
            return;
        }
        if(!res.success === true){
            this.fireEvent('exception', this, 'remote', action, trans, res, rs);
            trans.callback.call(trans.scope||window, null, res, false);
            return;
        }
        this.fireEvent("write", this, action, res.data, res, rs, trans.arg );
        trans.callback.call(trans.scope||window, res.data, res, true);
    },

    // private
    isLoading : function(){
        return this.trans ? true : false;
    },

    /**
     * Abort the current server request.
     */
    abort : function(){
        if(this.isLoading()){
            this.destroyTrans(this.trans);
        }
    },

    // private
    destroyTrans : function(trans, isLoaded){
        this.head.removeChild(document.getElementById(trans.scriptId));
        clearTimeout(trans.timeoutId);
        if(isLoaded){
            window[trans.cb] = undefined;
            try{
                delete window[trans.cb];
            }catch(e){}
        }else{
            // if hasn't been loaded, wait for load to remove it to prevent script error
            window[trans.cb] = function(){
                window[trans.cb] = undefined;
                try{
                    delete window[trans.cb];
                }catch(e){}
            };
        }
    },

    // private
    handleFailure : function(trans){
        this.trans = false;
        this.destroyTrans(trans, false);
        if (trans.action === Ext.data.Api.actions.read) {
            // @deprecated firing loadexception
            this.fireEvent("loadexception", this, null, trans.arg);
        }

        this.fireEvent('exception', this, 'response', trans.action, {
            response: null,
            options: trans.arg
        });
        trans.callback.call(trans.scope||window, null, trans.arg, false);
    },

    // inherit docs
    destroy: function(){
        this.abort();
        Ext.data.ScriptTagProxy.superclass.destroy.call(this);
    }
});


text:
<?php
namespace Chamilo\Application\Weblcms\Tool\Implementation\Assignment\Component;

use Chamilo\Application\Weblcms\Rights\WeblcmsRights;
use Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublication;
use Chamilo\Application\Weblcms\Tool\Implementation\Assignment\Manager;
use Chamilo\Application\Weblcms\Tool\Implementation\CourseGroup\Storage\DataClass\CourseGroup;
use Chamilo\Core\Group\Storage\DataClass\Group;
use Chamilo\Core\Repository\Form\ContentObjectForm;
use Chamilo\Core\Repository\Workspace\PersonalWorkspace;
use Chamilo\Libraries\Architecture\Exceptions\NotAllowedException;
use Chamilo\Libraries\Format\Structure\Breadcrumb;
use Chamilo\Libraries\Format\Structure\BreadcrumbTrail;
use Chamilo\Libraries\Platform\Session\Request;
use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Storage\DataManager\DataManager;
use Chamilo\Libraries\Storage\Parameters\DataClassRetrieveParameters;
use Chamilo\Libraries\Storage\Query\Condition\EqualityCondition;
use Chamilo\Libraries\Storage\Query\Variable\PropertyConditionVariable;
use Chamilo\Libraries\Storage\Query\Variable\StaticConditionVariable;

/**
 *
 * @package application.weblcms.tool.assignment.php.component Updater for submission feedback.
 * @author Joris Willems <joris.willems@gmail.com>
 * @author Alexander Van Paemel
 * @author Bert De Clercq (Hogeschool Gent)
 */
class FeedbackUpdaterComponent extends Manager
{

    public function run()
    {
        $feedback_id = Request::get(self::PARAM_FEEDBACK_ID);
        $tracker = new \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\SubmissionFeedback();
        $condition = new EqualityCondition(
            new PropertyConditionVariable(
                \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\SubmissionFeedback::class_name(),
                \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\SubmissionFeedback::PROPERTY_ID),
            new StaticConditionVariable($feedback_id));

        $feedback = DataManager::retrieve(
            \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\SubmissionFeedback::class_name(),
            new DataClassRetrieveParameters($condition));

        $feedback_content_object = $feedback->get_content_object();

        $object_form = ContentObjectForm::factory(
            ContentObjectForm::TYPE_EDIT,
            new PersonalWorkspace($this->get_user()),
            $feedback_content_object,
            'edit',
            'post',
            $this->get_url(array(self::PARAM_FEEDBACK_ID => $feedback_id)),
            null,
            null,
            false);

        $publication_id = Request::get(self::PARAM_PUBLICATION_ID);
        $target_id = Request::get(self::PARAM_TARGET_ID);
        $submitter_type = Request::get(self::PARAM_SUBMITTER_TYPE);

        if ($object_form->validate())
        {
            $success = $object_form->update_content_object();
            $this->redirect(
                Translation::get($success ? 'FeedbackUpdated' : 'UpdateFailed'),
                ! $success,
                array(
                    \Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION => self::ACTION_VIEW_SUBMISSION,
                    \Chamilo\Application\Weblcms\Tool\Manager::PARAM_PUBLICATION_ID => $publication_id,
                    self::PARAM_TARGET_ID => $target_id,
                    self::PARAM_SUBMITTER_TYPE => $submitter_type,
                    self::PARAM_SUBMISSION => $feedback->get_submission_id()));
        }
        else
        {
            $html = array();

            $html[] = $this->render_header();
            $html[] = $object_form->toHtml();
            $html[] = $this->render_footer();

            return implode(PHP_EOL, $html);
        }
    }

    public function add_additional_breadcrumbs(BreadcrumbTrail $breadcrumbtrail)
    {
        $submission_id = Request::get(self::PARAM_SUBMISSION);
        $tracker = new \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission();
        $condition = new EqualityCondition(
            new PropertyConditionVariable(
                \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission::class_name(),
                \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission::PROPERTY_ID),
            new StaticConditionVariable($submission_id));

        $submission_tracker = DataManager::retrieve(
            \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission::class_name(),
            new DataClassRetrieveParameters($condition));

        $submissions = \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission::get_data(
            \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission::class_name(),
            null,
            $condition)->as_array();
        $submission = $submissions[0]->get_content_object();

        $pub = \Chamilo\Application\Weblcms\Storage\DataManager::retrieve_by_id(
            ContentObjectPublication::class_name(),
            $submission_tracker->get_publication_id());

        if (! $this->is_allowed(WeblcmsRights::EDIT_RIGHT, $pub))
        {
            throw new NotAllowedException();
        }
        $assignment = $pub->get_content_object();

        $breadcrumbtrail->add(
            new Breadcrumb(
                $this->get_url(
                    array(
                        \Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION => \Chamilo\Application\Weblcms\Tool\Manager::ACTION_BROWSE)),
                Translation::get('BrowserComponent')));
        $breadcrumbtrail->add(
            new Breadcrumb(
                $this->get_url(
                    array(
                        \Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION => self::ACTION_BROWSE_SUBMITTERS,
                        \Chamilo\Application\Weblcms\Tool\Manager::PARAM_PUBLICATION_ID => $submission_tracker->get_publication_id())),
                $assignment->get_title()));
        $breadcrumbtrail->add(
            new Breadcrumb(
                $this->get_url(
                    array(
                        \Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION => self::ACTION_BROWSE_SUBMISSIONS,
                        \Chamilo\Application\Weblcms\Tool\Manager::PARAM_PUBLICATION_ID => $submission_tracker->get_publication_id(),
                        self::PARAM_TARGET_ID => $submission_tracker->get_submitter_id(),
                        self::PARAM_SUBMITTER_TYPE => $submission_tracker->get_submitter_type())),
                $this->get_submitter_name($submission_tracker)));
        $breadcrumbtrail->add(
            new Breadcrumb(
                $this->get_url(
                    array(
                        \Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION => self::ACTION_VIEW_SUBMISSION,
                        \Chamilo\Application\Weblcms\Tool\Manager::PARAM_PUBLICATION_ID => $submission_tracker->get_publication_id(),
                        self::PARAM_TARGET_ID => $submission_tracker->get_submitter_id(),
                        self::PARAM_SUBMITTER_TYPE => $submission_tracker->get_submitter_type(),
                        self::PARAM_SUBMISSION => $submission_id)),
                $submission->get_title() . ' - ' . Translation::get('Detail')));
    }

    public function get_additional_parameters()
    {
        return array(
            \Chamilo\Application\Weblcms\Tool\Manager::PARAM_PUBLICATION_ID,
            self::PARAM_FEEDBACK_ID,
            self::PARAM_SUBMISSION);
    }

    /**
     * Returns the name of the submitter as a string.
     * When submitted as a group, it will return the name of the user who
     * submitted followed by the group name.
     *
     * @return string The name of the submitter
     */
    private function get_submitter_name($submission_tracker)
    {
        // name of the user who submitted
        $user_name = \Chamilo\Core\User\Storage\DataManager::retrieve_by_id(
            \Chamilo\Core\User\Storage\DataClass\User::class_name(),
            $submission_tracker->get_user_id());

        switch ($submission_tracker->get_submitter_type())
        {
            case \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission::SUBMITTER_TYPE_USER :
                return $user_name->get_fullname();
            case \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission::SUBMITTER_TYPE_COURSE_GROUP :
                return $user_name->get_fullname() . ' - ' . \Chamilo\Application\Weblcms\Storage\DataManager::retrieve_by_id(
                    CourseGroup::class_name(),
                    $submission_tracker->get_submitter_id())->get_name();
            case \Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssignmentSubmission::SUBMITTER_TYPE_PLATFORM_GROUP :
                return $user_name->get_fullname() . ' - ' . \Chamilo\Core\Group\Storage\DataManager::retrieve_by_id(
                    Group::class_name(),
                    $submission_tracker->get_submitter_id())->get_name();
        }
    }
}


text:
<!DOCTYPE html>

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

  <title>Lezione6</title>
  <meta property="og:title" content="Lezione6" />
  <meta name="twitter:title" content="Lezione6" />
  <meta name="description" content="Fare pratica con i dati e regressione

Originally posted here.

">
  <meta property="og:description" content="Fare pratica con i dati e regressione

Originally posted here.

">
  <meta name="twitter:description" content="Fare pratica con i dati e regressione

Originally posted here.

">
  <meta name="author" content=""/>
  <link href='https://thefreolo.github.io/img/favicon.ico' rel='icon' type='image/x-icon'/>
  <meta property="og:image" content="https://thefreolo.github.io/media/Profile_PIC.jpg" />
  <meta name="twitter:image" content="https://thefreolo.github.io/media/Profile_PIC.jpg" />
  <meta name="twitter:card" content="summary" />
  <meta name="twitter:site" content="@TheFreolo" />
  <meta name="twitter:creator" content="@TheFreolo" />
  <meta property="og:url" content="https://thefreolo.github.io/calcolo-delle-probabilita-e-statistica-matematica/lezione6_2020/" />
  <meta property="og:type" content="website" />
  <meta property="og:site_name" content="Federico Reali" />

  <meta name="generator" content="Hugo 0.36.1" />
  <link rel="canonical" href="https://thefreolo.github.io/calcolo-delle-probabilita-e-statistica-matematica/lezione6_2020/" />
  <link rel="alternate" href="https://thefreolo.github.io/index.xml" type="application/rss+xml" title="Federico Reali">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="https://thefreolo.github.io/css/main.css" /><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />
  <link rel="stylesheet" href="https://thefreolo.github.io/css/highlight.min.css" /><link rel="stylesheet" href="https://thefreolo.github.io/css/codeblock.css" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.css" integrity="sha384-h/L2W9KefUClHWaty3SLE5F/qvc4djlyR4qY3NUV5HGQBBW7stbcfff1+I/vmsHh" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/default-skin/default-skin.min.css" integrity="sha384-iD0dNku6PYSIQLyfTOpB06F2KCZJAKLOThS5HRe8b3ibhdEQ6eKsFf/EeFxdOt5R" crossorigin="anonymous">

      <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
      <button class="pswp__button pswp__button--share" title="Share"></button>
      <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
      <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

    <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
    </button>
    <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
    </button>

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

      </button>
      Federico Reali

              Teaching

                  Home

                  Biostatistics

                  Calcolo delle Probabilità e Statistica Matematica

                  Note di R (it)

              Publications

              About

Lezione6

Fare pratica con i dati e regressione

Originally posted here.

Regressione lineare

Al link è possibile trovare delle note sulla regressione.

Ricordiamo che per applicare la regressione lineare dobbiamo essere sicuri che le ipotesi siano soddisfatte. In particolare dovremo assicurarci che i residui seguano una distribuzione normale centrata in 0 e siano indipendenti.

Alcune delle funzioni già viste possono aiutarci in questo compito.

Definire e richiamare un modello lineare in R è molto semplice. Basta infatti  utilizzare la funzione lm(), dove va specificata la variabile dipendente e il predittore ed i dati da usare per definire il modello.

Sebbene i modelli di regressione multipla siano concettualmente e praticamente più complessi, R li supporta usando la stessa funzione e la stessa notazione. In tal caso, invece che indicare un predittore, se ne indicano più usando il simbolo + per elencarli.

Mtcars

Vediamo alcuni esempi usando il dataset mtcars.

Supponiamo di voler investigare se il consumo di carburante e il numero di cavalli seguono una relazione lineare.

Un ottimo metodo per intuire se la relazione possa essere in qualche modo lineare è quello di disegnare la variabile dipendente in funzione del predittore.

plot(mpg ~ hp, data = mtcars)

Secondo i risultati della nostra analisi preliminare sembra plausibile che la relazione sia lineare. Continuiamo la nostra investigazione definendo il modello con la funzione lm() e visualizzando il risultato usando la ben nota funzione summary().

mtcars_reg <- lm(mpg ~ hp, data = mtcars)
summary(mtcars_reg)

Si può accedere ai vari elementi elencati da summary() usando la notazione $.

Tra le informazioni che fornisce summary, è presente anche il valore R-squared (R quadro), che è la proporzione di varianza della variabile dipendente che viene spiegata dal predittore. Tale valore è compreso tra 0 e 1. Valori vicino a 1 indicano un buon modello, mentre valori bassi possono indicare o che il modello non spieghi completamente/correttamente i dati, o che la varianza dei residui è molto alta.

Una volta definito il modello, è importante visualizzare i risultati per valutarne la bontà e per capire il comportamento dei residui. In questo modo è infatti possibile verificare quantitativamente (non formalmente) se i residui soddisfano le ipotesi di indipendenza (non si devono osservare dei pattern) e che la distribuzione dei quantili sia confrontabile con quella di una normale.

I seguenti comandi permettono di visualizzare la retta di regressione, i quantili e di confrontarli con la distribuzione in quantili di una normale.

par(mfrow = c(3,1), mar = c(2,2,1,1))
# Retta di regressione
plot(mpg ~ hp, data = mtcars)
abline(mtcars_reg$coefficients, col = "red")
# Pattern nei residui
plot(mtcars_reg$residuals, main = "Residui")
# Distribuzione in quantili
qqnorm(mtcars_reg$residuals)
qqline(mtcars_reg$residuals)

Esercizio A

In modo analogo a quanto fato sopra, si investighi la relazione tra consumo e peso delle auto in esame.

Esercizio B

Si discuta un modello lineare per le variabili x e y di Esercizo 1.

Regressione multipla

Come anticipato, se volessimo considerare una regressione multipla e per esempio considerare come predittori sia la potenza (cavalli) che il  peso, possiamo implementare il modello in modo simile in R.

mtcars_reg_hp_wt <- lm(mpg ~ hp + wt, data = mtcars)
summary(mtcars_reg_hp_wt)

Se volessimo che il modello considerasse tutte le variabili (eccetto mpg), si può usare la notazione lm(mpg ~ ., data = mtcars) senza esplicitamente indicare tutti i nomi delle colonne.

Esercitazione 3

Si consideri il dataset crabs contenuto nel pacchetto MASS.

Si verifichi che il dataset sia stato letto bene. Si usi l’help per comprendere il significato delle variabili.

Si visualizzi una tabella che riassume il numero di esemplari per genere e per colore. E’ il dataset equilibrato rispetto queste variabili categoriche?

Si visualizzi usando un solo boxplot la variabile BD al variare del sesso e del colore.

Si calcoli la retta di regressione lineare tra le variabili FL e CL (predittore). Si calcoli il summary del modello e si commenti.

Si visualizzi la retta di regressione rispetto ai dati, la distribuzione dei residui e i loro quantili. Si commentino i risultati.

Si determini se la lunghezza del carapace è statisticamente differente tra le due specie.

Esercizi

Esercizio 1

Si importi il dataset (descrizione). Si trovi un modo opportuno per importarlo in R e si analizzi la relazione tra le due variabili usando la regressione lineare. Si analizzino i risultati e si visualizzino i residui.

Esercizio 2

Si trovi un modo adeguato per importare i dati relativi al reddito nazionale lordo pro capite e alla percentuale di strade asfaltate in R. Dopo aver analizzato e preparato i dataset, si usino i dati per investigare le due variabili rispetto ad un paese del G7, un paese in via di sviluppo ed un paese del terzo mondo a scelta, nel periodo dal 1990 al 2009.
Si analizzino i dati e si visualizzino. Inoltre si usi la regressione lineare per analizzare la relazione tra le variabili. Si commentino e discutano i risultati.

Soluzione Es2

Esercizio 3

Usando il dataset ottenuto nell’Esercizio 3 della lezione 5, si investighi usando la regressione lineare la relazione tra prodotto interno lordo e aspettativa di vita per ognuno dei continenti. Si usi la funzione predict() per valutare il modello su dati diversi da quelli usati per definirlo. In particolare, si valuti il modello ottenuto per l’America sui dati europei e viceversa. Si visualizzino e si discutano i risultati ottenuti, dandone anche un interpretazione.

Esercizio 4

Si considerino i modelli ottenuto nell’Esercizio 3. Si valuti separatamente il modello ottenuto per l’America e quello l’Europa usando i dati dei paesi Canada, Italy, Argentina e Sierra Leone contentuti nel dataset originale. Si valutino i valori di R quadro ottenuti e si discutano i risultati.

Suggerimento si usi la formulazione equivalente di R quadro:

 © 2017-2020  Federico Reali

              ← Previous Post

              Next Post →

          2020

             •
            Federico Reali

          Hugo v0.36.1 powered  •  Theme by Beautiful Jekyll adapted to Beautiful Hugo


text:
This application makes use of the following third party libraries:

## AFNetworking

Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## CHTCollectionViewWaterfallLayout

Copyright (c) 2012 Nelson Tai <chiahsien@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## CWStatusBarNotification

The MIT License (MIT)

Copyright (c) 2015 Cezary Wojcik <http://www.cezarywojcik.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## FMDB

If you are using FMDB in your project, I'd love to hear about it.  Let Gus know
by sending an email to gus@flyingmeat.com.

And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you
might consider purchasing a drink of their choosing if FMDB has been useful to
you.

Finally, and shortly, this is the MIT License.

Copyright (c) 2008-2014 Flying Meat Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## IQKeyboardManager

IQKeyboardManager license
=========================

The MIT License (MIT)

Copyright (c) 2013-14 Iftekhar Qurashi

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

## MBProgressHUD

Copyright (c) 2009-2015 Matej Bukovinski

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## MJExtension

Copyright (c) 2013-2015 MJExtension (https://github.com/CoderMJLee/MJExtension)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## MJRefresh

Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## Masonry

Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## SDWebImage

Copyright (c) 2009 Olivier Poitrey <rs@dailymotion.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## UMengAnalytics

Copyright 2011 - 2015 UMeng.com. All rights reserved.

Generated by CocoaPods - http://cocoapods.org


text:
package org.apache.flink.formats.parquet.vector;

import org.apache.flink.core.fs.Path;
import org.apache.flink.table.data.ColumnarRowData;
import org.apache.flink.table.data.DecimalData;
import org.apache.flink.table.data.vector.VectorizedColumnBatch;
import org.apache.flink.table.runtime.functions.SqlDateTimeUtils;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.BigIntType;
import org.apache.flink.table.types.logical.BooleanType;
import org.apache.flink.table.types.logical.DateType;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.DoubleType;
import org.apache.flink.table.types.logical.FloatType;
import org.apache.flink.table.types.logical.IntType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.SmallIntType;
import org.apache.flink.table.types.logical.TimestampType;
import org.apache.flink.table.types.logical.TinyIntType;
import org.apache.flink.table.types.logical.VarCharType;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.types.Row;

import org.apache.hadoop.conf.Configuration;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.schema.OriginalType;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.Type;
import org.apache.parquet.schema.Types;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.IntStream;

import static org.apache.flink.formats.parquet.utils.ParquetWriterUtil.createTempParquetFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Test for {@link ParquetColumnarRowSplitReader}.
 */
@RunWith(Parameterized.class)
public class ParquetColumnarRowSplitReaderTest {

	private static final int FIELD_NUMBER = 15;
	private static final LocalDateTime BASE_TIME = LocalDateTime.now();

	private static final MessageType PARQUET_SCHEMA = new MessageType(
			"TOP",
			Types.primitive(PrimitiveType.PrimitiveTypeName.BINARY, Type.Repetition.OPTIONAL)
					.named("f0"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.BOOLEAN, Type.Repetition.OPTIONAL)
					.named("f1"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.INT32, Type.Repetition.OPTIONAL)
					.named("f2"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.INT32, Type.Repetition.OPTIONAL)
					.named("f3"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.INT32, Type.Repetition.OPTIONAL)
					.named("f4"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.INT64, Type.Repetition.OPTIONAL)
					.named("f5"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.FLOAT, Type.Repetition.OPTIONAL)
					.named("f6"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.DOUBLE, Type.Repetition.OPTIONAL)
					.named("f7"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.INT96, Type.Repetition.OPTIONAL)
					.named("f8"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.INT32, Type.Repetition.OPTIONAL)
					.precision(5)
					.as(OriginalType.DECIMAL)
					.named("f9"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.INT64, Type.Repetition.OPTIONAL)
					.precision(15)
					.as(OriginalType.DECIMAL)
					.named("f10"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.BINARY, Type.Repetition.OPTIONAL)
					.precision(20)
					.as(OriginalType.DECIMAL)
					.named("f11"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY, Type.Repetition.OPTIONAL)
					.length(16)
					.precision(5)
					.as(OriginalType.DECIMAL)
					.named("f12"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY, Type.Repetition.OPTIONAL)
					.length(16)
					.precision(15)
					.as(OriginalType.DECIMAL)
					.named("f13"),
			Types.primitive(PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY, Type.Repetition.OPTIONAL)
					.length(16)
					.precision(20)
					.as(OriginalType.DECIMAL)
					.named("f14")
			);

	@ClassRule
	public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();

	private final int rowGroupSize;

	@Parameterized.Parameters(name = "rowGroupSize-{0}")
	public static Collection<Integer> parameters() {
		return Arrays.asList(10, 1000);
	}

	public ParquetColumnarRowSplitReaderTest(int rowGroupSize) {
		this.rowGroupSize = rowGroupSize;
	}

	@Test
	public void testNormalTypesReadWithSplits() throws IOException {
		// prepare parquet file
		int number = 10000;
		List<Row> records = new ArrayList<>(number);
		List<Integer> values = new ArrayList<>(number);
		Random random = new Random();
		for (int i = 0; i < number; i++) {
			Integer v = random.nextInt(number / 2);
			if (v % 10 == 0) {
				values.add(null);
				records.add(new Row(FIELD_NUMBER));
			} else {
				values.add(v);
				records.add(newRow(v));
			}
		}

		testNormalTypes(number, records, values);
	}

	private void testNormalTypes(int number, List<Row> records,
			List<Integer> values) throws IOException {
		Path testPath = createTempParquetFile(
				TEMPORARY_FOLDER.newFolder(), PARQUET_SCHEMA, records, rowGroupSize);

		// test reading and splitting
		long fileLen = testPath.getFileSystem().getFileStatus(testPath).getLen();
		int len1 = readSplitAndCheck(0, 0, testPath, 0, fileLen / 3, values);
		int len2 = readSplitAndCheck(len1, 0, testPath, fileLen / 3, fileLen * 2 / 3, values);
		int len3 = readSplitAndCheck(len1 + len2, 0, testPath, fileLen * 2 / 3, Long.MAX_VALUE, values);
		assertEquals(number, len1 + len2 + len3);

		// test seek
		assertEquals(
				number - number / 2,
				readSplitAndCheck(number / 2, number / 2, testPath, 0, fileLen, values));
	}

	private int readSplitAndCheck(
			int start,
			long seekToRow,
			Path testPath,
			long splitStart,
			long splitLength,
			List<Integer> values) throws IOException {
		LogicalType[] fieldTypes = new LogicalType[]{
				new VarCharType(VarCharType.MAX_LENGTH),
				new BooleanType(),
				new TinyIntType(),
				new SmallIntType(),
				new IntType(),
				new BigIntType(),
				new FloatType(),
				new DoubleType(),
				new TimestampType(9),
				new DecimalType(5, 0),
				new DecimalType(15, 0),
				new DecimalType(20, 0),
				new DecimalType(5, 0),
				new DecimalType(15, 0),
				new DecimalType(20, 0)};

		ParquetColumnarRowSplitReader reader = new ParquetColumnarRowSplitReader(
				false,
				true,
				new Configuration(),
				fieldTypes,
				new String[] {
						"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
						"f8", "f9", "f10", "f11", "f12", "f13", "f14"},
				VectorizedColumnBatch::new,
				500,
				new org.apache.hadoop.fs.Path(testPath.getPath()),
				splitStart,
				splitLength);
		reader.seekToRow(seekToRow);

		int i = start;
		while (!reader.reachedEnd()) {
			ColumnarRowData row = reader.nextRecord();
			Integer v = values.get(i);
			if (v == null) {
				assertTrue(row.isNullAt(0));
				assertTrue(row.isNullAt(1));
				assertTrue(row.isNullAt(2));
				assertTrue(row.isNullAt(3));
				assertTrue(row.isNullAt(4));
				assertTrue(row.isNullAt(5));
				assertTrue(row.isNullAt(6));
				assertTrue(row.isNullAt(7));
				assertTrue(row.isNullAt(8));
				assertTrue(row.isNullAt(9));
				assertTrue(row.isNullAt(10));
				assertTrue(row.isNullAt(11));
				assertTrue(row.isNullAt(12));
				assertTrue(row.isNullAt(13));
				assertTrue(row.isNullAt(14));
			} else {
				assertEquals("" + v, row.getString(0).toString());
				assertEquals(v % 2 == 0, row.getBoolean(1));
				assertEquals(v.byteValue(), row.getByte(2));
				assertEquals(v.shortValue(), row.getShort(3));
				assertEquals(v.intValue(), row.getInt(4));
				assertEquals(v.longValue(), row.getLong(5));
				assertEquals(v.floatValue(), row.getFloat(6), 0);
				assertEquals(v.doubleValue(), row.getDouble(7), 0);
				assertEquals(
						toDateTime(v),
						row.getTimestamp(8, 9).toLocalDateTime());
				assertEquals(BigDecimal.valueOf(v), row.getDecimal(9, 5, 0).toBigDecimal());
				assertEquals(BigDecimal.valueOf(v), row.getDecimal(10, 15, 0).toBigDecimal());
				assertEquals(BigDecimal.valueOf(v), row.getDecimal(11, 20, 0).toBigDecimal());
				assertEquals(BigDecimal.valueOf(v), row.getDecimal(12, 5, 0).toBigDecimal());
				assertEquals(BigDecimal.valueOf(v), row.getDecimal(13, 15, 0).toBigDecimal());
				assertEquals(BigDecimal.valueOf(v), row.getDecimal(14, 20, 0).toBigDecimal());
			}
			i++;
		}
		reader.close();
		return i - start;
	}

	private Row newRow(Integer v) {
		return Row.of(
				"" + v,
				v % 2 == 0,
				v,
				v,
				v,
				v.longValue(),
				v.floatValue(),
				v.doubleValue(),
				toDateTime(v),
				BigDecimal.valueOf(v),
				BigDecimal.valueOf(v),
				BigDecimal.valueOf(v),
				BigDecimal.valueOf(v),
				BigDecimal.valueOf(v),
				BigDecimal.valueOf(v));
	}

	private LocalDateTime toDateTime(Integer v) {
		v = (v > 0 ? v : -v) % 10000;
		return BASE_TIME.plusNanos(v).plusSeconds(v);
	}

	@Test
	public void testDictionary() throws IOException {
		// prepare parquet file
		int number = 10000;
		List<Row> records = new ArrayList<>(number);
		List<Integer> values = new ArrayList<>(number);
		Random random = new Random();
		int[] intValues = new int[10];
		// test large values in dictionary
		for (int i = 0; i < intValues.length; i++) {
			intValues[i] = random.nextInt();
		}
		for (int i = 0; i < number; i++) {
			Integer v = intValues[random.nextInt(10)];
			if (v == 0) {
				values.add(null);
				records.add(new Row(FIELD_NUMBER));
			} else {
				values.add(v);
				records.add(newRow(v));
			}
		}

		testNormalTypes(number, records, values);
	}

	@Test
	public void testPartialDictionary() throws IOException {
		// prepare parquet file
		int number = 10000;
		List<Row> records = new ArrayList<>(number);
		List<Integer> values = new ArrayList<>(number);
		Random random = new Random();
		int[] intValues = new int[10];
		// test large values in dictionary
		for (int i = 0; i < intValues.length; i++) {
			intValues[i] = random.nextInt();
		}
		for (int i = 0; i < number; i++) {
			Integer v = i < 5000 ? intValues[random.nextInt(10)] : i;
			if (v == 0) {
				values.add(null);
				records.add(new Row(FIELD_NUMBER));
			} else {
				values.add(v);
				records.add(newRow(v));
			}
		}

		testNormalTypes(number, records, values);
	}

	@Test
	public void testContinuousRepetition() throws IOException {
		// prepare parquet file
		int number = 10000;
		List<Row> records = new ArrayList<>(number);
		List<Integer> values = new ArrayList<>(number);
		Random random = new Random();
		for (int i = 0; i < 100; i++) {
			Integer v = random.nextInt(10);
			for (int j = 0; j < 100; j++) {
				if (v == 0) {
					values.add(null);
					records.add(new Row(FIELD_NUMBER));
				} else {
					values.add(v);
					records.add(newRow(v));
				}
			}
		}

		testNormalTypes(number, records, values);
	}

	@Test
	public void testLargeValue() throws IOException {
		// prepare parquet file
		int number = 10000;
		List<Row> records = new ArrayList<>(number);
		List<Integer> values = new ArrayList<>(number);
		Random random = new Random();
		for (int i = 0; i < number; i++) {
			Integer v = random.nextInt();
			if (v % 10 == 0) {
				values.add(null);
				records.add(new Row(FIELD_NUMBER));
			} else {
				values.add(v);
				records.add(newRow(v));
			}
		}

		testNormalTypes(number, records, values);
	}

	@Test
	public void testProject() throws IOException {
		// prepare parquet file
		int number = 1000;
		List<Row> records = new ArrayList<>(number);
		for (int i = 0; i < number; i++) {
			Integer v = i;
			records.add(newRow(v));
		}

		Path testPath = createTempParquetFile(
				TEMPORARY_FOLDER.newFolder(), PARQUET_SCHEMA, records, rowGroupSize);

		// test reader
		LogicalType[] fieldTypes = new LogicalType[]{
				new DoubleType(),
				new TinyIntType(),
				new IntType()};
		ParquetColumnarRowSplitReader reader = new ParquetColumnarRowSplitReader(
				false,
				true,
				new Configuration(),
				fieldTypes,
				new String[] {"f7", "f2", "f4"},
				VectorizedColumnBatch::new,
				500,
				new org.apache.hadoop.fs.Path(testPath.getPath()),
				0,
				Long.MAX_VALUE);
		int i = 0;
		while (!reader.reachedEnd()) {
			ColumnarRowData row = reader.nextRecord();
			assertEquals(i, row.getDouble(0), 0);
			assertEquals((byte) i, row.getByte(1));
			assertEquals(i, row.getInt(2));
			i++;
		}
		reader.close();
	}

	@Test
	public void testPartitionValues() throws IOException {
		// prepare parquet file
		int number = 1000;
		List<Row> records = new ArrayList<>(number);
		for (int i = 0; i < number; i++) {
			Integer v = i;
			records.add(newRow(v));
		}

		Path testPath = createTempParquetFile(
				TEMPORARY_FOLDER.newFolder(), PARQUET_SCHEMA, records, rowGroupSize);

		// test reader
		Map<String, Object> partSpec = new HashMap<>();
		partSpec.put("f15", true);
		partSpec.put("f16", Date.valueOf("2020-11-23"));
		partSpec.put("f17", LocalDateTime.of(1999, 1, 1, 1, 1));
		partSpec.put("f18", 6.6);
		partSpec.put("f19", (byte) 9);
		partSpec.put("f20", (short) 10);
		partSpec.put("f21", 11);
		partSpec.put("f22", 12L);
		partSpec.put("f23", 13f);
		partSpec.put("f24", new BigDecimal(24));
		partSpec.put("f25", new BigDecimal(25));
		partSpec.put("f26", new BigDecimal(26));
		partSpec.put("f27", "f27");

		innerTestPartitionValues(testPath, partSpec, false);

		for (String k : new ArrayList<>(partSpec.keySet())) {
			partSpec.put(k, null);
		}

		innerTestPartitionValues(testPath, partSpec, true);
	}

	private void innerTestPartitionValues(
			Path testPath,
			Map<String, Object> partSpec,
			boolean nullPartValue) throws IOException {
		LogicalType[] fieldTypes = new LogicalType[]{
				new VarCharType(VarCharType.MAX_LENGTH),
				new BooleanType(),
				new TinyIntType(),
				new SmallIntType(),
				new IntType(),
				new BigIntType(),
				new FloatType(),
				new DoubleType(),
				new TimestampType(9),
				new DecimalType(5, 0),
				new DecimalType(15, 0),
				new DecimalType(20, 0),
				new DecimalType(5, 0),
				new DecimalType(15, 0),
				new DecimalType(20, 0),
				new BooleanType(),
				new DateType(),
				new TimestampType(9),
				new DoubleType(),
				new TinyIntType(),
				new SmallIntType(),
				new IntType(),
				new BigIntType(),
				new FloatType(),
				new DecimalType(5, 0),
				new DecimalType(15, 0),
				new DecimalType(20, 0),
				new VarCharType(VarCharType.MAX_LENGTH)};
		ParquetColumnarRowSplitReader reader = ParquetSplitReaderUtil.genPartColumnarRowReader(
				false,
				true,
				new Configuration(),
				IntStream.range(0, 28).mapToObj(i -> "f" + i).toArray(String[]::new),
				Arrays.stream(fieldTypes)
						.map(TypeConversions::fromLogicalToDataType)
						.toArray(DataType[]::new),
				partSpec,
				new int[]{7, 2, 4, 15, 19, 20, 21, 22, 23, 18, 16, 17, 24, 25, 26, 27},
				rowGroupSize,
				new Path(testPath.getPath()),
				0,
				Long.MAX_VALUE);
		int i = 0;
		while (!reader.reachedEnd()) {
			ColumnarRowData row = reader.nextRecord();

			// common values
			assertEquals(i, row.getDouble(0), 0);
			assertEquals((byte) i, row.getByte(1));
			assertEquals(i, row.getInt(2));

			// partition values
			if (nullPartValue) {
				for (int j = 3; j < 16; j++) {
					assertTrue(row.isNullAt(j));
				}
			} else {
				assertTrue(row.getBoolean(3));
				assertEquals(9, row.getByte(4));
				assertEquals(10, row.getShort(5));
				assertEquals(11, row.getInt(6));
				assertEquals(12, row.getLong(7));
				assertEquals(13, row.getFloat(8), 0);
				assertEquals(6.6, row.getDouble(9), 0);
				assertEquals(
						SqlDateTimeUtils.dateToInternal(Date.valueOf("2020-11-23")),
						row.getInt(10));
				assertEquals(
						LocalDateTime.of(1999, 1, 1, 1, 1),
						row.getTimestamp(11, 9).toLocalDateTime());
				assertEquals(
						DecimalData.fromBigDecimal(new BigDecimal(24), 5, 0),
						row.getDecimal(12, 5, 0));
				assertEquals(
						DecimalData.fromBigDecimal(new BigDecimal(25), 15, 0),
						row.getDecimal(13, 15, 0));
				assertEquals(
						DecimalData.fromBigDecimal(new BigDecimal(26), 20, 0),
						row.getDecimal(14, 20, 0));
				assertEquals("f27", row.getString(15).toString());
			}

			i++;
		}
		reader.close();
	}
}


text:
package com.asakusafw.lang.compiler.model.description;

/**
 * A root interface of descriptions.
 * @see Descriptions
 */
public interface Description {

    // no special members
}


text:
//
//  Help1ContentViewController.m
//  Embrace ios7
//
//  Created by Jim on 14-5-10.
//  Copyright (c) 2014年 d-red puma. All rights reserved.
//

#import "HelpContentViewController.h"

@interface HelpContentViewController ()

@end

@implementation HelpContentViewController
@synthesize currentHelpIndex;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    float iosVersion;
    float deltaY = 0;
    iosVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(iosVersion>=7.0)
        deltaY = 20;

	// Do any additional setup after loading the view.
    backButton.titleLabel.font=[UIFont fontWithName:@"Avenir" size:15];
    backButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    helpLabel.font = [UIFont fontWithName:@"Avenir Next Condensed" size:25];
    backButton.frame = CGRectMake(15, 8 + deltaY, 56, 34);

    nextButton.frame = CGRectMake(248, 8 + deltaY, 65, 34);
    nextButton.titleLabel.font=[UIFont fontWithName:@"Avenir" size:15];

    line1.frame = CGRectMake(0, 47 + deltaY, 320, 2);

    CGRect chooseLabelFrame = helpLabel.frame;
    chooseLabelFrame.origin.y = 7 + deltaY;
    chooseLabelFrame.size.width = self.view.bounds.size.width - backButton.frame.size.width - nextButton.frame.size.width - 15;
    chooseLabelFrame.origin.x = backButton.frame.origin.x + backButton.frame.size.width + 5;

    helpLabel.frame = chooseLabelFrame;
    helpLabel.textAlignment = NSTextAlignmentCenter;

    helpContentName = [[NSArray alloc]initWithObjects:
                       @"UI_Help_Welcome-to-embraceplus.png" ,
                       @"UI_Help_HowToGetStarted.png" ,
                       @"UI_Help_Mute-notifications.png" ,
                       @"UI_Help_Configure-light-effects.png",
                       @"UI_Help_Configure-calls-features.png",
                       @"UI_Help_Configure-clock-features.png",
                       @"UI_Help_Configure-calendar.png",
                       @"UI_Help_Other-info-notifications.png",
                       @"UI_Help_Important-iOS-Settings.png",
                       @"UI_Help_Important-thirdparty-settings.png",
                       @"UI_Help_Themes.png" ,
                       @"UI_Help_Connecting-a-new-band.png" ,
                       @"UI_Help_Troubleshooter.png" ,
                       nil];

    helpTitleArray =  [[NSArray alloc]  initWithObjects:
                       @"Welcome to Embrace+",
                       @"How to get started",
                       @"Mute notifications",
                       @"Configure light effects",
                       @"Configure calls feature",
                       @"Configure clock features",
                       @"Configure calendar",
                       @"Other info notifications",
                       @"Important iOS settings",
                       @"Important third-party app settings",
                       @"Themes",
                       @"Connecting a new band",
                       @"Troubleshooter",
                       nil];

    scrollView=[[UIScrollView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];

    //scroll.pagingEnabled=NO;
    scrollView.bounces=YES;
    scrollView.delegate=self;
    scrollView.showsHorizontalScrollIndicator=NO;
    scrollView.showsVerticalScrollIndicator=NO;
    scrollView.frame = CGRectMake(0, 49+deltaY, 320, [[UIScreen mainScreen] bounds].size.height-49-deltaY);
    [self.view addSubview:scrollView];
    scrollView.contentInset = UIEdgeInsetsMake(0, 0, 40.0, 0);

    UIImageView *imageView;
    imageView=[[UIImageView alloc]init];
    imageView.image=[UIImage imageNamed:[helpContentName objectAtIndex:currentHelpIndex]];

    imageView.frame = CGRectMake(0, 0, imageView.image.size.width/2.0, imageView.image.size.height/2.0);
    scrollView.contentSize=CGSizeMake(imageView.image.size.width/2.0, imageView.image.size.height/2.0);
    [scrollView addSubview:imageView];

#pragma mark - kane
    if(self.currentHelpIndex == helpTitleArray.count-1)
    {
        self.isLast = YES;
    }

}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    backgroundImageView.image = appDelegate.backgroundImage;

    helpLabel.text = [helpTitleArray objectAtIndex:currentHelpIndex];
}

- (IBAction)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)next:(id)sender
{
    if(self.isLast)
    {
        [self back:nil];
        return;
    }
    if(currentHelpIndex == helpTitleArray.count-1)
    {
        [self back:nil];
        return;
    }

    else
        currentHelpIndex ++;

    NSArray *viewsToRemove = [scrollView subviews];
    for (UIView *v in viewsToRemove) [v removeFromSuperview];

    UIImageView *imageView;
    imageView=[[UIImageView alloc]init];
    imageView.image=[UIImage imageNamed:[helpContentName objectAtIndex:currentHelpIndex]];
    imageView.frame = CGRectMake(0, 0, imageView.image.size.width/2.0, imageView.image.size.height/2.0);
    scrollView.contentSize=CGSizeMake(imageView.image.size.width/2.0, imageView.image.size.height/2.0);
    [scrollView addSubview:imageView];

    helpLabel.text = [helpTitleArray objectAtIndex:currentHelpIndex];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<code_scheme name="flowable profile" version="173">
  <option name="RIGHT_MARGIN" value="160" />
  <JavaCodeStyleSettings>
      <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="99" />
      <option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="99" />
      <option name="IMPORT_LAYOUT_TABLE">
        <value>
          <package name="" withSubpackages="true" static="true" />
          <emptyLine />
          <package name="java" withSubpackages="true" static="false" />
          <emptyLine />
          <package name="javax" withSubpackages="true" static="false" />
          <emptyLine />
          <package name="org" withSubpackages="true" static="false" />
          <emptyLine />
          <package name="com" withSubpackages="true" static="false" />
          <emptyLine />
          <package name="liquibase" withSubpackages="true" static="false" />
          <emptyLine />
          <package name="" withSubpackages="true" static="false" />
        </value>
      </option>
      <option name="JD_ALIGN_PARAM_COMMENTS" value="false" />
      <option name="JD_ALIGN_EXCEPTION_COMMENTS" value="false" />
  </JavaCodeStyleSettings>
  <codeStyleSettings language="JAVA">
      <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
      <option name="KEEP_CONTROL_STATEMENT_IN_ONE_LINE" value="false" />
      <option name="KEEP_BLANK_LINES_IN_DECLARATIONS" value="1" />
      <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
      <option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="1" />
      <option name="BLANK_LINES_AFTER_CLASS_HEADER" value="1" />
      <option name="BLANK_LINES_AFTER_ANONYMOUS_CLASS_HEADER" value="1" />
      <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
      <option name="SPACE_WITHIN_ARRAY_INITIALIZER_BRACES" value="true" />
      <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
      <option name="CALL_PARAMETERS_WRAP" value="1" />
      <option name="METHOD_PARAMETERS_WRAP" value="1" />
      <option name="EXTENDS_LIST_WRAP" value="1" />
      <option name="THROWS_LIST_WRAP" value="1" />
      <option name="EXTENDS_KEYWORD_WRAP" value="1" />
      <option name="THROWS_KEYWORD_WRAP" value="1" />
      <option name="METHOD_CALL_CHAIN_WRAP" value="1" />
      <option name="BINARY_OPERATION_WRAP" value="1" />
      <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
      <option name="TERNARY_OPERATION_WRAP" value="5" />
      <option name="ARRAY_INITIALIZER_WRAP" value="1" />
  </codeStyleSettings>
</code_scheme>


text:
NAME=alpine-firefox

all: help

help:
	@echo 'error: use "make build" to start!'

build:
	docker build -t $(NAME) .


text:
import {Page} from "ionic-framework/ionic";
import {HostInfoPage} from "../host-info/host-info";
import {SnapshotList} from "../snapshot-list/snapshot-list";
import {Page3} from "../page3/page3";

@Page({
  templateUrl: "build/pages/tabs/tabs.html"
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab"s root Page
  tab1Root: any = HostInfoPage;
  tab2Root: any = SnapshotList;
  tab3Root: any = Page3;
}


text:
package std

type Err struct {
	Code    int
	Message string
}

var (
	ErrOK          = newError(20000, "OK")
	ErrIllegalJson = newError(50001, "Illegal JSON")
)

func newError(code int, message string) *Err {
	return &Err{Code: code, Message: message}
}


text:
package com.simmarith.sqlCon;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Street extends DbEntity {
    // Properties
    private String name = null;
    private City city = new City();

    // Getter and Setter
    public String getName() {
        if (this.name == null) {
            this.name = this.fetchProperty("name");
        }
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public City getCity() {
        if (this.city.getId() == null) {
            this.city = new City(this.fetchProperty("id_city"));
        }
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    // Methods
    public void persist() {
        if (this.getId() == null) {
            ResultSet res = this.con.sql(String.format(
                    "insert into %s (id_city, name) values ('%s', '%s')",
                    this.tableName, this.getCity().getId(), this.getName()));
            try {
                res.next();
                this.setId(Long.toString(res.getLong(1)));
                return;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.con.sql(String.format(
                "update %s set id_city = '%s', name = '%s' where id = %s",
                this.tableName, this.getCity().getId(), this.getName(),
                this.getId()));
    }

    // Constructors
    public Street() {
        super("street");
    }

    public Street(String id) {
        this();
        this.setId(id);
    }

}


text:
<?php

namespace Molajo\Fieldhandler\Tests;

use Molajo\Fieldhandler\Request;
use PHPUnit_Framework_TestCase;

/**
 * Space Fieldhandler
 *
 * @package    Molajo
 * @copyright  2014-2015 Amy Stephen. All rights reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @since      1.0.0
 */
class SpaceTest extends PHPUnit_Framework_TestCase
{
    /**
     * Request
     *
     * @var    object  Molajo\Fieldhandler\Request
     * @since  1.0.0
     */
    protected $request;

    /**
     * Set up
     *
     * @return void
     * @since   1.0.0
     */
    protected function setUp()
    {
        $this->request = new Request();
    }

    /**
     * @covers  Molajo\Fieldhandler\Constraint\Space::validate
     * @covers  Molajo\Fieldhandler\Constraint\Space::validation
     * @covers  Molajo\Fieldhandler\Constraint\Space::getValidateMessages
     * @covers  Molajo\Fieldhandler\Constraint\Space::setValidateMessage
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::validate
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::validation
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::sanitizeByCType
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::getValidateMessages
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::setValidateMessage
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraintTests::sanitizeByCharacter
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraintTests::sanitizeCharacter
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::validate
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::getValidateMessages
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::setValidateMessage
     *
     * @return  void
     * @since   1.0.0
     */
    public function testValidateTrue()
    {
        $field_name  = 'test';
        $field_value = "\n \r \t";
        $constraint  = 'Space';
        $options     = array();

        $results = $this->request->validate($field_name, $field_value, $constraint, $options);

        $this->assertEquals(true, $results->getValidateResponse());
        $this->assertEquals(array(), $results->getValidateMessages());

        return;
    }

    /**
     * @covers  Molajo\Fieldhandler\Constraint\Space::validate
     * @covers  Molajo\Fieldhandler\Constraint\Space::validation
     * @covers  Molajo\Fieldhandler\Constraint\Space::getValidateMessages
     * @covers  Molajo\Fieldhandler\Constraint\Space::setValidateMessage
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::validate
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::validation
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::sanitizeByCType
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::getValidateMessages
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::setValidateMessage
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraintTests::sanitizeByCharacter
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraintTests::sanitizeCharacter
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::validate
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::getValidateMessages
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::setValidateMessage
     *
     * @return  void
     * @since   1.0.0
     */
    public function testValidateFalse()
    {
        $field_name  = 'test';
        $field_value = "xyz\n \r \t";
        $constraint  = 'Space';
        $options     = array();

        $results = $this->request->validate($field_name, $field_value, $constraint, $options);

        $this->assertEquals(false, $results->getValidateResponse());

        $expected_code    = 2000;
        $expected_message = 'Field: test must only contain Space values.';
        $messages         = $results->getValidateMessages();
        $this->assertEquals($expected_code, $messages[0]->code);
        $this->assertEquals($expected_message, $messages[0]->message);

        return;
    }

    /**
     * @covers  Molajo\Fieldhandler\Constraint\Space::sanitize
     * @covers  Molajo\Fieldhandler\Constraint\Space::validation
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::sanitize
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::validation
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::sanitizeByCType
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraintTests::sanitizeByCharacter
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraintTests::sanitizeCharacter
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::sanitize
     *
     * @return  void
     * @since   1.0.0
     */
    public function testSanitizeNoChange()
    {
        $field_name  = 'test';
        $field_value = "\n \r \t";
        $constraint  = 'Space';
        $options     = array();

        $results = $this->request->sanitize($field_name, $field_value, $constraint, $options);

        $this->assertEquals($field_value, $results->getFieldValue());
        $this->assertEquals(false, $results->getChangeIndicator());

        return;
    }

    /**
     * @covers  Molajo\Fieldhandler\Constraint\Space::sanitize
     * @covers  Molajo\Fieldhandler\Constraint\Space::validation
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::sanitize
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::validation
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::sanitizeByCType
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraintTests::sanitizeByCharacter
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraintTests::sanitizeCharacter
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::sanitize
     *
     * @return  void
     * @since   1.0.0
     */
    public function testSanitizeChange()
    {
        $field_name  = 'test';
        $field_value = "Dogfood\n \r \t";
        $constraint  = 'Space';
        $options     = array();

        $results = $this->request->sanitize($field_name, $field_value, $constraint, $options);

        $expected_value = "\n \r \t";
        $this->assertEquals($expected_value, $results->getFieldValue());
        $this->assertEquals(true, $results->getChangeIndicator());

        return;
    }

    /**
     * @covers  Molajo\Fieldhandler\Constraint\Space::format
     * @covers  Molajo\Fieldhandler\Constraint\AbstractCtype::format
     * @covers  Molajo\Fieldhandler\Constraint\AbstractConstraint::format
     *
     * @return  void
     * @since   1.0.0
     */
    public function testFormat()
    {
        $field_name  = 'test';
        $field_value = '1A2b3C4d5E6f7G8';
        $constraint  = 'Space';
        $options     = array();

        $results = $this->request->format($field_name, $field_value, $constraint, $options);

        $this->assertEquals($field_value, $results->getFieldValue());
        $this->assertEquals(false, $results->getChangeIndicator());

        return;
    }
}


text:
<?php

require_once 'base/PHPushbulletTestBase.php';

class ChannelTest extends PHPushbulletTestBase
{
    /** @test */

    public function it_can_chain_channels()
    {
        $response = $this->pushResponse([
                                          'type'  => 'note',
                                          'title' => 'Reminder',
                                          'body'  => 'Do this thing',
                                        ]);

        $this->mock([
            $this->okResponse($response),
            $this->okResponse($response),
        ]);

        $response = $this->pushbullet->channel('mychanneltag')->note('Title', 'Body');

        $this->assertInternalType('array', $response);
        $this->assertCount(1, $response);

        $this->assertRequestHistory(['pushes']);
    }

    /** @test */

    public function it_can_pass_multiple_channels()
    {
        $response = $this->pushResponse([
                                          'type'  => 'note',
                                          'title' => 'Reminder',
                                          'body'  => 'Do this thing',
                                        ]);

        $this->mock([
            $this->okResponse($response),
            $this->okResponse($response),
        ]);

        $response = $this->pushbullet->channel('mychanneltag', 'anotherchanneltag')->note('Title', 'Body');

        $this->assertInternalType('array', $response);
        $this->assertCount(2, $response);

        $this->assertRequestHistory(['pushes', 'pushes']);
    }
}


text:
<?php
/*
*Project: eYSIP_2015_IoT-Connected-valves-for-irrigation-of-greenhouse
*Team members: Jayant Solanki, Kevin D'Souza
*File name: time.php
*Author: Jayant Solanki
*display options to user for time scheduling
*options are, period, duration and frequency
*/
include_once 'iotdb.php';?>
<?php
date_default_timezone_set('Asia/Kolkata');//setting IST
//echo "Time is ".date('Hi');?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Schedule</title>
<?php include 'favicon.php';?>

<?php include_once 'css.php'; ?>

Your browser doesnt support javascript

<?php include_once "navigation.php";?>

IOT Based Valve control

Add Schedule

Choose Group        <select id="grps">
<option selected="true" disabled='disabled'>Choose</option>
<?php
mysql_select_db($dbname) or die(mysql_error());
$query="SELECT * FROM groups"; //displaying groups
$results=mysql_query($query);
if (mysql_num_rows($results) > 0)
	{
		while($row=mysql_fetch_assoc($results))
		{	//$id=$row['id'];
			$group=$row['name'];
			$id=$row['id'];
			echo " <option value='$id'>$group</option>";
		}
	}

?>

</select>

Type of Schedule   <select id="time">
<option selected="true" disabled='disabled'>Choose</option>
  <option value="period">Period</option>
  <option value="duration">Duration</option>
  <option value="frequency">Frequency</option>
</select>

Start time:(hhmm)

<?php
echo "Hrs:<select id='starth' name='starth'>";
$i=0;
while($i<=24)
{
echo "<option value='$i'>$i</option>";
$i++;
}
echo "</select>";
echo " Mins:<select id='startm' name='startm'>";
$j=0;
while($j<=60)
{
echo "<option value='$j'>$j</option>";
$j=$j+5;
}
echo "</select>";
?>

Stop time:(hhmm)

<?php
echo "Hrs:<select id='stoph' name='stoph'>";
$i=0;
while($i<=24)
{
echo "<option value='$i'>$i</option>";
$i++;
}
echo "</select>";
echo " Mins:<select id='stopm' name='stopm'>";
$j=0;
while($j<=60)
{
echo "<option value='$j'>$j</option>";
$j=$j+5;
}
echo "</select>";
?>

<input type='submit' name='submit' onclick='period()' value='Submit' />

Start time:(hhmm)

<?php
echo "Hrs:<select id='dstarth' name='starth'>";
$i=0;
while($i<=24)
{
echo "<option value='$i'>$i</option>";
$i++;
}
echo "</select>";
echo " Mins:<select id='dstartm' name='startm'>";
$j=0;
while($j<=60)
{
echo "<option value='$j'>$j</option>";
$j=$j+5;
}
echo "</select>";
?>

Duration:(mm)

<?php

echo "Mins:<select id='dduration' name='duration'>";
$j=5;
while($j<=60)
{
echo "<option value='$j'>$j</option>";
$j=$j+5;
}
echo "</select>";
?>

<input type='submit' name='submit' onclick='duration()' value='Submit' />

Start time:(hhmm)

<?php
echo "Hrs:<select id='fstarth' name='starth'>";
$i=0;
while($i<=24)
{
echo "<option value='$i'>$i</option>";
$i++;
}
echo "</select>";
echo "

Duration:(mm)
";
echo "Mins:<select id='fduration' name='duration'>";
$j=5;
while($j<=60)
{
echo "<option value='$j'>$j</option>";
$j=$j+5;
}
echo "</select>";

?>

Repeat after every :(hh)

<?php

echo "Hrs:<select id='repeath' name='repeath'>";
$i=4;
while($i<=12)
{
echo "<option value='$i'>$i</option>";
$i=$i+4;
}
echo "</select>";
?>

<input type='submit' name='submit' onclick='frequency()' value='Submit' />

<?php display();?>

<?php
include_once "app.php";?>

<?php //include_once "footer.php";?>

<?php

/*
 *
 * Function Name: display()
 * Input: -
 * Output: display the scheduled tasks
 * Logic: fetches tasks from tasks table
 *
 *
 */
function display()
{
	$dbname='IOT';
	mysql_select_db($dbname) or die(mysql_error());
	$query="SELECT * FROM tasks"; //displaying scheduled tasks
	$results=mysql_query($query);
	if (mysql_num_rows($results) > 0)
	{	$i=1;
		echo "

Scheduled Tasks
";
		while($row=mysql_fetch_assoc($results))
		{	$id=$row['id'];
			$start=$row['start'];
			$stop=$row['stop']; //online offline or new, 1, 0, 2
			$item=$row['item'];
			if($start>=2100 or $start<=300)
				$status="Shouldn't water plants during night";
			else
				$status='';
			echo "Task ".$i."   Item: $item    Start time : $start     Stop time : $stop  DELETE   $status
";
			$i++;

		}
	}
	else
	{
		echo "

No Tasks scheduled yet.
";
	}

}
?>


text:
<!DOCTYPE html>

    <title>Text example</title>

Examples of Text component functionality

Chapter has word wrap and scale false

Chapter has word wrap true and scale false

Chapter has word wrap false and scale true

Chapter has word wrap and scale true