text:
var AtomGdb, BufferedProcess, CompositeDisposable, File, dialog, fs, path;

BufferedProcess = require('atom').BufferedProcess;
CompositeDisposable = require('atom').CompositeDisposable;

File = require('atom').File;

path = require('path');

fs = require('fs');

dialog = require('remote').dialog;

module.exports = AtomGdb = {
    modalPanel: null,
    subscriptions: null,
    breakpoints: [],
    markers: {},
    settings: {},
    settingsFile: null,
    childProcess: null,
    config: {
        debuggerCommand: {
            type: 'string',
            "default": 'qtcreator -client -debug'
        },
        executableSuffix: {
            type: 'string',
            "default": ''
        },
        saveOnStart: {
            type: 'boolean',
            "default": true
        }
    },
    activate: function(state) {
        this.subscriptions = new CompositeDisposable();
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'atom-gdb:start': (function(_this) {
                return function() {
                    return _this.start();
                };
            })(this)
        }));
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'atom-gdb:start-no-debug': (function(_this) {
                return function() {
                    return _this.startNoDebug();
                };
            })(this)
        }));
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'atom-gdb:stop': (function(_this) {
                return function() {
                    return _this.stopChildProcess();
                };
            })(this)
        }));
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'atom-gdb:select-executable': (function(_this) {
                return function() {
                    return _this.selectExecutable();
                };
            })(this)
        }));
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'atom-gdb:select-startup-directory': (function(_this) {
                return function() {
                    return _this.selectStartupDirectory();
                };
            })(this)
        }));
        this.subscriptions.add(atom.commands.add('atom-text-editor', {
            'atom-gdb:toggle-breakpoint': (function(_this) {
                return function() {
                    return _this.toggleBreakpoint();
                };
            })(this)
        }));
        this.handleSettingsFile();
        this.checkGlobalGdbInit();

        atom.workspace.observeTextEditors(function(editor) {
            for(var i in AtomGdb.breakpoints)
            {
                var bp = AtomGdb.breakpoints[i];
                if(bp.filepath == editor.getPath())
                {
                    var marker = editor.markBufferPosition([bp.line - 1, 0], {
                        invalidate: 'never'
                    });

                    AtomGdb.setupMarker(editor, marker, bp);
                }
            }
        });
    },
    deactivate: function() {
        return this.subscriptions.dispose();
    },
    getSetting: function(name) {
        if (!(name in this.settings) || this.settings[name] === void 0) {
            this.settings[name] = "";
        }
        return this.settings[name];
    },
    runProcess: function(command, args, cwd) {
        if(this.childProcess !== null) {
            atom.notifications.addWarning("[atom-gdb] A child process is already running. (" + this.childProcess.command + ")");
            return null;
        }
        var exit, stderr, stdout;
        var that = this;
        stdout = function(output) {
            return console.log("stdout:", output);
        };
        stderr = function(output) {
            atom.notifications.addError("[atom-gdb] Error:" + output);
            return console.log("stderr:", output);
        };
        exit = function(return_code) {
            atom.notifications.addInfo("[atom-gdb] Child process has stopped.");
            that.childProcess = null;
            return console.log("Exit with ", return_code);
        };
        console.log('Starting process :', command, args.join(" "), 'in', cwd);
        process.chdir(cwd);
        atom.notifications.addInfo("[atom-gdb] Running command '" + command + "'");
        this.childProcess = new BufferedProcess({
            command: command,
            args: args,
            stdout: stdout,
            stderr: stderr,
            exit: exit
        });

        return this.childProcess;
    },
    selectExecutable: function() {
        var value;
        value = dialog.showOpenDialog({
            properties: ['openFile'],
            title: "Select the binary to debug",
            defaultPath: atom.project.getPaths()[0]
        });
        if (value !== void 0) {
            this.settings.executablePath = value[0];
            this.updateSettingsFile();
        }
        return value !== void 0;
    },
    selectStartupDirectory: function() {
        var value;
        value = dialog.showOpenDialog({
            properties: ['openDirectory'],
            title: "Select the startup directory",
            defaultPath: atom.project.getPaths()[0]
        });
        if (value !== void 0) {
            this.settings.startupDirectory = value[0];
            this.updateSettingsFile();
        }
        return value !== void 0;
    },
    start: function() {
        var args, command, commandWords, cwd, exe;
        if (atom.config.get('atom-gdb.saveOnStart')) {
            this.saveAll();
        }
        commandWords = atom.config.get('atom-gdb.debuggerCommand').split(" ");
        command = commandWords[0];
        args = commandWords.slice(1, +commandWords.length + 1 || 9e9);
        exe = this.getSetting('executablePath');
        if (!fs.existsSync(exe)) {
            if (this.selectExecutable()) {
                this.start();
            }
            return;
        }
        cwd = this.getSetting('startupDirectory');
        if (!fs.existsSync(cwd)) {
            if (this.selectStartupDirectory()) {
                this.start();
            }
            return;
        }
        args.push(exe + atom.config.get('atom-gdb.executableSuffix'));
        return this.runProcess(command, args, cwd);
    },
    startNoDebug: function() {
        var command, cwd, exe;
        if (atom.config.get('atom-gdb.saveOnStart')) {
            this.saveAll();
        }
        exe = this.getSetting('executablePath');
        if (!fs.existsSync(exe)) {
            if (this.selectExecutable()) {
                this.startNoDebug();
            }
            return;
        }
        cwd = this.getSetting('startupDirectory');
        if (!fs.existsSync(cwd)) {
            if (this.selectStartupDirectory()) {
                this.startNoDebug();
            }
            return;
        }
        command = exe;
        return this.runProcess(command, [], cwd);
    },
    stopChildProcess: function() {
        if(this.childProcess !== null) {
            require('tree-kill')(this.childProcess.process.pid, 'SIGKILL');
            this.childProcess = null;
        }
    },
    toggleBreakpoint: function() {
        var editor, index, item, marker, range;
        editor = atom.workspace.getActiveTextEditor();
        item = {
            filepath: editor.getPath(),
            filename: path.basename(editor.getPath()),
            line: Number(editor.getCursorBufferPosition().row + 1)
        };
        index = this.findBreakpointIndex(item);
        if (index === -1) {
            this.breakpoints.push(item);
            range = editor.getSelectedBufferRange();
            marker = editor.markBufferRange(range, {
                invalidate: 'never'
            });
            this.setupMarker(editor, marker, item);
            console.log("Added breakpoint:", item.filename, ":", item.line);
        } else {
            this.breakpoints.splice(index, 1);
            this.markers[this.generateKey(item)].destroy();
            console.log("Removed breakpoint:", item.filename, ":", item.line);
        }
        return this.updateGdbInit();
    },
    setupMarker: function(editor, marker, item) {
        editor.decorateMarker(marker, {
            type: 'line-number',
            "class": 'syntax--breakpoint'
        });
        this.markers[this.generateKey(item)] = marker;
        marker.item = item;
        bps = this.breakpoints;
        return marker.onDidChange(function(event) {
            var new_line, old_line;
            old_line = event.oldHeadBufferPosition.row + 1;
            new_line = event.newHeadBufferPosition.row + 1;
            marker.item.line = new_line;
            AtomGdb.updateGdbInit();
            console.log("Moved breakpoint:", item.filename, ":", old_line, "to", new_line);
        });
    },
    updateGdbInit: function() {
        var bps, cwd, outputFile;
        cwd = this.getSetting('startupDirectory');
        if (!fs.existsSync(cwd)) {
            if (this.selectStartupDirectory()) {
                this.updateGdbInit();
            }
            return;
        }
        process.chdir(cwd);
        outputFile = fs.createWriteStream(".gdbinit");
        bps = this.breakpoints;
        return outputFile.on('open', function(fd) {
            var item, j, len;
            outputFile.write("set breakpoint pending on\n");
            for (j = 0, len = bps.length; j < len; j++) {
                item = bps[j];
                outputFile.write("b " + AtomGdb.generateKey(item) + "\n");
            }
            outputFile.end();
        });
    },
    handleSettingsFile: function() {
        var _path;
        _path = atom.project.getPaths()[0];
        this.settingsFile = new File(_path + "/.atom-gdb.json", false);
        if (this.settingsFile.exists()) {
            this.settingsFile.read().then(function(content) {
                AtomGdb.settings = JSON.parse(content);
                if (AtomGdb.settings === null) {
                    return (AtomGdb.settings = {});
                }
            });
        } else {
            this.settingsFile.create();
        }
        return this.settingsFile.onDidChange(function() {
            return AtomGdb.settingsFile.read().then(function(content) {
                AtomGdb.settings = JSON.parse(content);
                if (AtomGdb.settings === null) {
                    return (AtomGdb.settings = {});
                }
            });
        });
    },
    updateSettingsFile: function() {
        return this.settingsFile.write(JSON.stringify(this.settings, null, 2));
    },
    generateKey: function(item) {
        return item.filename + ":" + item.line;
    },
    findBreakpointIndex: function(_item) {
        var i, item, length;
        i = 0;
        length = this.breakpoints.length;
        while (i < length) {
            item = this.breakpoints[i];
            if (item.filepath === _item.filepath && item.line === _item.line) {
                return i;
            }
            ++i;
        }
        return -1;
    },
    saveAll: function() {
        var editors, i, results;
        editors = atom.workspace.getTextEditors();
        results = [];
        for (i in editors) {
            results.push(editors[i].save());
        }
        return results;
    },
    checkGlobalGdbInit: function() {
        var globalGdbInitFile;
        globalGdbInitFile = new File(process.env.HOME + "/.gdbinit", false);
        return globalGdbInitFile.read().then(function(content) {
            if (content === null || !content.match(/^set auto-load safe-path/m)) {
                globalGdbInitFile.write((content || "") + "\n# Added by atom-gdb\nset auto-load safe-path /");
                return console.log("~/.gdbinit has been updated for atom-gdb");
            } else {
                return console.log("~/.gdbinit is fine for atom-gdb");
            }
        });
    }
};


