text:
(function($) {

    // Class: $.jqplot.LinDifferentColorMarkerLineRenderereRenderer
    // Line renderer for jqPlot, this class has one
    // markerColors: []
    // Draws series as a line.
    $.jqplot.DifferentColorMarkerLineRenderer = function(options){
        this.markerColors = [];
        this.shapeRenderer = new $.jqplot.ShapeRenderer();
        this.shadowRenderer = new $.jqplot.ShadowRenderer();
        $.extend(true, this, options);
    };

    // called with scope of series.
    $.jqplot.DifferentColorMarkerLineRenderer.prototype.init = function(options) {
        //$.extend(true, this, options);
        // set the shape renderer options
        this.markerColors = options.markerColors || this.markerColors;
        var opts = {
            lineJoin:'round',
            lineCap:'round',
            fill:this.fill,
            isarc:false,
            strokeStyle:this.color,
            fillStyle:this.fillColor,
            lineWidth:this.lineWidth,
            closePath:this.fill

        };
        this.renderer.shapeRenderer.init(opts);
        // set the shadow renderer options
        // scale the shadowOffset to the width of the line.
        if (this.lineWidth > 2.5) {
            var shadow_offset = this.shadowOffset* (1 + (Math.atan((this.lineWidth/2.5))/0.785398163 - 1)*0.6);
        // var shadow_offset = this.shadowOffset;
        }
        // for skinny lines, don't make such a big shadow.
        else {
            var shadow_offset = this.shadowOffset*Math.atan((this.lineWidth/2.5))/0.785398163;
        }
        var sopts = {
            lineJoin:'round',
            lineCap:'round',
            fill:this.fill,
            isarc:false,
            angle:this.shadowAngle,
            offset:shadow_offset,
            alpha:this.shadowAlpha,
            depth:this.shadowDepth,
            lineWidth:this.lineWidth,
            closePath:this.fill
        };
        this.renderer.shadowRenderer.init(sopts);
    };

    // Method: setGridData
    // converts the user data values to grid coordinates and stores them
    // in the gridData array.
    // Called with scope of a series.
    $.jqplot.DifferentColorMarkerLineRenderer.prototype.setGridData = function(plot) {
        // recalculate the grid data
        var xp = this._xaxis.series_u2p;
        var yp = this._yaxis.series_u2p;
        var data = this._plotData;
        var pdata = this._prevPlotData;
        this.gridData = [];
        this._prevGridData = [];
        for (var i=0; i<this.data.length; i++) {
            if (data[i] != null) {
                this.gridData.push([xp.call(this._xaxis, data[i][0]), yp.call(this._yaxis, data[i][1])]);
            }
            if (pdata[i] != null) {
                this._prevGridData.push([xp.call(this._xaxis, pdata[i][0]), yp.call(this._yaxis, pdata[i][1])]);
            }
        }
    };

    // Method: makeGridData
    // converts any arbitrary data values to grid coordinates and
    // returns them.  This method exists so that plugins can use a series'
    // linerenderer to generate grid data points without overwriting the
    // grid data associated with that series.
    // Called with scope of a series.
    $.jqplot.DifferentColorMarkerLineRenderer.prototype.makeGridData = function(data, plot) {
        // recalculate the grid data
        var xp = this._xaxis.series_u2p;
        var yp = this._yaxis.series_u2p;
        var gd = [];
        var pgd = [];
        for (var i=0; i<data.length; i++) {
            if (data[i] != null) {
                gd.push([xp.call(this._xaxis, data[i][0]), yp.call(this._yaxis, data[i][1])]);
            }
        }
        return gd;
    };

    // called within scope of series.
    $.jqplot.DifferentColorMarkerLineRenderer.prototype.draw = function(ctx, gd, options) {
        var i;
        var opts = (options != undefined) ? options : {};
        var shadow = (opts.shadow != undefined) ? opts.shadow : this.shadow;
        var showLine = (opts.showLine != undefined) ? opts.showLine : this.showLine;
        var fill = (opts.fill != undefined) ? opts.fill : this.fill;
        var fillAndStroke = (opts.fillAndStroke != undefined) ? opts.fillAndStroke : this.fillAndStroke;
        ctx.save();
        if (gd.length) {
            if (showLine) {
                // if we fill, we'll have to add points to close the curve.
                if (fill) {
                    if (this.fillToZero) {
                        // have to break line up into shapes at axis crossings
                        var negativeColors = new $.jqplot.ColorGenerator(this.negativeSeriesColors);
                        var negativeColor = negativeColors.get(this.index);
                        if (! this.useNegativeColors) {
                            negativeColor = opts.fillStyle;
                        }
                        var isnegative = false;
                        var posfs = opts.fillStyle;

                        // if stoking line as well as filling, get a copy of line data.
                        if (fillAndStroke) {
                            var fasgd = gd.slice(0);
                        }
                        // if not stacked, fill down to axis
                        if (this.index == 0 || !this._stack) {

                            var tempgd = [];
                            var pyzero = this._yaxis.series_u2p(0);
                            var pxzero = this._xaxis.series_u2p(0);

                            if (this.fillAxis == 'y') {
                                tempgd.push([gd[0][0], pyzero]);

                                for (var i=0; i<gd.length-1; i++) {
                                    tempgd.push(gd[i]);
                                    // do we have an axis crossing?
                                    if (this._plotData[i][1] * this._plotData[i+1][1] < 0) {
                                        if (this._plotData[i][1] < 0) {
                                            isnegative = true;
                                            opts.fillStyle = negativeColor;
                                        }
                                        else {
                                            isnegative = false;
                                            opts.fillStyle = posfs;
                                        }

                                        var xintercept = gd[i][0] + (gd[i+1][0] - gd[i][0]) * (pyzero-gd[i][1])/(gd[i+1][1] - gd[i][1]);
                                        tempgd.push([xintercept, pyzero]);
                                        // now draw this shape and shadow.
                                        if (shadow) {
                                            this.renderer.shadowRenderer.draw(ctx, tempgd, opts);
                                        }
                                        this.renderer.shapeRenderer.draw(ctx, tempgd, opts);
                                        // now empty temp array and continue
                                        tempgd = [[xintercept, pyzero]];
                                    }
                                }
                                if (this._plotData[gd.length-1][1] < 0) {
                                    isnegative = true;
                                    opts.fillStyle = negativeColor;
                                }
                                else {
                                    isnegative = false;
                                    opts.fillStyle = posfs;
                                }
                                tempgd.push(gd[gd.length-1]);
                                tempgd.push([gd[gd.length-1][0], pyzero]);
                            }
                            // now draw this shape and shadow.
                            if (shadow) {
                                this.renderer.shadowRenderer.draw(ctx, tempgd, opts);
                            }
                            this.renderer.shapeRenderer.draw(ctx, tempgd, opts);

                        // var gridymin = this._yaxis.series_u2p(0);
                        // // IE doesn't return new length on unshift
                        // gd.unshift([gd[0][0], gridymin]);
                        // len = gd.length;
                        // gd.push([gd[len - 1][0], gridymin]);
                        }
                        // if stacked, fill to line below
                        else {
                            var prev = this._prevGridData;
                            for (var i=prev.length; i>0; i--) {
                                gd.push(prev[i-1]);
                            }
                            if (shadow) {
                                this.renderer.shadowRenderer.draw(ctx, gd, opts);
                            }

                            this.renderer.shapeRenderer.draw(ctx, gd, opts);
                        }
                    }
                    else {
                        // if stoking line as well as filling, get a copy of line data.
                        if (fillAndStroke) {
                            var fasgd = gd.slice(0);
                        }
                        // if not stacked, fill down to axis
                        if (this.index == 0 || !this._stack) {
                            // var gridymin = this._yaxis.series_u2p(this._yaxis.min) - this.gridBorderWidth / 2;
                            var gridymin = ctx.canvas.height;
                            // IE doesn't return new length on unshift
                            gd.unshift([gd[0][0], gridymin]);
                            len = gd.length;
                            gd.push([gd[len - 1][0], gridymin]);
                        }
                        // if stacked, fill to line below
                        else {
                            var prev = this._prevGridData;
                            for (var i=prev.length; i>0; i--) {
                                gd.push(prev[i-1]);
                            }
                        }
                        if (shadow) {
                            this.renderer.shadowRenderer.draw(ctx, gd, opts);
                        }

                        this.renderer.shapeRenderer.draw(ctx, gd, opts);
                    }
                    if (fillAndStroke) {
                        var fasopts = $.extend(true, {}, opts, {
                            fill:false,
                            closePath:false
                        });
                        this.renderer.shapeRenderer.draw(ctx, fasgd, fasopts);
                        //////////
                        // TODO: figure out some way to do shadows nicely
                        // if (shadow) {
                        //     this.renderer.shadowRenderer.draw(ctx, fasgd, fasopts);
                        // }
                        // now draw the markers
                        if (this.markerRenderer.show) {
                            for (i=0; i<fasgd.length; i++) {
                                this.markerRenderer.draw(fasgd[i][0], fasgd[i][1], ctx, opts.markerOptions);
                            }
                        }
                    }
                }
                else {
                    if (shadow) {
                        this.renderer.shadowRenderer.draw(ctx, gd, opts);
                    }
                    this.renderer.shapeRenderer.draw(ctx, gd, opts);
                }
            }

            // now draw the markers
            if (this.markerRenderer.show && !fill) {
                for (i=0; i<gd.length; i++) {
                    // Grab each color and send it to a new markerRenderer.
                    opts.markerOptions = {
                        color: this.markerColors[i] || this.color,
                        shadow: false
                    };
                    this.markerRenderer = new $.jqplot.MarkerRenderer;
                    this.markerRenderer.init(opts.markerOptions);
                    this.markerRenderer.draw(gd[i][0], gd[i][1], ctx, opts.markerOptions);
                }
            }
        }

        ctx.restore();
    };

    $.jqplot.DifferentColorMarkerLineRenderer.prototype.drawShadow = function(ctx, gd, options) {
    // This is a no-op, shadows drawn with lines.
    };

})(jQuery);


text:
struct node{
	int item;
	struct node *next;
};
void insert(struct node **ref , int data){
	struct node *new_node = (struct node *)malloc(sizeof(struct node));
	new_node -> item = data;
	new_node -> next = NULL;
	if(*ref == NULL){
		(*ref) = new_node;
	}
	else{
		new_node -> next = (*ref);
		*ref = new_node;
	}
}
void findMiddle(struct node *ref){
	struct node *fast = ref;
	struct node *slow = ref;
	while((fast !=NULL) && (fast->next !=NULL) ){
		fast = fast->next->next;
		slow = slow->next;
	}
	printf("Middle %d",slow->item);
}
int main(void) {
	struct node * root = NULL;
	insert(&root,1);
	insert(&root,2);
	insert(&root,3);
	insert(&root,4);
	insert(&root,5);
	insert(&root,6);
	insert(&root,7);
	struct node * temp = root;
	while(temp!=NULL){
		printf("%d\n",temp->item);
		temp=temp->next;
	}
	findMiddle(root);

	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
/* Buffer object interface */

/* Note: the object's structure is private */

#ifndef Py_BUFFEROBJECT_H
#define Py_BUFFEROBJECT_H
#ifdef __cplusplus
extern "C" {
#endif

PyAPI_DATA(PyTypeObject) PyBuffer_Type;

#define PyBuffer_Check(op) ((op)->ob_type == &PyBuffer_Type)

#define Py_END_OF_BUFFER	(-1)

PyAPI_FUNC(PyObject *) PyBuffer_FromObject(PyObject *base,
                                           Py_ssize_t offset, Py_ssize_t size);
PyAPI_FUNC(PyObject *) PyBuffer_FromReadWriteObject(PyObject *base,
                                                    Py_ssize_t offset,
                                                    Py_ssize_t size);

PyAPI_FUNC(PyObject *) PyBuffer_FromMemory(void *ptr, Py_ssize_t size);
PyAPI_FUNC(PyObject *) PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size);

PyAPI_FUNC(PyObject *) PyBuffer_New(Py_ssize_t size);

#ifdef __cplusplus
}
#endif
#endif /* !Py_BUFFEROBJECT_H */


