text:
package graphql

import (
	"log"

	gql "github.com/graphql-go/graphql"
	"github.com/lucapette/deloominator/pkg/charts"
	"github.com/lucapette/deloominator/pkg/db"
	"github.com/lucapette/deloominator/pkg/db/storage"
)

type queryError struct {
	Message string `json:"message"`
}

type cell struct {
	Value string `json:"value"`
}

type row struct {
	Cells []cell `json:"cells"`
}

type column struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

type variable struct {
	Name           string `json:"name"`
	Value          string `json:"value"`
	IsControllable bool   `json:"isControllable"`
}

type results struct {
	Columns   []column   `json:"columns"`
	Rows      []row      `json:"rows"`
	ChartName string     `json:"chartName"`
	Variables []variable `json:"variables"`
}

type settings struct {
	IsReadOnly bool `json:"isReadOnly"`
}

type table struct {
	Name string `json:"name"`
}

type dataSource struct {
	Name   string   `json:"name"`
	Tables []*table `json:"tables"`
}

type payload struct {
	Query         string                 `json:"query"`
	OperationName string                 `json:"operationName,omitempty"`
	Variables     map[string]interface{} `json:"variables,omitempty"`
}

func convertToChartTypes(columns []db.Column) (types charts.DataTypes) {
	types = make(charts.DataTypes, len(columns))

	for i, col := range columns {
		switch col.Type {
		case db.Number:
			types[i] = charts.Number
		case db.Text:
			types[i] = charts.Text
		case db.Time:
			types[i] = charts.Time
		}
	}

	return types
}

func mutationRoot(s *storage.Storage) *gql.Object {
	fields := gql.Fields{
		"question": &gql.Field{
			Type: questionType,
			Args: gql.FieldConfigArgument{
				"title": &gql.ArgumentConfig{
					Type: gql.NewNonNull(gql.String),
				},
				"description": &gql.ArgumentConfig{
					Type: gql.String,
				},
				"query": &gql.ArgumentConfig{
					Type: gql.NewNonNull(gql.String),
				},
				"dataSource": &gql.ArgumentConfig{
					Type: gql.NewNonNull(gql.String),
				},
				"variables": &gql.ArgumentConfig{
					Type: gql.NewList(inputVariableType),
				},
			},
			Resolve: saveQuestion(s),
		},
	}
	return gql.NewObject(gql.ObjectConfig{Name: "Mutation", Fields: fields})
}

func queryRoot(dataSources db.DataSources, s *storage.Storage) *gql.Object {
	fields := gql.Fields{
		"settings": &gql.Field{
			Type:    settingsType,
			Resolve: resolveSettings(s),
		},
		"dataSources": &gql.Field{
			Type:    gql.NewList(dataSourceType),
			Resolve: resolveDataSources(dataSources),
		},
		"question": &gql.Field{
			Type: questionType,
			Args: gql.FieldConfigArgument{
				"id": &gql.ArgumentConfig{
					Type: gql.NewNonNull(gql.ID),
				},
			},
			Resolve: resolveQuestion(dataSources, s),
		},
		"questions": &gql.Field{
			Type:    gql.NewList(questionType),
			Resolve: resolveQuestions(dataSources, s),
		},
		"query": &gql.Field{
			Type: queryResultType,
			Args: gql.FieldConfigArgument{
				"dataSource": &gql.ArgumentConfig{
					Type: gql.NewNonNull(gql.String),
				},
				"query": &gql.ArgumentConfig{
					Type: gql.NewNonNull(gql.String),
				},
				"variables": &gql.ArgumentConfig{
					Type: gql.NewList(inputVariableType),
				},
			},
			Resolve: resolveQuery(dataSources),
		},
	}

	return gql.NewObject(gql.ObjectConfig{Name: "Query", Fields: fields})
}

func createSchema(dataSources db.DataSources, storage *storage.Storage) (schema gql.Schema) {
	schemaConfig := gql.SchemaConfig{
		Query:    queryRoot(dataSources, storage),
		Mutation: mutationRoot(storage),
	}

	schema, err := gql.NewSchema(schemaConfig)
	if err != nil {
		log.Fatalf("could not create gql schema: %v", err)
	}
	return schema
}


text:
using std::cout;

//Constructors
CoffeeShop::CoffeeShop(const char* name)
{
	SetName(name);
}

CoffeeShop::CoffeeShop(const CoffeeShop& otherCoffeeShop)
{
	this->name = new char[strlen(otherCoffeeShop.GetName()) + 1];
	strcpy(this->name, otherCoffeeShop.GetName());
}

CoffeeShop& CoffeeShop::operator= (const CoffeeShop& otherCoffeeShop)
{
	if (this != &otherCoffeeShop)
	{
		delete[] name;

		this->name = new char[strlen(otherCoffeeShop.GetName()) + 1];
		strcpy(this->name, otherCoffeeShop.GetName());
	}

	return *this;
}

CoffeeShop::~CoffeeShop()
{
	delete[] name;
}