text:
import Component from './Component';
import Config from '../../Config';
import Globals from '../../Globals';

import {
    selection,
    nest
} from 'd3';

class Legend extends Component {

    constructor() {
        super();
    }

    public render() {
        this.svg.append('g').attr('class', 'legend');
    }

    public update(data: any) {
        let propertyKey: string = this.config.get('propertyKey');
        let dataSeries = nest()
            .key((d: any) => d[propertyKey]).entries(data),
            legend = null,
            entries = null,
            colorScale = this.config.get('colorScale'),
            height = this.config.get('height'),
            width = this.config.get('width'),
            legendPosition = this.config.get('legendPosition') || 'right';

        if (dataSeries.length === 1 && dataSeries[0].key === 'undefined') {
            console.warn('Not showing legend, since there is a valid key');
            return;
        }

        legend = this.svg.select('.legend');

        entries = legend.selectAll(`.legend-entry`)
            .data(dataSeries, (d: any) => d.key);

        entries.exit().remove();

        let enterEntries = entries.enter().append('g')
            .attr('class', 'legend-entry')
            .attr(Globals.LEGEND_DATA_KEY_ATTRIBUTE, (d: any) => d.key);

        enterEntries.append('rect')
            .attr('class', 'legend-cb')
            .attr('height', 20)
            .attr('width', 20)
            .style('fill', (d: any) => colorScale(d.key))
            .style('stroke', (d: any) => colorScale(d.key))
            .style('opacity', 0.8)
            .style('cursor', 'pointer')
            .on('click.default', (d: any) => this.toggle(d));

        enterEntries.append('text')
            .attr('class', 'legend-txt')
            .attr('dy', '0.55em')
            .text((d: any) => d.key)
            .on('click.default', () => this.toggle);

        enterEntries.merge(entries);

        switch (legendPosition) {
            case 'top':
                this.drawTopLegendCb(legend);
                this.drawTopLegendTxt(legend);
                break;
            case 'right':
                this.drawRightLegendCb(legend, width);
                this.drawRightLegendTxt(legend, width);
                break;
            case 'bottom':
                this.drawBottomLegendCb(legend, height);
                this.drawBottomLegendTxt(legend, height);
                break;
        }

        entries.exit().remove();
    }

    public clear() {
        this.update([]);
    }

    public transition() {}

    private drawTopLegendCb(legend: any) {
        legend.selectAll('.legend-cb')
            .attr('x', (d: any, i: number) => i * 100)
            .attr('y', -20 - 15)
            .on('click.default', (d: any) => this.toggle(d));
    }

    private drawBottomLegendCb(legend: any, height: number) {
        legend.selectAll('.legend-cb')
            .attr('x', (d: any, i: number) => i * 100)
            .attr('y', height + 70)
            .on('click.default', (d: any) => this.toggle(d));
    }

    private drawRightLegendCb(legend: any, width: number) {
        legend.selectAll('.legend-cb')
            .attr('x', width + 10)
            .attr('y', (d: any, i: number) => i * 25)
            .on('click.default', (d: any) => this.toggle(d));
    }

    private drawBottomLegendTxt(legend: any, height: number) {
        legend.selectAll('.legend-txt')
            .attr('x', (d: any, i: number) => i * 100 + 20 + 5)
            .attr('y', height + 70 + 10)
            .on('click.default', () => this.toggle);
    }

    private drawTopLegendTxt(legend: any) {
        legend.selectAll('.legend-txt')
            .attr('x', (d: any, i: number) => i * 100 + 20 + 5)
            .attr('y', -20 - 15 + 10)
            .on('click.default', () => this.toggle);
    }

    private drawRightLegendTxt(legend: any, width: number) {
        legend.selectAll('.legend-txt')
            .attr('x', width + 25 + 10)
            .attr('y', (d: any, i: number) => i * 25 + 7)
            .on('click.default', () => this.toggle);
    }

    private toggle(d: any): void {
        let key: string = d.key,
            element = this.svg.selectAll(`*[${Globals.COMPONENT_DATA_KEY_ATTRIBUTE}='${key}']`),
            colorScale = this.config.get('colorScale');

        if (!element.empty()) {
            let opacity: number = parseInt(element.style('opacity'));
            opacity = (opacity == 1) ? Globals.COMPONENT_HIDE_OPACITY : 1;
            let legendEntry = this.svg.select(`.legend-entry[${Globals.LEGEND_DATA_KEY_ATTRIBUTE}='${key}']`);

            legendEntry.selectAll('rect')
                .style('fill', (field: any): any => (opacity === 1)
                    ? colorScale(field.key)
                    : 'transparent'
                );

            element
                .style('opacity', opacity);
        }
    }

}

export default Legend;

redpajama_set_name: RedPajamaGithub


text:
package director

import (
	// "fmt"
	"time"
)

const (
	FOREVER = -1
	ONCE    = 1
)

// A Looper is used in place of a direct call to "for {}" and implements some
// controls over how the loop will be run. The Loop() function is the main
// call used by dependant routines. Common patterns like Quit and Done
// channels are easily implemented in a Looper.
type Looper interface {
	Loop(fn func() error)
	Wait() error
	Done(err error)
	Quit()
}

// A TimedLooper is a Looper that runs on a timed schedule, using a Timer
// underneath. It also implements Quit and Done channels to allow external
// routines to more easily control and synchronize the loop.
//
// If you pass in a DoneChan at creation time, it will send a nil on the
// channel when the loop has completed successfully or an error if the loop
// resulted in an error condition.
//
// If you pass in a quitChan it can be used to tell the loop to exit on completion
// of the next iteration.  Using both Done and Quit channels allows full external
// control of the loop.

type TimedLooper struct {
	Count     int
	Interval  time.Duration
	DoneChan  chan error
	quitChan  chan bool
	Immediate bool
}

// Same as a TimedLooper, except it will execute an iteration of the loop
// immediately after calling on Loop() (as opposed to waiting until the tick)
func NewTimedLooper(count int, interval time.Duration, done chan error) *TimedLooper {
	return &TimedLooper{
		Count:     count,
		Interval:  interval,
		DoneChan:  done,
		quitChan:  make(chan bool),
		Immediate: false,
	}
}

func NewImmediateTimedLooper(count int, interval time.Duration, done chan error) *TimedLooper {
	return &TimedLooper{
		Count:     count,
		Interval:  interval,
		DoneChan:  done,
		quitChan:  make(chan bool),
		Immediate: true,
	}
}

func (l *TimedLooper) Wait() error {
	return <-l.DoneChan
}

// Signal a dependant routine that we're done with our work
func (l *TimedLooper) Done(err error) {
	if l.DoneChan != nil {
		l.DoneChan <- err
	}
}

// The main method of the Looper. This call takes a function with a single
// return value, an error. If the error is nil, the Looper will run the
// next iteration. If it's an error, it will not run the next iteration,
// will clean up any internals that need to be, and will invoke done().
func (l *TimedLooper) Loop(fn func() error) {
	i := 0

	var stop bool

	stopFunc := func(err error) {
		l.Done(err)
		stop = true
	}

	runIteration := func() {
		err := fn()
		if err != nil {
			stopFunc(err)
			return
		}

		// We have to make sure not to increment if we started
		// at -1 otherwise we quit on maxint rollover.
		if l.Count != FOREVER {
			i = i + 1
			if i >= l.Count {
				stopFunc(nil)
				return
			}
		}

		select {
		case <-l.quitChan:
			stopFunc(nil)
			return
		default:
		}
	}

	// Immediatelly run our function if we've been instantiated via
	// NewImmediateTimedLooper
	if l.Immediate {
		runIteration()
	}

	ticks := time.Tick(l.Interval)
	for range ticks {
		if stop {
			break
		}

		runIteration()
	}
}

// Quit() signals to the Looper to not run the next iteration and to
// call done() and return as quickly as possible. It is does not
// intervene between iterations.
func (l *TimedLooper) Quit() {
	go func() {
		l.quitChan <- true
	}()
}

// A FreeLooper is like a TimedLooper but doesn't wait between iterations.
type FreeLooper struct {
	Count    int
	DoneChan chan error
	quitChan chan bool
}

func NewFreeLooper(count int, done chan error) *FreeLooper {
	return &FreeLooper{
		Count:    count,
		DoneChan: done,
		quitChan: make(chan bool),
	}
}

func (l *FreeLooper) Wait() error {
	return <-l.DoneChan
}

// This is used internally, but can also be used by controlling routines
// to signal that a job is completed. The FreeLooper doesn's support its
// use outside the internals.
func (l *FreeLooper) Done(err error) {
	if l.DoneChan != nil {
		l.DoneChan <- err
	}
}