text:
require_relative "../base"
require_relative "../events/event"

module Fusuma
  module Plugin
    module Inputs
      # Inherite this base
      # @abstract Subclass and override {#io} to implement
      class Input < Base
        # Wait multiple inputs until it becomes readable
        # and read lines with nonblock
        # @param inputs [Array<Input>]
        # @return [Event]
        def self.select(inputs)
          ios = IO.select(inputs.map(&:io))
          io = ios&.first&.first

          input = inputs.find { |i| i.io == io }

          begin
            line = io.readline_nonblock("\n").chomp
          rescue EOFError => e
            warn "#{input.class.name}: #{e}"
            warn "Send SIGKILL to fusuma processes"
            inputs.reject { |i| i == input }.each do |i|
              warn "stop process: #{i.class.name.underscore}"
              Process.kill(:SIGKILL, i.pid)
            end
            exit 1
          rescue => e
            warn "#{input.class.name}: #{e}"
            exit 1
          end

          input.create_event(record: line)
        end

        # @return [Integer]
        def pid
          raise NotImplementedError, "override #{self.class.name}##{__method__}"
        end

        # @return [IO]
        def io
          raise NotImplementedError, "override #{self.class.name}##{__method__}"
        end

        # @return [Event]
        def create_event(record: "dummy input")
          e = Events::Event.new(tag: tag, record: record)
          MultiLogger.debug(input_event: e)
          e
        end

        def tag
          self.class.name.split("Inputs::").last.underscore
        end
      end
    end
  end
end

# ref: https://github.com/Homebrew/brew/blob/6b2dbbc96f7d8aa12f9b8c9c60107c9cc58befc4/Library/Homebrew/extend/io.rb
class IO
  def readline_nonblock(sep = $INPUT_RECORD_SEPARATOR)
    line = +""
    buffer = +""

    loop do
      break if buffer == sep

      read_nonblock(1, buffer)
      line.concat(buffer)
    end

    line.freeze
  rescue IO::WaitReadable, EOFError => e
    raise e if line.empty?

    line.freeze
  end
end


text:
<?php

define('DS', DIRECTORY_SEPARATOR);

class ProjectCreator
{
    private $templatePath;
    private $packageName;
    private $packageFullName;
    private $packageLastName;
    private $projectPath;
    private $orientation;
    private $noproj;

    private $vars = array();

    private $ready = false;

    function __construct(array $config)
    {
        $force = $config['force'];
        $this->noproj = $config['noproj'];

        // check template
        $templatePath = rtrim($config['templatePath'], "/\\") . DS;
        if (!is_dir($templatePath))
        {
            printf("ERROR: invalid template path \"%s\"\n", $templatePath);
            return;
        }
        if (!file_exists($templatePath . 'TEMPLATE_INFO.json'))
        {
            printf("ERROR: not found TEMPLATE_INFO.json in template path \"%s\"\n", $templatePath);
            return;
        }
        $info = file_get_contents($templatePath . 'TEMPLATE_INFO.json');
        $info = json_decode($info, true);
        if (!is_array($info) || empty($info['name']))
        {
            printf("ERROR: invalid TEMPLATE_INFO.json in template path \"%s\"\n", $templatePath);
            return;
        }

        $this->templatePath = $templatePath;

        // check packageName
        $packageName = str_replace('-', '_', strtolower($config['packageName']));
        $parts = explode('.', $packageName);
        $packageName = array();
        for ($i = 0; $i < count($parts); $i++)
        {
            $parts[$i] = preg_replace('/[^a-z0-9_]/', '', $parts[$i]);
            if (!empty($parts[$i])) $packageName[] = $parts[$i];
        }
        if (count($packageName) < 2)
        {
            printf("ERROR: invalid package name \"%s\"\n", implode('.', $packageName));
            return;
        }

        $lastname = $packageName[count($packageName) - 1];
        array_pop($packageName);
        $packageName = implode('.', $packageName);
        $this->packageName = $packageName;
        $this->packageLastName = $lastname;
        $this->packageFullName = $packageName . '.' . $lastname;

        // check projectName
        $this->projectPath = rtrim(getcwd(), '/\\') . DS . $lastname . DS;

        if (!$force && (is_dir($this->projectPath) || file_exists($this->projectPath)))
        {
            printf("ERROR: project path \"%s\" exists\n", $this->projectPath);
            return;
        }

        // check more options
        $orientation = strtolower($config['orientation']);
        if ($orientation != 'landscape' && $orientation != 'portrait')
        {
            printf("ERROR: invalid screen orientation \"%s\"\n", $orientation);
            return;
        }
        $this->orientation = $orientation;

        $this->ready = true;
    }

    function run()
    {
        if (!$this->ready) return false;

        echo <<<EOT

template            : {$this->templatePath}

package name        : {$this->packageFullName}
project path        : {$this->projectPath}
screen orientation  : {$this->orientation}

EOT;

        // create project dir
        if (!is_dir($this->projectPath)) mkdir($this->projectPath);
        if (!is_dir($this->projectPath))
        {
            printf("ERROR: create project dir \"%s\" failure\n", $this->projectPath);
            return;
        }

        // prepare contents
        $this->vars['__TEMPLATE_PATH__'] = $this->templatePath;
        $this->vars['__PROJECT_PACKAGE_NAME__'] = $this->packageName;
        $this->vars['__PROJECT_PACKAGE_NAME_L__'] = strtolower($this->packageName);
        $this->vars['__PROJECT_PACKAGE_FULL_NAME__'] = $this->packageFullName;
        $this->vars['__PROJECT_PACKAGE_FULL_NAME_L__'] = strtolower($this->packageFullName);
        $this->vars['__PROJECT_PACKAGE_LAST_NAME__'] = $this->packageLastName;
        $this->vars['__PROJECT_PACKAGE_LAST_NAME_L__'] = strtolower($this->packageLastName);
        $this->vars['__PROJECT_PACKAGE_LAST_NAME_UF__'] = ucfirst(strtolower($this->packageLastName));
        $this->vars['__PROJECT_PATH__'] = $this->projectPath;
        $this->vars['__SCREEN_ORIENTATION__'] = $this->orientation;
        $this->vars['__SCREEN_ORIENTATION_L__'] = strtolower($this->orientation);
        $this->vars['__SCREEN_ORIENTATION_UF__'] = ucfirst(strtolower($this->orientation));
        if ($this->orientation == 'landscape')
        {
            $this->vars['__SCREEN_WIDTH__'] = '960';
            $this->vars['__SCREEN_HEIGHT__'] = '640';
            $this->vars['__SCREEN_ORIENTATION_QUICK__'] = 'FIXED_HEIGHT';
        }
        else
        {
            $this->vars['__SCREEN_WIDTH__'] = '640';
            $this->vars['__SCREEN_HEIGHT__'] = '960';
            $this->vars['__SCREEN_ORIENTATION_QUICK__'] = 'FIXED_WIDTH';
        }

        if ($this->orientation == 'landscape')
        {
            $this->vars['__SCREEN_ORIENTATION_IOS__'] = "<string>UIInterfaceOrientationLandscapeRight</string>\n<string>UIInterfaceOrientationLandscapeLeft</string>";
        }
        else
        {
            $this->vars['__SCREEN_ORIENTATION_IOS__'] = '<string>UIInterfaceOrientationPortrait</string>';
        }

        // copy files
        $paths = $this->getPaths($this->templatePath);
        foreach ($paths as $sourcePath)
        {
            $sourceFilename = substr($sourcePath, strlen($this->templatePath));
            if ($sourceFilename == 'TEMPLATE_INFO.json') continue;
            if ($this->noproj && substr($sourceFilename, 0, 5) == 'proj.') continue;
            if ($this->noproj && substr($sourceFilename, 0, 8) == 'sources/') continue;
            if (!$this->copyFile($sourcePath, $sourceFilename)) return false;
        }

        return true;
    }

    private function copyFile($sourcePath, $sourceFilename)
    {
        // check filename
        $sourceFilename = substr($sourcePath, strlen($this->templatePath));
        $destinationFilename = $sourceFilename;

        foreach ($this->vars as $key => $value)
        {
            $value = str_replace('.', DS, $value);
            $destinationFilename = str_replace($key, $value, $destinationFilename);
        }

        printf("create file \"%s\" ... ", $destinationFilename);
        $dirname = pathinfo($destinationFilename, PATHINFO_DIRNAME);
        $destinationDir = $this->projectPath . $dirname;

        if (!is_dir($destinationDir))
        {
            mkdir($destinationDir, 0777, true);
        }
        if (!is_dir($destinationDir))
        {
            printf("ERROR: mkdir failure\n");
            return false;
        }

        $destinationPath = $this->projectPath . $destinationFilename;
        $contents = file_get_contents($sourcePath);
        if ($contents == false)
        {
            printf("ERROR: file_get_contents failure\n");
            return false;
        }
        $stat = stat($sourcePath);

        foreach ($this->vars as $key => $value)
        {
            $contents = str_replace($key, $value, $contents);
        }

        if (file_put_contents($destinationPath, $contents) == false)
        {
            printf("ERROR: file_put_contents failure\n");
            return false;
        }
        chmod($destinationPath, $stat['mode']);

        printf("OK\n");
        return true;
    }

    private function getPaths($dir)
    {
        $files = array();
        $dir = rtrim($dir, "/\\") . DS;
        $dh = opendir($dir);
        if ($dh == false)
        {
            return $files;
        }

        while (($file = readdir($dh)) !== false)
        {
            if ($file{0} == '.')
            {
                continue;
            }

            $path = $dir . $file;
            if (is_dir($path))
            {
                $files = array_merge($files, $this->getPaths($path));
            }
            elseif (is_file($path))
            {
                $files[] = $path;
            }
        }
        closedir($dh);
        return $files;
    }

}

// ----------------------------------------

function help()
{
    echo <<<EOT

usage: create_project [options] package_name

options:
    -f force copy files to project dir
    -o screen orientation, eg: -o landscape . default is portrait
    -t template path, eg: -t /quick-cocos2d-x/template/PROJECT_TEMPLATE_01
    -noproj skip create projects

    package name, eg: com.quickx.games.physics

examples:

    create_project com.quickx.game.physics

EOT;

}

if ($argc < 2)
{
    help();
    exit(1);
}

array_shift($argv);

$config = array(
    'orientation' => 'portrait',
    'force' => false,
    'templatePath' => '',
    'packageName' => '',
    'noproj' => false,
);

