text:
% myLength.m

% function to calculate length of a given path

    function dist_total = myLength(dist,path)

    dist_total=zeros(1);

    [m,mm]=size(dist);

    dist_total=dist(path(1,m),path(1,1));

    for i=1:(m-1)
        dist_total=dist_total+dist(path(1,i),path(1,i+1));
    end

% fitness.m

%To evaluate how good each path is

function fit = fitness(dist_total,max_dist,min_dist)

fit = zeros(length(dist_total),1);

for i=1:length(dist_total);
    fit(i,1)=(max_dist - dist_total(i,1)+0.000001) / (max_dist-min_dist+0.00000001);
end

%exchange.m

% simple exchange to use for mutation

function [x,y]=exchange(x,y)
temp=x;
x=y;
y=temp;

%mutate.m

% mutation, randomly choose 2 in the path and exchange them

function a=mutate(a)
L=length(a);
rray=randperm(L);
[a(rray(1)),a(rray(2))]=exchange(a(rray(1)),a(rray(2)));

%sort_path.m

% to sort the path by its fitness, so can directly select the top performing path to
% directly keep

function path_ranked = sort_path(path, dist_total,fit)
[t,tt]=size(path);
temp_path=[ path,dist_total];
temp_path = sortrows(temp_path, tt+1);
path_ranked=temp_path;

%index_by_prob.m

function e = index_by_prob(p,n)

% Reference: https://www.mathworks.com/matlabcentral/newsreader/view_thread/244719
% Generate random number from definite probility

% p is the fitness probility vector
% n is the number of the index we want for new pathes

p = p/sum(p);

x = rand(n,1);
y = cumsum(p);
t = size(p,1);
q = ones(size(x));
e = t*q;
for k = 1:ceil(log2(t))
 c = floor((q+e)/2);
 t = x > y(c);
 q = q + t.*(c-q);
 e = c + t.*(e-c);
end


text:
#pragma once

#include "core/containers/types.h"
#include "core/filesystem/types.h"
#include "core/strings/string_id.h"
#include "core/types.h"
#include "resource/types.h"
#include "world/material.h"

namespace crown
{
struct MaterialManager
{
	Allocator* _allocator;
	ResourceManager* _resource_manager;
	HashMap<StringId64, Material*> _materials;

	///
	MaterialManager(Allocator& a, ResourceManager& rm);

	///
	~MaterialManager();

	///
	void* load(File& file, Allocator& a);

	///
	void online(StringId64 id, ResourceManager& rm);

	///
	void offline(StringId64 id, ResourceManager& rm);

	///
	void unload(Allocator& a, void* res);

	/// Creates the material @a id.
	void create_material(StringId64 id);

	/// Destroys the material @a id.
	void destroy_material(StringId64 id);

	/// Returns the material @a id.
	Material* get(StringId64 id);
};

} // namespace crown

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: s👀n
---