func (l *FreeLooper) Loop(fn func() error) {
	i := 0

	for {
		err := fn()
		if err != nil {
			l.Done(err)
			return
		}

		// We have to make sure not to increment if we started
		// at -1 otherwise we quit on maxint rollover.
		if l.Count != FOREVER {
			i = i + 1
			if i >= l.Count {
				l.Done(nil)
				return
			}
		}

		select {
		case <-l.quitChan:
			l.Done(nil)
			return
		default:
		}
	}
}

// Quit() signals to the Looper to not run the next iteration and to
// call Done() and return as quickly as possible. It is does not
// intervene between iterations. It is a non-blocking operation.
func (l *FreeLooper) Quit() {
	go func() {
		l.quitChan <- true
	}()
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto

package com.google.cloud.compute.v1;

public interface RegionInstanceGroupManagersCreateInstancesRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.RegionInstanceGroupManagersCreateInstancesRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * [Required] List of specifications of per-instance configs.
   *

   *
   * repeated .google.cloud.compute.v1.PerInstanceConfig instances = 29097598;
   */
  java.util.List<com.google.cloud.compute.v1.PerInstanceConfig> getInstancesList();
  /**
   *
   *
   *

   * [Required] List of specifications of per-instance configs.
   *

   *
   * repeated .google.cloud.compute.v1.PerInstanceConfig instances = 29097598;
   */
  com.google.cloud.compute.v1.PerInstanceConfig getInstances(int index);
  /**
   *
   *
   *

   * [Required] List of specifications of per-instance configs.
   *

   *
   * repeated .google.cloud.compute.v1.PerInstanceConfig instances = 29097598;
   */
  int getInstancesCount();
  /**
   *
   *
   *

   * [Required] List of specifications of per-instance configs.
   *

   *
   * repeated .google.cloud.compute.v1.PerInstanceConfig instances = 29097598;
   */
  java.util.List<? extends com.google.cloud.compute.v1.PerInstanceConfigOrBuilder>
      getInstancesOrBuilderList();
  /**
   *
   *
   *

   * [Required] List of specifications of per-instance configs.
   *

   *
   * repeated .google.cloud.compute.v1.PerInstanceConfig instances = 29097598;
   */
  com.google.cloud.compute.v1.PerInstanceConfigOrBuilder getInstancesOrBuilder(int index);
}


text:
using J2N.Numerics;
using System;

namespace Lucene.Net.Replicator
{

    /// <summary>
    /// Describes a file in a <see cref="IRevision"/>. A file has a source, which allows a
    /// single revision to contain files from multiple sources (e.g. multiple indexes).
    /// </summary>
    /// <remarks>
    /// @lucene.experimental
    /// </remarks>
    public class RevisionFile : IEquatable<RevisionFile>
    {
        /// <summary>
        /// Gets the name of the file.
        /// </summary>
        public string FileName { get; private set; }

        /// <summary>
        /// Gets or sets the length of the file denoted by <see cref="FileName"/>.
        /// </summary>
        public long Length { get; set; }

        /// <summary>
        /// Constructor with the given file name and optionally length.
        /// </summary>
        /// <param name="fileName">The name of the file</param>
        /// <param name="length">Optional, the length of the file.</param>
        public RevisionFile(string fileName, long length = -1)
        {
            if (string.IsNullOrEmpty(fileName)) throw new ArgumentException("fileName must not be null or empty", nameof(fileName));

            FileName = fileName;
            Length = length;
        }

        public override bool Equals(object obj)
        {
            if (obj is null) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((RevisionFile)obj);
        }

        // LUCENENET specific Equals overload
        public virtual bool Equals(RevisionFile other)
        {
            if (other is null) return false;
            if (ReferenceEquals(this, other)) return true;
            return string.Equals(FileName, other.FileName, StringComparison.Ordinal) && Length == other.Length;
        }

        public override int GetHashCode()
        {
            return FileName.GetHashCode() ^ (int)(Length ^ Length.TripleShift(32));
        }

        public override string ToString()
        {
            return string.Format("fileName={0} length={1}", FileName, Length);
        }
    }
}


text:
import edu.washington.cs.knowitall.morpha.MorphaStemmer;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
import org.tartarus.snowball.ext.PorterStemmer;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * Contains Lucene related misc functions
 */
public final class LuceneUtils {

    public enum Stemmer {Porter, Morpho, Porter2}

    private static IndexReader ir = null;

    public static long TotalWordCount = 0;

    // looking up lucene index everytime is costly
    // thus maintaining a cache would result in much better performance
    private static TreeMap<String, Long> freqCache = new TreeMap<String, Long>();

    private LuceneUtils() {}

    /**
     * Tokenizes string using given analyzer
     * @param analyzer analyzer to tokenize string
     * @param string string to tokenize
     * @return list of tonkenized words
     */
    public static List<String> tokenizeString(Analyzer analyzer, String string) {
        List<String> result = new ArrayList<String>();
        TokenStream stream  = null;
        try {
            stream  = analyzer.tokenStream(null, new StringReader(string));
            stream.reset();
            while (stream.incrementToken()) {
                result.add(stream.getAttribute(CharTermAttribute.class).toString());
            }
        } catch (IOException e) {
            // not thrown b/c we're using a string reader...
            throw new RuntimeException(e);
        } finally {
            if(stream != null) try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * Generic stemmer method
     * @param lst list of words to stem
     * @param stmr type of stemmer to use
     * @return list of stemmed words
     */
    public static List<String> stemWords(List<String> lst, Stemmer stmr) {
        switch (stmr) {
            case Porter:
                PorterStemmer stemmer = new PorterStemmer();
                for(int i = 0; i < lst.size(); ++i) {
                    stemmer.setCurrent(lst.get(i));
                    stemmer.stem();
                    lst.set(i, stemmer.getCurrent());
                }
                break;
            case Morpho:
                // Morphological Stemmer
                for(int i = 0; i < lst.size(); ++i) {
                    lst.set(i, MorphaStemmer.stemToken(lst.get(i)));
                }
                break;
            case Porter2:
                org.tartarus.snowball.ext.PorterStemmer stemmer1 = new org.tartarus.snowball.ext.PorterStemmer();
                for(int i = 0; i < lst.size(); ++i) {
                    stemmer1.setCurrent(lst.get(i));
                    stemmer1.stem();
                    lst.set(i, stemmer1.getCurrent());
                }
                break;
        }

        // none of the above stemmers remove apostrophe S
        for(int i = 0; i < lst.size(); ++i) {
            String str = lst.get(i);
            str = str.replaceAll("\'$", "");
            lst.set(i, str);
        }
        return lst;
    }

    /**
     * Gives the term freq in the indexed corpus
     * @param word the word for which freq is requested
     * @return term frequency
     * @throws IOException
     */
    public static long getTermFreq(String word) throws IOException {
        if (ir == null)
            ir = DirectoryReader.open(FSDirectory.open(new File(Globals.INDEX_STORE_DIR)));

        // first look-up in cache
        Long f = freqCache.get(word);

        if(f == null) {
            // if not found
            Term termInstance = new Term("contents", word);
            long termFreq = ir.totalTermFreq(termInstance);

            // add it in cache
            freqCache.put(word, termFreq);
            return termFreq;
        }

        return f;
    }

    /**
     * Information Content(IC) : The IC of a word/concept(c) can be quantified as
     * the negative log likelihood [ -log p(c) ]. As probability of a word occurring in
     * a corpus increases, informativeness decreases, so the more abstract a concept,
     * the lower its information content
     *
     * @param word the word for which IC is requested
     * @return IC
     * @throws IOException
     */
    public static double informationContent(String word) throws IOException {
        long n; // freq of word in corpus
        long N; // Total no. of words in corpus

        n = getTermFreq(word);

        N = LuceneUtils.TotalWordCount;

        double ic = 1.0 - (Math.log(n + 1) / Math.log(N + 1));
        return ic;
    }
}


text:
============
Installation
============

Install the client from PyPI
----------------------------
The :program:`python-designateclient` package is published on `PyPI`_ and so can be installed using the pip tool, which will manage installing all
python dependencies:

.. code-block:: shell-session

   pip install python-designateclient

*Warning: the packages on PyPI may lag behind the git repo in functionality.*

Setup the client from source
----------------------------
If you want the latest version, straight from github:

.. code-block:: shell-session

    git clone git@github.com:openstack/python-designateclient.git
    cd python-designateclient
    virtualenv .venv
    . .venv/bin/activate
    pip install -r requirements.txt -r test-requirements.txt
    python setup.py install

Setup the client in development mode
------------------------------------

Installing in development mode allows your to make changes to the source code & test directly without having to re-run the "python setup.py install"
step.  You can find out more about `Development Mode`_

.. code-block:: shell-session

    git clone git@github.com:openstack/python-designateclient.git
    cd python-designateclient
    virtualenv .venv
    . .venv/bin/activate
    pip install -r requirements.txt -r test-requirements.txt
    python setup.py develop

.. _Development Mode: https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode
.. _PyPI: https://pypi.org/project/python-designateclient/


text:
<?php

return [
    'name' => 'AsgardGenerators',

    // migration
    'migration' => [
        'template' => base_path('Modules/Asgardgenerators/templates') . DIRECTORY_SEPARATOR . 'migration.txt',
        'output_path' => database_path('migrations'),
    ],
    // models
    'models' => [
        'template' => base_path('Modules/Asgardgenerators/templates') . DIRECTORY_SEPARATOR . 'model.txt',
        'output_path' => app_path('Models'),
    ],
    // repositories
    'repositories' => [
        'template' => base_path('Modules/Asgardgenerators/templates'),
        'bindings_template' => base_path('Modules/Asgardgenerators/templates') . DIRECTORY_SEPARATOR . 'bindings.txt',
        'output_path' => app_path('Repositories'),
    ],
    // views
    'views' => [
        'template' => base_path('Modules/Asgardgenerators/templates/views'),
        'output_path' => base_path('resource/views'),
        'base_template_name' => 'app',
    ],
    // controllers
    'controllers' => [
        'template' => base_path('Modules/Asgardgenerators/templates') . DIRECTORY_SEPARATOR . 'admin-controller.txt',
        'route_template' => base_path('Modules/Asgardgenerators/templates') . DIRECTORY_SEPARATOR . 'route-resource.txt',
        'output_path' => app_path('Http/Controllers'),
    ],
    // translations
    'translations' => [
        'template' => base_path('Modules/Asgardgenerators/templates') . DIRECTORY_SEPARATOR . 'translation.txt',
        'output_path' => base_path('resource/lang/en'),
    ],
];


text:
package advancedhud.client.huditems;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;

import org.lwjgl.opengl.GL11;

import advancedhud.api.Alignment;
import advancedhud.api.HUDRegistry;
import advancedhud.api.HudItem;
import advancedhud.api.RenderAssist;
import advancedhud.client.ui.GuiAdvancedHUDConfiguration;
import advancedhud.client.ui.GuiScreenHudItem;
import advancedhud.client.ui.GuiScreenReposition;

public class HudItemJumpBar extends HudItem {

    @Override
    public String getName() {
        return "jumpbar";
    }

    @Override
    public String getButtonLabel() {
        return "JUMPBAR";
    }

    @Override
    public Alignment getDefaultAlignment() {
        return Alignment.BOTTOMCENTER;
    }

    @Override
    public int getDefaultPosX() {
        return HUDRegistry.screenWidth / 2 - 91;
    }

    @Override
    public int getDefaultPosY() {
        return HUDRegistry.screenHeight - 29;
    }

    @Override
    public int getWidth() {
        return 182;
    }

    @Override
    public int getHeight() {
        return 4;
    }

    @Override
    public int getDefaultID() {
        return 9;
    }

    @Override
    public void render(float paramFloat) {
        Minecraft mc = Minecraft.getMinecraft();
        GL11.glPushMatrix();
        GL11.glEnable(GL11.GL_BLEND);
        RenderAssist.bindTexture(Gui.icons);
        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);

        float charge = mc.thePlayer.getHorseJumpPower();
        final int barWidth = 182;
        int x = posX;
        int filled = (int) (charge * (barWidth + 1));
        int top = posY;

        RenderAssist.drawTexturedModalRect(x, top, 0, 84, barWidth, 5);

        if ((mc.currentScreen instanceof GuiAdvancedHUDConfiguration || mc.currentScreen instanceof GuiScreenReposition) && filled == 0) {
            filled = 182;
        }

        if (filled > 0) {
            RenderAssist.drawTexturedModalRect(x, top, 0, 89, filled, 5);
        }
        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        GL11.glDisable(GL11.GL_BLEND);
        GL11.glPopMatrix();
    }

    @Override
    public boolean shouldDrawOnMount() {
        return true;
    }

    @Override
    public boolean shouldDrawAsPlayer() {
        return false;
    }

    @Override
    public GuiScreen getConfigScreen() {
        return new GuiScreenHudItem(Minecraft.getMinecraft().currentScreen, this);
    }

}


text:
<?php

namespace PHP\BitTorrent\Tracker\Event;

use PHP\BitTorrent\Tracker\Request\RequestInterface as Request,
    PHP\BitTorrent\Tracker\Response\ResponseInterface as Response,
    PHP\BitTorrent\Tracker\Backend\BackendInterface as Backend;

/**
 * Tracker event
 *
 * @package Event
 * @author Christer Edvartsen <cogo@starzinger.net>
 */
class Event implements EventInterface {
    /**
     * Name of the event
     *
     * @var string
     */
    private $name;