do
{
    if ($argv[0] == '-t')
    {
        $config['templatePath'] = $argv[1];
        array_shift($argv);
    }
    else if ($argv[0] == '-o')
    {
        $config['orientation'] = $argv[1];
        array_shift($argv);
    }
    else if ($argv[0] == '-f')
    {
        $config['force'] = true;
    }
    else if ($argv[0] == '-noproj')
    {
        $config['noproj'] = true;
    }
    else if ($config['packageName'] == '')
    {
        $config['packageName'] = $argv[0];
    }

    array_shift($argv);
} while (count($argv) > 0);

$creator = new ProjectCreator($config);
if ($creator->run())
{
    echo <<<EOT

DONE.

EOT;

}
else
{
    help();
}


text:
var gulp = require('gulp'),
    plumber = require('gulp-plumber'),
    rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin'),
    cache = require('gulp-cache');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');

browserSync.create();

///////////////
// Variables
//////////////

var dirs = {
    'server': {
        'main' : 'app.js'
    }
}

gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: "./server/"
        }
    });
});

gulp.task('bs-reload', function () {
    browserSync.reload();
});

gulp.task('images', function(){
    gulp.src('client/images/**/*')
        .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(gulp.dest('client/dist/images/'));
});

gulp.task('styles', function(){
    gulp.src(['client/scss/**/*.scss'])
        .pipe(plumber({
            errorHandler: function (error) {
                console.log(error.message);
                this.emit('end');
            }}))
        .pipe(sass())
        .pipe(autoprefixer('last 2 versions'))
        .pipe(gulp.dest('client/dist/styles/'))
        .pipe(browserSync.reload({stream:true}))
});

gulp.task('scripts', function(){
    return gulp.src('client/js/**/*.js')
        .pipe(plumber({
            errorHandler: function (error) {
                console.log(error.message);
                this.emit('end');
            }}))
        .pipe(concat('main.js'))
        .pipe(gulp.dest('client/dist/scripts/'))
        .pipe(rename({suffix: '.min'}))
        .pipe(uglify())
        .pipe(gulp.dest('client/dist/scripts/'))
        .pipe(browserSync.reload({stream:true}))
});

gulp.task('nodemon', function(cb) {
    nodemon({
        'script': dirs.server.main,
        'watch': dirs.server.main
    }).once('start', function() {
        cb();
    }).on('restart', function() {

    });
});

//TODO: Replace with environment configuration
gulp.task('browser-sync', ['nodemon'], function() {
    browserSync.init({
        proxy: "localhost:3000"
    });
});

gulp.task('default', ['browser-sync'], function(){
    gulp.watch("client/scss/**/*.scss", ['styles']);
    gulp.watch("client/js/**/*.js", ['scripts']);
    gulp.watch("*.html", ['bs-reload']);
});


text:
using System;
using System.Threading.Tasks;

namespace KeyWatcher.Dependencies
{
	internal sealed class Logger
		: ILogger
	{
		public Task LogAsync(string message)
		{
			return Console.Out.WriteLineAsync($"Log: {message}");
		}
	}
}


text:
<?php

namespace Doctrine\Tests\DBAL\Cache;

use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\DBAL\ParameterType;
use Doctrine\Tests\DbalTestCase;

class QueryCacheProfileTest extends DbalTestCase
{
    const LIFETIME = 3600;
    const CACHE_KEY = 'user_specified_cache_key';

    /** @var QueryCacheProfile */
    private $queryCacheProfile;

    protected function setUp()
    {
        $this->queryCacheProfile = new QueryCacheProfile(self::LIFETIME, self::CACHE_KEY);
    }

    public function testShouldUseTheGivenCacheKeyIfPresent()
    {
        $query  = 'SELECT * FROM foo WHERE bar = ?';
        $params = [666];
        $types  = [ParameterType::INTEGER];

        $connectionParams = array(
            'dbname'   => 'database_name',
            'user'     => 'database_user',
            'password' => 'database_password',
            'host'     => 'database_host',
            'driver'   => 'database_driver'
        );

        list($cacheKey) = $this->queryCacheProfile->generateCacheKeys(
            $query,
            $params,
            $types,
            $connectionParams
        );

        self::assertEquals(self::CACHE_KEY, $cacheKey, 'The returned cache key should match the given one');
    }

    public function testShouldGenerateAnAutomaticKeyIfNoKeyHasBeenGiven()
    {
        $query  = 'SELECT * FROM foo WHERE bar = ?';
        $params = [666];
        $types  = [ParameterType::INTEGER];

        $connectionParams = array(
            'dbname'   => 'database_name',
            'user'     => 'database_user',
            'password' => 'database_password',
            'host'     => 'database_host',
            'driver'   => 'database_driver'
        );

        $this->queryCacheProfile = $this->queryCacheProfile->setCacheKey(null);

        list($cacheKey) = $this->queryCacheProfile->generateCacheKeys(
            $query,
            $params,
            $types,
            $connectionParams
        );

        self::assertNotEquals(
            self::CACHE_KEY,
            $cacheKey,
            'The returned cache key should be generated automatically'
        );

        self::assertNotEmpty($cacheKey, 'The generated cache key should not be empty');
    }

    public function testShouldGenerateDifferentKeysForSameQueryAndParamsAndDifferentConnections()
    {
        $query  = 'SELECT * FROM foo WHERE bar = ?';
        $params = [666];
        $types  = [ParameterType::INTEGER];

        $connectionParams = array(
            'dbname'   => 'database_name',
            'user'     => 'database_user',
            'password' => 'database_password',
            'host'     => 'database_host',
            'driver'   => 'database_driver'
        );

        $this->queryCacheProfile = $this->queryCacheProfile->setCacheKey(null);

        list($firstCacheKey) = $this->queryCacheProfile->generateCacheKeys(
            $query,
            $params,
            $types,
            $connectionParams
        );

        $connectionParams['host'] = 'a_different_host';

        list($secondCacheKey) = $this->queryCacheProfile->generateCacheKeys(
            $query,
            $params,
            $types,
            $connectionParams
        );

        self::assertNotEquals($firstCacheKey, $secondCacheKey, 'Cache keys should be different');
    }

    public function testShouldGenerateSameKeysIfNoneOfTheParamsChanges()
    {
        $query  = 'SELECT * FROM foo WHERE bar = ?';
        $params = [666];
        $types  = [ParameterType::INTEGER];

        $connectionParams = array(
            'dbname'   => 'database_name',
            'user'     => 'database_user',
            'password' => 'database_password',
            'host'     => 'database_host',
            'driver'   => 'database_driver'
        );

        $this->queryCacheProfile = $this->queryCacheProfile->setCacheKey(null);

        list($firstCacheKey) = $this->queryCacheProfile->generateCacheKeys(
            $query,
            $params,
            $types,
            $connectionParams
        );

        list($secondCacheKey) = $this->queryCacheProfile->generateCacheKeys(
            $query,
            $params,
            $types,
            $connectionParams
        );

        self::assertEquals($firstCacheKey, $secondCacheKey, 'Cache keys should be the same');
    }
}


text:
$(document).on('ready page:load', function() {
  $('input.datepicker').datepicker({
    format: "dd-mm-yyyy"
  });

  $('form .submit').on('click', function(e) {
    e.preventDefault();
    $(this).parent().parent().parent().submit();
  });
})


text:
.. Copyright 2015 Peter K. G. Williams <peter@newton.cx> and collaborators.
   This file licensed under the Creative Commons Attribution-ShareAlike 3.0
   Unported License (CC-BY-SA).

Tracing contours (``pwkit.contours``)
==============================================================================

.. automodule:: pwkit.contours
   :members:


text:
<?php
class VoteresultModel extends CommonModel{
    protected $pk   = 'result_id';
    protected $tableName =  'vote_result';

}


text:
package fileSending;

import globalfunctions.FileTransfer;

import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.swing.JOptionPane;

import GuiElements.FileTransferPanelS;

public class Client implements Runnable {

	private int portNumber;
	private String ipAddress;
	private Path filePath;
	private FileTransferPanelS ftps;
	private long bytesSent;

	public Client(String ip, int pNumber, Path filePath, FileTransferPanelS ftps) {
		this.ipAddress = ip;
		this.portNumber = pNumber;
		this.filePath = filePath;
		this.ftps=ftps;
	}

	public Client(String ip, int pNumber, Path filePath) {
		this.ipAddress = ip;
		this.portNumber = pNumber;
		this.filePath = filePath;
	}

	public void run() {
		try {
			Socket socket = new Socket(ipAddress,portNumber);
			OutputStream os=  socket.getOutputStream();

			send(socket,filePath, os);
			socket.close();

		} catch(Exception e) {
			//Error
			displayError("Error in Sending File!");
		}
	}

	public void send(Socket socket,Path filePath, OutputStream os) throws IOException {
		if( FileTransfer.isFile(filePath.toString()) ) {
			sendFile(socket,filePath,os);
		} else if( FileTransfer.isDirectory(filePath.toString()) ){
			sendFile(socket,filePath,os);
			sendFolder(socket,filePath.toString(),os);
		}
		socket.close();
		os.close();
	}

	public long geti()
	{
		return bytesSent;
	}

	public void sendFile(Socket socket,Path filePath, OutputStream os) throws IOException {

		//String fileName = filePath.getFileName().toString().trim();
		File f = new File(filePath.toString());
		long fileSize= f.length();
		int chunkSize = 256*1024;

		boolean flag=false;
		char pathType= ' ';

		flag = FileTransfer.isPathValid(filePath.toString());
		if(flag==false) {
			displayError("Path Not Valid");
		}
		flag = FileTransfer.isFile(filePath.toString());
		if(flag==true) {
			pathType = 'f';
		}
		if(flag==false) {
			flag = FileTransfer.isDirectory(filePath.toString());
			if(flag==true) {
				pathType = 'd';
			}
		}

		/* File Header is of the format
		 * [f/d]*[file/directory Size]-[file/directory path][newline character]
		 * f represents a file
		 * d represents a directory
		 * */

		// header contains the content of file header which will be sent to receiver
		String header = pathType + "*" + Long.toString(fileSize) + "-" + filePath +  "\n" ;
		byte [] fileHeader  = new byte[header.length()*2];
		// Creation of file header
		fileHeader = header.getBytes("UTF-8");

		if(pathType=='d') {
			os.write(fileHeader);
			os.flush();

			return;
		}
		File transferfile = new File(filePath.toString());
		byte [] bytearray = new byte [chunkSize];
		FileInputStream fin = new FileInputStream(transferfile);
		BufferedInputStream bufferedinput = new BufferedInputStream(fin);

		// sending file header information to sender
		os.write(fileHeader);

		// sending file content to sender
		int read = 0;
		long leftBytes = fileSize; // number of bytes remaining to be written to socket stream

		if(ftps!=null)
			ftps.getprogbar().startProgress(fileSize, this);

		while (leftBytes>0) {
			leftBytes = leftBytes - read;
			if(chunkSize>leftBytes) {
				read = bufferedinput.read(bytearray,0,(int)leftBytes);
			}
			else {
				read=bufferedinput.read(bytearray,0,chunkSize);
			}
			os.write(bytearray,0,read);
			bytesSent=bytesSent+read;
		}

		if(ftps!=null)
			ftps.showMsg("File Transfer Complete");
		os.flush();
		bufferedinput.close();
		//don't close the outputstream here
	}

	public  void sendFolder(final Socket socket, String FilePath, OutputStream os) throws IOException  {
		walk(FilePath,socket, os);
		socket.close();
	}

	public static void displayError(String errorMessage)  {
		JOptionPane.showMessageDialog(null,errorMessage,"The Three Musketeers say",JOptionPane.ERROR_MESSAGE);
	}