![photo](https://raw.githubusercontent.com/dbemerydt/dbemerydt.github.io/master/images/gg.jpg)


text:
var Guid = require('guid');

var listeners = {};

// called by Actions
// payload is an object containing
//      the object to be acted on and
//      a string that helps the register determine what to do with it
var dispatch = function(payload) {
    for (var id in listeners) {
        listeners[id](payload);
    }
}

// called by Stores
// callback determines the proper action to take and
//      runs a function (add, delete, etc) from the Stores
var register = function(callback) {
    var id = Guid.create();
    listeners[id] = callback;
}

module.exports = {
    register: register,
    dispatch: dispatch
}


text:
(function ($) {

  // Creates an iframe with an embedded HipChat conversation window.
  //
  // Options:
  //   url        - The url to the room to embed; required
  //   container  - The container in which to insert the HipChat panel; required
  //   timezone   - The timezone to use in the embedded room; required
  //   welcome    - A welcome message to display when the room is joined; optional
  //   noframes   - Content to include when iframes are disabled in the browser; optional
  //   width      - The width of the iframe; defaults to 100%
  //   height     - The height of the iframe; defaults to 400px
  $.createHipChat = function (options) {
    if (options && options.url && options.container && options.timezone) {
      var $container = $(options.container);
      if ($container.length === 0) return;
      var params = {
        anonymous: 1,
        timezone: options.timezone,
        minimal: 1
      };
      if (options.welcome) {
        params.welcome_msg = options.welcome;
      }
      var url = options.url + (options.url.indexOf('?') > 0 ? '&' : '?') + $.param(params);
      if (url.indexOf('https://') !== 0) {
        url = 'https://' + url;
      }
      var w = options.width || '100%';
      var h = options.height || 400;
      var nf = (options.noframes || '');
      return {
        show: function () {
          $container.html('<iframe src="' + url + '" frameborder="' + 0 + '" width="' + w + '" height="' + h + '">' + nf + '</iframe>');
        }
      };
    }
  };

  $.fn.hipChatPanel = function (options) {
    options.container = this[0];
    var panel = $.createHipChat(options);
    this.html('<button class="show-hipchat ' + options.buttonClasses + '">' + (options.buttonTitle || 'Chat') + '</button>')
        .find('.show-hipchat').click(function (e) { panel.show(); });
  };

}(jQuery));


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

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fastScrollEnabled="false"
        android:cacheColorHint="#00000000"
    />
</LinearLayout>


text:
<?php

namespace Blackfire\Player\Guzzle;

use GuzzleHttp\Handler\CurlFactory as BaseCurlFactory;
use Psr\Http\Message\RequestInterface;

/**
 * @internal
 */
class CurlFactory extends BaseCurlFactory
{
    public function create(RequestInterface $request, array $options)
    {
        $easy = parent::create($request, $options);

        if (isset($options['player_context']) && $resolvedIp = $options['player_context']->getResolvedIp()) {
            $uri = $request->getUri();
            $scheme = $uri->getScheme() ?: 'http';
            $schemeMapping = ['http' => 80, 'https' => 443];
            $port = isset($schemeMapping[$scheme]) ? $schemeMapping[$scheme] : 80;
            $port = $uri->getPort() ?: $port;

            $resolveString = sprintf('%s:%d:%s', $uri->getHost(), $port, $resolvedIp);
            curl_setopt($easy->handle, \CURLOPT_RESOLVE, [$resolveString]);
        }

        return $easy;
    }
}


text:
from parlai.core.fbdialog_teacher import FbDialogTeacher
from .build import build

import copy
import os

def _path(opt, filtered):
    # Build the data if it doesn't exist.
    build(opt)
    dt = opt['datatype'].split(':')[0]
    return os.path.join(opt['datapath'], 'SimpleQuestions', 'sq', dt + '.txt')

class DefaultTeacher(FbDialogTeacher):
    def __init__(self, opt, shared=None):
        opt = copy.deepcopy(opt)
        opt['datafile'] = _path(opt, '')
        super().__init__(opt, shared)


text:
int main()
{
  using namespace std::chrono;

  // non-constexpr
  minutes mn1(6000);
  hours hr1 __attribute__((unused)) = duration_cast<hours>(mn1);

  // constexpr
  constexpr minutes mn2(6000);
  constexpr hours hr2 __attribute__((unused)) = duration_cast<hours>(mn2);

  return 0;
}


text:
using System;
using System.Collections.Generic;
using ServiceStack.Script;
using ServiceStack.Text;
using ServiceStack.Text.Json;

namespace ServiceStack
{
    public static class JSON
    {
        public static object parse(string json)
        {
            json.AsSpan().ParseJsToken(out var token);
            return token.Evaluate(JS.CreateScope());
        }

        public static object parseSpan(ReadOnlySpan<char> json)
        {
            if (json.Length == 0)
                return null;
            var firstChar = json[0];

            if (firstChar >= '0' && firstChar <= '9')
            {
                try {
                    var longValue = MemoryProvider.Instance.ParseInt64(json);
                    return longValue >= int.MinValue && longValue <= int.MaxValue
                        ? (int) longValue
                        : longValue;
                } catch {}

                if (json.TryParseDouble(out var doubleValue))
                    return doubleValue;
            }
            else if (firstChar == '{' || firstChar == '[')
            {
                json.ParseJsToken(out var token);
                return token.Evaluate(JS.CreateScope());
            }
            else if (json.Length == 4)
            {
                if (firstChar == 't' && json[1] == 'r' && json[2] == 'u' && json[3] == 'e')
                    return true;
                if (firstChar == 'n' && json[1] == 'u' && json[2] == 'l' && json[3] == 'l')
                    return null;
            }
            else if (json.Length == 5 && firstChar == 'f' && json[1] == 'a' && json[2] == 'l' && json[3] == 's' && json[4] == 'e')
            {
                return false;
            }

            var unescapedString = JsonTypeSerializer.Unescape(json);
            return unescapedString.ToString();
        }

        public static string stringify(object value) => value.ToJson();
    }

    public static class JS
    {
        /// <summary>
        /// Configure ServiceStack.Text JSON Serializer to use Templates JS parsing
        /// </summary>
        public static void Configure()
        {
            JsonTypeSerializer.Instance.ObjectDeserializer = JSON.parseSpan;
        }

        public static void UnConfigure() => JsonTypeSerializer.Instance.ObjectDeserializer = null;

        public static ScriptScopeContext CreateScope(Dictionary<string, object> args = null, ScriptMethods functions = null)
        {
            var context = new ScriptContext();
            if (functions != null)
                context.ScriptMethods.Insert(0, functions);

            context.Init();
            return new ScriptScopeContext(new PageResult(context.EmptyPage), null, args);
        }

        public static object eval(string js) => eval(js, CreateScope());
        public static object eval(string js, ScriptScopeContext scope)
        {
            js.ParseJsExpression(out var token);
            var result = token.Evaluate(scope);

            return result;
        }

        public static JsToken expression(string js)
        {
            js.ParseJsExpression(out var token);
            return token;
        }

    }
}


text:
/*csslint regex-selectors:false, known-properties:false, duplicate-properties:false*/

.pure-g {
    letter-spacing: -0.31em; /* Webkit: collapse white-space between units */
    *letter-spacing: normal; /* reset IE < 8 */
    *word-spacing: -0.43em; /* IE < 8: collapse white-space between units */
    text-rendering: optimizespeed; /* Webkit: fixes text-rendering: optimizeLegibility */

    /*
    Use flexbox when possible to avoid `letter-spacing` side-effects.

    NOTE: Firefox (as of 25) does not currently support flex-wrap, so the
    `-moz-` prefix version is omitted.
    */

    display: -webkit-flex;
    -webkit-flex-flow: row wrap;

    /* IE10 uses display: flexbox */
    display: -ms-flexbox;
    -ms-flex-flow: row wrap;
}

/* Opera as of 12 on Windows needs word-spacing.
   The ".opera-only" selector is used to prevent actual prefocus styling
   and is not required in markup.
*/
.opera-only :-o-prefocus,
.pure-g {
    word-spacing: -0.43em;
}

.pure-u {
    display: inline-block;
    *display: inline; /* IE < 8: fake inline-block */
    zoom: 1;
    letter-spacing: normal;
    word-spacing: normal;
    vertical-align: top;
    text-rendering: auto;
}


text:
const crc16ccitt = require('crc/crc16ccitt');
const crc16kermit = require('crc/crc16kermit');
const crc16modbus = require('crc/crc16modbus');
const crc16 = require('crc/crc16');
const crc16xmodem = require('crc/crc16xmodem');
const crc1 = require('crc/crc1');
const crc24 = require('crc/crc24');
const crc32 = require('crc/crc32');
const crc81wire = require('crc/crc81wire');
const crc8 = require('crc/crc8');
const crcjam = require('crc/crcjam');

crc16ccitt('hello world');
crc16kermit('hello world');
crc16modbus('hello world');
crc16('hello world');
crc16xmodem('hello world');
crc1('hello world');
crc24('hello world');
crc32('hello world');
crc81wire('hello world');
crc8('hello world');
crcjam('hello world');


text:
#ifndef _REISER_FS_I
#define _REISER_FS_I

#include <linux/list.h>

/** bitmasks for i_flags field in reiserfs-specific part of inode */
typedef enum {
    /** this says what format of key do all items (but stat data) of
	an object have.  If this is set, that format is 3.6 otherwise
	- 3.5 */
    i_item_key_version_mask    =  0x0001,
    /** If this is unset, object has 3.5 stat data, otherwise, it has
	3.6 stat data with 64bit size, 32bit nlink etc. */
    i_stat_data_version_mask   =  0x0002,
    /** file might need tail packing on close */
    i_pack_on_close_mask       =  0x0004,
    /** don't pack tail of file */
    i_nopack_mask              =  0x0008,
    /** If those is set, "safe link" was created for this file during
	truncate or unlink. Safe link is used to avoid leakage of disk
	space on crash with some files open, but unlinked. */
    i_link_saved_unlink_mask   =  0x0010,
    i_link_saved_truncate_mask =  0x0020
} reiserfs_inode_flags;

struct reiserfs_inode_info {
    __u32 i_key [4];/* key is still 4 32 bit integers */

    /** transient inode flags that are never stored on disk. Bitmasks
	for this field are defined above. */
    __u32 i_flags;

    __u32 i_first_direct_byte; // offset of first byte stored in direct item.

    /* copy of persistent inode flags read from sd_attrs. */
    __u32 i_attrs;

    int i_prealloc_block; /* first unused block of a sequence of unused blocks */
    int i_prealloc_count; /* length of that sequence */
    struct list_head i_prealloc_list;	/* per-transaction list of inodes which
					 * have preallocated blocks */

    int new_packing_locality:1;		/* new_packig_locality is created; new blocks
					 * for the contents of this directory should be
					 * displaced */

    /* we use these for fsync or O_SYNC to decide which transaction
    ** needs to be committed in order for this inode to be properly
    ** flushed */
    unsigned long i_trans_id ;
    unsigned long i_trans_index ;

    /* direct io needs to make sure the tail is on disk to avoid
     * buffer alias problems.  This records the transaction last
     * involved in a direct->indirect conversion for this file
     */
    unsigned long i_tail_trans_id;
    unsigned long i_tail_trans_index;
};

#endif


text:
module Google
  module Cloud
    module Vision
      ##
      # # Location
      #
      # A latitude/longitude pair with values conforming to the [WGS84
      # standard](http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf).
      #
      # @attr [Float] latitude The degrees latitude conforming to the [WGS84
      #   standard](http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf).
      # @attr [Float] longitude The degrees longitude conforming to the [WGS84
      #   standard](http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf).
      #
      # @example
      #   require "google/cloud/vision"
      #
      #   vision = Google::Cloud::Vision.new
      #
      #   image = vision.image "path/to/landmark.jpg"
      #   entity = image.landmark
      #
      #   location = entity.locations.first
      #
      #   location.latitude #=> 43.878264
      #   location.longitude #=> -103.45700740814209
      #
      class Location
        attr_accessor :latitude, :longitude

        ##
        # @private Creates a new Location instance.
        def initialize latitude, longitude
          @latitude  = latitude
          @longitude = longitude
        end

        ##
        # Returns the object's property values as an array.
        #
        # @return [Array]
        #
        def to_a
          [latitude, longitude]
        end

        ##
        # Converts object to a hash. All keys will be symbolized.
        #
        # @return [Hash]
        #
        def to_h
          { latitude: latitude, longitude: longitude }
        end

        # @private
        def to_s
          "(latitude: #{latitude.inspect}, longitude: #{longitude.inspect})"
        end

        # @private
        def inspect
          "#<#{self.class.name} #{self}>"
        end

        ##
        # @private New GRPC LatLng object.
        def to_grpc
          Google::Type::LatLng.new(
            latitude: latitude,
            longitude: longitude
          )
        end

        ##
        # @private New Location from a GRPC LatLng object.
        def self.from_grpc grpc
          new grpc.latitude, grpc.longitude
        end
      end
    end
  end
end


text:
package org.apache.activemq.artemis.core.security;

import org.junit.Assert;
import org.junit.Test;

import static org.apache.activemq.artemis.core.security.CheckType.BROWSE;
import static org.apache.activemq.artemis.core.security.CheckType.CONSUME;
import static org.apache.activemq.artemis.core.security.CheckType.CREATE_DURABLE_QUEUE;
import static org.apache.activemq.artemis.core.security.CheckType.CREATE_NON_DURABLE_QUEUE;
import static org.apache.activemq.artemis.core.security.CheckType.DELETE_DURABLE_QUEUE;
import static org.apache.activemq.artemis.core.security.CheckType.DELETE_NON_DURABLE_QUEUE;
import static org.apache.activemq.artemis.core.security.CheckType.MANAGE;
import static org.apache.activemq.artemis.core.security.CheckType.SEND;

public class RoleTest extends Assert {
   // Constants -----------------------------------------------------

   // Attributes ----------------------------------------------------

   // Static --------------------------------------------------------

   // Constructors --------------------------------------------------

   // Public --------------------------------------------------------

   @Test
   public void testWriteRole() throws Exception {
      Role role = new Role("testWriteRole", true, false, false, false, false, false, false, false);
      Assert.assertTrue(SEND.hasRole(role));
      Assert.assertFalse(CONSUME.hasRole(role));
      Assert.assertFalse(CREATE_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(CREATE_NON_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(DELETE_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(DELETE_NON_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(MANAGE.hasRole(role));
      Assert.assertFalse(BROWSE.hasRole(role));
   }

   @Test
   public void testReadRole() throws Exception {
      Role role = new Role("testReadRole", false, true, false, false, false, false, false, true);
      Assert.assertFalse(SEND.hasRole(role));
      Assert.assertTrue(CONSUME.hasRole(role));
      Assert.assertFalse(CREATE_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(CREATE_NON_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(DELETE_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(DELETE_NON_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(MANAGE.hasRole(role));
      Assert.assertTrue(BROWSE.hasRole(role));
   }

   @Test
   public void testCreateRole() throws Exception {
      Role role = new Role("testCreateRole", false, false, true, false, false, false, false, false);
      Assert.assertFalse(SEND.hasRole(role));
      Assert.assertFalse(CONSUME.hasRole(role));
      Assert.assertTrue(CREATE_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(CREATE_NON_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(DELETE_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(DELETE_NON_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(MANAGE.hasRole(role));
      Assert.assertFalse(BROWSE.hasRole(role));
   }

   @Test
   public void testManageRole() throws Exception {
      Role role = new Role("testManageRole", false, false, false, false, false, false, true, false);
      Assert.assertFalse(SEND.hasRole(role));
      Assert.assertFalse(CONSUME.hasRole(role));
      Assert.assertFalse(CREATE_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(CREATE_NON_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(DELETE_DURABLE_QUEUE.hasRole(role));
      Assert.assertFalse(DELETE_NON_DURABLE_QUEUE.hasRole(role));
      Assert.assertTrue(MANAGE.hasRole(role));
      Assert.assertFalse(BROWSE.hasRole(role));
   }

   @Test
   public void testEqualsAndHashcode() throws Exception {
      Role role = new Role("testEquals", true, true, true, false, false, false, false, false);
      Role sameRole = new Role("testEquals", true, true, true, false, false, false, false, false);
      Role roleWithDifferentName = new Role("notEquals", true, true, true, false, false, false, false, false);
      Role roleWithDifferentRead = new Role("testEquals", false, true, true, false, false, false, false, false);
      Role roleWithDifferentWrite = new Role("testEquals", true, false, true, false, false, false, false, false);
      Role roleWithDifferentCreate = new Role("testEquals", true, true, false, false, false, false, false, false);

      Assert.assertTrue(role.equals(role));

      Assert.assertTrue(role.equals(sameRole));
      Assert.assertTrue(role.hashCode() == sameRole.hashCode());

      Assert.assertFalse(role.equals(roleWithDifferentName));
      Assert.assertFalse(role.hashCode() == roleWithDifferentName.hashCode());

      Assert.assertFalse(role.equals(roleWithDifferentRead));
      Assert.assertFalse(role.hashCode() == roleWithDifferentRead.hashCode());

      Assert.assertFalse(role.equals(roleWithDifferentWrite));
      Assert.assertFalse(role.hashCode() == roleWithDifferentWrite.hashCode());

      Assert.assertFalse(role.equals(roleWithDifferentCreate));
      Assert.assertFalse(role.hashCode() == roleWithDifferentCreate.hashCode());

      Assert.assertFalse(role.equals(null));
   }

   // Package protected ---------------------------------------------

   // Protected -----------------------------------------------------

   // Private -------------------------------------------------------

   // Inner classes -------------------------------------------------
}


text:
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color:#fff;
}

.login {
text-align: center;
color: #444;
margin: 4em auto;
width: 280px;
padding:10px 40px;
background-color:#eee;
border-radius: 2px;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
}

.login input[type="submit"] {
font-size: 1em;
width: 100%;
display: block;
border: 1px solid #555;
color: #FFF;
background-color: #777;
font-weight: 700;
border-radius: 3px;
height: 36px;
}


text:
gmailcount is a simple tool to count the number of emails in your gmail
inbox. It's primary purpose is to allow status-bar programs like xmobar or
i3bar to poll your inbox without the need to store your password in plaintext.

## Installation

Look for releases on github or build with

    cargo build --release

## Usage

You'll first need to generate a Google app password and store it in the system
keyring with:

    gmailcount your-email@gmail.com set-password

Then, to get a count of emails, simply run:

    gmailcount your-email@gmail.com

Any program running gmailcount will need to have access to your keyring. The
current count of unread emails in your inbox will print to stdout. In case of
error, all output will print to stderr.

See `gmailcount -h` for detailed usage.

## Security concerns

One of the main goals of gmailcount is to provide a minimum level of
security. To that end, all requests are sent via SSL, passwords are stored in
your system keyring (and are presumably encrypted if your system keyring is
worth anything), and the recommended use pattern is with app passwords on
accounts with two-factor authentication enabled. This allows you to keep your
password out of your dotfiles and encrypted, and to revoke your password in
case your system is compromised.

Obviously though any system that allows your computer to poll your email
without any human interaction isn't going to be ideal from a security
standpoint. gmailcount is only as secure as your system keyring, which
depending on how you use it and your configuration may not be very secure at
all. Certainly if you're using gmailcount in a status bar, any one who
manages to get access to your logged in user account will have access to your
email, and if your keyring is secured by an insufficiently strong password,
someone with access to your hard drive may be able to crack your keyring
password and access your gmail password.

Use gmailcount at your own risk! Still, it should be a lot more secure than a
system that just stores your password as plain text at least.

## Examples

### Simple xmobar script

Here's an example of a script suitable for use with xmobar:

    #!/usr/bin/env sh

    url='https://mail.google.com'
    email='example@gmail.com'

    full_text=$(/path/to/gmailcount -t 1 "$email")
    full_text=${full_text:-?}

    case $full_text in
      ''|*[!0-9]*) color=\#FF0000 ;;
      0)           color=\#888888 ;;
      *)           color=\#00FF00 ;;
    esac

    echo "<action=\`xdg-open $url\`><fc=$color>✉ $full_text</fc></action>"

### Simple i3blocks script

Here's one suitable for use with i3blocks:

    #!/usr/bin/env sh

    url='https://mail.google.com'
    email='example@gmail.com'

    [ "$BLOCK_BUTTON" = 1 ] && xdg-open "$url"

    full_text=$(/path/to/gmailcount -t 1 "$email")
    full_text=${full_text:-?}

    case $full_text in
      ''|*[!0-9]*) color=\#FF0000 ;;
      0)           color=\#888888 ;;
      *)           color=\#00FF00 ;;
    esac

    echo "$full_text"
    echo "$short_text"
    echo "$color"

### Asynchronous example

The above scripts should work if your latency to google is low, but don't
behave particularly well if network connectivity is slow or interrupted.

Here's how I use gmailcount:

Systemd service (~/.config/systemd/<user>/gmailcount.service):

    [Unit]
    Description=Gmail Count Service

    [Service]
    ExecStart=/usr/bin/gmailcount <your-email>@gmail.com daemon --cache-dir /home/<user>/.cache/gmailcount --poll-time 10

    [Install]
    WantedBy=multi-user.target

Sample xmobar script:

    #!/usr/bin/env sh

    EMAIL="$1"
    URL='https://mail.google.com'
    CACHE_FILE="${XDG_CACHE_HOME:-$HOME/.cache}/gmailcount/$EMAIL"

    echo_status() {
      echo "<action=\`xdg-open $URL\`><fc=$2><fn=1></fn> $1</fc></action>"
    }

    get_status_output() {
      full_text=$(cat "$CACHE_FILE")
      full_text=${full_text:-?}

      case $full_text in
        ''|*[!0-9]*) color=\#dc322f ;;
        0)           color=\#586e75 ;;
        *)           color=\#2AA198 ;;
      esac

      echo_status "$full_text" "$color"
    }

    get_status_output


text:
namespace ui {

SurfacelessGlRenderer::BufferWrapper::BufferWrapper() {
}

SurfacelessGlRenderer::BufferWrapper::~BufferWrapper() {
  if (gl_fb_)
    glDeleteFramebuffersEXT(1, &gl_fb_);

  if (gl_tex_) {
    image_->ReleaseTexImage(GL_TEXTURE_2D);
    glDeleteTextures(1, &gl_tex_);
    image_->Destroy(true);
  }
}

bool SurfacelessGlRenderer::BufferWrapper::Initialize(
    gfx::AcceleratedWidget widget,
    const gfx::Size& size) {
  glGenFramebuffersEXT(1, &gl_fb_);
  glGenTextures(1, &gl_tex_);

  scoped_refptr<NativePixmap> pixmap =
      OzonePlatform::GetInstance()
          ->GetSurfaceFactoryOzone()
          ->CreateNativePixmap(widget, size, gfx::BufferFormat::RGBX_8888,
                               gfx::BufferUsage::SCANOUT);
  scoped_refptr<gfx::GLImageOzoneNativePixmap> image(
      new gfx::GLImageOzoneNativePixmap(size, GL_RGB));
  if (!image->Initialize(pixmap.get(), gfx::BufferFormat::RGBX_8888)) {
    LOG(ERROR) << "Failed to create GLImage";
    return false;
  }
  image_ = image;

  glBindFramebufferEXT(GL_FRAMEBUFFER, gl_fb_);
  glBindTexture(GL_TEXTURE_2D, gl_tex_);
  image_->BindTexImage(GL_TEXTURE_2D);

  glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                            gl_tex_, 0);
  if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    LOG(ERROR) << "Failed to create framebuffer "
               << glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
    return false;
  }

  widget_ = widget;
  size_ = size;

  return true;
}

void SurfacelessGlRenderer::BufferWrapper::BindFramebuffer() {
  glBindFramebufferEXT(GL_FRAMEBUFFER, gl_fb_);
}

void SurfacelessGlRenderer::BufferWrapper::SchedulePlane() {
  image_->ScheduleOverlayPlane(widget_, 0, gfx::OVERLAY_TRANSFORM_NONE,
                               gfx::Rect(size_), gfx::RectF(0, 0, 1, 1));
}

SurfacelessGlRenderer::SurfacelessGlRenderer(gfx::AcceleratedWidget widget,
                                             const gfx::Size& size)
    : GlRenderer(widget, size), weak_ptr_factory_(this) {}

SurfacelessGlRenderer::~SurfacelessGlRenderer() {
  // Need to make current when deleting the framebuffer resources allocated in
  // the buffers.
  context_->MakeCurrent(surface_.get());
}

bool SurfacelessGlRenderer::Initialize() {
  if (!GlRenderer::Initialize())
    return false;

  for (size_t i = 0; i < arraysize(buffers_); ++i)
    if (!buffers_[i].Initialize(widget_, size_))
      return false;

  PostRenderFrameTask(gfx::SwapResult::SWAP_ACK);
  return true;
}

void SurfacelessGlRenderer::RenderFrame() {
  float fraction = NextFraction();

  context_->MakeCurrent(surface_.get());
  buffers_[back_buffer_].BindFramebuffer();

  glViewport(0, 0, size_.width(), size_.height());
  glClearColor(1 - fraction, 0.0, fraction, 1.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  buffers_[back_buffer_].SchedulePlane();
  back_buffer_ ^= 1;
  if (!surface_->SwapBuffersAsync(base::Bind(&GlRenderer::PostRenderFrameTask,
                                             weak_ptr_factory_.GetWeakPtr())))
    LOG(FATAL) << "Failed to swap buffers";
}

scoped_refptr<gfx::GLSurface> SurfacelessGlRenderer::CreateSurface() {
  return gfx::GLSurface::CreateSurfacelessViewGLSurface(widget_);
}

}  // namespace ui


text:
package com.dao;

import java.util.Date;

import org.springframework.security.crypto.password.PasswordEncoder;

import com.dao.model.entity.NewsCategory;
import com.dao.model.entity.NewsEntry;
import com.dao.model.entity.User;
import com.dao.newscategory.NewsCategoryDao;
import com.dao.newsentry.NewsEntryDao;
import com.dao.user.UserDao;

public class DataBaseInitializer
{

	private NewsEntryDao newsEntryDao;
	private UserDao userDao;
	private NewsCategoryDao newsCategoryDao;
	private PasswordEncoder passwordEncoder;

	protected DataBaseInitializer()
	{
		/* Default constructor for reflection instantiation */
	}

	public DataBaseInitializer(UserDao userDao, NewsEntryDao newsEntryDao, NewsCategoryDao newsCategoryDao, PasswordEncoder passwordEncoder)
	{
		this.userDao = userDao;
		this.newsEntryDao = newsEntryDao;
		this.newsCategoryDao = newsCategoryDao;
		this.passwordEncoder = passwordEncoder;
	}

	public void initDataBase()
	{
		User userUser = new User("user", this.passwordEncoder.encode("user"));
		userUser.addRole("user");
		this.userDao.save(userUser);

		User adminUser = new User("admin", this.passwordEncoder.encode("admin"));
		adminUser.addRole("user");
		adminUser.addRole("admin");
		this.userDao.save(adminUser);

        User adminUser2 = new User("muksia", this.passwordEncoder.encode("muksia"));
        adminUser2.addRole("user");
        adminUser2.addRole("admin");
        this.userDao.save(adminUser2);

		NewsCategory newsCategory = createNewsCategory("Category Name");

		createNewsEntry(newsCategory);
	}

	private void createNewsEntry(final NewsCategory newsCategory) {
		long timestamp = System.currentTimeMillis() - 1000 * 60 * 60 * 24;
		for (int i = 0; i < 2; i++) {
			NewsEntry newsEntry = new NewsEntry();
			newsEntry.setContent("This is example content " + i);
			newsEntry.setDate(new Date(timestamp));
			newsEntry.setTitle("Some title");
			newsEntry.setNewsCategory(newsCategory);
			this.newsEntryDao.save(newsEntry);
			timestamp += 1000 * 60 * 60;
		}
	}

	private NewsCategory createNewsCategory(final String name){
		NewsCategory newsCategory = new NewsCategory();
		newsCategory.setName(name);
		return this.newsCategoryDao.save(newsCategory);
	}

}


text:
class ProfileSyncService;
class SupervisedUserSettingsService;
class SupervisedUserSharedSettingsService;

// The requests are stored using a prefix followed by a URIEncoded version of
// the URL/extension ID. Each entry contains a dictionary which currently has
// the timestamp of the request in it.
class PermissionRequestCreatorSync : public PermissionRequestCreator {
 public:
  PermissionRequestCreatorSync(
      SupervisedUserSettingsService* settings_service,
      SupervisedUserSharedSettingsService* shared_settings_service,
      ProfileSyncService* sync_service,
      const std::string& name,
      const std::string& supervised_user_id);
  ~PermissionRequestCreatorSync() override;

  // PermissionRequestCreator implementation:
  bool IsEnabled() const override;
  void CreateURLAccessRequest(const GURL& url_requested,
                              const SuccessCallback& callback) override;
  void CreateExtensionInstallRequest(const std::string& id,
                                     const SuccessCallback& callback) override;
  void CreateExtensionUpdateRequest(const std::string& id,
                                    const SuccessCallback& callback) override;

 private:
  // Note: Doesn't escape |data|. If you need it escaped, do it yourself!
  void CreateRequest(const std::string& prefix,
                     const std::string& data,
                     const SuccessCallback& callback);
  SupervisedUserSettingsService* settings_service_;
  SupervisedUserSharedSettingsService* shared_settings_service_;
  ProfileSyncService* sync_service_;
  std::string name_;
  std::string supervised_user_id_;
};

#endif  // CHROME_BROWSER_SUPERVISED_USER_LEGACY_PERMISSION_REQUEST_CREATOR_SYNC_H_


text:
var make = require('./make');

module.exports = make({
  entry: {
    server: './src/server.tsx',
  },
  target: 'node'
});


text:
<?php

declare(strict_types=1);

namespace PhpMyAdmin\Controllers\Table;

use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\Export\Options;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins;
use PhpMyAdmin\Response;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Statements\SelectStatement;
use PhpMyAdmin\SqlParser\Utils\Query;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function array_merge;
use function implode;
use function is_array;

class ExportController extends AbstractController
{
    /** @var Options */
    private $export;

    /**
     * @param Response $response
     * @param string   $db       Database name.
     * @param string   $table    Table name.
     */
    public function __construct(
        $response,
        Template $template,
        $db,
        $table,
        Options $export
    ) {
        parent::__construct($response, $template, $db, $table);
        $this->export = $export;
    }

    public function index(): void
    {
        global $db, $url_params, $table, $replaces, $cfg, $err_url;
        global $sql_query, $where_clause, $num_tables, $unlim_num_rows;

        $pageSettings = new PageSettings('Export');
        $pageSettingsErrorHtml = $pageSettings->getErrorHTML();
        $pageSettingsHtml = $pageSettings->getHTML();

        $this->addScriptFiles(['export.js']);

        Util::checkParameters(['db', 'table']);

        $url_params = ['db' => $db, 'table' => $table];
        $err_url = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
        $err_url .= Url::getCommon($url_params, '&');

        $url_params['goto'] = Url::getFromRoute('/table/export');
        $url_params['back'] = Url::getFromRoute('/table/export');

        // When we have some query, we need to remove LIMIT from that and possibly
        // generate WHERE clause (if we are asked to export specific rows)

        if (! empty($sql_query)) {
            $parser = new Parser($sql_query);

            if (! empty($parser->statements[0])
                && ($parser->statements[0] instanceof SelectStatement)
            ) {
                // Checking if the WHERE clause has to be replaced.
                if (! empty($where_clause) && is_array($where_clause)) {
                    $replaces[] = [
                        'WHERE',
                        'WHERE (' . implode(') OR (', $where_clause) . ')',
                    ];
                }

                // Preparing to remove the LIMIT clause.
                $replaces[] = [
                    'LIMIT',
                    '',
                ];

                // Replacing the clauses.
                $sql_query = Query::replaceClauses(
                    $parser->statements[0],
                    $parser->list,
                    $replaces
                );
            }
        }

        if (! isset($sql_query)) {
            $sql_query = '';
        }
        if (! isset($num_tables)) {
            $num_tables = 0;
        }
        if (! isset($unlim_num_rows)) {
            $unlim_num_rows = 0;
        }

        $GLOBALS['single_table'] = $_POST['single_table'] ?? $_GET['single_table'] ?? $GLOBALS['single_table'] ?? null;

        $exportList = Plugins::getExport('table', isset($GLOBALS['single_table']));

        if (empty($exportList)) {
            $this->response->addHTML(Message::error(
                __('Could not load export plugins, please check your installation!')
            )->getDisplay());

            return;
        }

        $exportType = 'table';
        $isReturnBackFromRawExport = isset($_POST['export_type']) && $_POST['export_type'] === 'raw';
        if (isset($_POST['raw_query']) || $isReturnBackFromRawExport) {
            $exportType = 'raw';
        }

        $options = $this->export->getOptions(
            $exportType,
            $db,
            $table,
            $sql_query,
            $num_tables,
            $unlim_num_rows,
            $exportList
        );

        $this->render('table/export/index', array_merge($options, [
            'export_type' => $exportType,
            'page_settings_error_html' => $pageSettingsErrorHtml,
            'page_settings_html' => $pageSettingsHtml,
        ]));
    }

    public function rows(): void
    {
        global $active_page, $single_table, $where_clause;

        if (isset($_POST['goto']) && (! isset($_POST['rows_to_delete']) || ! is_array($_POST['rows_to_delete']))) {
            $this->response->setRequestStatus(false);
            $this->response->addJSON('message', __('No row selected.'));

            return;
        }

        // Needed to allow SQL export
        $single_table = true;

        // As we got the rows to be exported from the
        // 'rows_to_delete' checkbox, we use the index of it as the
        // indicating WHERE clause. Then we build the array which is used
        // for the /table/change script.
        $where_clause = [];
        if (isset($_POST['rows_to_delete']) && is_array($_POST['rows_to_delete'])) {
            foreach ($_POST['rows_to_delete'] as $i => $i_where_clause) {
                $where_clause[] = $i_where_clause;
            }
        }

        $active_page = Url::getFromRoute('/table/export');

        $this->index();
    }
}


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#ifndef LIFE_CYCLE_MANAGER_H_
#define LIFE_CYCLE_MANAGER_H_

#include "ActionManager.h"
#include "VirtualMachinePool.h"
#include "HostPool.h"

using namespace std;

extern "C" void * lcm_action_loop(void *arg);

/**
 *  The Virtual Machine Life-cycle Manager module. This class is responsible for
 *  managing the life-cycle of a Virtual Machine.
 */
class LifeCycleManager : public ActionListener
{
public:

    LifeCycleManager(VirtualMachinePool * _vmpool, HostPool * _hpool):
        vmpool(_vmpool),hpool(_hpool)
    {
        am.addListener(this);
    };

    ~LifeCycleManager(){};

    enum Actions
    {
        SAVE_SUCCESS,     /**< Sent by the VMM when a save action succeeds    */
        SAVE_FAILURE,     /**< Sent by the VMM when a save action fails       */
        DEPLOY_SUCCESS,   /**< Sent by the VMM when a deploy/restore/migrate action succeeds  */
        DEPLOY_FAILURE,   /**< Sent by the VMM when a deploy/restore/migrate action fails     */
        SHUTDOWN_SUCCESS, /**< Sent by the VMM when a shutdown action succeeds*/
        SHUTDOWN_FAILURE, /**< Sent by the VMM when a shutdown action fails   */
        CANCEL_SUCCESS,   /**< Sent by the VMM when a cancel action succeeds  */
        CANCEL_FAILURE,   /**< Sent by the VMM when a cancel action fails     */
        MONITOR_FAILURE,  /**< Sent by the VMM when a VM has failed while active */
        MONITOR_SUSPEND,  /**< Sent by the VMM when a VM is paused while active */
        MONITOR_DONE,     /**< Sent by the VMM when a VM is not found */
        PROLOG_SUCCESS,   /**< Sent by the TM when the prolog phase succeeds  */
        PROLOG_FAILURE,   /**< Sent by the TM when the prolog phase fails     */
        EPILOG_SUCCESS,   /**< Sent by the TM when the epilog phase succeeds  */
        EPILOG_FAILURE,   /**< Sent by the TM when the epilog phase fails     */
        DEPLOY,           /**< Sent by the DM to deploy a VM on a host        */
        SUSPEND,          /**< Sent by the DM to suspend an running VM        */
        RESTORE,          /**< Sent by the DM to restore a suspended VM       */
        STOP,             /**< Sent by the DM to stop an running VM           */
        CANCEL,           /**< Sent by the DM to cancel an running VM         */
        MIGRATE,          /**< Sent by the DM to migrate a VM to other host   */
        LIVE_MIGRATE,     /**< Sent by the DM to live-migrate a VM            */
        SHUTDOWN,         /**< Sent by the DM to shutdown a running VM        */
        RESTART,          /**< Sent by the DM to restart a deployed VM        */
        DELETE,           /**< Sent by the DM to delete a VM                  */
        CLEAN,            /**< Sent by the DM to cleanup a VM for resubmission*/
        FINALIZE
    };

    /**
     *  Triggers specific actions to the Life-cycle Manager. This function
     *  wraps the ActionManager trigger function.
     *    @param action the LCM action
     *    @param vid VM unique id. This is the argument of the passed to the
     *    invoked action.
     */
    void trigger(
        Actions action,
        int     vid);

    /**
     *  This functions starts a new thread for the Life-cycle Manager. This
     *  thread will wait in  an action loop till it receives ACTION_FINALIZE.
     *    @return 0 on success.
     */
    int start();

    /**
     *  Gets the thread identification.
     *    @return pthread_t for the manager thread (that in the action loop).
     */
    pthread_t get_thread_id() const
    {
        return lcm_thread;
    };

private:
    /**
     *  Thread id for the Virtual Machine Manager
     */
    pthread_t               lcm_thread;

    /**
     *  Pointer to the Virtual Machine Pool, to access VMs
     */
    VirtualMachinePool *    vmpool;

    /**
     *  Pointer to the Host Pool, to access hosts
     */
    HostPool *              hpool;

    /**
     *  Action engine for the Manager
     */
    ActionManager           am;

    /**
     *  Function to execute the Manager action loop method within a new pthread
     * (requires C linkage)
     */
    friend void * lcm_action_loop(void *arg);

    /**
     *  The action function executed when an action is triggered.
     *    @param action the name of the action
     *    @param arg arguments for the action function
     */
    void do_action(
        const string &  action,
        void *          arg);

    /**
     *  Cleans up a VM, canceling any pending or ongoing action and closing
     *  the history registers
     *      @param vm with the lock aquired
     */
    void clean_up_vm (VirtualMachine *vm);

    void save_success_action(int vid);

    void save_failure_action(int vid);

    void deploy_success_action(int vid);

    void deploy_failure_action(int vid);

    void shutdown_success_action(int vid);

    void shutdown_failure_action(int vid);

    void cancel_success_action(int vid);

    void cancel_failure_action(int vid);

    void monitor_failure_action(int vid);

    void monitor_suspend_action(int vid);

    void monitor_done_action(int vid);

    void prolog_success_action(int vid);

    void prolog_failure_action(int vid);

    void epilog_success_action(int vid);

    void epilog_failure_action(int vid);

    void deploy_action(int vid);

    void suspend_action(int vid);

    void restore_action(int vid);

    void stop_action(int vid);

    void cancel_action(int vid);

    void checkpoint_action(int vid);

    void migrate_action(int vid);

    void live_migrate_action(int vid);

    void shutdown_action(int vid);

    void failure_action(VirtualMachine * vm);

    void restart_action(int vid);

    void delete_action(int vid);

    void clean_action(int vid);

    void timer_action();
};

#endif /*LIFE_CYCLE_MANAGER_H_*/


text:
.pad {
    height: 130px;
    width: 130px;
    border-radius: 1.5rem;
    margin: 15px;
    padding: 5px;
    float: left;
    transition: background 0.5s ease;
    background-image: linear-gradient( 135deg, #ABDCFF 0%, #0396FF 100%);
}

.pad.active {
    background-color: black;
    background-image: none;
}


text:
FactoryGirl.define do
  factory :validation do
    user # Belongs to
    report # Belongs to
    comments_for_provider Faker::Lorem.sentence
    comments_for_admin Faker::Lorem.sentence
    state ["Accepted", "Returned"].sample
  end
end


text:
                <form name="addDashboardForm" role="form" novalidate="novalidate">

                    <input type="text" class="form-control" id="title" name="title" placeholder="Give your dashboard a title"
                        data-ng-model="dashboard.title" ng-model-options="{debounce: 200}" ng-change="onDashboardTitleAdd('addDashboardForm', 'title', dashboard.title)" id="INPUT_ADD_DASHBOARD_TITLE" required="required">

/p>

                </form>

          <button ng-disabled="addDashboardForm.$invalid || addDashboardForm.title.$error.required" class="btn btn-primary" ng-click="save()" translate="BUTTON_SAVE" id="BUTTON_ADD_DASHBOARD_SAVE"></button>
          <button class="btn btn-link" onclick="javascript:window.history.back()" translate="BUTTON_CANCEL" id="BUTTON_ADD_DASHBOARD_CANCEL"></button>


text:
Heroku buildpack: Node.js with grunt support
============================================

Copy of https://github.com/mbuchetics/heroku-buildpack-nodejs-grunt & https://github.com/mirego/heroku-buildpack-bower

Supported Grunt versions: 0.3 and 0.4.
See the Grunt [migration guide](https://github.com/gruntjs/grunt/wiki/Upgrading-from-0.3-to-0.4) if you are upgrading from 0.3.

This is a fork of [Heroku's official Node.js buildpack](https://github.com/heroku/heroku-buildpack-nodejs) with added [Grunt](http://gruntjs.com/) support.
Using this buildpack you do not need to commit the results of your Grunt tasks (e.g. minification and concatination of files), keeping your repository clean.

After all the default Node.js and npm build tasks have finished, the buildpack checks if a Gruntfile (`Gruntfile.js`, `Gruntfile.coffee`or `grunt.js`) exists and executes the `heroku` task by running `grunt heroku`. For details about grunt and how to define tasks, check out the [offical documentation](http://gruntjs.com/getting-started). You must add grunt to the npm dependencies in your `package.json` file.
If no Gruntfile exists, the buildpacks simply skips the grunt step and executes like the standard Node.js buildpack.

How it Works
------------

Here's an overview of what this buildpack does:

- Uses the [semver.io](https://semver.io) webservice to find the latest version of node that satisfies the [engines.node semver range](https://npmjs.org/doc/json.html#engines) in your package.json.
- Allows any recent version of node to be used, including [pre-release versions](https://semver.io/node.json).
- Uses an [S3 caching proxy](https://github.com/heroku/s3pository#readme) of nodejs.org for faster downloads of the node binary.
- Discourages use of dangerous semver ranges like `*` and `>0.10`.
- Uses the version of `npm` that comes bundled with `node`.
- Puts `node` and `npm` on the `PATH` so they can be executed with [heroku run](https://devcenter.heroku.com/articles/one-off-dynos#an-example-one-off-dyno).
- Caches the `node_modules` directory across builds for fast deploys.
- Doesn't use the cache if `node_modules` is checked into version control.
- Runs `npm rebuild` if `node_modules` is checked into version control.
- Always runs `npm install` to ensure [npm script hooks](https://npmjs.org/doc/misc/npm-scripts.html) are executed.
- Always runs `npm prune` after restoring cached modules to ensure cleanup of unused dependencies.
- Runs `grunt` if a Gruntfile (`Gruntfile.js`, `Gruntfile.coffee`or `grunt.js`) is found.

For more technical details, see the [heavily-commented compile script](https://github.com/mbuchetics/heroku-buildpack-nodejs-grunt/blob/master/bin/compile).

Usage
-----

Create a new app with this buildpack:

    heroku create myapp --buildpack https://github.com/mbuchetics/heroku-buildpack-nodejs-grunt.git

Or add this buildpack to your current app:

    heroku config:add BUILDPACK_URL=https://github.com/mbuchetics/heroku-buildpack-nodejs-grunt.git

Enable heroku `user-env-compile` lab:

    heroku labs:enable user-env-compile

Set the `NODE_ENV` environment variable (e.g. `development` or `production`):

    heroku config:set NODE_ENV=production

Create your Node.js app and add a Gruntfile named  `Gruntfile.js` (or `Gruntfile.coffee` if you want to use CoffeeScript, or `grunt.js` if you are using Grunt 0.3) with a `heroku` task:

    grunt.registerTask('heroku:development', 'clean less mincss');

or

    grunt.registerTask('heroku:production', 'clean less mincss uglify');

Don't forget to add grunt to your dependencies in `package.json`. If your grunt tasks depend on other pre-defined tasks make sure to add these dependencies as well:

    "dependencies": {
        ...
        "grunt": "*",
        "grunt-contrib": "*",
        "less": "*"
    }

Push to heroku

    git push heroku master
    ...
    -----> Heroku receiving push
    -----> Fetching custom buildpack... done
    -----> Node.js app detected
    -----> Resolving engine versions
           Using Node.js version: 0.8.2
           Using npm version: 1.1.41
    -----> Fetching Node.js binaries
    -----> Vendoring node into slug
    -----> Installing dependencies with npm
           ...
           Dependencies installed
    -----> Building runtime environment
    -----> Found gruntfile, running grunt heroku task
    Running "heroku" task
    ...
    -----> Discovering process types

Debugging
---------

npm can be run with a verbose flag to help debugging if something fails when installing the dependencies.

* if the `VERBOSE` environment variable is set, npm is always run with verbose logging.
* if `BUILDPACK_RETRY_VERBOSE` is set, npm is relaunched in verbose mode if npm failed.

Thanks to [mackwic](https://github.com/mackwic) for these extensions.

Further Information
-------------------

For more information about using Node.js and buildpacks on Heroku, see these Dev Center articles:

- [Heroku Node.js Support](https://devcenter.heroku.com/articles/nodejs-support)
- [Getting Started with Node.js on Heroku](https://devcenter.heroku.com/articles/nodejs)
- [Buildpacks](https://devcenter.heroku.com/articles/buildpacks)
- [Buildpack API](https://devcenter.heroku.com/articles/buildpack-api)
- [Grunt: a task-based command line build tool for JavaScript projects](http://gruntjs.com/)


text:
import unittest
import openmesh
import os

import numpy as np

class ReadWritePLY(unittest.TestCase):

    def setUp(self):
        if not os.path.exists('OutFiles'):
            os.makedirs('OutFiles')

    def test_read_write_read(self):
        mesh1 = openmesh.read_trimesh("TestFiles/cube-minimal.obj")
        openmesh.write_mesh('OutFiles/test_read_write_read.ply', mesh1)
        mesh2 = openmesh.read_trimesh('OutFiles/test_read_write_read.ply')
        self.assertTrue(np.allclose(mesh1.points(), mesh2.points()))
        self.assertTrue(np.array_equal(mesh1.face_vertex_indices(), mesh2.face_vertex_indices()))

    def test_load_simple_point_ply_file_with_bad_encoding(self):
        self.mesh = openmesh.read_trimesh("TestFiles/pointCloudBadEncoding.ply")
        self.assertEqual(self.mesh.n_vertices(), 10)
        self.assertEqual(self.mesh.n_edges(), 0)
        self.assertEqual(self.mesh.n_faces(), 0)

    def test_load_simple_point_ply_file_with_good_encoding(self):
        self.mesh = openmesh.read_trimesh("TestFiles/pointCloudGoodEncoding.ply")
        self.assertEqual(self.mesh.n_vertices(), 10)
        self.assertEqual(self.mesh.n_edges(), 0)
        self.assertEqual(self.mesh.n_faces(), 0)

    def test_load_simple_ply(self):
        self.mesh = openmesh.read_trimesh("TestFiles/cube-minimal.ply")
        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

    def test_load_simple_ply_force_vertex_colors_although_not_available(self):
        with self.assertRaises(RuntimeError):
            openmesh.read_trimesh("TestFiles/cube-minimal.ply", vertex_color=True)

    def test_load_simple_ply_with_vertex_colors(self):
        self.mesh = openmesh.read_trimesh("TestFiles/cube-minimal-vertexColors.ply", vertex_color=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 1.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 0.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 1.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 0.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertTrue(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_colors()

    def test_load_ply_from_mesh_lab_with_vertex_colors(self):
        self.mesh = openmesh.read_trimesh("TestFiles/meshlab.ply", vertex_color=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertTrue(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_colors()

    def test_write_and_read_binary_ply_with_vertex_colors(self):
        self.mesh = openmesh.read_trimesh("TestFiles/meshlab.ply", vertex_color=True)
        openmesh.write_mesh("OutFiles/meshlab_binary.ply", self.mesh, vertex_color=True, binary=True)
        self.mesh = openmesh.read_trimesh("OutFiles/meshlab_binary.ply", vertex_color=True, binary=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertTrue(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_colors()

    def test_write_and_read_ply_with_float_vertex_colors(self):
        self.mesh = openmesh.read_trimesh("TestFiles/meshlab.ply", vertex_color=True)
        openmesh.write_mesh("OutFiles/meshlab_float.ply", self.mesh, vertex_color=True, color_float=True)
        self.mesh = openmesh.read_trimesh("OutFiles/meshlab_float.ply", vertex_color=True, color_float=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertTrue(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_colors()

    def test_write_and_read_binary_ply_with_float_vertex_colors(self):
        self.mesh = openmesh.read_trimesh("TestFiles/meshlab.ply", vertex_color=True)
        openmesh.write_mesh("OutFiles/meshlab_binary_float.ply", self.mesh, vertex_color=True, color_float=True, binary=True)
        self.mesh = openmesh.read_trimesh("OutFiles/meshlab_binary_float.ply", vertex_color=True, color_float=True, binary=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(0))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(3))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[0], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[1], 0.0)
        self.assertEqual(self.mesh.color(self.mesh.vertex_handle(7))[2], 1.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertTrue(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_colors()

    def test_load_simple_ply_with_texcoords(self):
        self.mesh = openmesh.read_trimesh("TestFiles/cube-minimal-texCoords.ply", vertex_tex_coord=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertEqual(self.mesh.texcoord2D(self.mesh.vertex_handle(0))[0], 10.0)
        self.assertEqual(self.mesh.texcoord2D(self.mesh.vertex_handle(0))[1], 10.0)

        self.assertEqual(self.mesh.texcoord2D(self.mesh.vertex_handle(2))[0], 6.0)
        self.assertEqual(self.mesh.texcoord2D(self.mesh.vertex_handle(2))[1], 6.0)

        self.assertEqual(self.mesh.texcoord2D(self.mesh.vertex_handle(4))[0], 9.0)
        self.assertEqual(self.mesh.texcoord2D(self.mesh.vertex_handle(4))[1], 9.0)

        self.assertEqual(self.mesh.texcoord2D(self.mesh.vertex_handle(7))[0], 12.0)
        self.assertEqual(self.mesh.texcoord2D(self.mesh.vertex_handle(7))[1], 12.0)

        self.assertFalse(self.mesh.has_vertex_normals())
        self.assertTrue(self.mesh.has_vertex_texcoords1D())
        self.assertTrue(self.mesh.has_vertex_texcoords2D())
        self.assertTrue(self.mesh.has_vertex_texcoords3D())
        self.assertFalse(self.mesh.has_vertex_colors())

        self.mesh.release_vertex_texcoords2D()

    def test_load_simple_ply_with_normals(self):
        self.mesh = openmesh.read_trimesh("TestFiles/cube-minimal-normals.ply", vertex_normal=True)

        self.assertEqual(self.mesh.n_vertices(), 8)
        self.assertEqual(self.mesh.n_edges(), 18)
        self.assertEqual(self.mesh.n_faces(), 12)

        self.assertTrue(self.mesh.has_vertex_normals())
        self.assertFalse(self.mesh.has_vertex_texcoords1D())
        self.assertFalse(self.mesh.has_vertex_texcoords2D())
        self.assertFalse(self.mesh.has_vertex_texcoords3D())
        self.assertFalse(self.mesh.has_vertex_colors())

        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(0))[0], 0.0)
        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(0))[1], 0.0)
        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(0))[2], 1.0)

        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(3))[0], 1.0)
        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(3))[1], 0.0)
        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(3))[2], 0.0)

        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(4))[0], 1.0)
        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(4))[1], 0.0)
        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(4))[2], 1.0)

        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(7))[0], 1.0)
        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(7))[1], 1.0)
        self.assertEqual(self.mesh.normal(self.mesh.vertex_handle(7))[2], 2.0)

        self.mesh.release_vertex_normals()

    def test_read_nonexistent_ply(self):
        with self.assertRaises(RuntimeError):
            self.mesh = openmesh.read_trimesh("TestFiles/nonexistent.ply")
        with self.assertRaises(RuntimeError):
            self.mesh = openmesh.read_polymesh("TestFiles/nonexistent.ply")

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(ReadWritePLY)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
<?php

/**
 * This file is part of the Future CI package.
 * Future CI is licensed under MIT (https://github.com/f500/future-ci/blob/master/LICENSE).
 */

namespace F500\CI\Console\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class QueueStatusCommand
 *
 * @copyright 2014 Future500 B.V.
 * @license   https://github.com/f500/future-ci/blob/master/LICENSE MIT
 * @package   F500\CI\Console\Command
 */
class QueueStatusCommand extends QueueCommand
{

    protected function configure()
    {
        $this
            ->setName('queue:status')
            ->setDescription('Checks the status of the job-queue.');

        parent::configure();
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     * @return void
     * @throws \RuntimeException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $connection = $this->pheanstalk->getConnection();

        $listening = $connection->isServiceListening();

        $output->writeln("\n                 Server status");
        $output->writeln('                 -------------');

        $output->writeln(sprintf('                       Server: <fg=yellow>%s</fg=yellow>', $connection->getHost()));
        $output->writeln(sprintf('                         Post: <fg=yellow>%s</fg=yellow>', $connection->getPort()));
        $output->writeln(
            sprintf('                      Timeout: <fg=yellow>%s</fg=yellow>', $connection->getConnectTimeout())
        );
        $output->writeln(
            sprintf(
                '                    Listening: %s',
                $listening ? '<fg=green>yes</fg=green>' : '<fg=red>no</fg=red>'
            )
        );

        if ($listening) {
            foreach ($this->pheanstalk->listTubes() as $tube) {
                $stats = $this->pheanstalk->statsTube($tube);

                $output->writeln(
                    sprintf(
                        "\n%sTube <fg=yellow>%s</fg=yellow> status",
                        str_repeat(' ', max(18 - strlen($tube), 0)),
                        $tube
                    )
                );
                $output->writeln(
                    sprintf('%s%s', str_repeat(' ', max(18 - strlen($tube), 0)), str_repeat('-', strlen($tube) + 12))
                );

                $output->writeln(
                    sprintf('          Current urgent jobs: <fg=yellow>%d</fg=yellow>', $stats['current-jobs-urgent'])
                );
                $output->writeln(
                    sprintf('           Current ready jobs: <fg=yellow>%d</fg=yellow>', $stats['current-jobs-ready'])
                );
                $output->writeln(
                    sprintf('        Current reserved jobs: <fg=yellow>%d</fg=yellow>', $stats['current-jobs-reserved'])
                );
                $output->writeln(
                    sprintf('         Current delayed jobs: <fg=yellow>%d</fg=yellow>', $stats['current-jobs-delayed'])
                );
                $output->writeln(
                    sprintf('          Current buried jobs: <fg=yellow>%d</fg=yellow>', $stats['current-jobs-buried'])
                );
                $output->writeln(
                    sprintf('                   Total jobs: <fg=yellow>%d</fg=yellow>', $stats['total-jobs'])
                );
                $output->writeln(
                    sprintf('     Current open connections: <fg=yellow>%d</fg=yellow>', $stats['current-using'])
                );
                $output->writeln(
                    sprintf(' Current watching connections: <fg=yellow>%d</fg=yellow>', $stats['current-watching'])
                );
                $output->writeln(
                    sprintf('  Current waiting connections: <fg=yellow>%d</fg=yellow>', $stats['current-waiting'])
                );
                $output->writeln(
                    sprintf('              Delete commands: <fg=yellow>%d</fg=yellow>', $stats['cmd-delete'])
                );
                $output->writeln(
                    sprintf('          Pause tube commands: <fg=yellow>%d</fg=yellow>', $stats['cmd-pause-tube'])
                );
                $output->writeln(sprintf('                       Paused: <fg=yellow>%d</fg=yellow>', $stats['pause']));
                $output->writeln(
                    sprintf('              Pause time left: <fg=yellow>%d</fg=yellow>', $stats['pause-time-left'])
                );
            }
        }
    }
}


text:
This directory contains the default API proxies that are provided with every
organization on Apigee Edge. If you create an account on Apigee Edge, and
then you log in to the Edge management UI, you will see these two API
proxies in your organization.

We provide them here for convenience. If you need to reset to 'factory settings'
you can simply deploy the API proxies provided here.

# Get help and interact with other API developers

For assistance, please use [StackOverflow](http://stackoverflow.com/tags/apigee)
and add the tag "apigee".

Copyright © 2014 Apigee Corporation

Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
from applications.assets.models import Equipment
from applications.station.models import StationBusiness, Station, StationRental
from django.forms import ModelForm

class StationBusinessForm(ModelForm):
    class Meta:
        model = StationBusiness
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        station_pk = kwargs.pop('station_pk', None)
        super(StationBusinessForm, self).__init__(*args, **kwargs)
        if station_pk is not None:
            self.fields['station'].queryset = Station.objects.filter(pk=station_pk)
        elif kwargs.get('instance', None) is not None:
            self.fields['station'].queryset = Station.objects.filter(pk=kwargs['instance'].station.pk)
        self.fields['business'].empty_label = None
        self.fields['station'].empty_label = None
        self.fields['station'].widget.attrs['readonly'] = 'readonly'

class StationRentalForm(ModelForm):
    class Meta:
        model = StationRental
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super(StationRentalForm, self).__init__(*args, **kwargs)
        instance = kwargs.get('instance', None)
        if instance is not None:
            self.fields['station'].queryset = Station.objects.filter(pk=instance.station.pk)
            self.fields['equipment'].queryset = Equipment.objects.filter(pk=instance.equipment.pk)
            self.fields['station'].empty_label = None
            self.fields['equipment'].empty_label = None
            self.fields['station'].widget.attrs['readonly'] = 'readonly'
            self.fields['equipment'].widget.attrs['readonly'] = 'readonly'


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>XMLHttpRequest Test: xhr2_XMLHttpRequest_response_responseType_empty_string_error_flag_set</title>
<link rel="author" title="Intel" href="http://www.intel.com"/>
<link rel="help" href="http://www.w3.org/TR/2012/WD-XMLHttpRequest-20121206/#dom-xmlhttprequest-response"/>


text:
title: Archive
subtitle:
layout: "archives"
type: page
---


text:
'''craigslist blob server module.

This module creates a thin HTTP wrapper over the client module. The server
exists to provide a persistent client for incoming HTTP requests. These
requests are calls to query or manipulate blobs or the blob service
itself. Each server instance is bound to a client library using a **shared
client object**.

When the server receives an incoming **request**, it calls the appropriate
method on shared client instance. When the client returns with the result,
the server returns this to the recipient as the body of the HTTP response.

Since the server is bound to the client with a shared client object,
and this object stores call state, the server can process incoming
requests independently (and asynchronously) from the client's processing
of requests.

Beyond the blob and admin methods of the client instance, the server
also supportes retreiving the config object for this server, as well
as a console page. The html diagnostic and admin console lives in
**console.html**. It is simply a web page frontend that uses AJAX requests
to query status information for each replica using the same HTTP calls that
the server/client system uses to manage the blob service. After starting
the server visit /_console on the server host and port to view it.'''

import os.path

import clblob.client
import clcommon.config
import clcommon.http
import clcommon.server

DEFAULT_CONFIG = clcommon.config.update(clblob.client.DEFAULT_CONFIG,
    clcommon.http.DEFAULT_CONFIG)

DEFAULT_CONFIG_FILES = clblob.client.DEFAULT_CONFIG_FILES + [
    '/etc/clblobserver.conf',
    '~/.clblobserver.conf']

DEFAULT_CONFIG_DIRS = clblob.client.DEFAULT_CONFIG_DIRS + [
    '/etc/clblobserver.d',
    '~/.clblobserver.d']

class Request(clcommon.http.Request):
    '''Request handler for blobs.'''

    def run(self):
        '''Run the request.'''
        name = self.env['PATH_INFO'].strip('/')
        if name[:1] == '_':
            name, body = self._run_admin(name[1:])
        else:
            name, body = self._run(name)
        return self.ok(self.set_content(name, body))

    def _run(self, name):
        '''Run a command.'''
        kwargs = self.parse_params(['replicate', 'response'],
            ['deleted', 'modified', 'modified_deleted', 'ttl'], ['encoded'])
        if self.method == 'DELETE':
            body = self.server.blob_client.delete(name, **kwargs)
        elif self.method == 'GET':
            try:
                body = self.server.blob_client.get(name, **kwargs)
            except clblob.InvalidRequest, exception:
                self.log.warning(_('Invalid request: %s'), exception)
                raise clcommon.http.BadRequest()
            except clblob.NotFound:
                raise clcommon.http.NotFound()
        elif self.method == 'PUT':
            body = self.server.blob_client.put(name, self.body, **kwargs)
        else:
            raise clcommon.http.MethodNotAllowed()
        return name, body

    def _run_admin(self, name):
        '''Run an admin command.'''
        parts = name.split('/', 1)
        if len(parts) == 1:
            parts.append(None)
        if name == 'config':
            body = self.server.config
        elif name == 'console':
            name = os.path.join(os.path.dirname(__file__), 'console.html')
            body = open(name)
        elif name == 'jquery.js':
            body = open(clcommon.http.JQUERY)
        elif name == 'favicon.ico':
            body = open(clcommon.http.FAVICON)
        elif parts[0] == 'buffer':
            body = self.server.blob_client.buffer(parts[1])
        elif parts[0] == 'configcheck':
            if len(self.body_data) == 0:
                raise clcommon.http.BadRequest()
            kwargs = self.parse_params(['tolerance'], None, ['brief'])
            body = self.server.blob_client.configcheck(self.body_data,
                parts[1], **kwargs)
        elif parts[0] == 'list':
            kwargs = self.parse_params(None,
                ['modified_start', 'modified_stop', 'checksum_modulo'],
                ['checksum'])
            body = self.server.blob_client.list(parts[1], **kwargs)
        elif parts[0] == 'logstatus':
            body = self.server.blob_client.logstatus(parts[1])
        elif parts[0] == 'purge':
            body = self.server.blob_client.purge(parts[1])
        elif parts[0] == 'status':
            body = self.server.blob_client.status(parts[1])
        elif parts[0] == 'sync':
            kwargs = self.parse_params(['source'],
                ['modified_start', 'modified_stop'])
            body = self.server.blob_client.sync(parts[1], **kwargs)
        else:
            raise clcommon.http.NotFound()
        return name, body

class Server(clcommon.http.Server):
    '''Wrapper for the HTTP server that adds a blob client that will be used
    for all request handling.'''

    def __init__(self, config, request):
        super(Server, self).__init__(config, request)
        self.blob_client = None

    def start(self):
        self.blob_client = clblob.client.Client(self.config)
        super(Server, self).start()

    def stop(self, timeout=None):
        super(Server, self).stop(timeout)
        self.blob_client.stop()
        self.blob_client = None

if __name__ == '__main__':
    clcommon.server.Server(DEFAULT_CONFIG, DEFAULT_CONFIG_FILES,
        DEFAULT_CONFIG_DIRS, [lambda config: Server(config, Request)]).start()


text:
export * from './directives';
export * from './services';
export * from './map-types';
export { LatLngBounds, LatLng, LatLngLiteral, MapTypeStyle, PolyMouseEvent } from './services/google-maps-types';
export { AgmCoreModule } from './core-module';


text:
<input type="hidden" name="phase" id="phase" value="<?php echo $Phase ?>">

Plan de Acción

Ordene las Actividades

Click sobre la pregunta y arrástrela al principio o al final, según su prioridad.

              Actividades

              {{p.question}}
              <input type="hidden" id="ordenPreguntas{{p.id}}" value="{{p.id}}">

                Fecha Inicial:
                <input type="text" id="from" name="from" class="form-control border-input" placeholder="Fecha Inicial">

                Fecha Final:
                <input type="text" id="to" name="to" class="form-control border-input" placeholder="Fecha Final">

        Atrás
        <button  type="button" class="btn btn-info btn-fill btn-wd" ng-click="siguiente()" >Siguiente</button>


text:
<?php

require_once 'tools/helpers/bookstore/BookstoreTestBase.php';

/**
 * Tests the generated classes by behaviors.
 *
 * @author     Francois Zaninotto
 * @package    generator.behavior
 */
class AddClassBehaviorTest extends BookstoreTestBase
{
  public function testClassExists()
  {
    $t = new AddClassTableFooClass();
    $this->assertTrue($t instanceof AddClassTableFooClass, 'behaviors can generate classes that are autoloaded');
  }
}


text:
#region BSD License

#endregion

namespace Clide
{
    using System;

    /// <summary>
	/// Provides members to interact with the Error List window
	/// </summary>
	public interface IErrorsManager
	{
        /// <summary>
        /// Adds an error to the error list.
        /// </summary>
        IErrorItem AddError(string text, Action<IErrorItem> handler);

        /// <summary>
        /// Adds a warning to the error list.
        /// </summary>
        IErrorItem AddWarning(string text, Action<IErrorItem> handler);

        /// <summary>
		/// Clear the errors.
		/// </summary>
		void ClearErrors();

		/// <summary>
		/// Shows the errors.
		/// </summary>
		void ShowErrors();
	}
}


text:
<?php

class Dotdigitalgroup_Email_Block_Adminhtml_Column_Renderer_Subscriber
    extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{

    /**
     * Render grid columns.
     *
     * @param Varien_Object $row
     *
     * @return string
     */
    public function render(Varien_Object $row)
    {
        $value = $this->_getValue($row);
        $storeId = $row->getStoreId();
        $websiteHash = Mage::getSingleton('adminhtml/system_store')
            ->getWebsiteOptionHash(true);
        if ($value == 0 && $storeId > 0) {
            return $websiteHash[Mage::app()->getStore($storeId)->getWebsite()->getId()];
        }

        return $websiteHash[$value];
    }
}


text:
package com.example.tests.GroupTests;
import com.example.tests.TestBase;
import com.example.utils.SortedListOf;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import static com.example.tests.GroupTests.GroupDataGenerator.loadGroupsFromCsvFile;
import static com.example.tests.GroupTests.GroupDataGenerator.loadGroupsFromXmlFile;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;

public class NonEmptyGroupCreationTest extends  TestBase{

    @DataProvider
    public Iterator<Object[]> groupsFromFile() throws IOException {
        return wrapGroupsForDataProvider(loadGroupsFromCsvFile(new File("groups.txt"))).iterator();
        //return wrapGroupsForDataProvider(loadGroupsFromXmlFile(new File("groups.xml"))).iterator();
    }

   @Test(dataProvider = "groupsFromFile")
        public void GroupCreationWithValidData (GroupData group)throws Exception {
            SortedListOf<GroupData> oldList = app.getGroupHelper().getGroups();
            //actions
            app.getGroupHelper().createGroup(group);
            SortedListOf<GroupData> newList = app.getGroupHelper().getGroups();
            //compare states
            assertThat(newList, equalTo(oldList.withAdded(group)));
        }

    }


text:
import { forwardRef } from "react";

import { FontIcon, FontIconProps } from "@react-md/icon";

export const InsertEmoticonFontIcon = forwardRef<HTMLElement, FontIconProps>(
  function InsertEmoticonFontIcon(props, ref) {
    return (
      <FontIcon {...props} ref={ref}>
        insert_emoticon
      </FontIcon>
    );
  }
);


text:
import { Some } from "../utils/maybe/Some";
import { None } from "../utils/maybe/None";
export const add3ToEvens = (x: number) => x % 2 == 0 ? Some(x + 3) : None;


text:
package rt

import (
	gocontext "context"
	"fmt"
	"math/rand"
	"os"
	"time"

	"v.io/v23/context"
	"v.io/v23/security"
	"v.io/x/ref"
	vsecurity "v.io/x/ref/lib/security"
)

func (r *Runtime) initPrincipal(ctx *context.T, credentials string) (security.Principal, func(), error) {
	if principal, _ := ctx.Value(principalKey{}).(security.Principal); principal != nil {
		return principal, func() {}, nil
	}
	if len(credentials) > 0 {
		// Explicitly specified credentials, load them from the credentials
		// location without the ability to write them back to persistent
		// storage, but rather reloading them periodically or on a signal.
		readonly := true // should this be an option?
		reloadPeriod := 5 * time.Minute
		if update := os.Getenv(ref.EnvCredentialsReloadInterval); len(update) > 0 {
			if tmp, err := time.ParseDuration(update); err == nil {
				reloadPeriod = tmp
			}
		}
		goctx, cancel := gocontext.WithCancel(gocontext.Background())
		principal, err := vsecurity.LoadPersistentPrincipalDaemon(
			goctx,
			credentials,
			nil, // no passphrase.
			readonly,
			reloadPeriod,
		)
		if err != nil {
			cancel()
			return nil, nil, fmt.Errorf("failed to initialize credentials, perhaps you need to create them with 'principal create %v: %v", credentials, err)
		}
		return principal, func() { cancel() }, nil
	}

	// No agent, no explicit credentials specified: create a new principal
	// and blessing in memory.
	principal, err := vsecurity.NewPrincipal()
	if err != nil {
		return principal, nil, err
	}
	return principal, func() {}, vsecurity.InitDefaultBlessings(principal, defaultBlessingName())
}

func defaultBlessingName() string {
	options := []string{
		"apple", "banana", "cherry", "dragonfruit", "elderberry", "fig", "grape", "honeydew",
	}
	name := fmt.Sprintf("anonymous-%s-%d",
		options[rand.New(rand.NewSource(time.Now().Unix())).Intn(len(options))],
		os.Getpid())
	host, _ := os.Hostname()
	// (none) is a common default hostname and contains parentheses,
	// which are invalid blessings characters.
	if host == "(none)" || len(host) == 0 {
		return name
	}
	return name + "@" + host
}


text:
name             'failing_cookbook'
maintainer       'Michael Kirk'
maintainer_email 'michael.john.kirk@gmail.com'
license          'MIT'
description      'Installs/Configures failing_cookbook'
long_description 'Installs/Configures failing_cookbook'
version          '0.1.0'