text:
"""
Trump.py

APP: TrumpaTron
DESC: A model class for performing tweet-based logic
CREATION_DATE: 2017-02-27

"""

# MODULES
# | Native
from random import choice, shuffle, randint
from curses.ascii import ispunct
import re
import os
import time

# | Third-Party
import tweepy

# | Custom
import lib.bannon

# METADATA
__author__ = 'Joshua Carlson-Purcell'
__copyright__ = 'Copyright 2017, CarlsoNet'
__license__ = 'MIT'
__version__ = '2.0.0'
__maintainer__ = 'Joshua Carlson-Purcell'
__email__ = 'jcarlson@carlso.net'
__status__ = 'Production'

class Trump(lib.bannon.Bannon):
    """
    Trump.py

    The main tweet-controlling class
    """

    apiConn = None
    tweetSet = []
    tweetClauses = []
    generatedTweet = ''

    def __init__(self, cliParams, configParams):
        lib.bannon.Bannon.__init__(self, cliParams, configParams)

        # connect to Twitter API
        self.createTwitterAPIConn()

    def createTwitterAPIConn(self):
        """
        Authenticate to Twitter API using Tweepy library

        :return: void
        """

        # auth to twitter using oAuth
        auth = tweepy.OAuthHandler(self.config['consumerKey'], self.config['consumerSecret'])
        auth.set_access_token(self.config['accessToken'], self.config['accessTokenSecret'])

        # connect to twitter API
        self.apiConn = tweepy.API(auth)

    def getTweets(self, twitterUsername):
        """
        Get default tweet list for given twitter username

        :param twitterUsername: Twitter username or ID to fetch tweets from
        :return: void
        """

        # get public timeline tweets for user
        rawTweets = self.apiConn.user_timeline(twitterUsername)

        # strip tweet text from raw tweets
        for tweet in rawTweets:
            self.tweetSet.append(tweet.text)

    def flushTweetData(self):
        """
        Flush all fetched tweets, tweet clauses, and generated tweets

        :return: void
        """

        self.tweetSet = []
        self.tweetClauses = []
        self.generatedTweet = ''

    def spliceTweets(self):
        """
        Splice a set of tweets into a list of individual clauses

        :return: void
        """

        clauses = []

        # list and splice fetched tweets
        for tweet in self.tweetSet:
            # split tweet into list of clauses
            clauseSet = tweet.split('. ')

            # add clause set to master set
            clauses += clauseSet

        self.tweetClauses = clauses

    def formatTweet(self, tweetTxt):
        """
        Format tweet text, e.g. remove urls, strip excess whitespace, add ending punctuation, etc

        :param tweetTxt: raw text of tweet
        :return: string - filtered tweet text
        """

        if not tweetTxt:
            raise ValueError('ERROR: blank tweet text provided')
        else:
            # filter out URLs and strip surrounding whitespace
            tweetTxt = re.sub(r'[:\s]*http\S+(|\s)', '', tweetTxt).strip()

            # check if ll text has been stripped
            if not tweetTxt:
                # set to default tweet clause
                tweetTxt = '<3'

        return tweetTxt

    def pruneTweetClauses(self):
        """
        Prune and deduplicate sets of Tweet clauses

        :return: void
        """

        # dedupe clause set
        prunedTweetClauseSet = list(set(self.tweetClauses))
        prunedTweetClauseSet.sort(key=self.tweetClauses.index)

        # filter tweet text
        for i in range(0, len(prunedTweetClauseSet)):
            prunedTweetClauseSet[i] = self.formatTweet(prunedTweetClauseSet[i])

        # sort list of clauses by length
        prunedTweetClauseSet.sort(key=len)

        self.tweetClauses = prunedTweetClauseSet

    def divideClausesIntoSlices(self):
        """
        Split self.tweetClauses into N number of slices, where n = numClauses

        :return: a list containing all clause slices
        """

        slices = []

        # divide the set of tweet clauses into n slices, where n = numClausesToUse
        numClausesInSlice = int(len(self.tweetClauses) / self.config['numClauses'])

        # iterate through slices
        for i in range(0, self.config['numClauses']):
            slices.append([])

            # fill up slice with values
            startTweetClauseIdx = i * numClausesInSlice
            endTweetClauseIdx = startTweetClauseIdx + numClausesInSlice
            slices[i] = self.tweetClauses[startTweetClauseIdx:endTweetClauseIdx]

        return slices

    def getRandomTweetClause(self, clauses):
        """
        Choose a random clause from the set of tweet clauses

        :return: clause from given list
        """

        # make selection
        clause = choice(clauses)

        # capitalize the first letter in the clause
        clause = clause[0].capitalize() + clause[1:]

        # make sure it's punctuated or the default clause
        if not ispunct(clause[-1]) and clause != '<3':
            clause += '!'

        return clause

    def generateTweet(self):
        """
        Generates a unique tweet from a given set of sentence clauses

        :return: void
        """

        # check if tweet clauses are available
        if self.tweetClauses:
            slices = self.divideClausesIntoSlices()

            # generate tweet from clause slices
            # longest slice clause is always first, shortest is last, and the middle are chosen at random for
            # n - 2 clausesToUse
            longestClause = self.getRandomTweetClause(slices[-1])
            slices.pop(-1)

            shortestClause = self.getRandomTweetClause(slices[0])
            slices.pop(0)

            # generate middle clauses if any slices are still left
            middleClauses = ''
            if slices:
                # shuffle middle slices
                shuffle(slices)
                for clauseSlice in slices:
                    currentClause = self.getRandomTweetClause(clauseSlice)
                    middleClauses += currentClause

                # cap w/ period if not already punctuated
                if not ispunct(middleClauses[-1]):
                    middleClauses += '.'

            # concatonate tweet
            newTweet = longestClause + ' ' + middleClauses + ' ' + shortestClause

            self.generatedTweet = newTweet
        else:
            raise ValueError('no tweet clauses available')

    def sendTweet(self):
        """
        Send new generated Tweet to Twitter API

        :return: int based on success/fail : -1=discarded;0=no tweet provided;1=published
        """

        if self.generatedTweet:
            # send tweet to authenticated account using tweepy api connection
            if not self.config['assumeYes'] and not self.config['daemonMode']:
                # confirmation required, prompt user
                print('GENERATED TWEET:', self.generatedTweet)
                shouldPublish = input('=> Would you like to publish this tweet? [y/N]: ')
                shouldPublish = shouldPublish.strip().lower()
                if (shouldPublish != 'y' and shouldPublish != 'yes') or not shouldPublish:
                    return -1

            # attempt to publish tweet
            return self.apiConn.update_status(self.generatedTweet)
        else:
            raise ValueError('empty tweet text provided')

    def startBot(self, twitterUser):
        """
        Start button for TrumpaTron

        :param twitterUser: username (or ID) of user to fetch tweets from
        :return: void
        """

        # start daemon loop
        while True:
            # fetch tweets
            self.getTweets(twitterUser)
            self.logger.debug('RAW TWEETS :: ' + str(self.tweetSet))

            # splice tweets into clauses and prune
            self.spliceTweets()
            self.pruneTweetClauses()
            self.logger.debug('SPLICED AND PRUNED TWEET CLAUSES :: ' + str(self.tweetClauses))

            # generate new tweet from clauses
            numTweetGenIterations = 0
            maxTweetGenIterations = 100
            while len(self.generatedTweet) == 0 or 140 < len(self.generatedTweet):
                # tweet msg is too long, try regenerating
                self.generateTweet()

                # increase generation count
                numTweetGenIterations += 1

                # check if iteration max has been hit
                if maxTweetGenIterations < numTweetGenIterations:
                    self.logger.critical('Maximum number of Tweet generation attempts ( ' + str(maxTweetGenIterations)
                                         + ' ) has been reached. Try reducing the number of clauses.')

                    exit(2)
            self.logger.debug('GENERATED TWEET: ' + self.generatedTweet)

            # publish tweet
            try:
                # check if this is a test run
                if not self.config['testRun']:
                    # not a test run, send tweet
                    tweetPubRslt = self.sendTweet()

                    # check result
                    if tweetPubRslt == -1:
                        self.logger.info('tweet not published, discarding...')
                    elif not tweetPubRslt:
                        self.logger.error('could not publish tweet for an unknown reason :(')
                    else:
                        self.logger.info('TWEET PUBLISHED SUCCESSFULLY! [ ID: ' + str(tweetPubRslt.id) + ' ]')
                else:
                    self.logger.info('application in test mode, not publishing tweet')
            except ValueError as valErr:
                self.logger.warning('invalid value provided for tweet :: ' + self.generatedTweet + ' :: ' + str(valErr))
            except tweepy.TweepError as err:
                self.logger.critical('could not publish tweet :: ' + self.generatedTweet + ' :: '
                                     + str(err.response) + ' :: ' + str(err.reason))

                exit(1)

            # check if daemonization is requested, break out of loop if not
            if not self.config['daemonMode']:
                break
            else:
                # try forking the process
                pidChild = os.fork()
                if pidChild:
                    # in parent process, exit
                    break
                else:
                    # in child process
                    # decouple process
                    try:
                        os.setsid()
                        os.chdir("/")
                        os.umask(0)
                    except PermissionError as permErr:
                        # this is normally caused by setsid, andmeans the user isn't sudo,
                        # it's non-critical, so we'll just log a message and move along
                        self.logger.warning('not able to ensure daemon will continue running between sessions, '
                                            'probably running as non-sudo user :: [ ' + str(permErr) + ' ]')
                        pass

                    # flush data
                    self.flushTweetData()

                    # in daemon mode, sleep for n second(s), where 1 <= n
                    if self.config['sleepDelay']:
                        # check if random delay has been requested
                        if self.config['randomSleep']:
                            sleepDelay = randint(1, self.config['sleepDelay'])
                        else:
                            sleepDelay = self.config['sleepDelay']
                    else:
                        # sleep delay not specified, use default
                        sleepDelay = 1

                    # perform sleep
                    self.logger.debug('sleeping for [ ' + str(sleepDelay) + ' ] seconds...')
                    time.sleep(sleepDelay)