	public void walk( String path, Socket socket, OutputStream os ) throws IOException {
		File root = new File( path );
		File[] list = root.listFiles();

		if (list == null) return;

		for ( File f : list ) {
			if ( f.isDirectory() ) {
				Path p = Paths.get(f.getAbsoluteFile().toString());

				sendFile(socket, p,os);
				walk( f.getAbsolutePath(), socket, os );
			} else {
				Path p = Paths.get(f.getAbsoluteFile().toString());

				sendFile(socket, p,os);
			}
		}
	}

	/*public static void main(String args[])  {
	  Socket s = null;
	  Path file = null;
	  int pNumber = 6666;
	  String ip = "127.0.0.1";
	  Client obj = new Client(ip,pNumber);
	  (new Thread(obj)).start();
	  ip = "127.0.0.2";
	  obj = new Client(ip,pNumber);
	  (new Thread(obj)).start();
	  }*/
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="green_primary">#4caf50</color>
    <color name="green_primary_dark">#388e3c</color>
    <color name="my_accent">#f44336</color>
</resources>


text: This is the blog of Dan McCormick, a software developer who lives on a farm in Pennsylvania and spends his time coding, writing, and planting.


text:
__requires__ = 'Nikola==7.8.3'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('Nikola', 'console_scripts', 'nikola')()
    )


text:
import 'react-native';
import * as React from 'react';
import renderer from 'react-test-renderer';

import Root from '../root.react';

// Note: test renderer must be required after react-native.

it('renders correctly', () => {
  renderer.create(<Root />);
});


text:
//
//  OCHamcrest - HCBoxNumber.h
//  Copyright 2009 www.hamcrest.org. See LICENSE.txt
//
//  Created by: Jon Reid
//

#ifdef __cplusplus

namespace hamcrest {

/**
    Boxes scalar value in NSNumber, specialized per type.
*/
template <typename T>
inline
NSNumber* boxNumber(T value)
    { return nil; }

template <>
inline
NSNumber* boxNumber(BOOL value)
    { return [NSNumber numberWithBool:value]; }

template <>
inline
NSNumber* boxNumber(char value)
    { return [NSNumber numberWithChar:value]; }

template <>
inline
NSNumber* boxNumber(double value)
    { return [NSNumber numberWithDouble:value]; }

template <>
inline
NSNumber* boxNumber(float value)
    { return [NSNumber numberWithFloat:value]; }

template <>
inline
NSNumber* boxNumber(int value)
    { return [NSNumber numberWithInt:value]; }

template <>
inline
NSNumber* boxNumber(long value)
    { return [NSNumber numberWithLong:value]; }

template <>
inline
NSNumber* boxNumber(long long value)
    { return [NSNumber numberWithLongLong:value]; }

template <>
inline
NSNumber* boxNumber(short value)
    { return [NSNumber numberWithShort:value]; }

template <>
inline
NSNumber* boxNumber(unsigned char value)
    { return [NSNumber numberWithUnsignedChar:value]; }

template <>
inline
NSNumber* boxNumber(unsigned int value)
    { return [NSNumber numberWithUnsignedInt:value]; }

template <>
inline
NSNumber* boxNumber(unsigned long value)
    { return [NSNumber numberWithUnsignedLong:value]; }

template <>
inline
NSNumber* boxNumber(unsigned long long value)
    { return [NSNumber numberWithUnsignedLongLong:value]; }

template <>
inline
NSNumber* boxNumber(unsigned short value)
    { return [NSNumber numberWithUnsignedShort:value]; }

}   // namespace hamcrest

#endif  // __cplusplus


text: R CMD REMOVE --library=$PREFIX/lib/R/library/ TxDb.Scerevisiae.UCSC.sacCer3.sgdGene


text:
'use strict';

var forEach = require('tui-code-snippet/collection/forEach');
var defineClass = require('tui-code-snippet/defineClass/defineClass');
var getTarget = require('tui-code-snippet/domEvent/getTarget');
var on = require('tui-code-snippet/domEvent/on');
var preventDefault = require('tui-code-snippet/domEvent/preventDefault');
var addClass = require('tui-code-snippet/domUtil/addClass');
var extend = require('tui-code-snippet/object/extend');
var isString = require('tui-code-snippet/type/isString');
var isHTMLNode = require('tui-code-snippet/type/isHTMLNode');

var util = require('./util.js');

var defaultTemplate = {
  page: '{{page}}',
  currentPage: '{{page}}',
  moveButton:
    '' +
    '{{type}}' +
    '',
  disabledMoveButton:
    '' +
    '{{type}}' +
    '',
  moreButton:
    '' +
    '...' +
    ''
};
var moveButtons = ['first', 'prev', 'next', 'last'];
var moreButtons = ['prev', 'next'];

var INVALID_CONTAINER_ELEMENT = 'The container element is invalid.';

/**
 * Pagination view class
 * @class View
 * @param {string|HTMLElement|jQueryObject} container - Container element or id selector
 * @param {object} options - Option object
 *     @param {number} [options.totalItems=10] Total item count
 *     @param {number} [options.itemsPerPage=10] Item count per page
 *     @param {number} [options.visiblePages=10] Display page link count
 *     @param {number} [options.page=1] Display page after pagination draw.
 *     @param {boolean}[options.centerAlign=false] Whether current page keep center or not
 *     @param {string} [options.firstItemClassName='first-child'] The class name of the first item
 *     @param {string} [options.lastItemClassName='last-child'] The class name of the last item
 *     @param {object} [options.template] A markup string set to make element
 *         @param {string|function} [options.template.page] HTML template
 *         @param {string|function} [options.template.currentPage] HTML template
 *         @param {string|function} [options.template.moveButton] HTML template
 *         @param {string|function} [options.template.disabledMoveButton] HTML template
 *         @param {string|function} [options.template.moreButton] HTML template
 * @param {function} handler - Event handler
 * @ignore
 */
var View = defineClass(
  /** @lends View.prototype */ {
    init: function(container, options, handler) {
      /**
       * Root element
       * @type {HTMLElement}
       * @private
       */
      this._containerElement = null;

      /**
       * First item's class name
       * @type {string}
       * @private
       */
      this._firstItemClassName = options.firstItemClassName;

      /**
       * Last item's class name
       * @type {string}
       * @private
       */
      this._lastItemClassName = options.lastItemClassName;

      /**
       * Default template
       * @type {object.<string, string|function>}
       * @private
       */
      this._template = extend({}, defaultTemplate, options.template);

      /**
       * Map of buttons
       * @type {object.<string, HTMLElement>}
       * @private
       */
      this._buttons = {};

      /**
       * Enabled page elements list
       * @type {array}
       * @private
       */

      this._enabledPageElements = [];

      this._setRootElement(container);
      this._setMoveButtons();
      this._setDisabledMoveButtons();
      this._setMoreButtons();
      this._attachClickEvent(handler);
    },
    /* eslint-enable complexity */

    /**
     * Set root element
     * @param {string|HTMLElement|jQueryObject} container - Container element or id selector
     * @private
     */
    _setRootElement: function(container) {
      if (isString(container)) {
        container = document.getElementById(container) || document.querySelector(container);
      } else if (container.jquery) {
        container = container[0];
      }

      if (!isHTMLNode(container)) {
        throw new Error(INVALID_CONTAINER_ELEMENT);
      }

      this._containerElement = container;
    },

    /**
     * Assign move buttons to option
     * @private
     */
    _setMoveButtons: function() {
      forEach(
        moveButtons,
        function(type) {
          this._buttons[type] = util.createElementByTemplate(this._template.moveButton, {
            type: type
          });
        },
        this
      );
    },

    /**
     * Assign disabled move buttons to option
     * @private
     */
    _setDisabledMoveButtons: function() {
      forEach(
        moveButtons,
        function(type) {
          var key = 'disabled' + util.capitalizeFirstLetter(type);
          this._buttons[key] = util.createElementByTemplate(this._template.disabledMoveButton, {
            type: type
          });
        },
        this
      );
    },

    /**
     * Assign more buttons to option
     * @private
     */
    _setMoreButtons: function() {
      forEach(
        moreButtons,
        function(type) {
          var key = type + 'More';
          this._buttons[key] = util.createElementByTemplate(this._template.moreButton, {
            type: type
          });
        },
        this
      );
    },
    /* eslint-enable camelcase */

    /**
     * Get container element
     * @returns {HTMLElement} Container element
     * @private
     */
    _getContainerElement: function() {
      return this._containerElement;
    },

    /**
     * Append first button on container element
     * @param {object} viewData - View data to render pagination
     * @private
     */
    _appendFirstButton: function(viewData) {
      var button;

      if (viewData.page > 1) {
        button = this._buttons.first;
      } else {
        button = this._buttons.disabledFirst;
      }

      this._getContainerElement().appendChild(button);
    },

    /**
     * Append previous button on container element
     * @param {object} viewData - View data to render pagination
     * @private
     */
    _appendPrevButton: function(viewData) {
      var button;

      if (viewData.currentPageIndex > 1) {
        button = this._buttons.prev;
      } else {
        button = this._buttons.disabledPrev;
      }

      this._getContainerElement().appendChild(button);
    },

    /**
     * Append next button on container element
     * @param {object} viewData - View data to render pagination
     * @private
     */
    _appendNextButton: function(viewData) {
      var button;

      if (viewData.currentPageIndex < viewData.lastPageListIndex) {
        button = this._buttons.next;
      } else {
        button = this._buttons.disabledNext;
      }

      this._getContainerElement().appendChild(button);
    },

    /**
     * Append last button on container element
     * @param {object} viewData - View data to render pagination
     * @private
     */
    _appendLastButton: function(viewData) {
      var button;

      if (viewData.page < viewData.lastPage) {
        button = this._buttons.last;
      } else {
        button = this._buttons.disabledLast;
      }

      this._getContainerElement().appendChild(button);
    },

    /**
     * Append previous more button on container element
     * @param {object} viewData - View data to render pagination
     * @private
     */
    _appendPrevMoreButton: function(viewData) {
      var button;

      if (viewData.prevMore) {
        button = this._buttons.prevMore;
        addClass(button, this._firstItemClassName);
        this._getContainerElement().appendChild(button);
      }
    },

    /**
     * Append next more button on container element
     * @param {object} viewData - View data to render pagination
     * @private
     */
    _appendNextMoreButton: function(viewData) {
      var button;

      if (viewData.nextMore) {
        button = this._buttons.nextMore;
        addClass(button, this._lastItemClassName);
        this._getContainerElement().appendChild(button);
      }
    },

    /**
     * Append page number elements on container element
     * @param {object} viewData - View data to render pagination
     * @private
     */
    // eslint-disable-next-line complexity
    _appendPages: function(viewData) {
      var firstPage = viewData.leftPageNumber;
      var lastPage = viewData.rightPageNumber;
      var pageItem, i;

      for (i = firstPage; i <= lastPage; i += 1) {
        if (i === viewData.page) {
          pageItem = util.createElementByTemplate(this._template.currentPage, { page: i });
        } else {
          pageItem = util.createElementByTemplate(this._template.page, { page: i });
          this._enabledPageElements.push(pageItem);
        }

        if (i === firstPage && !viewData.prevMore) {
          addClass(pageItem, this._firstItemClassName);
        }
        if (i === lastPage && !viewData.nextMore) {
          addClass(pageItem, this._lastItemClassName);
        }
        this._getContainerElement().appendChild(pageItem);
      }
    },

    /**
     * Attach click event
     * @param {function} callback - Callback function
     * @private
     */
    _attachClickEvent: function(callback) {
      var rootElement = this._getContainerElement();

      on(
        rootElement,
        'click',
        function(ev) {
          var target = getTarget(ev);
          var page, buttonType;

          preventDefault(ev);

          buttonType = this._getButtonType(target);

          if (!buttonType) {
            page = this._getPageNumber(target);
          }

          callback(buttonType, page);
        },
        this
      );
    },

    /**
     * Get button type to move button elements
     * @param {HTMLElement} targetElement - Each move button element
     * @returns {?string} Button type
     * @private
     */
    _getButtonType: function(targetElement) {
      var buttonType;
      var buttons = this._buttons;

      forEach(
        buttons,
        function(button, type) {
          if (util.isContained(targetElement, button)) {
            buttonType = type;

            return false;
          }

          return true;
        },
        this
      );

      return buttonType;
    },
    /* eslint-enable no-lonely-if */

    /**
     * Get number to page elements
     * @param {HTMLElement} targetElement - Each page element
     * @returns {?number} Page number
     * @private
     */
    _getPageNumber: function(targetElement) {
      var targetPage = this._findPageElement(targetElement);
      var page;

      if (targetPage) {
        page = parseInt(targetPage.innerText, 10);
      }

      return page;
    },

    /**
     * Find target element from page elements
     * @param {HTMLElement} targetElement - Each page element
     * @returns {HTMLElement} Found element
     * @ignore
     */
    _findPageElement: function(targetElement) {
      var i = 0;
      var length = this._enabledPageElements.length;
      var pickedItem;

      for (; i < length; i += 1) {
        pickedItem = this._enabledPageElements[i];

        if (util.isContained(targetElement, pickedItem)) {
          return pickedItem;
        }
      }

      return null;
    },

    /**
     * Reset container element
     * @private
     */
    _empty: function() {
      this._enabledPageElements = [];

      forEach(
        this._buttons,
        function(buttonElement, type) {
          this._buttons[type] = buttonElement.cloneNode(true);
        },
        this
      );

      this._getContainerElement().innerHTML = '';
    },

    /**
     * Update view
     * @param {object} viewData - View data to render pagination
     * @ignore
     */
    update: function(viewData) {
      this._empty();
      this._appendFirstButton(viewData);
      this._appendPrevButton(viewData);
      this._appendPrevMoreButton(viewData);
      this._appendPages(viewData);
      this._appendNextMoreButton(viewData);
      this._appendNextButton(viewData);
      this._appendLastButton(viewData);
    }
  }
);