    /**
     * Request instance
     *
     * @var Request
     */
    private $request;

    /**
     * Response instance
     *
     * @var Response
     */
    private $response;

    /**
     * Backend
     *
     * @var Backend
     */
    private $backend;

    /**
     * Event manager
     *
     * @var Manager
     */
    private $manager;

    /**
     * Propagation flag
     *
     * @var boolean
     */
    private $propagationIsStopped = false;

    /**
     * Class constructor
     *
     * @param string $name Name of the event
     * @param Request $request Request instance
     * @param Response $response Response instance
     * @param Backend $backend The current backend
     * @param Manager $manager The event manager
     */
    public function __construct($name, Request $request, Response $response, Backend $backend, Manager $manager) {
        $this->name = $name;
        $this->request = $request;
        $this->response = $response;
        $this->backend = $backend;
        $this->manager = $manager;
    }

    /**
     * {@inheritdoc}
     */
    public function getName() {
        return $this->name;
    }

    /**
     * {@inheritdoc}
     */
    public function getRequest() {
        return $this->request;
    }

    /**
     * {@inheritdoc}
     */
    public function getResponse() {
        return $this->response;
    }

    /**
     * {@inheritdoc}
     */
    public function getBackend() {
        return $this->backend;
    }

    /**
     * {@inheritdoc}
     */
    public function getManager() {
        return $this->manager;
    }

    /**
     * {@inheritdoc}
     */
    public function stopPropagation($flag) {
        $this->propagationIsStopped = $flag;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function propagationIsStopped() {
        return $this->propagationIsStopped;
    }
}


text:
package matgm50.twarden.lib;

/**
 * Created by MasterAbdoTGM50 on 5/11/2014.
 */

public class ModLib {

    public static final String ID = "TWarden";
    public static final String NAME = "Thaumic Warden";
    public static final String VERSION = "1.1.1";
    public static final String DEPENDENCIES = "required-after:Thaumcraft";

    public static final String CLIENTPROXY = "matgm50.twarden.proxy.ClientProxy";
    public static final String COMMONPROXY = "matgm50.twarden.proxy.CommonProxy";

}


text:
package k8ssdk

import brightbox "k8s.io/autoscaler/cluster-autoscaler/cloudprovider/brightbox/gobrightbox"

// CloudAccess is an abstraction over the Brightbox API to allow testing
type CloudAccess interface {
	//Fetch a server
	Server(identifier string) (*brightbox.Server, error)

	//creates a new server
	CreateServer(newServer *brightbox.ServerOptions) (*brightbox.Server, error)

	//Fetch a list of LoadBalancers
	LoadBalancers() ([]brightbox.LoadBalancer, error)

	//Retrieves a detailed view of one load balancer
	LoadBalancer(identifier string) (*brightbox.LoadBalancer, error)

	//Creates a new load balancer
	CreateLoadBalancer(newDetails *brightbox.LoadBalancerOptions) (*brightbox.LoadBalancer, error)

	//Updates an existing load balancer
	UpdateLoadBalancer(newDetails *brightbox.LoadBalancerOptions) (*brightbox.LoadBalancer, error)

	//Retrieves a list of all cloud IPs
	CloudIPs() ([]brightbox.CloudIP, error)

	//retrieves a detailed view of one cloud ip
	CloudIP(identifier string) (*brightbox.CloudIP, error)

	//Issues a request to map the cloud ip to the destination
	MapCloudIP(identifier string, destination string) error

	//UnMapCloudIP issues a request to unmap the cloud ip
	UnMapCloudIP(identifier string) error

	//Creates a new Cloud IP
	CreateCloudIP(newCloudIP *brightbox.CloudIPOptions) (*brightbox.CloudIP, error)
	//adds servers to an existing server group
	AddServersToServerGroup(identifier string, serverIds []string) (*brightbox.ServerGroup, error)

	//removes servers from an existing server group
	RemoveServersFromServerGroup(identifier string, serverIds []string) (*brightbox.ServerGroup, error)

	// ServerGroups retrieves a list of all server groups
	ServerGroups() ([]brightbox.ServerGroup, error)

	//Fetch a server group
	ServerGroup(identifier string) (*brightbox.ServerGroup, error)

	//creates a new server group
	CreateServerGroup(newServerGroup *brightbox.ServerGroupOptions) (*brightbox.ServerGroup, error)

	//creates a new firewall policy
	CreateFirewallPolicy(policyOptions *brightbox.FirewallPolicyOptions) (*brightbox.FirewallPolicy, error)

	//creates a new firewall rule
	CreateFirewallRule(ruleOptions *brightbox.FirewallRuleOptions) (*brightbox.FirewallRule, error)

	//updates an existing firewall rule
	UpdateFirewallRule(ruleOptions *brightbox.FirewallRuleOptions) (*brightbox.FirewallRule, error)

	//retrieves a list of all firewall policies
	FirewallPolicies() ([]brightbox.FirewallPolicy, error)

	// DestroyServer destroys an existing server
	DestroyServer(identifier string) error

	// DestroyServerGroup destroys an existing server group
	DestroyServerGroup(identifier string) error

	// DestroyFirewallPolicy issues a request to destroy the firewall policy
	DestroyFirewallPolicy(identifier string) error

	// DestroyLoadBalancer issues a request to destroy the load balancer
	DestroyLoadBalancer(identifier string) error

	// DestroyCloudIP issues a request to destroy the cloud ip
	DestroyCloudIP(identifier string) error

	// ConfigMaps retrieves a list of all config maps
	ConfigMaps() ([]brightbox.ConfigMap, error)

	// ConfigMap retrieves a detailed view on one config map
	ConfigMap(identifier string) (*brightbox.ConfigMap, error)

	// ServerTypes retrieves a list of all server types
	ServerTypes() ([]brightbox.ServerType, error)

	// ServerType retrieves a detailed view on one server type
	ServerType(identifier string) (*brightbox.ServerType, error)
}


text:
"""
Single Bubble Model:  Droplet simulations
=========================================

Use the ``TAMOC`` `single_bubble_model` to simulate the trajectory of a light
oil droplet rising through the water column. This script demonstrates the
typical steps involved in running the single bubble model.

It uses the ambient data stored in the file `../test/output/test_bm54.nc`,
created by the `test_ambient` module.  Please make sure all tests have
passed before running this script or modify the script to use a different
source of ambient data.

"""
# S. Socolofsky, July 2013, Texas A&M University <socolofs@tamu.edu>.

from __future__ import (absolute_import, division, print_function)

from tamoc import ambient
from tamoc import dbm
from tamoc import seawater
from tamoc import single_bubble_model

import numpy as np

if __name__ == '__main__':