//Checks if drinks is available
int CoffeeShop::IsDrinkAvailable(Drink& drink)
{
	int begin = 0,
		end = drinks.size();
	bool isFound = false;

	while (begin < end && !isFound)
	{
		if (drinks[begin] == drink)
		{
			isFound = true;
		}

		begin++;
	}

	if (isFound)
	{
		return begin;
	}

	return -1;
}

//Getter for Name
const char* CoffeeShop::GetName() const
{
	return this->name;
}

//Setter for Name
void CoffeeShop::SetName(const char* name)
{
	if (!name)
	{
		throw std::invalid_argument("CoffeShop name must not be null.");
	}

	this->name = new char[strlen(name) + 1];
	strcpy(this->name, name);
}

//AddDrink method
void CoffeeShop::AddDrink(Drink& drink)
{
	if (IsDrinkAvailable(drink) == -1)
	{
		this->drinks.push_back(drink);
	}
	else
	{
		cout << "Drink already added.";
	}
}

//Finds drink and prints it if it is availavle
void CoffeeShop::PrintDrinkIfFound(Drink& drink)
{
	int isAvailable = IsDrinkAvailable(drink);

	if (isAvailable != -1)
	{
		drinks[isAvailable].Print();
	}
	else
	{
		cout << "Drink not available.\n";
	}
}