module.exports = View;


text:
/**
  * Automatically generated file. Please do not edit.
  * @author Highcharts Config Generator by Karasiq
  * @see [[http://api.highcharts.com/highmaps]]
  */
package com.highmaps.config

import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._

/**
  * @note JavaScript name: legend-navigation
  */
@js.annotation.ScalaJSDefined
class LegendNavigation extends com.highcharts.HighchartsGenericObject {

  /**
    *
The color for the active up or down arrow in the legend page
    * navigation.

    * @example Legend page navigation demonstrated
Legend page navigation demonstrated
    * @since 2.2.4
    */
  val activeColor: js.UndefOr[String | js.Object] = js.undefined

  /**
    *
The color of the inactive up or down arrow in the legend page
    * navigation. .

    * @example Legend page navigation demonstrated
Legend page navigation demonstrated
    * @since 2.2.4
    */
  val inactiveColor: js.UndefOr[String | js.Object] = js.undefined

  /**
    *
How to animate the pages when navigating up or down. A value of
    * true applies the default navigation given in the
    * chart.animation option. Additional options can be given as an
    * object containing values for easing and duration.

    * @example Legend page navigation demonstrated
Legend page navigation demonstrated
    * @since 2.2.4
    */
  val animation: js.UndefOr[Boolean] = js.undefined

  /**
    *
The pixel size of the up and down arrows in the legend paging
    * navigation.

    * @example Legend page navigation demonstrated
Legend page navigation demonstrated
    * @since 2.2.4
    */
  val arrowSize: js.UndefOr[Double] = js.undefined

  /**
    *
Whether to enable the legend navigation. In most cases, disabling
    * the navigation results in an unwanted overflow.

    *
See also the adapt chart to legend
    * plugin for a solution to extend the chart height to make room for
    * the legend, optionally in exported charts only.

    * @since 4.2.4
    */
  val enabled: js.UndefOr[Boolean] = js.undefined

  /**
    *
Text styles for the legend page navigation.

    * @example Legend page navigation demonstrated
Legend page navigation demonstrated
    * @since 2.2.4
    */
  val style: js.UndefOr[js.Object] = js.undefined
}

object LegendNavigation {
  /**
    * @param activeColor
The color for the active up or down arrow in the legend page. navigation.

    * @param inactiveColor
The color of the inactive up or down arrow in the legend page. navigation. .

    * @param animation
How to animate the pages when navigating up or down. A value of. true applies the default navigation given in the. chart.animation option. Additional options can be given as an. object containing values for easing and duration.

    * @param arrowSize
The pixel size of the up and down arrows in the legend paging. navigation.

    * @param enabled
Whether to enable the legend navigation. In most cases, disabling. the navigation results in an unwanted overflow.
.
See also the adapt chart to legend. plugin for a solution to extend the chart height to make room for. the legend, optionally in exported charts only.

    * @param style
Text styles for the legend page navigation.

    */
  def apply(activeColor: js.UndefOr[String | js.Object] = js.undefined, inactiveColor: js.UndefOr[String | js.Object] = js.undefined, animation: js.UndefOr[Boolean] = js.undefined, arrowSize: js.UndefOr[Double] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, style: js.UndefOr[js.Object] = js.undefined): LegendNavigation = {
    val activeColorOuter: js.UndefOr[String | js.Object] = activeColor
    val inactiveColorOuter: js.UndefOr[String | js.Object] = inactiveColor
    val animationOuter: js.UndefOr[Boolean] = animation
    val arrowSizeOuter: js.UndefOr[Double] = arrowSize
    val enabledOuter: js.UndefOr[Boolean] = enabled
    val styleOuter: js.UndefOr[js.Object] = style
    com.highcharts.HighchartsGenericObject.toCleanObject(new LegendNavigation {
      override val activeColor: js.UndefOr[String | js.Object] = activeColorOuter
      override val inactiveColor: js.UndefOr[String | js.Object] = inactiveColorOuter
      override val animation: js.UndefOr[Boolean] = animationOuter
      override val arrowSize: js.UndefOr[Double] = arrowSizeOuter
      override val enabled: js.UndefOr[Boolean] = enabledOuter
      override val style: js.UndefOr[js.Object] = styleOuter
    })
  }
}