    # Open an ambient profile object from the netCDF dataset
    nc = '../../test/output/test_bm54.nc'
    bm54 = ambient.Profile(nc, chem_names='all')
    bm54.close_nc()

    # Initialize a single_bubble_model.Model object with this data
    sbm = single_bubble_model.Model(bm54)

    # Create a light oil droplet particle to track
    composition = ['benzene', 'toluene', 'ethylbenzene']
    drop = dbm.FluidParticle(composition, fp_type=1.)

    # Set the mole fractions of each component at release.
    mol_frac = np.array([0.4, 0.3, 0.3])

    # Specify the remaining particle initial conditions
    de = 0.02
    z0 = 1000.
    T0 = 273.15 + 30.

    # Simulate the trajectory through the water column and plot the results
    sbm.simulate(drop, z0, de, mol_frac, T0, K_T=1, fdis=1e-8, delta_t=10.)
    sbm.post_process()

    # Save the simulation to a netCDF file
    sbm.save_sim('./drop.nc', '../../test/output/test_bm54.nc',
                 'Results of ./drops.py script')

    # Save the data for importing into Matlab
    sbm.save_txt('./drop.txt', '../../test/output/test_bm54.nc',
                 'Results of ./drops.py script')


text:
/* global _groundDbConstructor:true */
/*

TODO:
  `Meteor.default_server` - `Meteor.server`

*/
///////////////////////////////// TEST SCOPE ///////////////////////////////////

Meteor.server = Meteor.server || Meteor.default_server; // jshint ignore:line

//////////////////////////////// GROUND DATABASE ///////////////////////////////

_groundDbConstructor = function(collection, options) { // jshint ignore:line
  var self;
  // XXX: Write the grounddb constructor

  // // This is the basic interface allowing users easily access for handling
  // // method calls, this.super() is the super and this.collection is self
  // // TODO: Remove this section to the README
  // self.conflictHandlers = (options && options.conflictHandlers)?
  //       options.conflictHandlers: {
  //   'insert': function(doc) {
  //     //console.log('insert');
  //     //console.log(doc);
  //     this.super(doc);
  //   },
  //   'update': function(id, modifier) {
  //     //console.log('update');
  //     //console.log(id);
  //     //console.log(modifier);
  //     this.super(id, modifier);
  //   },
  //   'remove': function(id) {
  //     //console.log('remove');
  //     //console.log(id);
  //     this.super(id);
  //   }
  // };

  // // Create overwrite interface
  // _.each(['insert', 'update', 'remove'], function(name) {
  //   // TODO: init default conflict handlers
  //   //self.conflictHandlers[name] = function() {
  //   //  this.super.apply(this, arguments);
  //   //};

  //   // Save super
  //   var _super = Meteor.default_server.method_handlers['/'+self.name+'/'+name];
  //   // Overwrite
  //   Meteor.default_server.method_handlers['/'+self.name+'/'+name] = function() {
  //     var _this = this;
  //     _this.collection = self;
  //     _this.super = _super;
  //     // Call the conflicthandlers
  //     self.conflictHandlers[name].apply(_this, arguments);
  //   };
  // });

  return self;
};

// Global helper for applying grounddb on a collection
Ground.Collection = function(name, options) {
  var self;
  // Inheritance Meteor Collection can be set by options.collection
  // Accepts smart collections by Arunoda Susiripala
  // Check if user used the "new" keyword

  // Make sure we got some options
  options = options || {};

  // Either name is a Meteor collection or we create a new Meteor collection
  if (name instanceof _groundUtil.Collection) {
    self = name;
  } else {
    self = new _groundUtil.Collection(name, options);
  }

  // Throw an error if something went wrong
  if (!(self instanceof _groundUtil.Collection)) {
    throw new Error('Ground.Collection expected a Mongo.Collection');
  }

  // Add grounddb to the collection, circular reference since self is
  // grounddb.collection
  self.grounddb = new _groundDbConstructor(self, options);

  // Return grounded collection - We dont return this eg if it was an instance
  // of Ground.Collection
  return self;
};

////////////////////////// TIMESTAMP CONFLICTHANDLER ///////////////////////////

// TODO:
// When clients make changes the server should track the documents from the
// clients to see if the changes are new or old changes.
// This could be done in several ways.
// Either by versions or server timestamps - both could work.
//
// Conflicting overview:
// We could cut it down to comparing two documents and keep / broadcast the
// winning document.
//
// conflictHandler = function(clientDoc, serverDoc) { return serverDoc; }
//
//
// There should be found a way of registrating deleted documents - eg. by having
// a flag set 'active' all nonactive documents should then be removed from
// published documents.
//
// This could be a standalone package since it would introduce conflict
// handling in generel
//
// Regz. RaiX


text:
package org.lpw.tephra.ctrl.template.string;

import org.lpw.tephra.ctrl.Failure;
import org.lpw.tephra.ctrl.template.TemplateSupport;
import org.lpw.tephra.ctrl.template.Templates;
import org.lpw.tephra.util.Context;
import org.lpw.tephra.util.Message;
import org.springframework.stereotype.Controller;

import javax.inject.Inject;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author lpw
 */
@Controller("tephra.ctrl.template.string")
public class TemplateImpl extends TemplateSupport {
    @Inject
    private Context context;
    @Inject
    private Message message;

    @Override
    public String getType() {
        return Templates.STRING;
    }

    @Override
    public String getContentType() {
        return "text/plain";
    }

    @Override
    public void process(String name, Object data, OutputStream outputStream) throws IOException {
        if (data instanceof Failure) {
            Failure failure = (Failure) data;
            write(getFailureCode(failure) + ":" + message.get(failure.getMessageKey()), outputStream);

            return;
        }

        write(data, outputStream);
    }

    private void write(Object data, OutputStream outputStream) throws IOException {
        outputStream.write(data.toString().getBytes(context.getCharset(null)));
    }
}


text:
/// <reference path="../RisingTideApp.ts" />
/// <reference path='../../typings/angularjs/angular.d.ts'/>
/// <reference path='../../typings/angularjs/angular-resource.d.ts'/>

class AzureNetLoginService implements ILoginService {
    static serviceId: string = "LoginService";
    client;
    isSignedIn: boolean = false;

    constructor(private $timeout: ng.ITimeoutService, private dataService: IDataService) {
    }

    loginWithMicrosoft(successCallback: Function) {
        this.client = new WindowsAzure.MobileServiceClient('https://risingtide-testnet.azure-mobile.net/', '0000000044112CA5');
        this.dataService.client = this.client;
        this.client.login("microsoftaccount").then(() => {
            this.isSignedIn = true;
            this.$timeout(() => {
                successCallback(this.client.currentUser.userId)
                });
        }, (error) => {
                console.error(error);
            });
    }