//Prints all the menu items
void CoffeeShop::PrintMenu() const
{
	cout << this->GetName() << "\n";

	unsigned menuItemsCount = this->drinks.size();
	if (menuItemsCount == 0)
	{
		cout << "No items in the menu.";
	}
	else
	{
		for (unsigned index = 0; index < menuItemsCount; index++)
		{
			cout << this->drinks[index].GetName() << " -> $" << this->drinks[index].GetPrice() << "\n";
		}
	}

	cout << std::endl;
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

// TODO(gdeepti): Clean up global variables.
var mounterBackground = null;
var mounterThumb = null;
var mounterHeader = null;
var mounter = null;
var isVisible = false;
var mounterClient = null;

function intToPixels(int) {
  return int + 'px';
}

function walkDom(callback) {
  var body = document.body;
  var loop = function(element) {
    do {
      var recurse = true;
      if(element.nodeType == 1)
        recurse = callback(element);
      if (recurse && element.hasChildNodes() && !element.hidden)
        loop(element.firstChild);
      element = element.nextSibling;
    }
    while (element);
  };
  loop(body);
}

function grabFocus() {
  walkDom(function(element) {
    if (element == mounterBackground)
      return false;

    if (element.hasAttribute('tabIndex')) {
       element.oldTabIndex = element.getAttribute('tabIndex');
     }
    element.setAttribute('tabIndex', '-1');
    return true;
  })
}

function releaseFocus() {
  walkDom(function(element) {
    if (element == mounterBackground)
      return false;

    if (element.oldTabIndex) {
      element.setAttribute('tabIndex', element.oldTabIndex);
      delete element.oldTabIndex;
    } else {
      element.removeAttribute('tabIndex');
    }
    return true;
  })
  mounterClient.terminal.focus();
}

function sizeBackground() {
  mounterBackground.style.height = intToPixels(window.innerHeight);
  var bgTop = 0;
  if (!isVisible)
    bgTop = 10 - window.innerHeight
  mounterBackground.style.top = intToPixels(bgTop);
}

function changeVisibility(visible) {
  isVisible = visible;

  sizeBackground()
  if (!mounterClient)
    return;

  if (isVisible)
    grabFocus();
  else
    releaseFocus();
}

function backgroundClicked() {
  if (isVisible)
    changeVisibility(false);
}

function thumbClicked(event) {
  if (!isVisible)
    changeVisibility(true);
  event.stopPropagation();
}

function mounterClicked(event) {
  event.stopPropagation();
}

function initMounterclient(mount, chooseFolder,
    mountHandler, unmountHandler, terminal) {
  this.mount = mount;
  this.onChooseFolder = chooseFolder;
  this.onMount = mountHandler;
  this.onUnmount = unmountHandler
  this.terminal = terminal;
}

function addMountControlItem(item, mountControl) {
  mountControl.appendChild(item);
  item.mountControl = mountControl;
}

function populateMountControl(mountControl) {
  mountControl.pathEdit.value = g_mount.mountPoint;
  // TODO(gdeepti): Enable this to accept mountPoint specified by th user.
  // Temporarily disabled to fix sync issues.
  mountControl.pathEdit.disabled = g_mount.mounted;
  mountControl.localPathEdit.value = g_mount.localPath;
  mountControl.localPathEdit.disabled = g_mount.mounted;
  mountControl.selectButton.disabled = g_mount.mounted;
  mountControl.mountButton.disabled =
      (g_mount.mounted ||
      (g_mount.entry == null));
  mountControl.unmountButton.disabled = !g_mount.mounted;
}

function mountPointChanged(event) {
  var mountControl = event.target.mountControl;
  mountControl.mount.mountPoint = event.target.value;
  populateMountControl(mountControl);
}

function chooseFolderClicked(event) {
  var mountControl = event.target.mountControl;
  mounterClient.onChooseFolder(mountControl.mount, function() {
    populateMountControl(mountControl);
  });
}

function mountClicked(event) {
  var mountControl = event.target.mountControl;
  mounterClient.onMount(mountControl.mount, function() {
    populateMountControl(mountControl);
  });
}

function unmountClicked(event) {
  var mountControl = event.target.mountControl;
  mounterClient.onUnmount(mountControl.mount, function() {
    populateMountControl(mountControl);
  });
}

function removeMountClicked(event) {
  var mountControl = event.target.mountControl;
  mounterClient.onRemoveMount(mountControl.mount);
}

function addMountControl(mount, init) {
  var mountControl = document.createElement('div');
  mountControl.classList.add('mountControl');

  var selectButton = document.createElement('button');
  selectButton.textContent = 'Choose Folder';
  addMountControlItem(selectButton, mountControl);
  mountControl.selectButton = selectButton;
  selectButton.onclick = chooseFolderClicked;

  var localPathLabel = document.createElement('span');
  localPathLabel.textContent = 'Local path:';
  mountControl.appendChild(localPathLabel);

  var localPathEdit = document.createElement('input');
  localPathEdit.textContent = '';
  localPathEdit.readOnly = true;
  addMountControlItem(localPathEdit, mountControl);
  mountControl.localPathEdit = localPathEdit;

  var pathEditLabel = document.createElement('span');
  pathEditLabel.textContent = 'Mount point:';
  mountControl.appendChild(pathEditLabel);

  var pathEdit = document.createElement('input');
  pathEdit.value = mount.mountPoint;
  addMountControlItem(pathEdit, mountControl);
  mountControl.pathEdit = pathEdit;
  pathEdit.oninput = mountPointChanged;

  var mountButton = document.createElement('button');
  mountButton.textContent = 'Mount';
  addMountControlItem(mountButton, mountControl);
  mountControl.mountButton = mountButton;
  mountButton.onclick = mountClicked;

  var unmountButton = document.createElement('button');
  unmountButton.textContent = 'Unmount';
  addMountControlItem(unmountButton, mountControl);
  mountControl.unmountButton = unmountButton;
  unmountButton.onclick = unmountClicked;

  mountControl.mount = mount;

  init(function() {
    populateMountControl(mountControl);
  });
  mounter.appendChild(mountControl);

  return mountControl;
}

function initMounter(makeVisible, aMounterClient, init) {
  mounterBackground.onclick = backgroundClicked;
  mounter.onclick = mounterClicked;
  mounterThumb.onclick = thumbClicked;

  mounterClient = aMounterClient;

  addMountControl(g_mount, init);
  changeVisibility(makeVisible);

  window.onresize = function() {
    sizeBackground();
  }
}


text:
$(function () {

	var route = {
		new_message: '?r=messenger/new-message',
		deleteMessage: '?r=messenger/delete-message',
	};

	var methods = {
		new_message: 'new_message',
		delete_message: 'delete_message'
	};

	var csrfToken = $('meta[name="csrf-token"]').attr("content");
	var user = userName;
	var attaches = [];

	var conn = new WebSocket('ws://localhost:3030');

	/**
	 *
	 * @param url
	 * @param data
	 * @param error
	 * @param done
	 */
	var ajaxRequest = function (url, data, error, done) {
		$.ajax({
			url: url,
			method: 'POST',
			data: data,
			dataType: 'json'
		}).error(function (d) {
			error(d)
		}).done(function (d) {
			done(d);
		});
	};

	var waitForConnection = function (callback, interval) {
	    if (conn.readyState === 1) {
	        callback();
	    } else {
	        var that = this;
	        // optional: implement backoff for interval here
	        setTimeout(function () {
	            waitForConnection(callback, interval);
	        }, interval);
	    }
	};

	/**
	 * Результат открытия сокета
	 * @param result
	 */
	conn.onopen = function (result) {
		console.log(result);
	};

	/**
	 * Рассылка сообщений подписчикам
	 * @param result
	 */
	conn.onmessage = function (result) {
		var json = JSON.parse(result.data);
		var idMessage = null;
		var content = null;
		var userName = null;
		var createdAt = null;

		if (json !== null) {
			switch (json['type']) {
				case methods.new_message:
					idMessage = json['idMessage'];
					content = json['content'];
					userName = json['userName'];
					createdAt = json['createdAt'];

					addMessage(idMessage, content, userName, createdAt);

					break;

				case methods.delete_message:
					idMessage = json['idMessage'];
					deleteMessage(idMessage);

					break;

			}
		}
	};

	/**
	 * Отправка сообщения в чат
	 */
	$('#send-message').on('click', function () {
		var input = $('#message-text');
		var text = input.val();
		var content = '';
		if (text.length > 0) {
			var attachToString = '';
			$.each(attaches, function (key, value) {
				switch (value.type) {
					case 'image':
						attachToString += '';
						break;
					case 'video':
						attachToString += '';
						break;
					case 'link':
						attachToString += '
Ссылка
';
						break;
				}
			});

			content = text + attachToString;

			ajaxRequest(
				route.new_message,
				{_csrf: csrfToken, content: content, userName: user},
				function (error) {
					console.log(error);
				},
				function (message) {
					waitForConnection(function () {
				        conn.send(JSON.stringify({
							type: methods.new_message,
							content: content,
							userName: user,
							idMessage: message.id,
							createdAt: message.createdAt
						}));
				        if (typeof callback !== 'undefined') {
				          callback();
				        }
				    }, 1000);

					input.val('');

					addMessage(message.id, text, user, message.createdAt);
				}
			);
		}
	});

	/**
	 * Удаление сообщения из чата
	 */
	$('.messages').on('click', '#delete', function () {
		var message = $(this).parent('.message');
		var idMessage = message.attr('id');

		ajaxRequest(
			route.deleteMessage,
			{_csrf: csrfToken, idMessage: idMessage},
			function (error) {
				console.log(error);
			},
			function () {
				conn.send(JSON.stringify({
					type: methods.delete_message,
					idMessage: idMessage
				}));

				deleteMessage(idMessage);
			}
		);

		return false;
	});

	/**
	 *
	 * @param id
	 * @param content
	 * @param userName
	 * @returns {string}
	 * @param createdAt
	 */
	function addMessage(id, content, userName, createdAt) {
		var attachToString = '';
		$.each(attaches, function (key, value) {
			switch (value.type) {
				case 'image':
					attachToString += '';
					break;
				case 'video':
					attachToString += '';
					break;
				case 'link':
					attachToString += '
Ссылка
';
					break;
			}
		});

		var deleteLink = user === userName ? 'Удалить' : '';
		var msg = $('

' + userName + ' says:
' + content + attachToString + '

' + createdAt + '
' + deleteLink + '
');

		$('.messages').append(msg);
		msg.hide().fadeIn(500);

		attaches = [];
		$('#attaches').text('');
	}

	function deleteMessage(idMessage) {
		var message = $('#' + idMessage);

		message.slideUp();
	}

	/**
	 * Вызов диалога для загрузки изображений
	 */
	$('.add-pictures-link').on('click', function () {
		$('.add-pictures-dialog').fadeIn();
		$('.attach-menu').fadeOut();
		return false;
	});

	/**
	 * Вызов диалога для добавления видео
	 */
	$('.add-video-link').on('click', function () {
		$('.add-video-dialog').fadeIn();
		return false;
	});

	$('.add-url-link').on('click', function () {
		$('.add-url-dialog').fadeIn();
		return false;
	});

	/**
	 * Закрытие диалогового окна
	 */
	$('.close-dialog').on('click', function () {
		$('.dialog').fadeOut();
		return false;
	});

	/**
	 *
	 */
	$('.add-video').on('click', function () {
		var videoUrl = $('#video-url').val();
		var youtubeId = youTubeGetId(videoUrl);

		if (youtubeId) {
			attaches.push({
				type: 'video',
				content: youtubeId
			});

			$('#video-form').hide();
			$('#success_video').hide().fadeIn().text('Видео было добавлено к сообщению');
		} else {
			alert('Убедитесь в правильности ссылки на видео');
		}

		return false;
	});

	$('.add-url').on('click', function () {
		var url = $('#url').val();

		if (validationUrl(url)) {
			attaches.push({
				type: 'link',
				content: url
			});

			$('#url-form').hide();
			$('#success_url').hide().fadeIn().text('Ссылка добавлена к сообщению');
		} else {
			alert('Убедитесь в правильности ссылки');
		}

		return false;
	});

	/**
	 * Прослушивание события fileuploaded,
	 * для определения какие файлы были загружены
	 */
	$('input[name=\'UploadForm[file]\']').on('fileuploaded', function (event, data) {
		var response = data.response;

		attaches.push({
			type: 'image',
			content: response
		});

		$('#attaches').append('');
	});

	/**
	 *
	 * @param url
	 * @returns {*|Array|{index: number, input: string}}
	 */
	function youTubeGetId(url) {
		var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
		var video = (url.match(p)) ? RegExp.$1 : false;

		if (video) {
			return video;
		} else {
			return false;
		}
	}

	function validationUrl(url) {
		var p = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
		var link = (url.match(p)) ? RegExp.$1 : false;

		if (link) {
			return link;
		} else {
			return false;
		}
	}
});


text:
require 'pine/inheritable'
require 'pine/routing/namespace'

module Pine
  class Base
    include Inheritable

    inheritable :middlewares, []
    inheritable :route, Route.new

    def initialize
      puts "!! " + self.class.route.routes.inspect
      self.class.middlewares.each { |m, args, blk| builder.use m, *args, &blk }
      builder.run self.class.route.endpoint
      @app = builder.to_app
    end

    def call(env)
      @app.call env
    end

    def builder
      @builder ||= Rack::Builder.new
    end

    class << self
      def use middleware, *args, &block
        self.middlewares << [middleware, args, block]
      end

      HTTP_VERBS.each do |verb|
        define_method verb do |path, options={}|
          route.write verb, path, options
        end
      end

      def namespace namespace, &blk
        Namespace.new self, namespace, &blk
      end
    end
  end
end


text:
This contains sham-spinner directive that allows you to add Identified Sham
Spinner to Angular applications easily.

###Note:

In 0.10 and above the sham-spinner element will not be hidden. A new div sham-spinner-blocker is added. Checkout the sample scss on how to configure it.

### Requirements
- sham-spinner
- angularjs 1.2.0 (or latest version)

### Installation

Use bower to install angular-sham-spinner. This will also install sham-spinner
bower component.

````
$ bower install angular-sham-spinner
````

In the index.html add the directive and the reference to the script. The
attribute text will be shown beside the spinner.

```html
    <sham-spinner text="Loading..."></sham-spinner>

    <script src="bower_components/angular-sham-spinner/angular-sham-spinner.js"></script>

```

Enable the angularShamSpinner module in your app.js or any application config
javascript.
```js
angular.module('yourApp', [
        'ngRoute',
        'ngResource',
        'ngSanitize',
        'ngAnimate',
        'angularShamSpinner']);
```

Import Sham Spinner scss and add appropriate style for class
sham-spinner-container, spinner and text. The following style will
show the spinner on the top left corner.

```scss
@import "sham-spinner/sham-spinner";
.sham-spinner-blocker {
    .sham-spinner-container {
        padding: 2px 15px;
        background-color: #000;
        border: 1px solid #333;
        color: #ffffff;
        position: fixed;
        left: 5px;
        top: 0px;
        z-index: 5000;

        .spinner {
            display: block;
            float: left;
            width: 50px;
            height: 50px;
            @include sham-spinner-spokes(LightCoral, 44px, 2s);
        }
        .text {
            padding: 10px 12px;
            float: left;
            font-weight: 700;
        }
    }
}
```

The following is another example where the spinner is shown in the
middle of the page blocking the view.

```scss
@import "sham-spinner/sham-spinner";
.sham-spinner-blocker {
    background: #333;
    opacity: 0.8;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 5000;

    .sham-spinner-container {
        border: none;
        background-color: #000000;
        display: table;
        position: relative;
        width: auto;
        top: 45%;
        margin: auto;
        @include border-radius(5px);

        .spinner {
            display: block;
            float: left;
            width: 50px;
            height: 50px;
            @include sham-spinner-spokes(LightCoral, 44px, 2s);
        }
    }
}
```

### Disabling Sham Spinner
(Available from release 0.0.6)

Sometimes it may be necessary to disable the spinner. For example, if the spinner is blocking the
view and you are using AJAX to do validation of user input, it may be a good idea to disable the
spinner until the current call is complete.

In your controller, directive or service, you can inject the AngularShamNotification.
The AngularShamNotification has a method: setDisabled(disable, resetTime). If resetTime
(in milliseconds) is provided, the spinner will enable itself after the resetTime. Set resetTime
to a negative number to disable automatic reset. In that case, you may have to manually reset
the spinner by invoking this method with 'false' argument.

Example:

```js
angular.module('yourApp').controller('ghValidateEnrolled', [
    'AngularShamNotification',
    'YourSomeService', function(angularShamNotification, yourSomeService) {
        // disable spinner -do not reset automatically
        angularShamNotification.setDisabled(true, -1);
        yourSomeService.doAnApiCall()
        .then(function(data) {
            angularShamNotification.setDisabled(false);
        }, function(reason) {
            angularShamNotification.setDisabled(false);
        });
    }]
);

```

### License

The MIT License


text:
Basic example

To create a DragDrop, you need at least a root element, and a set of elements with the drag-item class.

This is done through adding the drag-handle class.

Demo

{% capture demo_code %}

drag-item 1

drag-item 2

drag-item 3

drag-item 4

{% endcapture %}
{{ demo_code }}

Code

{% highlight html %}
{{ demo_code }}
{% endhighlight %}

Multiple drop zones

DragDrop works with multiple drop zones, if you want. Elements with the class drop-zone are considered drop-zones, and dragged items will be placed in them.

By default, there is only one drop-zone which will be the root element. This is to ease development and avoid people having to create wrapper elements.

Demo

{% capture demo_code %}

Left sort item 1

Left sort item 2

Left sort item 3

Right sort item 1

Right sort item 2

Right sort item 3

{% endcapture %}
{{ demo_code }}

Code

{% highlight html %}
{{ demo_code }}
{% endhighlight %}

drag-handle example

You can only drag these items by their handle. This is useful if you want the user to interact with some parts of the drag-item, but enable them to drag the drag-item by a handle.

This is done through by adding the drag-handle class.

Demo

{% capture demo_code %}

 Drag me 1

 Drag me 2

 Drag me 3

 Drag me 4

 Drag me 5

 Drag me 6

 Drag me 7

 Drag me 8

 Drag me 9

{% endcapture %}
{{ demo_code }}

Code

{% highlight html %}
{{ demo_code }}
{% endhighlight %}


text:
bh2014
======
[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/cuemby/bh2014?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

We just hanging out and doing some code :) - Hackathon 2014.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#fff5f5f5" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginBottom="45dp" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <cn.sharesdk.socialization.component.TopicTitle
                android:id="@+id/llTopicTitle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />

            <ImageView
                android:id="@+id/ivIllustration"
                android:layout_width="fill_parent"
                android:layout_height="240dp"
                android:scaleType="centerInside"
                android:src="@drawable/pic" />

            <TextView
                android:id="@+id/tvText"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:autoLink="all"
                android:padding="10dp"
                android:text="@string/share_content"
                android:textColor="#ff383838"
                android:textSize="17dp" />
        </LinearLayout>
    </ScrollView>

    <cn.sharesdk.socialization.QuickCommentBar
        android:id="@+id/qcBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:background="#fff3f3f3" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_above="@+id/qcBar"
        android:background="#ffa6a6a6" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_above="@+id/qcBar"
        android:layout_marginBottom="1px"
        android:background="#ffd6d6d6" />

</RelativeLayout>


text:
/*
 * 2015
 */
package oli.bbp.sfx;

import java.io.File;
import java.util.ArrayList;
import oli.bbp.gfx.OliRenderer;

public class ToFileSoundScheduler extends SoundScheduler {
    public ArrayList<SoundEvent> soundEvents = new ArrayList<>();

    @Override
    public void playSound(File sound, float volume, int startOffset, int trimLength) {
        soundEvents.add(new SoundEvent(OliRenderer.frameNum, sound, volume, startOffset, trimLength));
    }

    public void mixAndSave(String soundFilename) {
        AudioMixer am = new AudioMixer();
        am.mixDown(soundEvents, new File(soundFilename));
    }

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


text:
module RegClass
        ( RegClass (..) )

where

import GhcPrelude

import  Outputable
import  Unique

-- | The class of a register.
--      Used in the register allocator.
--      We treat all registers in a class as being interchangeable.
--
data RegClass
        = RcInteger
        | RcFloat
        | RcDouble
        deriving Eq

instance Uniquable RegClass where
    getUnique RcInteger = mkRegClassUnique 0
    getUnique RcFloat   = mkRegClassUnique 1
    getUnique RcDouble  = mkRegClassUnique 2

instance Outputable RegClass where
    ppr RcInteger       = Outputable.text "I"
    ppr RcFloat         = Outputable.text "F"
    ppr RcDouble        = Outputable.text "D"


text:
"""
System time configuration
=========================

This is a collection of parsers that all deal with the system's configuration
of its time setting resources.

"""

import re
from .. import Parser, parser, get_active_lines, CommandParser
from insights.specs import Specs

class NTPConfParser(Parser):
    """
    NTP and Chrony both use the same format for their configuration file -
    a series of keywords with optional values.  Some keywords can appear
    more than once, so all keyword values are stored as a list of strings.
    Keywords that have no value, like 'iburst' or 'rtcsync', are left as
    keys but have None as a value.

    Also provides the ``servers`` and ``peers`` properties as (sorted) lists
    of the found 'server' and 'peer' data (respectively).

    Sample Input::
        >>> ntp_conf_data = '''
        ... server 0.rhel.pool.ntp.org iburst
        ... server 1.rhel.pool.ntp.org iburst
        ... server 2.rhel.pool.ntp.org iburst
        ... server 3.rhel.pool.ntp.org iburst
        ... # Enable kernel RTC synchronization.
        ... rtcsync
        ... leapsecmode slew
        ... maxslewrate 1000
        ... smoothtime 400 0.001 leaponly
        ... tinker step 0.9
        ... '''

    Examples:

        >>> ntp = shared[NTP_conf]
        >>> 'rtcsync' in ntp.data # Single word options are present but None
        True
        >>> ntp.data['rtcsync'] # Not in dictionary if option not set
        None
        >>> len(ntp.data['server'])
        4
        >>> ntp.data['server'][0]
        '0.rhel.pool.ntp.org iburst'
        >>> ntp.servers[0] # same data as above
        '0.rhel.pool.ntp.org iburst'
        >>> ntp.data['maxslewrate']
        '1000'
        >>> ntp.get_last('rtcsync') # See above for fetching single-word options
        None
        >>> ntp.get_last('leapsecmode')
        'slew'
        >>> ntp.get_last('tinker', 'panic', 'none') # Use default value
        'none'
        >>> ntp.get_last('tinker', 'step', '1') # Use value set in file
        '0.9'
        >>> ntp.get_param('tinker', 'step') # Get list of all settings
        ['0.9']
    """
    def parse_content(self, content):
        data = {}
        for line in get_active_lines(content):
            if ' ' in line or '\t' in line:
                k, rest = line.split(None, 1)
                if k in data:
                    data[k].append(rest)
                else:
                    data[k] = [rest]
            else:
                data[line] = None
        self.data = data

        # Also set up some convenience access to lists of stuff:
        if 'server' in data:
            self.servers = sorted(data['server'])
        else:
            self.servers = []
        if 'peer' in data:
            self.peers = sorted(data['peer'])
        else:
            self.peers = []

    def get_param(self, keyword, param=None, default=None):
        """
        Get all the parameters for a given keyword, or default if keyword or
        parameter are not present in the configuration.

        This finds every declaration of the given parameter (which is the
        one which takes effect).  If no parameter is given, then the entire
        line is treated as the parameter.  There is always at least one
        element returned - the default, or

        Parameters:
            keyword(str): The keyword name, e.g. 'tinker' or 'driftfile'
            param(str): The parameter name, e.g. 'panic' or 'step'.  If not
                given, all the definitions of that keyword are given.
            default(str): The default (singular) value if the keyword or
                parameter is not found.  If not given, None is used.

        Returns:
            list: All the values of the given parameter, or an empty list if
            not found.
        """
        if not keyword or keyword not in self.data:
            return [default]
        # keyword in data - if no value, we store None, so return that in a list
        if self.data[keyword] is None:
            return [None]
        # If we're not searching for a particular parameter, just return all
        # the values for this keyword.
        if not param:
            return self.data[keyword]

        found = []
        for line in self.data[keyword]:
            # Line has already had keyword removed.
            words = line.strip().split()
            if len(words) > 1:
                # Line has param and value - check param:
                if words[0] == param:
                    found.append(words[1])
            else:
                found.append(words[0])
        if found == []:
            return [default]
        else:
            return found

    def get_last(self, keyword, param=None, default=None):
        """
        Get the parameters for a given keyword, or default if keyword or
        parameter are not present in the configuration.

        This finds the last declaration of the given parameter (which is the
        one which takes effect).  If no parameter is given, then the entire
        line is treated as the parameter and returned.

        Parameters:
            keyword(str): The keyword name, e.g. 'tinker' or 'driftfile'
            param(str): The parameter name, e.g. 'panic' or 'step'.  If not
                given, the last definition of that keyword is given.

        Returns:
            str or None: The value of the given parameter, or None if not
            found.
        """
        return self.get_param(keyword, param, default)[-1]

@parser(Specs.chrony_conf)
class ChronyConf(NTPConfParser):
    """
    A parser for analyzing the chrony service config file ``/etc/chrony.conf``

    Uses the ``NTPConfParser`` class defined in this module.
    """
    pass

@parser(Specs.ntp_conf)
class NTPConf(NTPConfParser):
    """
    A parser for analyzing the ntpd service config file ``/etc/ntp.conf``

    Uses the ``NTPConfParser`` class defined in this module.
    """
    pass

@parser(Specs.localtime)
class LocalTime(CommandParser):
    """
    A parser for working with the output of command: `file -L /etc/localtime`

    Sample Input::

        /etc/localtime: timezone data, version 2, 5 gmt time flags, 5 std time flags, no leap seconds, 69 transition times, 5 abbreviation chars

    Examples:

        >>> localtime = shared[LocalTime]
        >>> localtime.data['name']
        '/etc/localtime'
        >>> localtime.data['version']
        '2'
        >>> localtime.data['gmt_time_flag']
        '5'
        >>> localtime.data['leap_second']
        'no'
    """
    def parse_content(self, content):
        result = {}
        title = [
            'version',
            'gmt_time_flag',
            'std_time_flag',
            'leap_second',
            'transition_time',
            'abbreviation_char'
        ]
        for line in content:
            filename, info = line.strip().split(':', 1)
            result['name'] = filename.strip()
            info_list = info.split(', ')
            if len(info_list) == 7 and info_list[0].strip() == 'timezone data':
                # A bit of a hack - version field has the data second, all
                # other fields have the data first.
                for idx, k in enumerate(title):
                    if idx == 0:
                        result[k] = info_list[idx + 1].strip().split()[1]
                    else:
                        result[k] = info_list[idx + 1].strip().split()[0]
        self.data = result

@parser(Specs.ntptime)
class NtpTime(CommandParser):
    """
    A parser for working with the output of the ``ntptime``.

    This doesn't attempt to get much out of the output; useful things that
    it retrieves are:

    * ``ntp_gettime`` - the return code of the ``ntp_gettime()`` call.
    * ``ntp_adjtime`` - the return code of the ``ntp_adjtime()`` call.
    * ``status`` - the hexadecimal status code as a string.
    * ``flags`` - the flags in brackets after the status code.

    Sample Input::

        ntp_gettime() returns code 0 (OK)
          time dbbc595d.1adbd720  Thu, Oct 27 2016 18:45:49.104, (.104917550),
          maximum error 263240 us, estimated error 102 us, TAI offset 0
        ntp_adjtime() returns code 0 (OK)
          modes 0x0 (),
          offset 0.000 us, frequency 4.201 ppm, interval 1 s,
          maximum error 263240 us, estimated error 102 us,
          status 0x2011 (PLL,INS,NANO),
          time constant 2, precision 0.001 us, tolerance 500 ppm,

    Examples:

        >>> ntptime = shared[NtpTime]
        >>> ntptime.data['stats']
        '0x2011'
        >>> ntptime.data['ntp_gettime']
        '0'
        >>> ntptime.data['flags']
        ['PLL', 'INS', 'NANO']
        >>> ntptime.data['interval']  # Other values are integers or floats
        1
        >>> ntptime.data['precision']  # Note floats may not be exact
        0.001
        >>> ntptime.data['maximum error']
        263240

    """
    def parse_content(self, content):
        result = {}
        return_code_re = re.compile(r'(?P<func>ntp_(?:get|adj)time)\(\) returns code (?P<code>\d+) ')
        status_code_re = re.compile(r'status (?P<status>0x[0-9a-f]+) \((?P<flags>.*)\)')
        time_data_re = re.compile(r'time (?P<timecode>[0-9a-f]{8}\.[0-9a-f]{8}) +(?P<timestamp>\w{3}, \w{3} \d+ .*),')
        value_re = re.compile(r'(?P<keyword>[A-Za-z][A-Za-z ]+) (?P<value>\d+(?:\.\d+|x[0-9a-f]+)?) ?(?P<units>us|ppm|s|\(.*\))?')
        # Note that maximum and estimated error appear in both sections but
        # have the same value, so we don't bother to make them unique
        for line in content:
            # Check for function line
            match = return_code_re.search(line)
            if match:
                function = match.group('func')
                result[function] = match.group('code')
                continue

            # Check for status line specially
            match = status_code_re.search(line)
            if match:
                result['status'] = match.group('status')
                result['flags'] = match.group('flags').split(',')
                continue

            # Check for time data specially
            match = time_data_re.search(line)
            if match:
                # Get timecode and timestamp in one go
                result.update(match.groupdict())
                continue

            # Otherwise, try to read comma-separated key-value groups
            for match in value_re.finditer(line):
                value = match.group('value')
                if '.' in value:
                    vnum = float(value)
                elif 'x' in value:
                    vnum = int(value, 16)
                else:
                    vnum = int(value)
                result[match.group('keyword')] = vnum

        self.data = result


text:
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2021 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#pragma once

#include <cursespp/IScrollable.h>
#include <cursespp/IScrollAdapter.h>
#include <cursespp/ScrollableWindow.h>
#include <sigslot/sigslot.h>
#include <functional>

namespace cursespp {
    class ListWindow: public ScrollableWindow {
        public:
            static size_t NO_SELECTION;

            using Decorator = std::function<void(ListWindow*)>;

            sigslot::signal3<ListWindow*, size_t, size_t> SelectionChanged;
            sigslot::signal2<ListWindow*, size_t> Invalidated;
            sigslot::signal2<ListWindow*, size_t> EntryActivated;
            sigslot::signal2<ListWindow*, size_t> EntryContextMenu;

            ListWindow(std::shared_ptr<IScrollAdapter> adapter, IWindow *parent = nullptr);
            ListWindow(IWindow *parent = nullptr);

            virtual ~ListWindow();

            void ScrollToTop() override;
            void ScrollToBottom() override;
            void ScrollUp(int delta = 1) override;
            void ScrollDown(int delta = 1) override;
            void PageUp() override;
            void PageDown() override;

            void Invalidate() override;
            void OnAdapterChanged() override;

            const IScrollAdapter::ScrollPosition& GetScrollPosition() override;

            bool KeyPress(const std::string& key) override;
            bool ProcessMouseEvent(const IMouseHandler::Event& event) override;

            void SetScrollbarVisible(bool visible);
            void SetDecorator(Decorator decorator);

            /* virtual methods we define */
            virtual void ScrollTo(size_t index);
            virtual size_t GetSelectedIndex();
            virtual void SetSelectedIndex(size_t index);
            virtual bool IsEntryVisible(size_t index);

        protected:
            void OnDimensionsChanged() override;
            void DecorateFrame() override;
            IScrollAdapter::ScrollPosition& GetMutableScrollPosition() override;

            /* virtual methods we define */
            virtual void OnSelectionChanged(size_t newIndex, size_t oldIndex);
            virtual bool OnEntryActivated(size_t index);
            virtual bool OnEntryContextMenu(size_t index);
            virtual void OnInvalidated();

        private:
            bool IsSelectedItemCompletelyVisible();

            bool showScrollbar;
            IScrollAdapter::ScrollPosition scrollPosition;
            size_t selectedIndex;
            Decorator decorator;
    };
}