text:
The tracking issue for this feature is [#29625]

See Also: [`fn_traits`](library-features/fn-traits.html)

[#29625]: https://github.com/rust-lang/rust/issues/29625

----

The `unboxed_closures` feature allows you to write functions using the `"rust-call"` ABI,
required for implementing the [`Fn*`] family of traits. `"rust-call"` functions must have
exactly one (non self) argument, a tuple representing the argument list.

[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html

```rust
#![feature(unboxed_closures)]

extern "rust-call" fn add_args(args: (u32, u32)) -> u32 {
    args.0 + args.1
}

fn main() {}
```


text:
@interface STRemoteImage : STRemoteObject {
	@protected
//	NSURL* baseURL;
	UIImage* image;

	BOOL use2xImage;

//	NSString* cacheFileName;
}

-(id) initWithFilename:(NSString*)file baseURL:(NSURL*)_url;
-(id) initWithURL:(NSURL*)_url;

+(BOOL) deviceUses2x;

@property (nonatomic,readonly) 	UIImage* image;
//@property (nonatomic,readonly)	NSString* filename;
@property (nonatomic,assign) 	BOOL use2xImage;

// setting this disables @2x Images
//@property (nonatomic,retain) 	NSString* cacheFileName;

@end


text:
import java.util.*;

class Foo {
    void test(boolean b) {
        List<String> list = new ArrayList<>();
        if (b) {
            list = Collections.emptyList();
        }
        System.out.println(list.trimTo);
    }
}


text:
Q_DECLARE_METATYPE(QList<ApiTraceFrame*>);
Q_DECLARE_METATYPE(QVector<ApiTraceCall*>);
Q_DECLARE_METATYPE(Qt::CaseSensitivity);
Q_DECLARE_METATYPE(ApiTrace::SearchResult);
Q_DECLARE_METATYPE(ApiTrace::SearchRequest);
Q_DECLARE_METATYPE(ImageHash);

static void usage(void)
{
    qInfo("usage: qapitrace [options] [TRACE] [CALLNO]\n"
             "Valid options include:\n"
             "    -h, --help            Print this help message\n"
             "    -v, --version         Print version\n"
             "    --remote-target HOST  Replay trace on remote target HOST\n");
}
static void version(void)
{
    qInfo("qapitrace %s", APITRACE_VERSION);
}

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    app.setWindowIcon(QIcon(":/resources/qapitrace.png"));

    QCoreApplication::setOrganizationName("ApiTrace");
    QCoreApplication::setApplicationName("QApiTrace");

    qRegisterMetaType<QList<ApiTraceFrame*> >();
    qRegisterMetaType<QVector<ApiTraceCall*> >();
    qRegisterMetaType<ApiTraceState>();
    qRegisterMetaType<Qt::CaseSensitivity>();
    qRegisterMetaType<ApiTrace::SearchResult>();
    qRegisterMetaType<ApiTrace::SearchRequest>();
    qRegisterMetaType<ImageHash>();

#ifndef Q_OS_WIN
    os::String currentProcess = os::getProcessName();
    currentProcess.trimFilename();
    QString path = qgetenv("PATH");
    path = QLatin1String(currentProcess.str()) + QLatin1String(":") + path;
    qputenv("PATH", path.toLatin1());
#endif

    QStringList args = app.arguments();
    QString remoteTarget;

    int i = 1;
    while (i < args.count()) {
        QString arg = args[i];
        if (arg[0] != QLatin1Char('-')) {
            break;
        }
        ++i;
        if (arg == QLatin1String("--")) {
            break;
        } else if (arg == QLatin1String("--remote-target")) {
            if (i == args.count()) {
                qWarning("Option --remote-target requires an argument.\n");
                exit(1);
            }
            remoteTarget = args[i];
            ++i;
        } else if (arg == QLatin1String("-h") ||
                   arg == QLatin1String("--help")) {
            usage();
            exit(0);
        } else if (arg == QLatin1String("-v") ||
                   arg == QLatin1String("--version")) {
            version();
            exit(0);
        } else {
            usage();
            exit(1);
        }
    }

    MainWindow window;
    window.show();

    if (i < args.count()) {
        QString fileName = args[i++];

        int callNum = -1;
        if (i < args.count()) {
            callNum = args[i++].toInt();
        }
        window.loadTrace(fileName, callNum);
    }

    if (remoteTarget.length()) {
        window.setRemoteTarget(remoteTarget);
    }

    app.exec();
}


text:
package org.apache.hadoop.fs.azure;

import com.microsoft.azure.storage.blob.BlockEntry;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.contract.ContractTestUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;

/**
 * Test class that runs WASB block compaction process for block blobs.
 */

public class TestNativeAzureFileSystemBlockCompaction extends AbstractWasbTestBase {

  private static final String TEST_FILE = "/user/active/test.dat";
  private static final Path TEST_PATH = new Path(TEST_FILE);

  private static final String TEST_FILE_NORMAL = "/user/normal/test.dat";
  private static final Path TEST_PATH_NORMAL = new Path(TEST_FILE_NORMAL);

  private AzureBlobStorageTestAccount testAccount = null;

  @Before
  public void setUp() throws Exception {
    super.setUp();
    testAccount = createTestAccount();
    fs = testAccount.getFileSystem();
    Configuration conf = fs.getConf();
    conf.setBoolean(NativeAzureFileSystem.APPEND_SUPPORT_ENABLE_PROPERTY_NAME, true);
    conf.set(AzureNativeFileSystemStore.KEY_BLOCK_BLOB_WITH_COMPACTION_DIRECTORIES, "/user/active");
    URI uri = fs.getUri();
    fs.initialize(uri, conf);
  }

  /*
   * Helper method that creates test data of size provided by the
   * "size" parameter.
   */
  private static byte[] getTestData(int size) {
    byte[] testData = new byte[size];
    System.arraycopy(RandomStringUtils.randomAlphabetic(size).getBytes(), 0, testData, 0, size);
    return testData;
  }

  @Override
  protected AzureBlobStorageTestAccount createTestAccount() throws Exception {
    return AzureBlobStorageTestAccount.create();
  }

  private BlockBlobAppendStream getBlockBlobAppendStream(FSDataOutputStream appendStream) {
    SyncableDataOutputStream dataOutputStream = null;

    if (appendStream.getWrappedStream() instanceof NativeAzureFileSystem.NativeAzureFsOutputStream) {
      NativeAzureFileSystem.NativeAzureFsOutputStream fsOutputStream =
              (NativeAzureFileSystem.NativeAzureFsOutputStream) appendStream.getWrappedStream();

      dataOutputStream = (SyncableDataOutputStream) fsOutputStream.getOutStream();
    }

    if (appendStream.getWrappedStream() instanceof SyncableDataOutputStream) {
      dataOutputStream = (SyncableDataOutputStream) appendStream.getWrappedStream();
    }

    Assert.assertNotNull("Did not recognize " + dataOutputStream,
        dataOutputStream);

    return (BlockBlobAppendStream) dataOutputStream.getOutStream();
  }

  private void verifyBlockList(BlockBlobAppendStream blockBlobStream,
                               int[] testData) throws Throwable {
    List<BlockEntry> blockList = blockBlobStream.getBlockList();
    Assert.assertEquals("Block list length", testData.length, blockList.size());

    int i = 0;
    for (BlockEntry block: blockList) {
      Assert.assertTrue(block.getSize() == testData[i++]);
    }
  }

  private void appendBlockList(FSDataOutputStream fsStream,
                              ByteArrayOutputStream memStream,
                              int[] testData) throws Throwable {

    for (int d: testData) {
      byte[] data = getTestData(d);
      memStream.write(data);
      fsStream.write(data);
    }
    fsStream.hflush();
  }

  @Test
  public void testCompactionDisabled() throws Throwable {

    try (FSDataOutputStream appendStream = fs.create(TEST_PATH_NORMAL)) {

      // testing new file

      SyncableDataOutputStream dataOutputStream = null;

      OutputStream wrappedStream = appendStream.getWrappedStream();
      if (wrappedStream instanceof NativeAzureFileSystem.NativeAzureFsOutputStream) {
        NativeAzureFileSystem.NativeAzureFsOutputStream fsOutputStream =
                (NativeAzureFileSystem.NativeAzureFsOutputStream) wrappedStream;

        dataOutputStream = (SyncableDataOutputStream) fsOutputStream.getOutStream();
      } else if (wrappedStream instanceof SyncableDataOutputStream) {
        dataOutputStream = (SyncableDataOutputStream) wrappedStream;
      } else {
        Assert.fail("Unable to determine type of " + wrappedStream
            + " class of " + wrappedStream.getClass());
      }

      Assert.assertFalse("Data output stream is a BlockBlobAppendStream: "
          + dataOutputStream,
          dataOutputStream.getOutStream() instanceof BlockBlobAppendStream);

    }
  }

  @Test
  public void testCompaction() throws Throwable {

    final int n2 = 2;
    final int n4 = 4;
    final int n10 = 10;
    final int n12 = 12;
    final int n14 = 14;
    final int n16 = 16;

    final int maxBlockSize = 16;
    final int compactionBlockCount = 4;

    ByteArrayOutputStream memStream = new ByteArrayOutputStream();

    try (FSDataOutputStream appendStream = fs.create(TEST_PATH)) {

      // test new file

      BlockBlobAppendStream blockBlobStream = getBlockBlobAppendStream(appendStream);
      blockBlobStream.setMaxBlockSize(maxBlockSize);
      blockBlobStream.setCompactionBlockCount(compactionBlockCount);

      appendBlockList(appendStream, memStream, new int[]{n2});
      verifyBlockList(blockBlobStream, new int[]{n2});

      appendStream.hflush();
      verifyBlockList(blockBlobStream, new int[]{n2});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream, new int[]{n2, n4});

      appendStream.hsync();
      verifyBlockList(blockBlobStream, new int[]{n2, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream, new int[]{n2, n4, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream, new int[]{n2, n4, n4, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream, new int[]{n14, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream, new int[]{n14, n4, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream, new int[]{n14, n4, n4, n4});

      appendBlockList(appendStream, memStream, new int[]{n2, n4, n4});
      verifyBlockList(blockBlobStream, new int[]{n14, n12, n10});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream, new int[]{n14, n12, n10, n4});

      appendBlockList(appendStream, memStream,
              new int[]{n4, n4, n4, n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16});

      appendBlockList(appendStream, memStream,
              new int[]{n4, n4, n4, n4, n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16, n16, n4});

      appendBlockList(appendStream, memStream,
              new int[]{n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16, n16, n4, n4});

      appendBlockList(appendStream, memStream,
              new int[]{n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16, n16, n4, n4, n4});

      appendBlockList(appendStream, memStream,
              new int[]{n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16, n16, n4, n4, n4, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});

      appendStream.close();

      ContractTestUtils.verifyFileContents(fs, TEST_PATH, memStream.toByteArray());
    }

    try (FSDataOutputStream appendStream = fs.append(TEST_PATH)) {

      // test existing file

      BlockBlobAppendStream blockBlobStream = getBlockBlobAppendStream(appendStream);
      blockBlobStream.setMaxBlockSize(maxBlockSize);
      blockBlobStream.setCompactionBlockCount(compactionBlockCount);

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16, n16, n16, n4, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16, n16, n16, n4, n4, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16, n16, n16, n4, n4, n4, n4});

      appendBlockList(appendStream, memStream, new int[]{n4});
      verifyBlockList(blockBlobStream,
              new int[]{n14, n12, n14, n16, n16, n16, n16, n4});

      appendStream.close();

      ContractTestUtils.verifyFileContents(fs, TEST_PATH, memStream.toByteArray());
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Graph name="Export PDP_ACH_TRANS_CD_T" revision="1.0">
  <Global>
    <Property fileURL="workspace.prm" id="WorkspaceParameters" />
    <Connection dbConfig="${DATABASE}" id="TargetDB" type="JDBC" />
    <Metadata id="OutputFileFormat" fileURL="${FORMAT_DIR}/pdp_ach_trans_cd_t.fmt.xml" />
  </Global>
   <Phase number="0">
     <Node id="DATABASE_RUN"
           type="DB_EXECUTE"
           dbConnection="TargetDB"
           sqlQuery="TRUNCATE TABLE PDP_ACH_TRANS_CD_T" />
   </Phase>
   <Phase number="1">
    <Node id="INPUT" type="DATA_READER" skipLeadingBlanks="false" fileURL="${DATA_DIR}/pdp_ach_trans_cd_t.txt" skipFirstLine="true" dataPolicy="strict" charset="UTF-8" quotedStrings="false" trim="false" treatMultipleDelimitersAsOne="false" />
    <Edge fromNode="INPUT:0" toNode="FIX_DELIM:0" id="INPUT_TO_FIX_DELIM" metadata="OutputFileFormat" />
    <Node id="FIX_DELIM" type="REFORMAT">
      <attr name="transform"><![CDATA[
//#TL
    function transform() {
        $0.trans_cd := replace(nvl($trans_cd, ""), "~!~", "|" );
        $0.obj_id := replace(nvl($obj_id, ""), "~!~", "|" );
        $0.ver_nbr := $ver_nbr;
        $0.trans_desc := replace(nvl($trans_desc, ""), "~!~", "|" );
   }
      ]]></attr>
    </Node>
    <Edge fromNode="FIX_DELIM:0" toNode="DB_OUTPUT:0" id="TO_OUTPUT"  metadata="OutputFileFormat" />
    <Node id="DB_OUTPUT" type="KUL_DB_OUTPUT_TABLE" metadata="OutputFileFormat" dbConnection="TargetDB" dbTable="pdp_ach_trans_cd_t" batchMode="true" errorAction="ROLLBACK" />
  </Phase>
</Graph>


text:
#import "NSObject.h"

#import "IDEClientTrackingToken.h"

@class DVTSystemActivityToken, IDEConcreteClientTracker, NSString;

@interface IDEConcreteClientTrackingToken : NSObject <IDEClientTrackingToken>
{
    NSString *_clientName;
    id _cancellationBlock;
    BOOL _hasUnregistered;
    IDEConcreteClientTracker *_clientTracker;
    DVTSystemActivityToken *_systemActivityToken;
}

- (void).cxx_destruct;
- (void)cancelClient;
@property(readonly) NSString *clientName; // @synthesize clientName=_clientName;
@property(readonly, copy) NSString *description;
- (id)initWithClientName:(id)arg1 clientTracker:(id)arg2 cancellationBlock:(id)arg3;
@property(retain) DVTSystemActivityToken *systemActivityToken; // @synthesize systemActivityToken=_systemActivityToken;
- (void)unregisterClient;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
<?php

namespace o;

require_once('FormBuilder.php');

// Form Object
class Form extends OClass {

    use FormBuilder;

    protected $errorClass = 'Form';
    protected $cleanClass = 'Form';

    private $method = '';
    private $formId = '';

    private $data = [];
    private $formConfig = [];

    // Make sure helpLink points to module, not class
    function error($msg, $method = '') {
        Tht::module('Form')->error($msg, $method);
    }

    function __construct($formId, $formConfig) {

        $this->formId = $formId;

        $this->initFormConfig($formConfig);
    }

    private function initFormConfig($formConfig) {

        foreach ($formConfig as $fieldName => $fieldConfig) {
            $formConfig[$fieldName] = $this->initFieldConfig($fieldName, $fieldConfig);
        }

        $this->formConfig = $formConfig;
    }

    // TODO: Organize this a bit more.
    private function initFieldConfig($fieldName, $fieldConfig) {

        $validator = new u_InputValidator();

        // Require HTML input type
        if (!isset($fieldConfig['tag'])) {
            $this->error("Input field `$fieldName` needs a `tag`.");
        }

        // Derive the rule from the type, if missing.
        if (!isset($fieldConfig['rule'])) {
            $tag = $fieldConfig['tag'];
            if ($tag == 'checkbox' && isset($fieldConfig['options'])) {
                $tag = 'checkbox+options';
            }
            $derivedRule = $validator->getRuleForInputTag($tag);
            if (!$derivedRule) {
                $this->error("Input field `$fieldName` needs a `rule`.");
            }
            $fieldConfig['rule'] = $derivedRule;
        }

        // Process Rule
        $fieldConfig['rule'] = $validator->initFieldRules($fieldName, $fieldConfig['rule']);

        // Some rules only work with certain field tags. e.g. email
        $tagType = $fieldConfig['tag'];
        $derivedFieldType = $fieldConfig['rule']['fieldType'];
        if (!isset($fieldConfig['options'])) {
            if ($derivedFieldType && $tagType !== 'hidden') {
                if ($tagType !== $derivedFieldType) {
                    $this->error("Input field `$fieldName` needs a `tag` of `$derivedFieldType` or `hidden`. Got: `$tagType`");
                }
            }
        }

        // Require 'options' field for select, radio, checkbox
        if (in_array($tagType, ['select', 'radio'])) {
            if (!isset($fieldConfig['options']) || !OBag::isa($fieldConfig['options'])) {
                $this->error("Input field `$fieldName` needs an `options` field with a Map or List.");
            }
        }

        // If you have options, you need a compatible type
        if (isset($fieldConfig['options'])) {
            if (!in_array($tagType, ['select', 'checkbox', 'radio'])) {
                $this->error(
                    "Input field `$fieldName` has an `options` Map, so it needs a `type` of `select`, `checkbox`, or `radio`."
                );
            }
        }

        // Add rule depending on type of checkbox
        if ($tagType == 'checkbox') {
            if ($fieldConfig['options']) {
                // List of checkboxes
                $rule = $fieldConfig['rule'];
                $rule['list'] = true;
                $fieldConfig['rule'] = $rule;
            }
            else {
                // Boolean toggle
                $rule = $fieldConfig['rule'];
                $rule['b'] = true;
                $fieldConfig['rule'] = $rule;
            }
        }

        // Auto-populate 'in' rule with option values
        if (isset($fieldConfig['options'])) {
            $rule = $fieldConfig['rule'];
            $options = $fieldConfig['options'];
            if (OList::isa($options)) {
                $rule['in'] = $options;
            }
            else if (OMap::isa($options)) {
                $rule['in'] = $options->u_keys();
            }

            $fieldConfig['rule'] = $rule;
        }

        // Pre-filled value
        if (isset($fieldConfig['value'])) {
            $this->u_set_values(OMap::create([$fieldName => $fieldConfig['value']]));
        }

        return $fieldConfig;
    }

    // Basic Methods
    // --------------------------------------------------

    function u_get_form_id() {

        $this->ARGS('', func_get_args());

        return $this->formId;
    }

    function u_get_config($filterForJs = false) {

        $this->ARGS('b', func_get_args());

        $config = [];

        if ($filterForJs) {

            foreach ($this->formConfig as $fieldName => $fieldConfig) {

                $rules = $fieldConfig['rule'];
                $newRule = [
                    'min' => $rules['min'],
                    'max' => $rules['max'],
                    'optional' => $rules['optional'],
                ];
                if ($rules['step']) { $newRule['step'] = $rules['step']; }
                if ($rules['regex']) { $newRule['regex'] = $rules['regex']; }

                $config[$fieldName] = [ 'rule' => $newRule ];
            }
        }
        else {
            $config = $this->formConfig;
        }

        return v($config);
    }

    function u_set_values($data) {

        $this->ARGS('m', func_get_args());

        $this->fillData($data);

        return $this;
    }

    // Form Post Logic
    // --------------------------------------------------

    // Undocumented
    function u_is_submitted() {

        $this->ARGS('', func_get_args());

        $postData = $this->getRawPostData();

        return !is_null($postData);
    }

    function u_process($cb) {

        $this->ARGS('c', func_get_args());

        $result = $this->validateAllFields();

        if ($result['ok']) {

            $cbReturn = $cb($result['fields']);

            if ($cbReturn === false) {
                // noop
            }
            else if ($cbReturn === true) {
                // Redirect to same URL
                $url = OTypeString::create(
                    'url', Tht::getPhpGlobal('server', 'SCRIPT_NAME')
                );
                $this->sendOk($url);
            }
            else if (OList::isa($cbReturn)) {

                if (count($cbReturn) != 2) {
                    $this->error("Returned list must have two elements: `[$fieldName, $errorMessage]`");
                }

                $fieldName = $cbReturn[ONE_INDEX];
                if (!isset($this->formConfig[$fieldName])) {
                    $this->error("Unknown input field `$fieldName` when returning validation error.");
                }

                $this->sendError($cbReturn[ONE_INDEX], $cbReturn[ONE_INDEX + 1]);
            }
            else if (UrlTypeString::isa($cbReturn)) {
                // Redirect to custom URL
                $this->sendOk($cbReturn);
            }
            else if (HtmlTypeString::isa($cbReturn)) {
                // Send HTML snippet to replace form.
                $this->sendOkHtml($cbReturn);
            }
            else if (OMap::isa($cbReturn)) {
                // Return JSON object
                Tht::module('Output')->u_send_json($cbReturn);
            }
            else {
                $this->error(
                    'Callback `process` function must return a boolean, Map (json), URL TypeString, or HTML TypeString.'
                );
            }

            return true;
        }
        else {

            $error = $result['errors'][ONE_INDEX];
            $this->sendError($error['field'], $error['error']);

            return false;
        }
    }

    // Validation
    // --------------------------------------------------

    function validateAllFields() {

        $rawPostData = $this->getRawPostData();

        $iv = new u_InputValidator();

        return $iv->validateFields(
            $rawPostData,
            $this->formConfig
        );
    }

    function sendError($field, $message) {

        $this->ARGS('ss', func_get_args());

        Tht::module('Output')->u_send_json(OMap::create([
            'status' => 'fail',
            'error' => ['field' => $field, 'message' => $message],
        ]));

        return false;
    }

    function sendOk($redirectUrl = '') {

        $this->ARGS('*', func_get_args());

        Tht::module('Output')->u_send_json(OMap::create([
            'status' => 'ok',
            'redirect' => $redirectUrl ? OTypeString::getUntyped($redirectUrl, 'url') : '',
        ]));
    }

    function sendOkHtml($html) {

        $this->ARGS('*', func_get_args());

        Tht::module('Output')->u_send_json(OMap::create([
            'status' => 'ok',
            'html' => $html->u_render_string(),
        ]));
    }

    // Data Getters
    // --------------------------------------------------

    function getRawPostData() {

        $postData = Tht::getPhpGlobal('post', '*');

        if (Tht::module('Request')->u_get_method() !== 'post') {
            $postData = [];
        }
        else if (!isset($postData['formId'])) {
            $this->error('Missing formId in form data.');
        }
        else if ($postData['formId'] !== $this->formId) {
            $postData = [];
        }

        return OMap::create($postData);
    }
}


text:
![build](https://github.com/iondrimba/marvel-api-explorer/workflows/build/badge.svg?branch=main)
![deploy](https://github.com/iondrimba/marvel-api-explorer/workflows/deploy/badge.svg?branch=main)
[![Coverage Status](https://coveralls.io/repos/github/iondrimba/marvel-api-explorer/badge.svg)](https://coveralls.io/github/iondrimba/marvel-api-explorer)

![Demo](https://github.com/iondrimba/images/blob/master/marvel-demo.gif?raw=true)

## About

This is a personal project built in my spare time for learning purposes.
It uses the official [Marvel API](https://developer.marvel.com/docs)

## Features

* PWA
* Responsive
* Offline ready
* Installable (add to Homescreen )
* Swipe gestures for pagination
* Pull to refresh keeps current pagination page

## Running

```bash
npm start
```

## Testing

```bash
npm test
```

or

```bash
npm run start:watch ## watch/tdd mode
```

## Built with

* ES6
* Sass
* React + Redux
* Jest
* VSCode
* WebPack

## Todo

* Write more tests(especially jsx components)
* Refactor bits of code
* Add more mobile friendly gestures


text:
+++
title = "Gabriela Dias"
Twitter = ""
linkedin = ""
image = "gabriela-dias.png"
type = "speaker"
linktitle = "gabriela-dias"
+++

Gerente de SRE e DevOps - PagSeguro


text:
package syndieutil

import (
	"archive/zip"
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"strings"
)

type Message struct {
	Page       []Page
	Attachment []Attachment
	Avatar     []byte
	References string
}

type Attachment struct {
	Name        string
	ContentType string
	Description string
	Data        []byte
}

type Page struct {
	ContentType string
	Title       string
	References  string
	Data        string
}

func (p *Page) ReadLine(s string) error {
	if strings.Contains(s, "=") {
		split := strings.SplitN(s, "=", 2)
		key := strings.ToLower(string(split[0]))
		value := string(split[1])
		switch key {
		case "content-type":
			p.ContentType = value
		case "title":
			p.Title = value
		case "references":
			p.References = value
		default:
			return errors.New("malformed page")
		}
	}
	return nil
}

// ParseMessage is probably broken with multiple attachments/pages
func (h *Header) ParseMessage(zr *zip.Reader) (Message, error) {
	var foundPageCfg, foundPageDat bool
	var foundAttachCfg, foundAttachDat bool
	var pagenum, attachnum int
	attachnum++
	m := Message{}
	a := Attachment{}
	for _, file := range zr.File {
		fileReader, err := file.Open()
		if err != nil {
			return Message{}, fmt.Errorf("error opening enclosed zip file %s", err)
		}
		contents, err := ioutil.ReadAll(fileReader)
		if err != nil {
			return Message{}, fmt.Errorf("error reading from enclosed zip file %s", err)
		}
		defer fileReader.Close()
		switch file.Name {
		case "headers.dat":
			scanner := bufio.NewScanner(bytes.NewReader(contents))
			for scanner.Scan() {
				h.ReadLine(scanner.Text())
			}
		case "references.cfg":
			m.References = string(contents)
		case "avatar32.png":
			m.Avatar = contents
		}
		if strings.HasPrefix(file.Name, "page") {
			if foundPageCfg && foundPageDat {
				pagenum++
			}
			p := Page{}
			m.Page = append(m.Page, p)
			if strings.HasSuffix(file.Name, ".dat") {
				foundPageDat = true
				m.Page[pagenum].Data = string(contents)
			}
			if strings.HasSuffix(file.Name, ".cfg") {
				foundPageCfg = true
				scanner := bufio.NewScanner(bytes.NewReader(contents))
				for scanner.Scan() {
					m.Page[pagenum].ReadLine(scanner.Text())
				}
			}
		}
		// The spec is unclear if this should be "attach" or "attachment"
		if strings.HasPrefix(file.Name, "attachment") {
			if strings.HasSuffix(file.Name, ".dat") {
				a.Data = contents
				foundAttachDat = true
				continue
			}
			if strings.HasSuffix(file.Name, ".cfg") {
				scanner := bufio.NewScanner(bytes.NewReader(contents))
				for scanner.Scan() {
					if strings.Contains(scanner.Text(), "=") {
						split := strings.SplitN(scanner.Text(), "=", 2)
						key := strings.ToLower(string(split[0]))
						value := string(split[1])
						switch key {
						case "name":
							a.Name = value
						case "content-type":
							a.ContentType = value
						case "description":
							a.Description = value
						}
					}
				}
				foundAttachCfg = true
				if foundAttachCfg && foundAttachDat {
					m.Attachment = append(m.Attachment, a)
					foundAttachCfg = false
					foundAttachDat = false
				}
				continue
			}
		}
	}
	return m, nil
}


text:
package fredboat.event;

import net.dv8tion.jda.core.events.Event;
import net.dv8tion.jda.core.hooks.EventListener;

public class ShardWatchdogListener implements EventListener {

    private Event lastEvent = null;
    private long lastEventTime = System.currentTimeMillis();
    private long eventCount = 0;

    @Override
    public void onEvent(Event event) {
        lastEvent = event;
        lastEventTime = System.currentTimeMillis();
        eventCount++;
    }

    public Event getLastEvent() {
        return lastEvent;
    }

    public long getLastEventTime() {
        return lastEventTime;
    }

    public long getEventCount() {
        return eventCount;
    }
}


text:
<?php

/**
 * Runtime Method _callBlock, _callParentBlock, _callChildBlock, _registerBlock
 *
 * @package    Smarty
 * @subpackage PluginsInternal
 * @author     Uwe Tews
 *
 **/
class Smarty_Internal_Runtime_Block
{

    public $inheritanceBlocks = array();

    /**
     * Call inheritance {block} tag
     *
     * @param \Smarty_Internal_Template $callerTpl template object of caller
     * @param array                     $block     block parameter
     */
    public function callBlock(Smarty_Internal_Template $callerTpl, $block)
    {
        $function = $block['function'];
        $level = isset($block['level']) ? $block['level'] : 0;
        // find to level child block
        while (!isset($block['callChildBlock']) &&
            isset($this->inheritanceBlocks[$block['name']][$level])) {
            $block = $this->inheritanceBlocks[$block['name']][$level];
            $block['level'] = $level;
            $level ++;
        }
        // ignore hidden block
        if (isset($block['hide'])) {
            return;
        }
        // root block function for possible parent block call
        $block['root'] = $function;
        if (isset($block['append'])) {
            $this->callParentBlock($callerTpl, $block);
        }
        $block['function']($callerTpl, $block);
        if (isset($block['prepend'])) {
            $this->callParentBlock($callerTpl, $block);
        }
    }

    /**
     * Call inheritance parent {block} tag
     *
     * @param \Smarty_Internal_Template $callerTpl template object of caller
     * @param array                     $block     block parameter
     */
    public function callParentBlock(Smarty_Internal_Template $callerTpl, $block)
    {
        $level = isset($block['level']) ? $block['level'] : 0;
        if (isset($this->inheritanceBlocks[$block['name']][$level - 1])) {
            // call registered parent
            $parent = $this->inheritanceBlocks[$block['name']][$level - 1];
            $parent['root'] = $block['root'];
            $parent['function']($callerTpl, $parent);
        } else {
            // default to root block
            $block['root']($callerTpl, $block);
        }
    }

    /**
     * Call inheritance child {block} tag
     *
     * @param \Smarty_Internal_Template $callerTpl template object of caller
     * @param array                     $block     block parameter
     */
    public function callChildBlock(Smarty_Internal_Template $callerTpl, $block)
    {
        $level = isset($block['level']) ? $block['level'] : - 1;
        if (isset($this->inheritanceBlocks[$block['name']][$level + 1])) {
            $child = $this->inheritanceBlocks[$block['name']][$level + 1];
            $child['level'] = $level + 1;
            $child['function']($callerTpl, $child);
        }
    }

    /**
     * Register inheritance {block} tag
     *
     * @param \Smarty_Internal_Template $callerTpl template object of caller
     * @param array                     $block     block parameter
     */
    public function registerBlock(Smarty_Internal_Template $callerTpl, $block)
    {
        if (!isset($this->inheritanceBlocks[$block['name']])) {
            $this->inheritanceBlocks[$block['name']][0] = $block;
        } else {
            array_unshift($this->inheritanceBlocks[$block['name']], $block);
        }
    }
}


text:
import eventlet  # noqa
import fixtures
from oslo_config import cfg

from ironic_inspector import main
from ironic_inspector.test import base as test_base
from ironic_inspector import utils
from ironic_inspector import wsgi_service

CONF = cfg.CONF

class BaseWSGITest(test_base.BaseTest):
    def setUp(self):
        # generic mocks setUp method
        super(BaseWSGITest, self).setUp()
        self.app = self.useFixture(fixtures.MockPatchObject(
            main, '_app', autospec=True)).mock
        self.server = self.useFixture(fixtures.MockPatchObject(
            wsgi_service.wsgi, 'Server', autospec=True)).mock

class TestWSGIServiceInitMiddleware(BaseWSGITest):
    def setUp(self):
        super(TestWSGIServiceInitMiddleware, self).setUp()
        self.mock_add_auth_middleware = self.useFixture(
            fixtures.MockPatchObject(utils, 'add_auth_middleware')).mock
        self.mock_add_basic_auth_middleware = self.useFixture(
            fixtures.MockPatchObject(utils, 'add_basic_auth_middleware')).mock
        self.mock_add_cors_middleware = self.useFixture(
            fixtures.MockPatchObject(utils, 'add_cors_middleware')).mock
        self.mock_log = self.useFixture(fixtures.MockPatchObject(
            main, 'LOG')).mock
        # 'positive' settings
        CONF.set_override('auth_strategy', 'keystone')
        CONF.set_override('store_data', 'swift', 'processing')

    def test_init_middleware(self):
        wsgi_service.WSGIService()
        self.mock_add_auth_middleware.assert_called_once_with(self.app)
        self.mock_add_cors_middleware.assert_called_once_with(self.app)

    def test_init_middleware_basic(self):
        CONF.set_override('auth_strategy', 'http_basic')
        wsgi_service.WSGIService()

        self.mock_add_auth_middleware.assert_not_called()
        self.mock_add_basic_auth_middleware.assert_called_once_with(self.app)
        self.mock_add_cors_middleware.assert_called_once_with(self.app)

    def test_init_middleware_noauth(self):
        CONF.set_override('auth_strategy', 'noauth')
        wsgi_service.WSGIService()

        self.mock_add_auth_middleware.assert_not_called()
        self.mock_log.warning.assert_called_once_with(
            'Starting unauthenticated, please check configuration')
        self.mock_add_cors_middleware.assert_called_once_with(self.app)

class TestWSGIService(BaseWSGITest):
    def setUp(self):
        super(TestWSGIService, self).setUp()
        self.service = wsgi_service.WSGIService()
        self.service.server = self.server
        self.mock__init_middleware = self.useFixture(fixtures.MockPatchObject(
            main, '_init_middleware')).mock

        # 'positive' settings
        CONF.set_override('listen_address', '42.42.42.42')
        CONF.set_override('listen_port', 42)

    def test_start(self):
        self.service.start()
        self.server.start.assert_called_once_with()

    def test_stop(self):
        self.service.stop()
        self.server.stop.assert_called_once_with()

    def test_wait(self):
        self.service.wait()
        self.server.wait.assert_called_once_with()

    def test_reset(self):
        self.service.reset()
        self.server.reset.assert_called_once_with()


text:
A Container Linux Config is a YAML document which declares how Container Linux instances' disks should be provisioned on network boot and first-boot from disk. Configs can declare disk paritions, write files (regular files, systemd units, networkd units, etc.), and configure users. See the Container Linux Config [spec](https://coreos.com/os/docs/latest/configuration.html).

### Ignition

Container Linux Configs are validated and converted to *machine-friendly* Ignition configs (JSON) by matchbox when serving to booting machines. [Ignition](https://coreos.com/ignition/docs/latest/), the provisioning utility shipped in Container Linux, will parse and execute the Ignition config to realize the desired configuration. Matchbox users usually only need to write Container Linux Configs.

*Note: Container Linux directory names are still named "ignition" for historical reasons as outlined below. A future breaking change will rename to "container-linux-config".*

## Adding Container Linux Configs

Container Linux Config templates can be added to the `/var/lib/matchbox/ignition` directory or in an `ignition` subdirectory of a custom `-data-path`. Template files may contain [Go template](https://golang.org/pkg/text/template/) elements which will be evaluated with group metadata, selectors, and query params.

```
/var/lib/matchbox
 ├── cloud
 ├── ignition
 │   └── k8s-controller.yaml
 │   └── etcd.yaml
 │   └── k8s-worker.yaml
 │   └── raw.ign
 └── profiles
```

## Referencing in Profiles

Profiles can include a Container Linux Config for provisioning machines. Specify the Container Linux Config in a [Profile](matchbox.md#profiles) with `ignition_id`. When PXE booting, use the kernel option `coreos.first_boot=1` and `coreos.config.url` to point to the `matchbox` [Ignition endpoint](api.md#ignition-config).

## Examples

Here is an example Container Linux Config template. Variables will be interpreted using group metadata, selectors, and query params. Matchbox will convert the config to Ignition to serve Container Linux machines.

ignition/format-disk.yaml.tmpl:

<!-- {% raw %} -->
```yaml

---
storage:
  disks:
    - device: /dev/sda
      wipe_table: true
      partitions:
        - label: ROOT
  filesystems:
    - name: root
      mount:
        device: "/dev/sda1"
        format: "ext4"
        create:
          force: true
          options:
            - "-LROOT"
  files:
    - filesystem: root
      path: /home/core/foo
      mode: 0644
      user:
        id: 500
      group:
        id: 500
      contents:
        inline: |
          {{.example_contents}}
{{ if index . "ssh_authorized_keys" }}
passwd:
  users:
    - name: core
      ssh_authorized_keys:
        {{ range $element := .ssh_authorized_keys }}
        - {{$element}}
        {{end}}
{{end}}
```
<!-- {% endraw %} -->

The Ignition config response (formatted) to a query `/ignition?label=value` for a CoreOS instance supporting Ignition 2.0.0 would be:

```json
{
  "ignition": {
    "version": "2.0.0",
    "config": {}
  },
  "storage": {
    "disks": [
      {
        "device": "/dev/sda",
        "wipeTable": true,
        "partitions": [
          {
            "label": "ROOT",
            "number": 0,
            "size": 0,
            "start": 0
          }
        ]
      }
    ],
    "filesystems": [
      {
        "name": "root",
        "mount": {
          "device": "/dev/sda1",
          "format": "ext4",
          "create": {
            "force": true,
            "options": [
              "-LROOT"
            ]
          }
        }
      }
    ],
    "files": [
      {
        "filesystem": "root",
        "path": "/home/core/foo",
        "contents": {
          "source": "data:,Example%20file%20contents%0A",
          "verification": {}
        },
        "mode": 420,
        "user": {
          "id": 500
        },
        "group": {
          "id": 500
        }
      }
    ]
  },
  "systemd": {},
  "networkd": {},
  "passwd": {}
}
```

See [examples/ignition](../examples/ignition) for numerous Container Linux Config template examples.

### Raw Ignition

If you prefer to design your own templating solution, raw Ignition files (suffixed with `.ign` or `.ignition`) are served directly.


text:
Create class t1(a integer, b float(10), c integer);
insert into t1 values(100, 1919.81, null);
insert into t1 values(200, null, 999);
insert into t1 values(null, null, 888);
insert into t1 values(null, null, null);
insert into t1 values(null, 99.19, 51);

select COALESCE(a, COALESCE(b,c)) from t1 order by 1;
select COALESCE(b, COALESCE(a,c)) from t1 order by 1;
select COALESCE(c, COALESCE(a,b)) from t1 where a is null order by 1;

drop table t1;