    loginWithGoogle(successCallback: Function) {
        this.client = new WindowsAzure.MobileServiceClient('https://risingtide-testnet.azure-mobile.net/', '642356303291.apps.googleusercontent.com');
        this.dataService.client = this.client;
        this.client.login("google").then(() => {
            this.isSignedIn = true;
            this.$timeout(() => {
                successCallback(this.client.currentUser.userId)
                });
        }, (error) => {
                console.error(error);
            });
    }
}

RisingTideApp.factory(AzureNetLoginService.serviceId, ['$timeout', 'DataService', ($timeout, dataService) =>
    new AzureNetLoginService($timeout, dataService)
]);


text:
package trace

import "time"

// Types of events recorded during the trace.
const (
	UnknownEvent = iota
	CountEvent
	SetEvent
	RecordEvent
	LogEvent
	StartEvent
	EnterEvent
	LeaveEvent
)

// Event contains the data gathered for a single event during a trace.
type Event struct {
	// From contains the index of the parent span.
	From int64
	// Kind contains the type of event.
	Kind int
	// When indicates when this event was recorded relative to the beginning of the trace.
	When time.Duration
	// What contains the name of the event.
	What string
	// Path is filled so that children can use it as a prefix to build their name.
	Path string
	// Data contains whatever relevant data is needed for this event.
	Data interface{}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _range2 = require('lodash/range');

var _range3 = _interopRequireDefault(_range2);

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _class, _class2, _temp2; /**
                              * @fileOverview Radar Bar Chart
                              */

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _d3Scale = require('d3-scale');

var _Surface = require('../container/Surface');

var _Surface2 = _interopRequireDefault(_Surface);

var _RadialBar = require('../polar/RadialBar');

var _RadialBar2 = _interopRequireDefault(_RadialBar);

var _DataUtils = require('../util/DataUtils');

var _Cell = require('../component/Cell');

var _Cell2 = _interopRequireDefault(_Cell);

var _Legend = require('../component/Legend');

var _Legend2 = _interopRequireDefault(_Legend);

var _Tooltip = require('../component/Tooltip');

var _Tooltip2 = _interopRequireDefault(_Tooltip);

var _ReactUtils = require('../util/ReactUtils');

var _PolarUtils = require('../util/PolarUtils');

var _PureRender = require('../util/PureRender');

var _PureRender2 = _interopRequireDefault(_PureRender);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var RadialBarChart = (0, _PureRender2.default)(_class = (_temp2 = _class2 = function (_Component) {
  _inherits(RadialBarChart, _Component);

  function RadialBarChart() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, RadialBarChart);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = RadialBarChart.__proto__ || Object.getPrototypeOf(RadialBarChart)).call.apply(_ref, [this].concat(args))), _this), _this.state = _this.createDefaultState(), _this.handleMouseEnter = function (el) {
      var children = _this.props.children;
      var cx = el.cx,
          cy = el.cy,
          endAngle = el.endAngle,
          outerRadius = el.outerRadius;

      var tooltipItem = (0, _ReactUtils.findChildByType)(children, _Tooltip2.default);

      if (tooltipItem) {
        _this.setState({
          isTooltipActive: true,
          activeTooltipCoord: (0, _PolarUtils.polarToCartesian)(cx, cy, outerRadius, endAngle),
          activeTooltipPayload: [el.payload]
        });
      }
    }, _this.handleMouseLeave = function () {
      var children = _this.props.children;

      var tooltipItem = (0, _ReactUtils.findChildByType)(children, _Tooltip2.default);

      if (tooltipItem) {
        _this.setState({
          isTooltipActive: false
        });
      }
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(RadialBarChart, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (nextProps.data !== this.props.data) {
        this.setState(this.createDefaultState());
      }
    }
    /**
     * Compose the data of each group
     * @param  {Object} item        An instance of RadialBar
     * @param  {Array}  barPosition The offset and size of each bar
     * @param  {Object} radiusScale The scale function of radius of bars
     * @param  {Object} center      The coordinate of center
     * @param  {String} dataKey     The unique key of a group
     * @return {Array}              Composed data
     */

  }, {
    key: 'getComposedData',
    value: function getComposedData(item, barPosition, radiusScale, center, dataKey) {
      var data = this.props.data;

      var pos = barPosition[dataKey];
      var cells = (0, _ReactUtils.findAllByType)(item.props.children, _Cell2.default);

      return data.map(function (entry, index) {
        var value = entry[dataKey];
        var radius = radiusScale(index);

        return _extends({}, entry, center, {
          value: value,
          innerRadius: radius - pos.offset,
          outerRadius: radius - pos.offset + pos.radius,
          payload: entry
        }, cells && cells[index] && cells[index].props);
      });
    }
    /**
     * Calculate the size of all groups
     * @param  {Array} items All the instance of RadialBar
     * @return {Object} The size of all groups
     */

  }, {
    key: 'getRadiusList',
    value: function getRadiusList(items) {
      var barSize = this.props.barSize;

      return items.map(function (child) {
        return _extends({}, child.props, {
          barSize: child.props.barSize || barSize
        });
      });
    }

    /**
     * Calculate the scale function of radius
     * @param {Number} innerRadius The outer radius
     * @param {Number} outerRadius The inner radius
     * @return {Object}            A scale function
     */

  }, {
    key: 'getRadiusScale',
    value: function getRadiusScale(innerRadius, outerRadius) {
      var data = this.props.data;

      var bandCount = Math.max(data.length, 1);
      var range = [outerRadius, innerRadius];
      var scale = (0, _d3Scale.scaleBand)().domain((0, _range3.default)(0, bandCount)).range(range);

      return scale;
    }

    /**
     * Calculate the size of each bar and the gap between two bars
     * @param  {Number} bandRadius  The radius of each category
     * @param  {Array} radiusList   The radius of all groups
     * @return {Number} The size of each bar and the gap between two bars
     */

  }, {
    key: 'getBarPosition',
    value: function getBarPosition(bandRadius, radiusList) {
      var _props = this.props,
          barGap = _props.barGap,
          barCategoryGap = _props.barCategoryGap;

      var len = radiusList.length;
      var result = void 0;

      // whether or not is barSize setted by user
      if (len && radiusList[0].barSize === +radiusList[0].barSize) {
        (function () {
          var sum = radiusList.reduce(function (res, entry) {
            return res + entry.barSize;
          }, 0);
          sum += (len - 1) * barGap;
          var offset = -sum / 2 >> 0;
          var prev = { offset: offset - barGap, radius: 0 };

          result = radiusList.reduce(function (res, entry) {
            prev = {
              offset: prev.offset + prev.radius + barGap,
              radius: entry.barSize
            };

            return _extends({}, res, _defineProperty({}, entry.dataKey, prev));
          }, {});
        })();
      } else {
        (function () {
          var offset = (0, _DataUtils.getPercentValue)(barCategoryGap, bandRadius);
          var radius = (bandRadius - 2 * offset - (len - 1) * barGap) / len >> 0;
          offset = -Math.max((radius * len + (len - 1) * barGap) / 2 >> 0, 0);

          result = radiusList.reduce(function (res, entry, i) {
            return _extends({}, res, _defineProperty({}, entry.dataKey, {
              offset: offset + (radius + barGap) * i,
              radius: radius
            }));
          }, {});
        })();
      }

      return result;
    }
    /**
     * Returns default, reset state for the radial bar chart.
     * @return {Object} Whole new state
     */

  }, {
    key: 'createDefaultState',
    value: function createDefaultState() {
      return {
        activeTooltipLabel: '',
        activeTooltipPayload: [],
        activeTooltipCoord: { x: 0, y: 0 },
        isTooltipActive: false
      };
    }
  }, {
    key: 'renderLegend',

    /**
     * Draw legend
     * @param  {ReactElement} legendItem The instance of Legend
     * @return {ReactElement}            The instance of Legend
     */
    value: function renderLegend() {
      var children = this.props.children;

      var legendItem = (0, _ReactUtils.findChildByType)(children, _Legend2.default);
      if (!legendItem) {
        return null;
      }

      var _props2 = this.props,
          data = _props2.data,
          width = _props2.width,
          height = _props2.height,
          margin = _props2.margin;

      var legendData = legendItem.props && legendItem.props.payload || data.map(function (entry) {
        return {
          type: 'square',
          color: entry.fill || '#000',
          value: entry.name,
          payload: entry
        };
      });

      return _react2.default.cloneElement(legendItem, _extends({}, _Legend2.default.getWithHeight(legendItem, width), {
        payload: legendData,
        chartWidth: width,
        chartHeight: height,
        margin: margin
      }));
    }
  }, {
    key: 'renderTooltip',
    value: function renderTooltip() {
      var children = this.props.children;

      var tooltipItem = (0, _ReactUtils.findChildByType)(children, _Tooltip2.default);

      if (!tooltipItem) {
        return null;
      }

      var _props3 = this.props,
          width = _props3.width,
          height = _props3.height;
      var _state = this.state,
          isTooltipActive = _state.isTooltipActive,
          activeTooltipLabel = _state.activeTooltipLabel,
          activeTooltipCoord = _state.activeTooltipCoord,
          activeTooltipPayload = _state.activeTooltipPayload;

      var viewBox = { x: 0, y: 0, width: width, height: height };

      return _react2.default.cloneElement(tooltipItem, {
        viewBox: viewBox,
        active: isTooltipActive,
        label: activeTooltipLabel,
        payload: activeTooltipPayload,
        coordinate: activeTooltipCoord
      });
    }

    /**
     * Draw the main part of bar chart
     * @param  {Array} items     All the instance of RadialBar
     * @param  {Object} radiusScale The scale function of radius of bars
     * @param  {Object} center      The coordinate of center
     * @return {ReactComponent}  All the instances of RadialBar
     */

  }, {
    key: 'renderItems',
    value: function renderItems(items, radiusScale, center) {
      var _this2 = this;

      if (!items || !items.length) {
        return null;
      }

      var _props4 = this.props,
          onMouseEnter = _props4.onMouseEnter,
          onMouseLeave = _props4.onMouseLeave,
          onClick = _props4.onClick;

      var radiusList = this.getRadiusList(items);
      var bandRadius = radiusScale.bandwidth();
      var barPosition = this.getBarPosition(bandRadius, radiusList);

      return items.map(function (child, i) {
        var _child$props = child.props,
            dataKey = _child$props.dataKey,
            childOnMouseEnter = _child$props.onMouseEnter,
            childOnMouseLeave = _child$props.onMouseLeave,
            childOnClick = _child$props.onClick;

        return _react2.default.cloneElement(child, _extends({}, center, {
          key: 'radial-bar-' + i,
          onMouseEnter: (0, _DataUtils.combineEventHandlers)(_this2.handleMouseEnter, onMouseEnter, childOnMouseEnter),
          onMouseLeave: (0, _DataUtils.combineEventHandlers)(_this2.handleMouseLeave, onMouseLeave, childOnMouseLeave),
          onClick: (0, _DataUtils.combineEventHandlers)(null, onClick, childOnClick),
          data: _this2.getComposedData(child, barPosition, radiusScale, center, dataKey)
        }));
      }, this);
    }
  }, {
    key: 'render',
    value: function render() {
      var data = this.props.data;

      if (!(0, _ReactUtils.validateWidthHeight)(this) || !data || !data.length) {
        return null;
      }

      var _props5 = this.props,
          style = _props5.style,
          children = _props5.children,
          className = _props5.className,
          width = _props5.width,
          height = _props5.height,
          margin = _props5.margin,
          others = _objectWithoutProperties(_props5, ['style', 'children', 'className', 'width', 'height', 'margin']);

      var items = (0, _ReactUtils.findAllByType)(children, _RadialBar2.default);
      var cx = (0, _DataUtils.getPercentValue)(this.props.cx, width, width / 2);
      var cy = (0, _DataUtils.getPercentValue)(this.props.cy, height, height / 2);
      var maxRadius = (0, _PolarUtils.getMaxRadius)(width, height, margin);
      var innerRadius = (0, _DataUtils.getPercentValue)(this.props.innerRadius, maxRadius, 0);
      var outerRadius = (0, _DataUtils.getPercentValue)(this.props.outerRadius, maxRadius, maxRadius * 0.8);
      var radiusScale = this.getRadiusScale(innerRadius, outerRadius);
      var attrs = (0, _ReactUtils.getPresentationAttributes)(others);

      return _react2.default.createElement(
        'div',
        {
          className: (0, _classnames2.default)('recharts-wrapper', className),
          style: _extends({}, style, { cursor: 'default', position: 'relative', width: width, height: height })
        },
        _react2.default.createElement(
          _Surface2.default,
          _extends({}, attrs, { width: width, height: height }),
          this.renderItems(items, radiusScale, { cx: cx, cy: cy }),
          (0, _ReactUtils.filterSvgElements)(children)
        ),
        this.renderLegend(),
        this.renderTooltip(items)
      );
    }
  }]);

  return RadialBarChart;
}(_react.Component), _class2.displayName = 'RadialBarChart', _class2.propTypes = {
  width: _react.PropTypes.number,
  height: _react.PropTypes.number,
  margin: _react.PropTypes.shape({
    top: _react.PropTypes.number,
    right: _react.PropTypes.number,
    bottom: _react.PropTypes.number,
    left: _react.PropTypes.number
  }),
  cy: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]),
  cx: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]),

  data: _react.PropTypes.array,
  innerRadius: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]),
  outerRadius: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]),
  // The offset radius between two categorys
  barCategoryGap: _react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.string]),
  // The gap radius of two radial bar in one category
  barGap: _react.PropTypes.number,
  // The radius of each radial bar
  barSize: _react.PropTypes.number,
  title: _react.PropTypes.string,
  style: _react.PropTypes.object,
  onMouseEnter: _react.PropTypes.func,
  onMouseLeave: _react.PropTypes.func,
  onClick: _react.PropTypes.func,
  children: _react.PropTypes.oneOfType([_react.PropTypes.arrayOf(_react.PropTypes.node), _react.PropTypes.node]),
  className: _react.PropTypes.string
}, _class2.defaultProps = {
  cx: '50%',
  cy: '50%',
  innerRadius: '30%',
  outerRadius: '90%',
  barGap: 2,
  barCategoryGap: '10%',
  style: {},
  margin: { top: 0, right: 0, bottom: 0, left: 0 }
}, _temp2)) || _class;