text:
`Rack::Pygmoku` is a middleware for generating code syntax highlighting using the
[Pygments](http://pygments.org/) library in an environment where you cannot
install Pygments directly.

In other words, it's ideal for use on Heroku.

## Installation

Gem install, as usual:

    gem install rack-pygmoku

Then add Pygmoku to your middleware stack:

    # Within your Rackup file or similar
    use Rack::Pygmoku

## Usage

Currently, `rack-pygmoku` only supports Markdown-style code blocks, like
so:

        def greeting
          'Hello World!'
        end

_Note:_ Put the short name of the
[Pygments lexer](http://pygments.org/docs/lexers/) that you want to use in the
`data-lang` attribute on the `pre` block.

## Status

This is mainly a _toy project_ that I put together for my Nesta-powered
blog, and is likely to be maintained as such unless others find it
useful.

## Copyright

Copyright 2012 Kevin Rohrbaugh.

See LICENSE.txt for further details.

redpajama_set_name: RedPajamaGithub


text:
package com.google.teampot.util;

import com.google.appengine.api.utils.SystemProperty;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.ApiProxy.Environment;

public class AppHelper {

	public AppHelper() {

	}

	public static String getBaseUrl() {
		return "https://"+AppHelper.getBaseUrlWithoutSchema();
	}

	public static String getBaseUrlWithoutSchema() {
		if (SystemProperty.environment.value()!=SystemProperty.Environment.Value.Development) {
			String appId = AppHelper.getAppId();
			return appId+".appspot.com";
		} else {
			return "127.0.0.1:8888";
		}
	}

	public static String getAppId() {
		Environment environment = ApiProxy.getCurrentEnvironment();

		String appFullId = environment.getAppId();
		int tildeIndex = appFullId.indexOf("~");

		return tildeIndex>-1 ? appFullId.substring(tildeIndex+1) : appFullId;
	}

	public static String getAppEmail(String emailId) {
		return emailId+"@"+AppHelper.getAppId()+".appspotmail.com";
	}

	public static boolean isAppEmail(String emailAddress) {
		return emailAddress.endsWith("@"+AppHelper.getAppId()+".appspotmail.com");
	}

	public static String getTaskBaseUrl() {
		return "/gae/task";
	}

}


text:
<?php
	class Model_Comments extends EntityPHP\Entity
	{
		protected static $table_name = 'comments';

		protected $user;
		protected $content;
		protected $file;

		const	COMMENT_SUCCESS = 1;

		public function __construct(Model_Users $user = null, $content = null, Model_Files $file = null)
		{
			$this->user = $user;
			$this->content = $content;
			$this->file = $file;
		}

		public static function __structure()
		{
			return [
				'user' => 'Model_Users',
				'content' => 'TEXT',
				'file' => 'Model_Files',
			];
		}

		public function getUser()
		{
			return $this->load('user');
		}

		public function getFile()
		{
			return $this->load('file');
		}

		public static function getLastComments($number)
		{
			$request = Model_Comments::createRequest();
			$results = $request->select('*')
							   ->getOnly($number)
                               ->orderBy('id DESC')
							   ->exec();

			return $results;
		}

		public function remove()
		{
			$request = Model_Comments::createRequest();
			$results = $request->select('*')
							   ->getOnly($number)
							   ->exec();

			return $results;
		}
	}


text:
using System;

namespace ITLibrium.Hexagon.Domain.Entities
{
    public struct AppliedEvent<TAggregate, TEvent>
        where TAggregate : IAggregate<TAggregate>
        where TEvent : IAggregateEvent<TAggregate>
    {
        public TAggregate Aggregate { get; }
        public TEvent Event { get; }

        public AppliedEvent(TAggregate aggregate, TEvent @event)
        {
            Aggregate = aggregate;
            Event = @event;
        }

        public AppliedEvent<TAggregate, TEvent> Emit(EventHandler<TEvent> handler)
        {
            handler?.Invoke(Aggregate, Event);
            return this;
        }

        public static implicit operator TAggregate(AppliedEvent<TAggregate, TEvent> appliedEvent)
            => appliedEvent.Aggregate;

        public static implicit operator TEvent(AppliedEvent<TAggregate, TEvent> appliedEvent)
            => appliedEvent.Event;
    }
}


text:
require 'json'
require 'erb'
require 'set'

class Codegen
  TEMPLATES_DIRECTORY = "#{File.dirname(__FILE__)}/templates/"

  def initialize(paths, language_type_by_schema_type)
    @paths = paths
    @language_type_by_schema_type = language_type_by_schema_type

    @schemas = {}
    @enum_set = Set.new

    @paths.each do |path|
      expanded_path = File.expand_path(path)
      begin
        schema = JSON.parse(File.read(path))
        add_schema(expanded_path, schema)
      rescue => e
        e.message << "\npath: #{path}"
        raise e
      end
    end

    @schemas = @schemas.sort
    @enums = @enum_set.to_a.sort{|a,b| a[:name] <=> b[:name]}
  end

  def generate(template_name)
    template_source = File.read("#{TEMPLATES_DIRECTORY}/#{template_name}")
    template = ERB.new(template_source, nil, '-')
    STDOUT.write template.result(binding)
  end

  def add_schema(key, schema)
    @schemas[key] = schema
    (schema['definitions'] || {}).each do |name, subschema|
      subkey = "#{key}/#{name}"
      add_schema(subkey, subschema)
    end

    schema['properties'].each do |property_name, property|
      enum = property['enum']
      if enum
        parent_type_name = class_name(key)
        enum_name(parent_type_name, property_name, enum)
      end
    end
  end

  def native_type?(type_name)
    STDERR.puts "NATIVE #{type_name}"
    @language_type_by_schema_type.values.include?(type_name)
  end

  def default_value(parent_type_name, property_name, property)
    if property['items']
      '[]'
    elsif property['type'] == 'string'
      if property['enum']
        enum_type_name = type_for(parent_type_name, property_name, property)
        default_enum(enum_type_name, property)
      else
        "''"
      end
    elsif property['type'] == 'integer'
      "0"
    elsif property['type'] == 'boolean'
      "false"
    elsif property['$ref']
      type = type_for(parent_type_name, nil, property)
      "new #{type}()"
    else
      raise "Cannot create default value for #{parent_type_name}##{property.to_json}"
    end
  end

  def default_enum(enum_type_name, property)
    "#{enum_type_name}.#{enum_constant(property['enum'][0])}"
  end

  def enum_constant(value)
    value.gsub(/[\.\/\+]/, '_').upcase
  end

  def type_for(parent_type_name, property_name, property)
    ref = property['$ref']
    type = property['type']
    items = property['items']
    enum = property['enum']

    if ref
      property_type_from_ref(property['$ref'])
    elsif type
      if type == 'array'
        array_type_for(type_for(parent_type_name, nil, items))
      else
        raise "No type mapping for JSONSchema type #{type}. Schema:\n#{JSON.pretty_generate(property)}" unless @language_type_by_schema_type[type]
        if enum
          enum_type_name = enum_name(parent_type_name, property_name, enum)
          property_type_from_enum(enum_type_name)
        else
          @language_type_by_schema_type[type]
        end
      end
    else
      # Inline schema (not supported)
      raise "Property #{name} did not define 'type' or '$ref'"
    end
  end

  def property_type_from_ref(ref)
    class_name(ref)
  end

  def property_type_from_enum(enum)
    enum
  end

  def enum_name(parent_type_name, property_name, enum)
    enum_type_name = "#{parent_type_name}#{capitalize(property_name)}"
    @enum_set.add({ name: enum_type_name, values: enum })
    enum_type_name
  end

  def class_name(ref)
    File.basename(ref, '.json')
  end

  def capitalize(s)
    s.sub(/./,&:upcase)
  end

  # Thank you very much rails!
  # https://github.com/rails/rails/blob/v6.1.3.2/activesupport/lib/active_support/inflector/methods.rb#L92
  def underscore(camel_cased_word)
    return camel_cased_word unless /[A-Z-]/.match?(camel_cased_word)
    word = camel_cased_word.gsub(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
    word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
    word.tr!("-", "_")
    word.downcase!
    word
  end
end

class TypeScript < Codegen
  def initialize(paths)
    language_type_by_schema_type = {
      'integer' => 'number',
      'string' => 'string',
      'boolean' => 'boolean',
    }

    super(paths, language_type_by_schema_type)
  end

  def array_type_for(type_name)
    "readonly #{type_name}[]"
  end
end

class Java < Codegen
  def initialize(paths)
    language_type_by_schema_type = {
      'integer' => 'Long',
      'string' => 'String',
      'boolean' => 'Boolean',
    }

    super(paths, language_type_by_schema_type)
  end

  def array_type_for(type_name)
    "java.util.List<#{type_name}>"
  end
end

class Perl < Codegen
  def initialize(paths)
    language_type_by_schema_type = {
      'integer' => 'number',
      'string' => 'string',
      'boolean' => 'boolean',
    }

    super(paths, language_type_by_schema_type)
  end

  def array_type_for(type_name)
    "[]#{type_name}"
  end

  def default_value(parent_type_name, property_name, property)
    if property['type'] == 'string'
      if property['enum']
        "#{property_name.upcase}_#{enum_constant(property['enum'][0])}"
      else
        "''"
      end
    elsif property['type'] == 'boolean'
      "''"  # an empty string renders evaluates to false
    elsif property['$ref']
      type = type_for(parent_type_name, nil, property)
      "#{type}->new()"
    else
      super(parent_type_name, property_name, property)
    end
  end

  def property_type_from_ref(ref)
    "Cucumber::Messages::#{class_name(ref)}"
  end

  def property_type_from_enum(enum)
    ''
  end

  def format_description(raw_description)
    return '' if raw_description.nil?

    raw_description
      .split("\n")
      .map { |description_line| "#{description_line}" }
      .join("\n")
  end
end

class Ruby < Codegen
  def initialize(paths)
    language_type_by_schema_type = {
      'integer' => 'number',
      'string' => 'string',
      'boolean' => 'boolean',
    }

    super(paths, language_type_by_schema_type)
  end

  def array_type_for(type_name)
    "[]"
  end

  def default_value(parent_type_name, property_name, property)
    if property['type'] == 'string'
      if property['enum']
        enum_type_name = type_for(parent_type_name, property_name, property)
        "#{enum_type_name}::#{enum_constant(property['enum'][0])}"
      else
        "''"
      end
    elsif property['$ref']
      type = type_for(parent_type_name, nil, property)
      "#{type}.new"
    else
      super(parent_type_name, property_name, property)
    end
  end

  def format_description(raw_description, indent_string: "    ")
    return '' if raw_description.nil?

    raw_description
      .split("\n")
      .map { |description_line| "# #{description_line}" }
      .join("\n#{indent_string}")
  end
end

class Go < Codegen
  def initialize(paths)
    language_type_by_schema_type = {
      'integer' => 'int64',
      'string' => 'string',
      'boolean' => 'bool',
    }
    super(paths, language_type_by_schema_type)
  end

  def property_type_from_ref(ref)
    "*#{class_name(ref)}"
  end

  def array_type_for(type_name)
    "[]#{type_name}"
  end
end

class Markdown < Codegen
  def initialize(paths)
    language_type_by_schema_type = {
      'integer' => 'integer',
      'string' => 'string',
      'boolean' => 'boolean',
    }
    super(paths, language_type_by_schema_type)
  end

  def property_type_from_ref(ref)
    "[#{class_name(ref)}](##{class_name(ref).downcase})"
  end

  def property_type_from_enum(enum)
    "[#{enum}](##{enum.downcase})"
  end

  def array_type_for(type_name)
    "#{type_name}[]"
  end
end

class Php < Codegen
  def initialize(paths)
    language_type_by_schema_type = {
      'string' => 'string',
      'integer' => 'int',
      'boolean' => 'bool',
    }
    super(paths, language_type_by_schema_type)
  end

  def format_description(raw_description, indent_string: "        ")
    return '' if raw_description.nil?

    raw_description
      .split("\n")
      .map { |line| line.strip() }
      .filter { |line| line != '*' }
      .map { |line| " * #{line}" }
      .join("\n#{indent_string}")
  end

  def array_type_for(type_name)
    "array"
  end

  def enum_name(parent_type_name, property_name, enum)
    enum_type_name = "#{class_name(parent_type_name)}\\#{capitalize(property_name)}"
    @enum_set.add({ name: enum_type_name, values: enum })
    enum_type_name
  end

  def array_contents_type(parent_type_name, property_name, property)
    type_for(parent_type_name, nil, property['items'])
  end

  def is_nullable(property_name, schema)
    !(schema['required'] || []).index(property_name)
  end

  def is_scalar(property)
    property.has_key?('type') && @language_type_by_schema_type.has_key?(property['type'])
  end

  def scalar_type_for(property)
    raise "No type mapping for JSONSchema type #{type}. Schema:\n#{JSON.pretty_generate(property)}" unless @language_type_by_schema_type[property['type']]

    @language_type_by_schema_type[property['type']]
  end

  def constructor_for(parent_type, property, property_name, schema, arr_name)
    constr = non_nullable_constructor_for(parent_type, property, property_name, schema, arr_name)

    is_nullable(property_name, schema) ? "isset($#{arr_name}['#{property_name}']) ? #{constr} : null" : constr
  end

  def non_nullable_constructor_for(parent_type, property, property_name, schema, arr_name)
    source = property_name.nil? ? "#{arr_name}" : "#{arr_name}['#{property_name}']"
    if is_scalar(property)
      if property['enum']
        "#{enum_name(parent_type, property_name, property['enum'])}::from((#{scalar_type_for(property)}) $#{source})"
      else
        "(#{scalar_type_for(property)}) $#{source}"
      end
    else
      type = type_for(parent_type, property_name, property)
      if type == 'array'
        constructor = non_nullable_constructor_for(parent_type, property['items'], nil, schema, "member")
        member_type = (property['items']['type'] ? 'mixed' : 'array')
        "array_values(array_map(fn (#{member_type} $member) => #{constructor}, $#{source}))"
      else
        "#{type_for(parent_type, property_name, property)}::fromArray($#{source})"
      end
    end
  end

  def default_value(class_name, property_name, property, schema)
	if is_nullable(property_name, schema)
	  return 'null'
	end

	super(class_name, property_name, property)
  end

  def default_enum(enum_type_name, property)
    "#{enum_type_name}::#{enum_constant(property['enum'][0])}"
  end
end

clazz = Object.const_get(ARGV[0])
path = ARGV[1]
paths = File.file?(path) ? [path] : Dir["#{path}/*.json"]
codegen = clazz.new(paths)
template_name = ARGV[2]
codegen.generate(template_name)


text:
{% load staticfiles %}
<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>Menú Principal - Sistema Administrativo Guardabosques USB</title>
        <meta name="generator" content="Bootply" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">

        <link href="{% static 'css/font-awesome.min.css' %}" type="text/css" rel="stylesheet">

        <link href="{% static 'css/main.css' %}" rel="stylesheet">

    {% if dominio %}

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

                </button>
                Inicio

                {% if admin %}

                    Validación de Horas

                      Crear Actividad

                    Calendario

                    Información de los Estudiantes

Activos

Finalizados

                {% else %}

                    Registro de Actividades

                    Calendario

                    Horas Acumuladas

                {% endif %}

                      {% if request.user.first_name%}
                        {{ request.user.first_name }}
                      {% else %}
                        {{ request.user.username }}
                      {% endif %}

                        {% if admin %}

Cerrar Sesión

                        {% else %}

Mis Datos

Cerrar Sesión

                        {% endif %}

                    {% if admin %}

                      Bienvenido al Sistema de Administración del Servicio Comunitario de los Guardabosques de la Universidad Simón Bolívar.
                      Como administrador podrá ver información de los estudiantes que se encuentran actualmente en el servicio, o ya lo han culminado.
                      Validar las horas de las actividades registradas por los estudiantes, crear eventos futuros y nuevas actividades.

                    {% else %}

                      Bienvenido al Sistema de Administración del Servicio Comunitario de los Guardabosques de la Universidad Simón Bolívar.
                      Como estudiante podrá visualizar la agenda de las actividades a realizarse en los próximos días, administrar sus horas,
                      y consultar las actividades realizadas.

                    {% endif %}

                 Creado por DevLab USB

    {% else %}

Necesita entrar con una cuenta USB.VE

Volver a Inicio

    {% endif %}


text:
\hypertarget{interface_s_c_general_merchant}{}\section{S\+C\+General\+Merchant Class Reference}
\label{interface_s_c_general_merchant}\index{S\+C\+General\+Merchant@{S\+C\+General\+Merchant}}
Inheritance diagram for S\+C\+General\+Merchant\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=3.000000cm]{interface_s_c_general_merchant}
\end{center}
\end{figure}
\subsection*{Properties}
\begin{DoxyCompactItemize}
\item
N\+S\+String $\ast$ {\bfseries name}\hypertarget{interface_s_c_general_merchant_a9df90bf0f3cc8ef79dcb7779d43f4e20}{}\label{interface_s_c_general_merchant_a9df90bf0f3cc8ef79dcb7779d43f4e20}

\item
N\+S\+String $\ast$ {\bfseries email}\hypertarget{interface_s_c_general_merchant_af5798e1548df7f7b027a50bb4104374f}{}\label{interface_s_c_general_merchant_af5798e1548df7f7b027a50bb4104374f}

\item
\hyperlink{interface_s_c_general_components_meta_data}{S\+C\+General\+Components\+Meta\+Data} $\ast$ {\bfseries metadata}\hypertarget{interface_s_c_general_merchant_a5b30b17e6f83982772c31f976f90af62}{}\label{interface_s_c_general_merchant_a5b30b17e6f83982772c31f976f90af62}

\item
\hyperlink{interface_s_c_general_location}{S\+C\+General\+Location} $\ast$ {\bfseries location}\hypertarget{interface_s_c_general_merchant_acb2778b70594939b0b269db1eddf85b3}{}\label{interface_s_c_general_merchant_acb2778b70594939b0b269db1eddf85b3}

\item
N\+S\+Array $\ast$ {\bfseries photo}\hypertarget{interface_s_c_general_merchant_a2b06e74095bbe9a064d2018230b31053}{}\label{interface_s_c_general_merchant_a2b06e74095bbe9a064d2018230b31053}

\item
N\+S\+String $\ast$ {\bfseries photo\+Main}\hypertarget{interface_s_c_general_merchant_a472c37606369f898d336e20b1eb38480}{}\label{interface_s_c_general_merchant_a472c37606369f898d336e20b1eb38480}

\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
Pod/\+Classes/\+Model/\+General/S\+C\+General\+Merchant.\+h\end{DoxyCompactItemize}


text:
package org.ontosoft.client.components.chart.events;

import com.google.gwt.event.shared.HandlerRegistration;

public interface HasCategoryChartHandlers {
  public HandlerRegistration addCategorySelectionHandler(
      CategorySelectionHandler handler);
}


text:
package org.minijax.nio;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Set;

public class MockSocketChannel extends SocketChannel {
    private final Socket socket = new Socket();
    private final ByteBuffer inputBuffer;
    private final ByteBuffer outputBuffer;

    protected MockSocketChannel(final SelectorProvider provider) {
        super(provider);
        inputBuffer = ByteBuffer.allocate(1000);
        outputBuffer = ByteBuffer.allocate(1000);
    }

    public MockSocketChannel(final SelectorProvider provider, final String input) {
        this(provider);
        inputBuffer.put(input.getBytes());
        inputBuffer.flip();
    }

    @Override
    public Socket socket() {
        return socket;
    }

    @Override
    protected void implConfigureBlocking(final boolean block) throws IOException {
    }

    @Override
    protected void implCloseSelectableChannel() throws IOException {
    }

    @Override
    public int read(final ByteBuffer dst) throws IOException {
        final int bytesRead = inputBuffer.remaining();
        dst.put(inputBuffer);
        return bytesRead;
    }

    @Override
    public int write(final ByteBuffer src) throws IOException {
        final int bytesWritten = src.remaining();
        outputBuffer.put(src);
        return bytesWritten;
    }

    public String getOutputAsString() {
        outputBuffer.flip();
        final StringBuilder b = new StringBuilder();
        while (outputBuffer.hasRemaining()) {
            b.append((char) outputBuffer.get());
        }
        return b.toString();
    }

    // Unsupported

    @Override
    public <T> T getOption(final SocketOption<T> name) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Set<SocketOption<?>> supportedOptions() {
        throw new UnsupportedOperationException();
    }

    @Override
    public SocketChannel bind(final SocketAddress local) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public <T> SocketChannel setOption(final SocketOption<T> name, final T value) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public SocketChannel shutdownInput() throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public SocketChannel shutdownOutput() throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isConnected() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isConnectionPending() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean connect(final SocketAddress remote) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean finishConnect() throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public SocketAddress getRemoteAddress() throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public long read(final ByteBuffer[] dsts, final int offset, final int length) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public long write(final ByteBuffer[] srcs, final int offset, final int length) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public SocketAddress getLocalAddress() throws IOException {
        throw new UnsupportedOperationException();
    }
}


text:
Sample of how to animate a marker to follow a line path in  Google Maps

See the [demo] (http://dezkareid.github.io/Speed-Map/)


text:
package org.openqa.selenium.browserlaunchers;

import static org.openqa.selenium.remote.CapabilityType.PROXY;
import static org.openqa.selenium.remote.CapabilityType.ForSeleniumServer.AVOIDING_PROXY;
import static org.openqa.selenium.remote.CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC;
import static org.openqa.selenium.remote.CapabilityType.ForSeleniumServer.PROXYING_EVERYTHING;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.CapabilityType.ForSeleniumServer;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

public class Proxies {
  public static final String PROXY_CONFIG = CapabilityType.PROXY;

  public static boolean isProxyRequired(Capabilities capabilities) {
    return capabilities.is("proxyRequired") || capabilities.getCapability(PROXY_CONFIG) != null;
  }

  /**
   * Generate a proxy.pac file, configuring a dynamic proxy.
   * <p/>
   * If proxySeleniumTrafficOnly is true, then the proxy applies only to URLs containing
   * "/selenium-server/". Otherwise the proxy applies to all URLs.
   */
  public static File makeProxyPAC(File parentDir, int port, Capabilities capabilities) {
    return makeProxyPAC(parentDir, port,
        System.getProperty("http.proxyHost"),
        System.getProperty("http.proxyPort"),
        System.getProperty("http.nonProxyHosts"), capabilities);
  }

  public static File makeProxyPAC(File parentDir, int port, String configuredProxy,
      String proxyPort, String nonProxyHosts, Capabilities capabilities) {
    DoNotUseProxyPac pac =
        newProxyPac(port, configuredProxy, proxyPort, nonProxyHosts, capabilities);

    Proxy proxy = extractProxy(capabilities);
    if (proxy != null && proxy.getHttpProxy() != null) {
      pac.defaults().toProxy(proxy.getHttpProxy());
    }

    try {
      File pacFile = new File(parentDir, "proxy.pac");
      Writer out = new FileWriter(pacFile);
      pac.outputTo(out);
      out.close();
      return pacFile;
    } catch (IOException e) {
      throw new WebDriverException("Unable to configure proxy. Selenium will not work.", e);
    }
  }

  @SuppressWarnings({"unchecked"})
  public static Proxy extractProxy(Capabilities capabilities) {
    Object rawProxy = capabilities.getCapability(PROXY);
    Proxy proxy = null;
    if (rawProxy != null) {
      if (rawProxy instanceof Proxy) {
        proxy = (Proxy) rawProxy;
      } else if (rawProxy instanceof Map) {
        proxy = new Proxy((Map<String, ?>) rawProxy);
      }
    }
    return proxy;
  }

  static DoNotUseProxyPac newProxyPac(int port, String configuredProxy, String proxyPort,
      String nonProxyHosts, Capabilities capabilities) {
    DoNotUseProxyPac existingConfig = (DoNotUseProxyPac) capabilities.getCapability(
        ForSeleniumServer.PROXY_PAC);
    DoNotUseProxyPac pac = existingConfig == null ? new DoNotUseProxyPac() : existingConfig;

    Object tempProxy = capabilities.getCapability(CapabilityType.PROXY);
    if (tempProxy != null) {
      Proxy proxy = extractProxy(capabilities);
      if (proxy.getHttpProxy() != null) {
        pac.defaults().toProxy(proxy.getHttpProxy());
      } else if (proxy.getProxyAutoconfigUrl() != null) {
        URI pacUri = null;
        try {
          pacUri = new URI(proxy.getProxyAutoconfigUrl());
          pac.deriveFrom(pacUri);
        } catch (URISyntaxException e) {
          throw new WebDriverException(e);
        }
      }
    }

    if (configuredProxy != null) {
      String proxyToUse = configuredProxy;
      if (proxyPort != null) {
        proxyToUse += ":" + proxyPort;
      }
      pac.defaults().toProxy(proxyToUse);
    }

    String defaultProxy = "DIRECT";
    if (configuredProxy != null) {
      defaultProxy = "PROXY " + configuredProxy;
      if (proxyPort != null) {
        defaultProxy += ":" + proxyPort;
      }
    }

    String seleniumServerAsProxy = "localhost:" + port + "; " + defaultProxy;
    if (isOnlyProxyingSelenium(capabilities)) {
      pac.map("*/selenium-server/*").toProxy(seleniumServerAsProxy);
      if (nonProxyHosts != null && nonProxyHosts.trim().length() > 0) {
        String[] hosts = nonProxyHosts.split("\\|");
        for (String host : hosts) {
          pac.mapHost(host).toNoProxy();
        }
      }
    } else {
      pac.defaults().toProxy(seleniumServerAsProxy);
    }
    return pac;
  }

  public static boolean isProxyingAllTraffic(Capabilities capabilities) {
    // According to the original logic of Selenium Server, the only time when
    // the selenium sever wouldn't be proxying all traffic was when it was
    // configured to only proxy selenium traffic, was avoid the proxy and had
    // not been asked to proxy everything. Modeling that first before tidying
    // up the logic.
    return !(capabilities.is(ONLY_PROXYING_SELENIUM_TRAFFIC) &&
        capabilities.is(AVOIDING_PROXY) && !capabilities.is(PROXYING_EVERYTHING));
  }

  public static boolean isOnlyProxyingSelenium(Capabilities capabilities) {
    return !isProxyingAllTraffic(capabilities);
  }

  public static Capabilities setProxyEverything(Capabilities source, boolean isProxyingEverything) {
    DesiredCapabilities toReturn = newDesiredCapabilities(source);
    toReturn.setCapability(PROXYING_EVERYTHING, isProxyingEverything);
    return toReturn;
  }

  public static Capabilities setAvoidProxy(Capabilities source, boolean avoidProxy) {
    DesiredCapabilities toReturn = newDesiredCapabilities(source);
    toReturn.setCapability(AVOIDING_PROXY, avoidProxy);
    return toReturn;
  }

  public static Capabilities setOnlyProxySeleniumTraffic(Capabilities source,
      boolean onlyProxySeleniumTraffic) {
    DesiredCapabilities toReturn = newDesiredCapabilities(source);
    toReturn.setCapability(ONLY_PROXYING_SELENIUM_TRAFFIC, onlyProxySeleniumTraffic);
    return toReturn;
  }

  public static Capabilities setProxyRequired(Capabilities source, boolean proxyRequired) {
    DesiredCapabilities toReturn = newDesiredCapabilities(source);
    toReturn.setCapability("proxyRequired", proxyRequired);
    return toReturn;
  }

  private static DesiredCapabilities newDesiredCapabilities(Capabilities source) {
    if (source instanceof DesiredCapabilities) {
      return (DesiredCapabilities) source;
    }
    return new DesiredCapabilities(source);
  }
}


text:
input[type=range]{
    -webkit-appearance: none;
}

input[type=range]::-webkit-slider-runnable-track {
    width: 300px;
    height: 5px;
    background: #ddd;
    border: none;
    border-radius: 3px;
}

input[type=range]::-webkit-slider-thumb {
    -webkit-appearance: none;
    border: none;
    height: 24px;
    width: 24px;
    border-radius: 50%;
    background: #730100;
    margin-top: -10px;
}

input[type=range]:focus {
    outline: none;
}

input[type=range]:focus::-webkit-slider-runnable-track {
    background: #ccc;
}

input[type=range]{
    /* fix for FF unable to apply focus style bug  */
    border: 1px solid white;

    /*required for proper track sizing in FF*/
    width: 300px;
}

input[type=range]::-moz-range-track {
    height: 5px;
    background: #ddd;
    border: none;
    border-radius: 3px;
}

input[type=range]::-moz-range-thumb {
    border: none;
    height: 24px;
    width: 24px;
    border-radius: 50%;
    background: #730100;
}

/*hide the outline behind the border*/
input[type=range]:-moz-focusring{
    outline: 1px solid white;
    outline-offset: -1px;
}

input[type=range]:focus::-moz-range-track {
    background: #ccc;
}


text:
export schemaversion = $(shell ls -1 xsd/rpd-*xsd | tail -1 | sed 's^xsd/rpd-^^;s^.xsd^^')

all: default-subdirs default-all

.PHONY: clean dist install html docs

export TOPDIR = $(shell pwd)
# DISTDIR is not a typo: "rpath-product-definition" is the name
# of the package that contains the code; "product-definition" is
# the name of packages containing a product definition
export DISTDIR = $(TOPDIR)/rpath-product-definition-$(VERSION)

SUBDIRS=rpath_proddef xsd doc

dist_files = $(extra_files)

.PHONY: clean dist install subdirs

subdirs: default-subdirs

install: install-subdirs install-compat

clean: clean-subdirs default-clean

generate:
	make -C rpath_proddef generate

validate-schema:
	make -C xsd validate-schema

install-compat:
	# Compatibility stubs for old rbuild (RPCL-63)
	mkdir -p $(DESTDIR)$(sitedir)rpath_common/proddef
	echo "from rpath_proddef.api1 import *" >$(DESTDIR)$(sitedir)rpath_common/proddef/__init__.py
	echo "from rpath_proddef.api1 import *" >$(DESTDIR)$(sitedir)rpath_common/proddef/api1.py
	python -c "from compileall import *; compile_dir('$(DESTDIR)$(sitedir)rpath_common/proddef', 10, '$(sitedir)rpath_common/proddef')"
	python -O -c "from compileall import *; compile_dir('$(DESTDIR)$(sitedir)rpath_common/proddef', 10, '$(sitedir)rpath_common/proddef')"

dist:
	if ! grep "^Changes in $(VERSION)" NEWS > /dev/null 2>&1; then \
		echo "no NEWS entry"; \
		exit 1; \
	fi
	$(MAKE) forcedist

archive: checkversion
	hg archive --exclude .hgignore -t tbz2 $(DISTDIR).tar.bz2

forcedist: archive

doc: html
html: default-subdirs
	scripts/generate_docs.sh

checkversion:
	@echo $(VERSION) | grep "^$(schemaversion)" || { echo "version mismatch between latest schema $(schemaversion) and product version $(VERSION)"; exit 1; }

show-version:
	@echo $(VERSION)

forcetag: checkversion
	hg tag -f product-definition-$(VERSION)
tag: checkversion
	hg tag product-definition-$(VERSION)

clean: clean-subdirs default-clean
	@rm -rf $(DISTDIR).tar.bz2

include Make.rules
include Make.defs

# vim: set sts=8 sw=8 noexpandtab :


text:
define(function () {

  // Syntactic sugar to provide some structure to SimpleForm inputs - Just
  // wraps options with { type: type, viewOptions: viewOptions, addOptions: addOptions }

  var INPUT = 'INPUT';
  var BUTTON = 'BUTTON';
  var DIVIDER = 'DIVIDER';
  var TOOLBAR = 'TOOLBAR';
  var VIEW = 'VIEW';

  function wrap(type) {
    return function (viewOptions, addOptions) {
      return { type: type, viewOptions: viewOptions, addOptions: addOptions };
    };
  }

  return {
    Input: wrap(INPUT),
    Button: wrap(BUTTON),
    Divider: wrap(DIVIDER),
    Toolbar: wrap(TOOLBAR),
    View: wrap(VIEW),

    INPUT: INPUT,
    BUTTON: BUTTON,
    DIVIDER: DIVIDER,
    TOOLBAR: TOOLBAR,
    VIEW: VIEW
  };

});


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Card, { CardActions, CardContent, CardMedia } from 'material-ui/Card';
import { CircularProgress } from 'material-ui/Progress';
import IconButton from 'material-ui/IconButton';
import Button from 'material-ui/Button';
import Typography from 'material-ui/Typography';
import apiSpec from '../apiSpec';

const styles = theme => ({
    card: {
        width: '240px',
        [theme.breakpoints.up('sm')]: {
            minHeight: '400px',
        },
        [theme.breakpoints.up('md')]: {
            width: '320px',
            minHeight: '480px',
        }
    },
    actions: {
        justifyContent: 'center',
    },
    spacer: {
        flex: '1 1 auto',
    },
    statusButton: {
        fontSize: theme.typography.subheading.fontSize,
        fontWeight: theme.typography.button.fontWeight
    },
    progressContainer: {
        width: '100%',
        height: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
    }
});

class MediaListItem extends Component {

    static propTypes = {
        mediaId: PropTypes.number.isRequired,
        mediaType: PropTypes.oneOf([
            apiSpec.mediaType.anime,
            apiSpec.mediaType.manga
        ]).isRequired,
        isLoading: PropTypes.bool,
        error: PropTypes.string,
        media: PropTypes.object,
        progress: PropTypes.number,
        score: PropTypes.number,
        loadMedia: PropTypes.func.isRequired,
    };

    componentDidMount() {
        this.props.loadMedia({
            id: this.props.mediaId,
            mediaType: this.props.mediaType
        });
    }

    render() {
        const {
            classes,
            mediaType,
            isLoading,
            media,
            progress,
            score,
        } = this.props;
        const {
            coverImage,
            title,
            [mediaType === apiSpec.mediaType.anime ? 'episodes' : 'chapters'] : total,
        } = media ? media : {};
        return (
            <Card className={classes.card}>
                { media ?

                    <CardMedia className={classes.cover} component="img"
                    src={coverImage.large}
                    title={title.english ? title.english : title.romaji}/>
                    <CardContent>
                        <Typography type="headline" component="h2" gutterBottom>
                            {title.romaji}
                        </Typography>
                    </CardContent>
                    <CardActions className={classes.actions}>
                        <Button focusRipple className={classes.statusButton}>
                            {progress}/{total ? total : '?'}
                        </Button>
                        <IconButton>add</IconButton>

                        <Button focusRipple color="primary" className={classes.statusButton}>
                            {score}
                        </Button>
                    </CardActions>

 :
                isLoading ?

                    <CircularProgress className={classes.progress} size={160} color="accent"/>

 :
                null
                }
            </Card>
        );
    }
}

export default withStyles(styles)(MediaListItem);


text:
import Settings, { FilterFunction } from '../settings';
import { Errno } from '../types';
export declare function isFatalError(settings: Settings, error: Errno): boolean;
export declare function isAppliedFilter<T>(filter: FilterFunction<T> | null, value: T): boolean;
export declare function replacePathSegmentSeparator(filepath: string, separator: string): string;
export declare function joinPathSegments(a: string, b: string, separator: string): string;
//# sourceMappingURL=common.d.ts.map


text:
package leakybucket

import (
	"time"
)

// START OMIT
type Storage interface {
	Create(name string, capacity uint, rate time.Duration) (Bucket, error)
}

// END OMIT

type Bucket interface {
	Capacity() uint
	Remaining() uint
	// Reset returns when the bucket will be drained.
	Reset() time.Time
	// Add to the bucket. Returns bucket state after adding.
	Add(uint) (BucketState, error)
}

type BucketState struct {
	Capacity  uint
	Remaining uint
	Reset     time.Time
}


text:
<!DOCTYPE html>

		<title>Tinysort unit test</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<link href="qunit-1.15.0-iddqd.css" type="text/css" rel="stylesheet" />


text:
require_relative '../mikrotik_api'

Puppet::Type.type(:mikrotik_snmp_community).provide(:mikrotik_api, :parent => Puppet::Provider::Mikrotik_Api) do
  confine :feature => :mtik

  mk_resource_methods

  def self.instances
    communities = Puppet::Provider::Mikrotik_Api::get_all("/snmp/community")
    Puppet.debug("/snmp/community: #{communities.inspect}")
    instances = communities.collect { |community| snmpCommunity(community) }

    instances
  end

  def self.snmpCommunity(data)
    addresses = data['addresses'].nil? ? nil : data['addresses'].split(',')

    new(
      :ensure       => :present,
      :name         => data['name'],
      :read_access  => data['read-access'],
      :write_access => data['write-access'],
      :addresses    => addresses
    )
  end

  def flush
    Puppet.debug("Flushing SNMP Community #{resource[:name]}")

    params = {}
    params["name"] = resource[:name]
    params["read-access"] = resource[:read_access] if ! resource[:read_access].nil?
    params["write-access"] = resource[:write_access] if ! resource[:write_access].nil?
    params["addresses"] = resource[:addresses].join(',') if ! resource[:addresses].nil?

    lookup = {}
    lookup["name"] = resource[:name]

    Puppet.debug("Params: #{params.inspect} - Lookup: #{lookup.inspect}")

    simple_flush("/snmp/community", params, lookup)
  end
end


text:
soco.music_services.music_service module
========================================

.. automodule:: soco.music_services.music_service


text:
using EPiServer.Core;

namespace StarRepublic.Episerver.SPA.Models.WebApi
{
    public class ContentTreeLinkItem
    {
        public ContentTreeLinkItem(PageData pageData, string url)
        {
            Name = pageData.Name;
            ContentReference = pageData.ContentLink;
            Type = pageData.PageTypeName;
            Url = url;
        }

        public ContentReference ContentReference { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
    }
}


text:
namespace web_app {
namespace {

class WebAppUninstallJobTest : public WebAppTest {
 public:
  WebAppUninstallJobTest() = default;

  void SetUp() override {
    WebAppTest::SetUp();

    fake_registry_controller_ =
        std::make_unique<FakeWebAppRegistryController>();

    controller().SetUp(profile());

    install_manager_ = std::make_unique<WebAppInstallManager>(profile());

    file_utils_wrapper_ =
        base::MakeRefCounted<testing::StrictMock<MockFileUtilsWrapper>>();
    icon_manager_ =
        std::make_unique<WebAppIconManager>(profile(), file_utils_wrapper_);
    icon_manager_->SetSubsystems(&controller().registrar(), &install_manager());
  }

  void TearDown() override {
    file_utils_wrapper_ = nullptr;
    WebAppTest::TearDown();
  }

  FakeWebAppRegistryController& controller() {
    return *fake_registry_controller_;
  }

  WebAppInstallManager& install_manager() const { return *install_manager_; }

  WebAppInstallFinalizer& install_finalizer() const {
    return *install_finalizer_;
  }

  testing::StrictMock<MockOsIntegrationManager> os_integration_manager_;
  std::unique_ptr<WebAppInstallManager> install_manager_;
  std::unique_ptr<WebAppInstallFinalizer> install_finalizer_;
  std::unique_ptr<FakeWebAppRegistryController> fake_registry_controller_;
  std::unique_ptr<WebAppIconManager> icon_manager_;
  scoped_refptr<testing::StrictMock<MockFileUtilsWrapper>> file_utils_wrapper_;
};

TEST_F(WebAppUninstallJobTest, SimpleUninstall) {
  Registry registry;
  auto web_app =
      test::CreateWebApp(GURL("https://www.example.com"), Source::kSync);
  AppId id = web_app->app_id();
  registry.emplace(id, std::move(web_app));
  controller().database_factory().WriteRegistry(registry);
  controller().Init();

  WebAppUninstallJob task(&os_integration_manager_, &controller().sync_bridge(),
                          icon_manager_.get(), &controller().registrar(),
                          &install_manager(), &install_finalizer(),
                          &controller().translation_manager(),
                          profile()->GetPrefs());

  OsHooksErrors result;
  EXPECT_CALL(os_integration_manager_, UninstallAllOsHooks(id, testing::_))
      .WillOnce(base::test::RunOnceCallback<1>(result));

  base::FilePath deletion_path = GetManifestResourcesDirectoryForApp(
      GetWebAppsRootDirectory(profile()), id);

  EXPECT_CALL(*file_utils_wrapper_, DeleteFileRecursively(deletion_path))
      .WillOnce(testing::Return(true));

  base::RunLoop loop;
  task.Start(id, url::Origin(), webapps::WebappUninstallSource::kAppMenu,
             WebAppUninstallJob::ModifyAppRegistry::kYes,
             base::BindLambdaForTesting([&](webapps::UninstallResultCode code) {
               EXPECT_EQ(webapps::UninstallResultCode::kSuccess, code);
               loop.Quit();
             }));
  loop.Run();

  EXPECT_EQ(controller().registrar().GetAppById(id), nullptr);
}

TEST_F(WebAppUninstallJobTest, FailedDataDelete) {
  Registry registry;
  auto web_app =
      test::CreateWebApp(GURL("https://www.example.com"), Source::kSync);
  AppId id = web_app->app_id();
  registry.emplace(id, std::move(web_app));
  controller().database_factory().WriteRegistry(registry);
  controller().Init();

  WebAppUninstallJob task(&os_integration_manager_, &controller().sync_bridge(),
                          icon_manager_.get(), &controller().registrar(),
                          &install_manager(), &install_finalizer(),
                          &controller().translation_manager(),
                          profile()->GetPrefs());

  OsHooksErrors result;
  EXPECT_CALL(os_integration_manager_, UninstallAllOsHooks(id, testing::_))
      .WillOnce(base::test::RunOnceCallback<1>(result));

  base::FilePath deletion_path = GetManifestResourcesDirectoryForApp(
      GetWebAppsRootDirectory(profile()), id);

  EXPECT_CALL(*file_utils_wrapper_, DeleteFileRecursively(deletion_path))
      .WillOnce(testing::Return(false));

  base::RunLoop loop;
  task.Start(id, url::Origin(), webapps::WebappUninstallSource::kAppMenu,
             WebAppUninstallJob::ModifyAppRegistry::kYes,
             base::BindLambdaForTesting([&](webapps::UninstallResultCode code) {
               EXPECT_EQ(webapps::UninstallResultCode::kError, code);
               loop.Quit();
             }));
  loop.Run();

  EXPECT_EQ(controller().registrar().GetAppById(id), nullptr);
}

TEST_F(WebAppUninstallJobTest, FailedOsHooks) {
  Registry registry;
  auto web_app =
      test::CreateWebApp(GURL("https://www.example.com"), Source::kSync);
  AppId id = web_app->app_id();
  registry.emplace(id, std::move(web_app));
  controller().database_factory().WriteRegistry(registry);
  controller().Init();

  WebAppUninstallJob task(&os_integration_manager_, &controller().sync_bridge(),
                          icon_manager_.get(), &controller().registrar(),
                          &install_manager(), &install_finalizer(),
                          &controller().translation_manager(),
                          profile()->GetPrefs());

  OsHooksErrors result;
  result.set(true);
  EXPECT_CALL(os_integration_manager_, UninstallAllOsHooks(id, testing::_))
      .WillOnce(base::test::RunOnceCallback<1>(result));

  base::FilePath deletion_path = GetManifestResourcesDirectoryForApp(
      GetWebAppsRootDirectory(profile()), id);

  EXPECT_CALL(*file_utils_wrapper_, DeleteFileRecursively(deletion_path))
      .WillOnce(testing::Return(true));

  base::RunLoop loop;
  task.Start(id, url::Origin(), webapps::WebappUninstallSource::kAppMenu,
             WebAppUninstallJob::ModifyAppRegistry::kYes,
             base::BindLambdaForTesting([&](webapps::UninstallResultCode code) {
               EXPECT_EQ(webapps::UninstallResultCode::kError, code);
               loop.Quit();
             }));
  loop.Run();

  EXPECT_EQ(controller().registrar().GetAppById(id), nullptr);
}

}  // namespace
}  // namespace web_app


text:
$(".login.index").ready(function(){
  function doLogin(){
    $.ajax(
      base_url("login/do_login"),
        {
          method: "POST",
          data: $("#login-form").serialize(),
          dataType: "json",
          success: function(resp, status, req) {
            redirect("places/my_places");
          },
          error: function(req, status, error) {
            displayMessage("#alerts-container", req.responseJSON.message, req.responseJSON.level, true);
            boundErrors("#login-form", req.responseJSON.level, req.responseJSON.data, false);
          }
        }
      );
  }
  $("#login-form").submit(function(e){
    e.preventDefault();
  })
  $("#btn-login").click(function(){
    doLogin();
  });
});

$(".login.forgot_password").ready(function(){
  function requestNewPassword(){
    $.ajax(
      base_url("login/request_new_password"),
        {
          method: "POST",
          data: $("#request-password-form").serialize(),
          dataType: "json",
          success: function(resp, status, req) {
            $("#msg-heading").slideUp();
            $(".dismissable").slideUp({
              duration: 400,
              done: function() {
                displayMessage("#alerts-container", resp.message, resp.level, false);
            }});

          },
          error: function(req, status, error) {
            displayMessage("#alerts-container", req.responseJSON.message, req.responseJSON.level, true);
            boundErrors("#request-password-form", req.responseJSON.level, req.responseJSON.data, true);
          }
        }
      );
  }
  $("#request-password-form").submit(function(e){
    e.preventDefault();
  })
  $("#btn-request").click(function(){
    requestNewPassword();
  });
});

$(".login.reset_password").ready(function(){
  function saveNewPassword() {
    $.ajax(
      base_url("login/save_new_password"),
        {
          method: "POST",
          data: $("#reset-password-form").serialize(),
          dataType: "json",
          success: function(resp, status, req) {
            $("#msg-heading").slideUp();
            $(".dismissable").slideUp({
              duration: 400,
              done: function() {
                displayMessage("#alerts-container", resp.message, resp.level, false);
            }});

          },
          error: function(req, status, error) {
            boundErrors("#reset-password-form", req.responseJSON.level, req.responseJSON.data, true);
            displayMessage("#alerts-container", req.responseJSON.message, req.responseJSON.level, true);
          }
        }
      );
  }
  $("#reset-password-form").submit(function(e){
    e.preventDefault();
  })
  $("#btn-reset").click(function(){
    saveNewPassword();
  });
});


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_
#define FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_

#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/macros.h"
#include "flutter/vulkan/vulkan_handle.h"

namespace vulkan {

class VulkanProcTable;

class VulkanCommandBuffer {
 public:
  VulkanCommandBuffer(const VulkanProcTable& vk,
                      const VulkanHandle<VkDevice>& device,
                      const VulkanHandle<VkCommandPool>& pool);

  ~VulkanCommandBuffer();

  bool IsValid() const;

  VkCommandBuffer Handle() const;

  FML_WARN_UNUSED_RESULT
  bool Begin() const;

  FML_WARN_UNUSED_RESULT
  bool End() const;

  FML_WARN_UNUSED_RESULT
  bool InsertPipelineBarrier(
      VkPipelineStageFlagBits src_stage_flags,
      VkPipelineStageFlagBits dest_stage_flags,
      uint32_t /* mask of VkDependencyFlagBits */ dependency_flags,
      uint32_t memory_barrier_count,
      const VkMemoryBarrier* memory_barriers,
      uint32_t buffer_memory_barrier_count,
      const VkBufferMemoryBarrier* buffer_memory_barriers,
      uint32_t image_memory_barrier_count,
      const VkImageMemoryBarrier* image_memory_barriers) const;

 private:
  const VulkanProcTable& vk;
  const VulkanHandle<VkDevice>& device_;
  const VulkanHandle<VkCommandPool>& pool_;
  VulkanHandle<VkCommandBuffer> handle_;
  bool valid_;

  FML_DISALLOW_COPY_AND_ASSIGN(VulkanCommandBuffer);
};

}  // namespace vulkan

#endif  // FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_


text:
package db

import (
	"context"
	"database/sql"
	"time"

	"github.com/google/uuid"
)

const approveTask = `-- name: ApproveTask :one
UPDATE tasks
SET approved_at = $3,
    updated_at  = $3
WHERE workflow_id = $1
  AND name = $2
RETURNING workflow_id, name, finished, result, error, created_at, updated_at, approved_at, ready_for_approval, started, retry_count
`

type ApproveTaskParams struct {
	WorkflowID uuid.UUID
	Name       string
	ApprovedAt sql.NullTime
}

func (q *Queries) ApproveTask(ctx context.Context, arg ApproveTaskParams) (Task, error) {
	row := q.db.QueryRow(ctx, approveTask, arg.WorkflowID, arg.Name, arg.ApprovedAt)
	var i Task
	err := row.Scan(
		&i.WorkflowID,
		&i.Name,
		&i.Finished,
		&i.Result,
		&i.Error,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ApprovedAt,
		&i.ReadyForApproval,
		&i.Started,
		&i.RetryCount,
	)
	return i, err
}

const clearWorkflowSchedule = `-- name: ClearWorkflowSchedule :many
UPDATE workflows
SET schedule_id = NULL
WHERE schedule_id = $1::int
RETURNING id
`

func (q *Queries) ClearWorkflowSchedule(ctx context.Context, dollar_1 int32) ([]uuid.UUID, error) {
	rows, err := q.db.Query(ctx, clearWorkflowSchedule, dollar_1)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []uuid.UUID
	for rows.Next() {
		var id uuid.UUID
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const createSchedule = `-- name: CreateSchedule :one
INSERT INTO schedules (workflow_name, workflow_params, spec, once, interval_minutes, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, workflow_name, workflow_params, spec, once, interval_minutes, created_at, updated_at
`

type CreateScheduleParams struct {
	WorkflowName    string
	WorkflowParams  sql.NullString
	Spec            string
	Once            time.Time
	IntervalMinutes int32
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

func (q *Queries) CreateSchedule(ctx context.Context, arg CreateScheduleParams) (Schedule, error) {
	row := q.db.QueryRow(ctx, createSchedule,
		arg.WorkflowName,
		arg.WorkflowParams,
		arg.Spec,
		arg.Once,
		arg.IntervalMinutes,
		arg.CreatedAt,
		arg.UpdatedAt,
	)
	var i Schedule
	err := row.Scan(
		&i.ID,
		&i.WorkflowName,
		&i.WorkflowParams,
		&i.Spec,
		&i.Once,
		&i.IntervalMinutes,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const createTask = `-- name: CreateTask :one
INSERT INTO tasks (workflow_id, name, finished, result, error, created_at, updated_at, approved_at,
                   ready_for_approval)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING workflow_id, name, finished, result, error, created_at, updated_at, approved_at, ready_for_approval, started, retry_count
`

type CreateTaskParams struct {
	WorkflowID       uuid.UUID
	Name             string
	Finished         bool
	Result           sql.NullString
	Error            sql.NullString
	CreatedAt        time.Time
	UpdatedAt        time.Time
	ApprovedAt       sql.NullTime
	ReadyForApproval bool
}

func (q *Queries) CreateTask(ctx context.Context, arg CreateTaskParams) (Task, error) {
	row := q.db.QueryRow(ctx, createTask,
		arg.WorkflowID,
		arg.Name,
		arg.Finished,
		arg.Result,
		arg.Error,
		arg.CreatedAt,
		arg.UpdatedAt,
		arg.ApprovedAt,
		arg.ReadyForApproval,
	)
	var i Task
	err := row.Scan(
		&i.WorkflowID,
		&i.Name,
		&i.Finished,
		&i.Result,
		&i.Error,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ApprovedAt,
		&i.ReadyForApproval,
		&i.Started,
		&i.RetryCount,
	)
	return i, err
}

const createTaskLog = `-- name: CreateTaskLog :one
INSERT INTO task_logs (workflow_id, task_name, body)
VALUES ($1, $2, $3)
RETURNING id, workflow_id, task_name, body, created_at, updated_at
`

type CreateTaskLogParams struct {
	WorkflowID uuid.UUID
	TaskName   string
	Body       string
}

func (q *Queries) CreateTaskLog(ctx context.Context, arg CreateTaskLogParams) (TaskLog, error) {
	row := q.db.QueryRow(ctx, createTaskLog, arg.WorkflowID, arg.TaskName, arg.Body)
	var i TaskLog
	err := row.Scan(
		&i.ID,
		&i.WorkflowID,
		&i.TaskName,
		&i.Body,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const createWorkflow = `-- name: CreateWorkflow :one
INSERT INTO workflows (id, params, name, schedule_id, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, params, name, created_at, updated_at, finished, output, error, schedule_id
`

type CreateWorkflowParams struct {
	ID         uuid.UUID
	Params     sql.NullString
	Name       sql.NullString
	ScheduleID sql.NullInt32
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

func (q *Queries) CreateWorkflow(ctx context.Context, arg CreateWorkflowParams) (Workflow, error) {
	row := q.db.QueryRow(ctx, createWorkflow,
		arg.ID,
		arg.Params,
		arg.Name,
		arg.ScheduleID,
		arg.CreatedAt,
		arg.UpdatedAt,
	)
	var i Workflow
	err := row.Scan(
		&i.ID,
		&i.Params,
		&i.Name,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Finished,
		&i.Output,
		&i.Error,
		&i.ScheduleID,
	)
	return i, err
}

const deleteSchedule = `-- name: DeleteSchedule :one
DELETE
FROM schedules
WHERE id = $1
RETURNING id, workflow_name, workflow_params, spec, once, interval_minutes, created_at, updated_at
`

func (q *Queries) DeleteSchedule(ctx context.Context, id int32) (Schedule, error) {
	row := q.db.QueryRow(ctx, deleteSchedule, id)
	var i Schedule
	err := row.Scan(
		&i.ID,
		&i.WorkflowName,
		&i.WorkflowParams,
		&i.Spec,
		&i.Once,
		&i.IntervalMinutes,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const failUnfinishedTasks = `-- name: FailUnfinishedTasks :exec
UPDATE tasks
    SET finished = TRUE,
    started      = TRUE,
    error        = 'task interrupted before completion',
    updated_at   = $2
WHERE workflow_id = $1 and started and not finished
`

type FailUnfinishedTasksParams struct {
	WorkflowID uuid.UUID
	UpdatedAt  time.Time
}

func (q *Queries) FailUnfinishedTasks(ctx context.Context, arg FailUnfinishedTasksParams) error {
	_, err := q.db.Exec(ctx, failUnfinishedTasks, arg.WorkflowID, arg.UpdatedAt)
	return err
}

const schedules = `-- name: Schedules :many
SELECT id, workflow_name, workflow_params, spec, once, interval_minutes, created_at, updated_at
FROM schedules
ORDER BY id
`

func (q *Queries) Schedules(ctx context.Context) ([]Schedule, error) {
	rows, err := q.db.Query(ctx, schedules)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []Schedule
	for rows.Next() {
		var i Schedule
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowName,
			&i.WorkflowParams,
			&i.Spec,
			&i.Once,
			&i.IntervalMinutes,
			&i.CreatedAt,
			&i.UpdatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const schedulesLastRun = `-- name: SchedulesLastRun :many
WITH last_scheduled_run AS (
    SELECT DISTINCT ON (schedule_id) schedule_id, id, created_at, workflows.error, finished
    FROM workflows
    ORDER BY schedule_id, workflows.created_at DESC
)
SELECT schedules.id,
       last_scheduled_run.id AS workflow_id,
       last_scheduled_run.created_at AS workflow_created_at,
       last_scheduled_run.error AS workflow_error,
       last_scheduled_run.finished AS workflow_finished
FROM schedules
LEFT OUTER JOIN last_scheduled_run ON last_scheduled_run.schedule_id = schedules.id
`

type SchedulesLastRunRow struct {
	ID                int32
	WorkflowID        uuid.UUID
	WorkflowCreatedAt sql.NullTime
	WorkflowError     sql.NullString
	WorkflowFinished  sql.NullBool
}

func (q *Queries) SchedulesLastRun(ctx context.Context) ([]SchedulesLastRunRow, error) {
	rows, err := q.db.Query(ctx, schedulesLastRun)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []SchedulesLastRunRow
	for rows.Next() {
		var i SchedulesLastRunRow
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowID,
			&i.WorkflowCreatedAt,
			&i.WorkflowError,
			&i.WorkflowFinished,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const task = `-- name: Task :one
SELECT tasks.workflow_id, tasks.name, tasks.finished, tasks.result, tasks.error, tasks.created_at, tasks.updated_at, tasks.approved_at, tasks.ready_for_approval, tasks.started, tasks.retry_count
FROM tasks
WHERE workflow_id = $1
  AND name = $2
LIMIT 1
`

type TaskParams struct {
	WorkflowID uuid.UUID
	Name       string
}

func (q *Queries) Task(ctx context.Context, arg TaskParams) (Task, error) {
	row := q.db.QueryRow(ctx, task, arg.WorkflowID, arg.Name)
	var i Task
	err := row.Scan(
		&i.WorkflowID,
		&i.Name,
		&i.Finished,
		&i.Result,
		&i.Error,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ApprovedAt,
		&i.ReadyForApproval,
		&i.Started,
		&i.RetryCount,
	)
	return i, err
}

const taskLogs = `-- name: TaskLogs :many
SELECT task_logs.id, task_logs.workflow_id, task_logs.task_name, task_logs.body, task_logs.created_at, task_logs.updated_at
FROM task_logs
ORDER BY created_at
`

func (q *Queries) TaskLogs(ctx context.Context) ([]TaskLog, error) {
	rows, err := q.db.Query(ctx, taskLogs)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskLog
	for rows.Next() {
		var i TaskLog
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowID,
			&i.TaskName,
			&i.Body,
			&i.CreatedAt,
			&i.UpdatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const taskLogsForTask = `-- name: TaskLogsForTask :many
SELECT task_logs.id, task_logs.workflow_id, task_logs.task_name, task_logs.body, task_logs.created_at, task_logs.updated_at
FROM task_logs
WHERE workflow_id = $1
  AND task_name = $2
ORDER BY created_at
`

type TaskLogsForTaskParams struct {
	WorkflowID uuid.UUID
	TaskName   string
}

func (q *Queries) TaskLogsForTask(ctx context.Context, arg TaskLogsForTaskParams) ([]TaskLog, error) {
	rows, err := q.db.Query(ctx, taskLogsForTask, arg.WorkflowID, arg.TaskName)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskLog
	for rows.Next() {
		var i TaskLog
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowID,
			&i.TaskName,
			&i.Body,
			&i.CreatedAt,
			&i.UpdatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const taskLogsForWorkflow = `-- name: TaskLogsForWorkflow :many
SELECT task_logs.id, task_logs.workflow_id, task_logs.task_name, task_logs.body, task_logs.created_at, task_logs.updated_at
FROM task_logs
WHERE workflow_id = $1
ORDER BY created_at
`

func (q *Queries) TaskLogsForWorkflow(ctx context.Context, workflowID uuid.UUID) ([]TaskLog, error) {
	rows, err := q.db.Query(ctx, taskLogsForWorkflow, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskLog
	for rows.Next() {
		var i TaskLog
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowID,
			&i.TaskName,
			&i.Body,
			&i.CreatedAt,
			&i.UpdatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const tasks = `-- name: Tasks :many
WITH most_recent_logs AS (
    SELECT workflow_id, task_name, MAX(updated_at) AS updated_at
    FROM task_logs
    GROUP BY workflow_id, task_name
)
SELECT tasks.workflow_id, tasks.name, tasks.finished, tasks.result, tasks.error, tasks.created_at, tasks.updated_at, tasks.approved_at, tasks.ready_for_approval, tasks.started, tasks.retry_count,
       GREATEST(most_recent_logs.updated_at, tasks.updated_at)::timestamptz AS most_recent_update
FROM tasks
LEFT JOIN most_recent_logs ON tasks.workflow_id = most_recent_logs.workflow_id AND
                              tasks.name = most_recent_logs.task_name
ORDER BY most_recent_update DESC
`

type TasksRow struct {
	WorkflowID       uuid.UUID
	Name             string
	Finished         bool
	Result           sql.NullString
	Error            sql.NullString
	CreatedAt        time.Time
	UpdatedAt        time.Time
	ApprovedAt       sql.NullTime
	ReadyForApproval bool
	Started          bool
	RetryCount       int32
	MostRecentUpdate time.Time
}

func (q *Queries) Tasks(ctx context.Context) ([]TasksRow, error) {
	rows, err := q.db.Query(ctx, tasks)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TasksRow
	for rows.Next() {
		var i TasksRow
		if err := rows.Scan(
			&i.WorkflowID,
			&i.Name,
			&i.Finished,
			&i.Result,
			&i.Error,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.ApprovedAt,
			&i.ReadyForApproval,
			&i.Started,
			&i.RetryCount,
			&i.MostRecentUpdate,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const tasksForWorkflow = `-- name: TasksForWorkflow :many
SELECT tasks.workflow_id, tasks.name, tasks.finished, tasks.result, tasks.error, tasks.created_at, tasks.updated_at, tasks.approved_at, tasks.ready_for_approval, tasks.started, tasks.retry_count
FROM tasks
WHERE workflow_id = $1
ORDER BY created_at
`

func (q *Queries) TasksForWorkflow(ctx context.Context, workflowID uuid.UUID) ([]Task, error) {
	rows, err := q.db.Query(ctx, tasksForWorkflow, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []Task
	for rows.Next() {
		var i Task
		if err := rows.Scan(
			&i.WorkflowID,
			&i.Name,
			&i.Finished,
			&i.Result,
			&i.Error,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.ApprovedAt,
			&i.ReadyForApproval,
			&i.Started,
			&i.RetryCount,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const tasksForWorkflowSorted = `-- name: TasksForWorkflowSorted :many
WITH most_recent_logs AS (
    SELECT workflow_id, task_name, MAX(updated_at) AS updated_at
    FROM task_logs
    GROUP BY workflow_id, task_name
)
SELECT tasks.workflow_id, tasks.name, tasks.finished, tasks.result, tasks.error, tasks.created_at, tasks.updated_at, tasks.approved_at, tasks.ready_for_approval, tasks.started, tasks.retry_count,
       GREATEST(most_recent_logs.updated_at, tasks.updated_at)::timestamptz AS most_recent_update
FROM tasks
LEFT JOIN most_recent_logs ON tasks.workflow_id = most_recent_logs.workflow_id AND
                              tasks.name = most_recent_logs.task_name
WHERE tasks.workflow_id = $1
ORDER BY most_recent_update DESC
`

type TasksForWorkflowSortedRow struct {
	WorkflowID       uuid.UUID
	Name             string
	Finished         bool
	Result           sql.NullString
	Error            sql.NullString
	CreatedAt        time.Time
	UpdatedAt        time.Time
	ApprovedAt       sql.NullTime
	ReadyForApproval bool
	Started          bool
	RetryCount       int32
	MostRecentUpdate time.Time
}

func (q *Queries) TasksForWorkflowSorted(ctx context.Context, workflowID uuid.UUID) ([]TasksForWorkflowSortedRow, error) {
	rows, err := q.db.Query(ctx, tasksForWorkflowSorted, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TasksForWorkflowSortedRow
	for rows.Next() {
		var i TasksForWorkflowSortedRow
		if err := rows.Scan(
			&i.WorkflowID,
			&i.Name,
			&i.Finished,
			&i.Result,
			&i.Error,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.ApprovedAt,
			&i.ReadyForApproval,
			&i.Started,
			&i.RetryCount,
			&i.MostRecentUpdate,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const unfinishedWorkflows = `-- name: UnfinishedWorkflows :many
SELECT workflows.id, workflows.params, workflows.name, workflows.created_at, workflows.updated_at, workflows.finished, workflows.output, workflows.error, workflows.schedule_id
FROM workflows
WHERE workflows.finished = FALSE
`

func (q *Queries) UnfinishedWorkflows(ctx context.Context) ([]Workflow, error) {
	rows, err := q.db.Query(ctx, unfinishedWorkflows)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []Workflow
	for rows.Next() {
		var i Workflow
		if err := rows.Scan(
			&i.ID,
			&i.Params,
			&i.Name,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Finished,
			&i.Output,
			&i.Error,
			&i.ScheduleID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const updateTaskReadyForApproval = `-- name: UpdateTaskReadyForApproval :one
UPDATE tasks
SET ready_for_approval = $3
WHERE workflow_id = $1
  AND name = $2
RETURNING workflow_id, name, finished, result, error, created_at, updated_at, approved_at, ready_for_approval, started, retry_count
`

type UpdateTaskReadyForApprovalParams struct {
	WorkflowID       uuid.UUID
	Name             string
	ReadyForApproval bool
}

func (q *Queries) UpdateTaskReadyForApproval(ctx context.Context, arg UpdateTaskReadyForApprovalParams) (Task, error) {
	row := q.db.QueryRow(ctx, updateTaskReadyForApproval, arg.WorkflowID, arg.Name, arg.ReadyForApproval)
	var i Task
	err := row.Scan(
		&i.WorkflowID,
		&i.Name,
		&i.Finished,
		&i.Result,
		&i.Error,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ApprovedAt,
		&i.ReadyForApproval,
		&i.Started,
		&i.RetryCount,
	)
	return i, err
}

const upsertTask = `-- name: UpsertTask :one
INSERT INTO tasks (workflow_id, name, started, finished, result, error, created_at, updated_at,
                   retry_count)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (workflow_id, name) DO UPDATE
    SET workflow_id = excluded.workflow_id,
        name        = excluded.name,
        started     = excluded.started,
        finished    = excluded.finished,
        result      = excluded.result,
        error       = excluded.error,
        updated_at  = excluded.updated_at,
        retry_count = excluded.retry_count
RETURNING workflow_id, name, finished, result, error, created_at, updated_at, approved_at, ready_for_approval, started, retry_count
`

type UpsertTaskParams struct {
	WorkflowID uuid.UUID
	Name       string
	Started    bool
	Finished   bool
	Result     sql.NullString
	Error      sql.NullString
	CreatedAt  time.Time
	UpdatedAt  time.Time
	RetryCount int32
}

func (q *Queries) UpsertTask(ctx context.Context, arg UpsertTaskParams) (Task, error) {
	row := q.db.QueryRow(ctx, upsertTask,
		arg.WorkflowID,
		arg.Name,
		arg.Started,
		arg.Finished,
		arg.Result,
		arg.Error,
		arg.CreatedAt,
		arg.UpdatedAt,
		arg.RetryCount,
	)
	var i Task
	err := row.Scan(
		&i.WorkflowID,
		&i.Name,
		&i.Finished,
		&i.Result,
		&i.Error,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ApprovedAt,
		&i.ReadyForApproval,
		&i.Started,
		&i.RetryCount,
	)
	return i, err
}

const workflow = `-- name: Workflow :one
SELECT id, params, name, created_at, updated_at, finished, output, error, schedule_id
FROM workflows
WHERE id = $1
`

func (q *Queries) Workflow(ctx context.Context, id uuid.UUID) (Workflow, error) {
	row := q.db.QueryRow(ctx, workflow, id)
	var i Workflow
	err := row.Scan(
		&i.ID,
		&i.Params,
		&i.Name,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Finished,
		&i.Output,
		&i.Error,
		&i.ScheduleID,
	)
	return i, err
}

const workflowCount = `-- name: WorkflowCount :one
SELECT COUNT(*)
FROM workflows
`

func (q *Queries) WorkflowCount(ctx context.Context) (int64, error) {
	row := q.db.QueryRow(ctx, workflowCount)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const workflowFinished = `-- name: WorkflowFinished :one
UPDATE workflows
SET finished   = $2,
    output     = $3,
    error      = $4,
    updated_at = $5
WHERE workflows.id = $1
RETURNING id, params, name, created_at, updated_at, finished, output, error, schedule_id
`

type WorkflowFinishedParams struct {
	ID        uuid.UUID
	Finished  bool
	Output    string
	Error     string
	UpdatedAt time.Time
}

func (q *Queries) WorkflowFinished(ctx context.Context, arg WorkflowFinishedParams) (Workflow, error) {
	row := q.db.QueryRow(ctx, workflowFinished,
		arg.ID,
		arg.Finished,
		arg.Output,
		arg.Error,
		arg.UpdatedAt,
	)
	var i Workflow
	err := row.Scan(
		&i.ID,
		&i.Params,
		&i.Name,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Finished,
		&i.Output,
		&i.Error,
		&i.ScheduleID,
	)
	return i, err
}

const workflowNames = `-- name: WorkflowNames :many
SELECT DISTINCT name::text
FROM workflows
`

func (q *Queries) WorkflowNames(ctx context.Context) ([]string, error) {
	rows, err := q.db.Query(ctx, workflowNames)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var name string
		if err := rows.Scan(&name); err != nil {
			return nil, err
		}
		items = append(items, name)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const workflowSidebar = `-- name: WorkflowSidebar :many
SELECT name, COUNT(*)
FROM workflows
GROUP BY name
ORDER BY name
`

type WorkflowSidebarRow struct {
	Name  sql.NullString
	Count int64
}

func (q *Queries) WorkflowSidebar(ctx context.Context) ([]WorkflowSidebarRow, error) {
	rows, err := q.db.Query(ctx, workflowSidebar)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []WorkflowSidebarRow
	for rows.Next() {
		var i WorkflowSidebarRow
		if err := rows.Scan(&i.Name, &i.Count); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const workflows = `-- name: Workflows :many

SELECT id, params, name, created_at, updated_at, finished, output, error, schedule_id
FROM workflows
ORDER BY created_at DESC
`

// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
func (q *Queries) Workflows(ctx context.Context) ([]Workflow, error) {
	rows, err := q.db.Query(ctx, workflows)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []Workflow
	for rows.Next() {
		var i Workflow
		if err := rows.Scan(
			&i.ID,
			&i.Params,
			&i.Name,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Finished,
			&i.Output,
			&i.Error,
			&i.ScheduleID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const workflowsByName = `-- name: WorkflowsByName :many
SELECT id, params, name, created_at, updated_at, finished, output, error, schedule_id
FROM workflows
WHERE name = $1
ORDER BY created_at DESC
`

func (q *Queries) WorkflowsByName(ctx context.Context, name sql.NullString) ([]Workflow, error) {
	rows, err := q.db.Query(ctx, workflowsByName, name)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []Workflow
	for rows.Next() {
		var i Workflow
		if err := rows.Scan(
			&i.ID,
			&i.Params,
			&i.Name,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Finished,
			&i.Output,
			&i.Error,
			&i.ScheduleID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const workflowsByNames = `-- name: WorkflowsByNames :many
SELECT id, params, name, created_at, updated_at, finished, output, error, schedule_id
FROM workflows
WHERE name = ANY($1::text[])
ORDER BY created_at DESC
`

func (q *Queries) WorkflowsByNames(ctx context.Context, names []string) ([]Workflow, error) {
	rows, err := q.db.Query(ctx, workflowsByNames, names)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []Workflow
	for rows.Next() {
		var i Workflow
		if err := rows.Scan(
			&i.ID,
			&i.Params,
			&i.Name,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Finished,
			&i.Output,
			&i.Error,
			&i.ScheduleID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}


text:
@interface IconElement : NSObject
@end


text:
import java.util.*;

public class CollectionViewsSize {

  void test(Map<String, String> map) {
    if (map.size() == 1 && <warning descr="Condition 'map.values().size() == 1' is always 'true' when reached">map.values().size() == 1</warning>) {}
  }

  void test(List<String> input) {
    List<String> list1 = Collections.unmodifiableList(Arrays.asList("1", "2", "3"));
    if (<warning descr="Condition 'list1.size() == 3' is always 'true'">list1.size() == 3</warning>) {}
    List<String> list2 = Collections.synchronizedList(Collections.checkedList(input, String.class));
    if (<warning descr="Condition 'list2.size() == input.size()' is always 'true'">list2.size() == input.size()</warning>) {}
  }
}