exports.default = RadialBarChart;


text:
package nl.coenvl.sam.messages;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Message
 *
 * @author leeuwencjv
 * @version 0.1
 * @since 4 feb. 2014
 *
 */
public final class HashMessage implements Message {

    private static final StringSerializer serializer = new StringSerializer();
    private final String type;
    private final UUID source;

    private final Map<String, String> valueMap;

    public HashMessage(final UUID source, final String type) {
        super();
        this.source = source;
        this.type = type;
        this.valueMap = new HashMap<>();
    }

    @Override
    public void put(final String key, final Object value) {
        if (value != null) {
            this.valueMap.put(key, HashMessage.serializer.serialize(value));
        }
    }

    @Override
    public UUID getSource() {
        return this.source;
    }

    @Override
    public Object get(final String key) {
        if (!this.valueMap.containsKey(key)) {
            return null;
        }
        return HashMessage.serializer.deserialize(this.valueMap.get(key));
    }

    @Override
    public HashMessage clone() {
        final HashMessage clone = new HashMessage(this.source, this.type);
        clone.valueMap.putAll(this.valueMap);
        return clone;
    }

    @Override
    public String getType() {
        return this.type;
    }

    @Override
    public long messageSize() {
        return 0L;
    }

    @Override
    public String toString() {
        return "Message of Type " + this.type + "(" + super.toString() + ")";
    }

    /*
     * (non-Javadoc)
     *
     * @see nl.coenvl.sam.messages.Message#containsKey()
     */
    @Override
    public boolean containsKey(final String key) {
        return this.valueMap.containsKey(key);
    }

}


text:
import * as React from 'react';
import { visualize, story, snap } from 'storybook-snapper';
// import { TPAComponentsProvider } from '../TPAComponentsConfig';
import { {%ComponentName%} } from './';

visualize('{%ComponentName%}', () => {
  story('simple', () => {
    snap('default props', <{%ComponentName%} />);
    snap('custom buttonText', <{%ComponentName%} buttonText={'Some custom text'} />);
    // snap('mobile', (
    //   <TPAComponentsProvider value={{mobile: true}}>
    //     <{%ComponentName%} buttonText={'Some custom text'} />
    //   </TPAComponentsProvider>
    // ));
    // snap('rtl', (
    //   <TPAComponentsProvider value={{rtl: true}}>
    //     <{%ComponentName%} buttonText={'Some custom text'} />
    //   </TPAComponentsProvider>
    // ));
  });
});


text:
package docker

import (
	"crypto/tls"
	"crypto/x509"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"
	"runtime"
	"testing"

	dockerapi "github.com/docker/docker/api"
	"github.com/openshift/source-to-image/pkg/api"
	"github.com/openshift/source-to-image/pkg/docker"
)

const (
	tcpListener  = "127.0.0.1:8080"
	tlsListener  = "127.0.0.1:8443"
	unixListener = "/tmp/test.sock"
)

var serverCert tls.Certificate
var caPool *x509.CertPool

func init() {
	var err error
	serverCert, err = tls.LoadX509KeyPair("../testdata/127.0.0.1.crt", "../testdata/127.0.0.1.key")
	if err != nil {
		panic(err)
	}

	ca, err := ioutil.ReadFile("../testdata/ca.crt")
	if err != nil {
		panic(err)
	}

	caPool = x509.NewCertPool()
	caPool.AppendCertsFromPEM(ca)

	log.SetOutput(ioutil.Discard)
}

type Server struct {
	l net.Listener
	c chan struct{}
}

func (s *Server) Close() {
	s.l.Close()
	<-s.c
}

func (s *Server) serveFakeDockerAPIServer() {
	mux := http.NewServeMux()
	mux.HandleFunc("/v"+dockerapi.DefaultVersion+"/version", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Add("Content-Type", "application/json")
		w.Write([]byte("{}"))
	})
	hs := http.Server{Handler: mux}
	// Disable keepalives in order to prevent an explosion in the number of
	// goroutines that makes stack traces noisy.  TODO: when using Go 1.8,
	// http.Server.Shutdown() should do this for us.
	hs.SetKeepAlivesEnabled(false)
	hs.Serve(s.l)
	s.c <- struct{}{}
}

func serveTLS(t *testing.T, config *tls.Config) *Server {
	config.Certificates = []tls.Certificate{serverCert}

	l, err := tls.Listen("tcp", tlsListener, config)
	if err != nil {
		t.Fatal(err)
	}

	s := &Server{l: l, c: make(chan struct{})}
	go s.serveFakeDockerAPIServer()

	return s
}

func serveTCP(t *testing.T) *Server {
	l, err := net.Listen("tcp", tcpListener)
	if err != nil {
		t.Fatal(err)
	}

	s := &Server{l: l, c: make(chan struct{})}
	go s.serveFakeDockerAPIServer()

	return s
}

func serveUNIX(t *testing.T) *Server {
	os.Remove(unixListener)

	l, err := net.Listen("unix", unixListener)
	if err != nil {
		t.Fatal(err)
	}

	s := &Server{l: l, c: make(chan struct{})}
	go s.serveFakeDockerAPIServer()

	return s
}

func runTest(t *testing.T, config *api.DockerConfig, expectedSuccess bool) {
	client, err := docker.NewEngineAPIClient(config)
	if err != nil {
		if expectedSuccess {
			t.Errorf("with DockerConfig %+v, expected success %v, got error %v", config, expectedSuccess, err)
		}
		return
	}
	d := docker.New(client, api.AuthConfig{})
	err = d.CheckReachable()
	if (err == nil) != expectedSuccess {
		t.Errorf("with DockerConfig %+v, expected success %v, got error %v", config, expectedSuccess, err)
	}
}

func TestTCP(t *testing.T) {
	s := serveTCP(t)
	defer s.Close()

	dc := &api.DockerConfig{Endpoint: "tcp://" + tcpListener}

	for _, dc.UseTLS = range []bool{true, false} {
		for _, dc.TLSVerify = range []bool{true, false} {
			for _, dc.CAFile = range []string{"../testdata/ca.crt", "bad", ""} {
				for _, dc.CertFile = range []string{"../testdata/client.crt", "bad", ""} {
					for _, dc.KeyFile = range []string{"../testdata/client.key", "bad", ""} {
						runTest(t, dc, !dc.UseTLS && !dc.TLSVerify)
					}
				}
			}
		}
	}
}

func TestUNIX(t *testing.T) {
	if runtime.GOOS == "windows" {
		return
	}

	s := serveUNIX(t)
	defer s.Close()

	dc := &api.DockerConfig{Endpoint: "unix://" + unixListener}

	for _, dc.UseTLS = range []bool{true, false} {
		for _, dc.TLSVerify = range []bool{true, false} {
			for _, dc.CAFile = range []string{"../testdata/ca.crt", "bad", ""} {
				for _, dc.CertFile = range []string{"../testdata/client.crt", "bad", ""} {
					for _, dc.KeyFile = range []string{"../testdata/client.key", "bad", ""} {
						runTest(t, dc, !dc.UseTLS && !dc.TLSVerify)
					}
				}
			}
		}
	}
}

func TestSSL(t *testing.T) {
	s := serveTLS(t, &tls.Config{})
	defer s.Close()

	dc := &api.DockerConfig{Endpoint: "tcp://" + tlsListener}

	for _, dc.UseTLS = range []bool{true, false} {
		for _, dc.TLSVerify = range []bool{true, false} {
			for _, dc.CAFile = range []string{"../testdata/ca.crt", "bad", ""} {
				for _, dc.CertFile = range []string{"../testdata/client.crt", "bad", ""} {
					for _, dc.KeyFile = range []string{"../testdata/client.key", "bad", ""} {
						expected := dc.UseTLS && !dc.TLSVerify || dc.TLSVerify && dc.CAFile == "../testdata/ca.crt"

						if (dc.CertFile == "../testdata/client.crt") != (dc.KeyFile == "../testdata/client.key") {
							expected = false
						}

						runTest(t, dc, expected)
					}
				}
			}
		}
	}
}

func TestSSLClientCert(t *testing.T) {
	s := serveTLS(t, &tls.Config{
		ClientAuth: tls.RequireAndVerifyClientCert,
		ClientCAs:  caPool,
	})
	defer s.Close()

	dc := &api.DockerConfig{Endpoint: "tcp://" + tlsListener}

	for _, dc.UseTLS = range []bool{true, false} {
		for _, dc.TLSVerify = range []bool{true, false} {
			for _, dc.CAFile = range []string{"../testdata/ca.crt", "bad", ""} {
				for _, dc.CertFile = range []string{"../testdata/client.crt", "bad", ""} {
					for _, dc.KeyFile = range []string{"../testdata/client.key", "bad", ""} {
						expected := dc.UseTLS && !dc.TLSVerify || dc.TLSVerify && dc.CAFile == "../testdata/ca.crt"

						if dc.CertFile != "../testdata/client.crt" || dc.KeyFile != "../testdata/client.key" {
							expected = false
						}

						runTest(t, dc, expected)
					}
				}
			}
		}
	}
}


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Sync\V1\Service\SyncMap;

use Twilio\Deserialize;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;

/**
 * @property string $key
 * @property string $accountSid
 * @property string $serviceSid
 * @property string $mapSid
 * @property string $url
 * @property string $revision
 * @property array $data
 * @property \DateTime $dateExpires
 * @property \DateTime $dateCreated
 * @property \DateTime $dateUpdated
 * @property string $createdBy
 */
class SyncMapItemInstance extends InstanceResource {
    /**
     * Initialize the SyncMapItemInstance
     *
     * @param Version $version Version that contains the resource
     * @param mixed[] $payload The response payload
     * @param string $serviceSid The SID of the Sync Service that the resource is
     *                           associated with
     * @param string $mapSid The SID of the Sync Map that contains the Map Item
     * @param string $key The key value of the Sync Map Item resource to fetch
     */
    public function __construct(Version $version, array $payload, string $serviceSid, string $mapSid, string $key = null) {
        parent::__construct($version);

        // Marshaled Properties
        $this->properties = [
            'key' => Values::array_get($payload, 'key'),
            'accountSid' => Values::array_get($payload, 'account_sid'),
            'serviceSid' => Values::array_get($payload, 'service_sid'),
            'mapSid' => Values::array_get($payload, 'map_sid'),
            'url' => Values::array_get($payload, 'url'),
            'revision' => Values::array_get($payload, 'revision'),
            'data' => Values::array_get($payload, 'data'),
            'dateExpires' => Deserialize::dateTime(Values::array_get($payload, 'date_expires')),
            'dateCreated' => Deserialize::dateTime(Values::array_get($payload, 'date_created')),
            'dateUpdated' => Deserialize::dateTime(Values::array_get($payload, 'date_updated')),
            'createdBy' => Values::array_get($payload, 'created_by'),
        ];

        $this->solution = [
            'serviceSid' => $serviceSid,
            'mapSid' => $mapSid,
            'key' => $key ?: $this->properties['key'],
        ];
    }

    /**
     * Generate an instance context for the instance, the context is capable of
     * performing various actions.  All instance actions are proxied to the context
     *
     * @return SyncMapItemContext Context for this SyncMapItemInstance
     */
    protected function proxy(): SyncMapItemContext {
        if (!$this->context) {
            $this->context = new SyncMapItemContext(
                $this->version,
                $this->solution['serviceSid'],
                $this->solution['mapSid'],
                $this->solution['key']
            );
        }

        return $this->context;
    }

    /**
     * Fetch the SyncMapItemInstance
     *
     * @return SyncMapItemInstance Fetched SyncMapItemInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch(): SyncMapItemInstance {
        return $this->proxy()->fetch();
    }

    /**
     * Delete the SyncMapItemInstance
     *
     * @param array|Options $options Optional Arguments
     * @return bool True if delete succeeds, false otherwise
     * @throws TwilioException When an HTTP error occurs.
     */
    public function delete(array $options = []): bool {
        return $this->proxy()->delete($options);
    }

    /**
     * Update the SyncMapItemInstance
     *
     * @param array|Options $options Optional Arguments
     * @return SyncMapItemInstance Updated SyncMapItemInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function update(array $options = []): SyncMapItemInstance {
        return $this->proxy()->update($options);
    }

    /**
     * Magic getter to access properties
     *
     * @param string $name Property to access
     * @return mixed The requested property
     * @throws TwilioException For unknown properties
     */
    public function __get(string $name) {
        if (\array_key_exists($name, $this->properties)) {
            return $this->properties[$name];
        }

        if (\property_exists($this, '_' . $name)) {
            $method = 'get' . \ucfirst($name);
            return $this->$method();
        }

        throw new TwilioException('Unknown property: ' . $name);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        $context = [];
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Sync.V1.SyncMapItemInstance ' . \implode(' ', $context) . ']';
    }
}


text:
$(function() {
    // Datepicker
    $('.input-group.date').datepicker({
        format: 'dd/mm/yyyy',
        startView: 1,
        todayBtn: true,
        language: 'ru',
        autoclose: true
    });

    // Switchers for all users
    var radioGender = $('.radio1');
    var checkboxDriver = $('.checkbox2');
    radioGender.bootstrapSwitch();
    $('#checkbox1').bootstrapSwitch();
    checkboxDriver.bootstrapSwitch();

    radioGender.on('switch-change', function() {
        $('.radio1').bootstrapSwitch('toggleRadioState');
    });

    // Switcher for drivers
    $('#driverLicenseId').hide();
    $('#experience').hide();

    checkboxDriver.on('switch-change', function() {
        $('#driverLicenseId').slideToggle(200);
        $('#experience').slideToggle(200);
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".QrWearActivity"
    tools:deviceIds="wear_square">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/imgQrCode"
        android:layout_gravity="center_horizontal" />
</LinearLayout>


text:
jQuery(document).ready(function($) {
	var $messageRow = $('.message-row');

	$messageRow.on('click', function(e) {
		$this = $(this);
		var href = $this.attr('data-href');
		var messageId = $this.attr('data-message-id');

		if (messageId) {
			$.request('onClickMessageRow', {
		    	data: {
			    	messageId: messageId
			    },
		    	success: function(data) {
			    	this.success(data).done(function() {
				    	$messageRow.removeClass('unread');
				    	$this.addClass('unread');
			    	});
		    	}
		    });
		}

		if (href) {
			window.location = href;
		}
	});
});