text:
using System;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using NuGet;

namespace NuPlug
{
    /// <summary>
    /// The generic NuPlug <see cref="IPackageContainer{TItem}"/> using MEF composition to resolve items/plugins from NuGet packages.
    /// </summary>
    public class NuGetPackageContainer<TItem>
        : PackageContainer<TItem> where TItem : class
    {
        /// <summary>
        /// The underlying <see cref="IPackageManager"/>.
        /// </summary>
        public IPackageManager PackageManager { get; }

        /// <summary>
        /// The <see cref="FrameworkName"/>.
        /// </summary>
        public FrameworkName Framework { get; } = VersionHelper.GetTargetFramework();

        /// <summary>
        ///     Initializes a new instance of the <see cref="NuGetPackageContainer{TItem}" /> class.
        /// </summary>
        /// <param name="packageManager">The NuGet package manager to use. Usually a <see cref="NuPlugPackageManager"/></param>
        /// <param name="assemblyResolver">A custom <see cref="IResolveAssembly"/>. If null, uses the default <see cref="AssemblyResolver"/>.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public NuGetPackageContainer(IPackageManager packageManager, IResolveAssembly assemblyResolver = null) : base(assemblyResolver)
        {
            if (packageManager == null) throw new ArgumentNullException(nameof(packageManager));
            PackageManager = packageManager;

            foreach (var package in PackageManager.LocalRepository.GetPackages())
                AddPackageDirectory(package);

            PackageManager.PackageInstalled += OnPackageInstalled;
            PackageManager.PackageUninstalled += OnPackageUninstalled;
        }

        private void OnPackageInstalled(object sender, PackageOperationEventArgs e)
        {
            AddPackageDirectory(e.Package, e.FileSystem, e.InstallPath);
        }

        private void OnPackageUninstalled(object sender, PackageOperationEventArgs e)
        {
            var libDir = Path.Combine(e.InstallPath, Constants.LibDirectory);
            RemoveDirectory(libDir);
        }

        private void AddPackageDirectory(IPackage package, IFileSystem fileSystem = null, string installPath = null)
        {
            var libDir = GetLibDir(package, fileSystem, installPath);
            if (!string.IsNullOrWhiteSpace(libDir))
                AddDirectory(libDir);
        }

        private string GetLibDir(IPackage package, IFileSystem fileSystem = null, string installPath = null)
        {
            var libDir = Path.Combine(installPath ?? PackageManager.PathResolver.GetInstallPath(package), Constants.LibDirectory);

            var fs = fileSystem ?? PackageManager.FileSystem;

            if (!fs.DirectoryExists(libDir))
                return null;

            // match framework
            var folderNames = fs.GetDirectories(libDir)
                .Select(p => p.Split(Path.DirectorySeparatorChar).Last())
                .ToList();
            if (folderNames.Any())
            {
                var bestMatch = Framework.Version.BestMatch(folderNames);
                if (!string.IsNullOrWhiteSpace(bestMatch))
                    return Path.Combine(libDir, bestMatch);
            }

            // fall back to lib-dir
            if (fs.GetFiles(libDir, "*.dll", false).Any())
                return libDir;

            return null;
        }
    }
}


text:
/*
 * File:   TempFault.cpp
 * Author: rmartins
 *
 * Created on February 8, 2011, 3:20 PM
 */

#include "TempFault.h"

TempFault::TempFault(int level,ACE_Time_Value& startTime, ACE_Time_Value& duration) :
Fault(Fault::TEMP_FAULT,level,startTime),
m_duration(duration) {
}

TempFault::TempFault(const TempFault& orig) :
Fault(orig),
m_duration(orig.m_duration) {
}

TempFault::~TempFault() {
}

redpajama_set_name: RedPajamaGithub


text:
import codecs

from dupescan import (
    __version__,
    platform,
    units,
)

def add_common_cli_args(arg_parser):
    arg_parser.add_argument("--max-memory",
        type=units.parse_byte_count,
        default=platform.DEFAULT_MAX_MEMORY,
        metavar="SIZE",
        help="""Specifies the maximum amount of memory to use when comparing
                a set of potentially duplicate files.  This option accepts a
                byte count.  The default is %(default)s."""
    )

    arg_parser.add_argument("--max-buffer-size",
        type=units.parse_byte_count,
        default=platform.DEFAULT_MAX_BUFFER_SIZE,
        metavar="SIZE",
        help="""Specifies the maximum size of buffers used when comparing a set
                of potentially duplicate files.  This option accepts a byte
                count.  The default is %(default)s."""
    )

    arg_parser.add_argument("--version",
        action="version",
        version="%(prog)s " + __version__
    )

def set_encoder_errors(stream, errors):
    encoder = codecs.getwriter(stream.encoding)
    return encoder(stream.buffer, errors)


text:
package com.indra.sofia2.ssapandroid.kp;

import com.indra.sofia2.ssapandroid.ssap.SSAPMessage;

/**
 * Interfaz para recibir las notificaciones de suscripciones del Sib
 * @author jfgpimpollo
 *
 */
public interface Listener4SIBIndicationNotifications {

	/**
	 * Metodo que el API del kp-core invocará en el listener
	 * @param message
	 */
	void onIndication(String idNotifition, SSAPMessage message);

}


text:
<?php

namespace Google\Service\Analytics;

class AccountTreeRequest extends \Google\Model
{
  /**
   * @var string
   */
  public $accountName;
  /**
   * @var string
   */
  public $kind;
  /**
   * @var string
   */
  public $profileName;
  /**
   * @var string
   */
  public $timezone;
  /**
   * @var string
   */
  public $webpropertyName;
  /**
   * @var string
   */
  public $websiteUrl;

  /**
   * @param string
   */
  public function setAccountName($accountName)
  {
    $this->accountName = $accountName;
  }
  /**
   * @return string
   */
  public function getAccountName()
  {
    return $this->accountName;
  }
  /**
   * @param string
   */
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  /**
   * @return string
   */
  public function getKind()
  {
    return $this->kind;
  }
  /**
   * @param string
   */
  public function setProfileName($profileName)
  {
    $this->profileName = $profileName;
  }
  /**
   * @return string
   */
  public function getProfileName()
  {
    return $this->profileName;
  }
  /**
   * @param string
   */
  public function setTimezone($timezone)
  {
    $this->timezone = $timezone;
  }
  /**
   * @return string
   */
  public function getTimezone()
  {
    return $this->timezone;
  }
  /**
   * @param string
   */
  public function setWebpropertyName($webpropertyName)
  {
    $this->webpropertyName = $webpropertyName;
  }
  /**
   * @return string
   */
  public function getWebpropertyName()
  {
    return $this->webpropertyName;
  }
  /**
   * @param string
   */
  public function setWebsiteUrl($websiteUrl)
  {
    $this->websiteUrl = $websiteUrl;
  }
  /**
   * @return string
   */
  public function getWebsiteUrl()
  {
    return $this->websiteUrl;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AccountTreeRequest::class, 'Google_Service_Analytics_AccountTreeRequest');


text:
create table #prefix#polls (
	id integer primary key,
	title varchar(48) not null,
	question varchar(140) not null,
	created datetime not null,
	creator integer not null,
	edited datetime not null,
	editor integer not null,
	allowed integer not null default 1,
	required integer not null default 1,
	votable boolean not null default 0,
	visible boolean not null default 0,
	fallback boolean default 0,
	options text not null
);
create index #prefix#polls_fallback on #prefix#polls (fallback);
create index #prefix#polls_visible on #prefix#polls (visible);

create table #prefix#polls_votes (
	id integer primary key,
	poll_id integer not null,
	ts datetime not null,
	ip varchar(15) not null,
	user_id integer,
	votes text not null
);
create index #prefix#polls_id on #prefix#polls_votes (poll_id, ts);


text:
/**
 *
 */
package com.dtcc.csc.jrparks.final_project;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

/**
 * @author jrparks
 *
 */
public class Game {
	private static final String	ALPHABET	= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private static final Random	rand		= new Random();
	private Scanner				inputScanner;
	private List<Puzzle>		puzzles;
	private String				revealedPuzzle;
	private Boolean				solved, quit, incorrectGuess;
	private char[]				guessableLetters, guessedLetters;
	private List<Player>		players;
	private int					currentPlayerIndex, currentPuzzleIndex;
	private GameWheel			wheel;

	/**
	 * Game constructor
	 */
	public Game() {
		this.guessableLetters = ALPHABET.toCharArray();
		this.guessedLetters = new char[guessableLetters.length];
		this.puzzles = new LinkedList<Puzzle>();
		this.revealedPuzzle = "";
		this.solved = this.quit = this.incorrectGuess = false;
		this.players = new LinkedList<Player>();
		this.currentPlayerIndex = this.currentPuzzleIndex = 0;

		this.wheel = new GameWheel();
		this.inputScanner = new Scanner(System.in);

		generateNewPuzzle();
	}

	/**
	 * @return the revealedPuzzle
	 */
	public String getRevealedPuzzle() {
		return generateRevealedPuzzle();
	}

	/**
	 * @return whether the puzzle is solved
	 */
	public Boolean getSolved() {
		return this.solved;
	}

	/**
	 * @return whether to quit the game
	 */
	public Boolean getQuit() {
		return this.quit;
	}

	/**
	 * Add a new puzzle(s) to the game.
	 *
	 * @param puzzles
	 */
	public void addPuzzles(Puzzle... puzzles) {
		for (Puzzle puzzle : puzzles)
			this.puzzles.add(puzzle);
		generateNewPuzzle();
	}

	/**
	 * Retrieve the current puzzle.
	 *
	 * @return Current Puzzle
	 */
	public Puzzle currentPuzzle() {
		return this.puzzles.get(this.currentPuzzleIndex);
	}

	/**
	 * Reset game and generate new puzzle.
	 */
	public void generateNewPuzzle() {
		int prevPuzzle = this.currentPuzzleIndex;
		if (this.puzzles.isEmpty()) this.currentPuzzleIndex = 0;
		else do { // Prevent repeat puzzles
			this.currentPuzzleIndex = rand.nextInt(this.puzzles.size());
		} while (prevPuzzle == this.currentPuzzleIndex && solved);
		// Reset game
		this.solved = false;
		// Empty guessed letters
		this.guessedLetters = new char[guessableLetters.length];
	}

	/**
	 * Add a new player(s) to the game.
	 *
	 * @param players
	 */
	public void addPlayers(Player... players) {
		for (Player player : players)
			this.players.add(player);
	}

	/**
	 * Retrieve the current player.
	 *
	 * @return Current player.
	 */
	public Player currentPlayer() {
		return this.players.get(this.currentPlayerIndex);
	}

	/**
	 * Draw the game screen
	 */
	public void drawGame() {
		for (int i = 0; i < 8; ++i)
			System.out.println();

		System.out.println("Welcome to the Wheel of Fortune");
		System.out.println();
		for (Player player : this.players) {
			System.out.printf("%s\t", player.getName());
		}
		System.out.println();
		for (Player player : this.players) {
			System.out.printf("$%10d\t", player.getWinnings());
		}
		System.out.println();
		System.out.printf("Available Letters: %s\n", getAvailableLetters());
		System.out.println();
		System.out.printf("Puzzle: (%s)\n", this.currentPuzzle().getHint());
		System.out.printf("\t%s\n", getRevealedPuzzle());
		System.out.println();

		if (this.incorrectGuess) {
			this.incorrectGuess = false;
			System.out.println("The puzzel guess was incorrect.");
			System.out.println();
		}

		System.out.printf("Player %s - would you like to Spin (1) or Guess (2) the puzzle?\n", currentPlayer().getName());
		System.out.print("Action (q to quit): ");
	}

	/**
	 * Ask the current player for action
	 */
	public void queryPlayer() {
		String action = this.inputScanner.next();
		this.inputScanner.nextLine();
		switch (action) {
			default:
				break;

			case "1":
			case "s":
			case "spin":
				int spinPrize = this.spinWheel();
				System.out.printf("You landed on $%d.\n", spinPrize);
				if (spinPrize <= 0) {
					this.currentPlayer().setWinnings(this.currentPlayer().getWinnings() + spinPrize);
					System.out.println("You have lost your turn.");
					++this.currentPlayerIndex;
				} else {
					Object[] letterData = this.guessLetter();
					if ((int) letterData[1] > 0) {
						if ((int) letterData[1] > 1) System.out.printf("There are %d %s's in the puzzle.\n", (int) letterData[1], letterData[0]);
						else System.out.printf("There is %d %s in the puzzle.\n", (int) letterData[1], letterData[0]);
						this.currentPlayer().setWinnings(this.currentPlayer().getWinnings() + (spinPrize * (int) letterData[1]));
					} else {
						System.out.printf("I'm sorry but the letter '%s' is not a valid choice.\n", letterData[0]);
						++this.currentPlayerIndex;
					}
				}
				sleep(5 * 1000);
				break;

			case "2":
			case "g":
			case "guess":
				if (this.querySolve()) {
					System.out.println("The puzzel guess was correct.");
					System.out.printf("Player %s has won the current round.\n", currentPlayer().getName());
				} else {
					System.out.println("The puzzel guess was incorrect.");
				}
				++this.currentPlayerIndex;
				sleep(5 * 1000);
				break;

			case "q":
			case "quit":
			case "exit":
			case "stop":
				this.quit = true;
				break;
		}
		if (this.currentPlayerIndex >= this.players.size()) this.currentPlayerIndex = 0;
	}

	/**
	 * Ask the current player for a letter
	 *
	 * @return [letter, count]
	 */
	public Object[] guessLetter() {
		char letter;
		do {
			System.out.print("Please guess a letter: ");
			letter = this.inputScanner.next().toUpperCase().charAt(0);
		} while (Arrays.asList(this.guessedLetters).contains(letter));
		this.inputScanner.nextLine();
		return new Object[] { letter, this.guessLetter(letter) };
	}

	/**
	 * Try for game solve
	 *
	 * @return whether puzzle was solved
	 */
	public Boolean querySolve() {
		System.out.print("Please guess the puzzle: ");
		String guess = "";
		guess = this.inputScanner.nextLine();
		return this.solvePuzzle(guess);
	}

	/**
	 * Return available letter choices
	 *
	 * @return String of letters
	 */
	public String getAvailableLetters() {
		String availableLetters = new String(guessableLetters);
		for (char c : guessedLetters) {
			availableLetters = availableLetters.replace(c, '_');
		}
		return availableLetters;
	}

	/**
	 * Get revealed puzzle
	 *
	 * @return revealed puzzle
	 */
	private String generateRevealedPuzzle() {
		this.revealedPuzzle = "";
		if (!this.solved) {
			String[] puzzleWords = this.currentPuzzle().getPuzzle().split(" ");
			for (String puzzleWord : puzzleWords) {
				for (char c : puzzleWord.toCharArray()) {
					if (new String(guessedLetters).indexOf(c) >= 0) this.revealedPuzzle += c;
					else this.revealedPuzzle += "_";
				}
				this.revealedPuzzle += " ";
			}
			this.revealedPuzzle.trim();
		} else {
			this.revealedPuzzle = this.currentPuzzle().getPuzzle();
		}
		return this.revealedPuzzle;
	}

	/**
	 * Guess letter
	 *
	 * @param c
	 *            - Letter to guess
	 * @return letter count
	 */
	public int guessLetter(char c) {
		c = Character.toUpperCase(c);
		int count = 0, index = this.getAvailableLetters().indexOf(c);
		if (index >= 0) {
			guessedLetters[index] = guessableLetters[index];
			for (char _c : this.currentPuzzle().getPuzzle().toCharArray()) {
				if (_c == c) {
					++count;
				}
			}
		}
		return count;
	}

	/**
	 * Solve puzzle
	 *
	 * @param guess
	 *            - Puzzle guess
	 * @return whether guess was correct
	 */
	public Boolean solvePuzzle(String guess) {
		Boolean solve = guess.equalsIgnoreCase(this.currentPuzzle().getPuzzle());
		this.solved = solve;
		return solve;
	}

	/**
	 * Spin the wheel
	 *
	 * @return wheel value
	 */
	public int spinWheel() {
		return this.wheel.spin();
	}

	/**
	 * Sleep
	 *
	 * @param millis
	 */
	protected void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


text:
#ifndef _ELIM_TERM_ITE_H_
#define _ELIM_TERM_ITE_H_

#include"simplifier.h"
#include"defined_names.h"

class elim_term_ite : public simplifier {
    defined_names &    m_defined_names;
    proof_ref_vector   m_coarse_proofs;
    expr_ref_vector *  m_new_defs;
    proof_ref_vector * m_new_def_proofs;
    void reduce_core(expr * n);
    bool visit_children(expr * n);
    void reduce1(expr * n);
    void reduce1_app(app * n);
    void reduce1_quantifier(quantifier * q);
public:
    elim_term_ite(ast_manager & m, defined_names & d):simplifier(m), m_defined_names(d), m_coarse_proofs(m) {
        m_use_oeq = true;
        enable_ac_support(false);
    }
    virtual ~elim_term_ite() {}
    void operator()(expr * n,                          // [IN]
                    expr_ref_vector & new_defs,        // [OUT] new definitions
                    proof_ref_vector & new_def_proofs, // [OUT] proofs of the new definitions
                    expr_ref & r,                      // [OUT] resultant expression
                    proof_ref & pr                     // [OUT] proof for (~ n r)
                    );
};

#endif /* _ELIM_TERM_ITE_H_ */


text:
var _       = require('lodash'),
    pfs     = require('./promised-fs'),
    checker = require('./checker'),
    format   = require('./format'),
    readZip = require('./read-zip'),
    middleware,
    checkZip;

checkZip = function checkZip(themePath, options) {
    options = options || {
        keepExtractedDir: false
    };

    var zip;

    if (_.isString(themePath)) {
        zip = {
            path: themePath,
            name: themePath.match(/(.*\/)?(.*).zip$/)[2]
        };
    } else {
        zip = _.clone(themePath);
    }

    return readZip(zip).then(function thenCheckTheme(resultZip) {
        return checker(resultZip.path);
    }).then(function cleanup(theme) {
        if (options.keepExtractedDir) {
            return theme;
        }

        return pfs.removeDir(zip.origPath).then(function returnResult() {
            return theme;
        });
    });
};

module.exports = {
    check: checker,
    checkZip: checkZip,
    format: format
};


text:
import 'es6-shim';
// (these modules are what are in 'angular2/bundles/angular2-polyfills' so don't use that here)
import 'es6-promise';
import 'zone.js/lib/browser/zone-microtask';

if ('production' !== process.env.ENV) {
  // Reflect Polyfill
  require('es7-reflect-metadata/dist/browser');
  Error['stackTraceLimit'] = Infinity;
  Zone['longStackTraceZone'] = require('zone.js/lib/zones/long-stack-trace.js');
}

if ('production' === process.env.ENV) {
  // Reflect with es7-reflect-metadata/reflect-metadata is added
  // by webpack.prod.config ProvidePlugin
  let ngCore = require('angular2/core');
  ngCore.enableProdMode();
}
// Angular 2
import 'angular2/platform/browser';
import 'angular2/platform/common_dom';
import 'angular2/router';
import 'angular2/http';
import 'angular2/core';

// RxJS
import 'rxjs';

// Other vendors for example jQuery, Lodash, angular2-jwt
import 'jquery';
import 'bootstrap-webpack';


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lichenologist 37(2): 163 (2005)

#### Original name
Echinoplaca serusiauxii Lücking

### Remarks
null


text:
Drag and drop sans the GUI.
Work in progress.

This is a clean re-implementation of drag and drop primitives and will eventually become core of [React DnD](https://github.com/gaearon/react-dnd).

## Wat?

To give you a better idea:

* There is no DOM here
* We let you define drop target and drag source logic
* We let you supply custom underlying implementations (console, DOM via jQuery, React, React Native, *whatever*)
* We manage drag source and drop target interaction

This was written to support some rather complicated scenarios that were too hard to implement in [React DnD](https://github.com/gaearon/react-dnd) due to its current architecture:

* [Mocking drag and drop interaction in tests](https://github.com/gaearon/react-dnd/issues/55)
* [Full support for arbitrary nesting and handling drag sources and drop targets](https://github.com/gaearon/react-dnd/issues/87)
* [Dragging multiple items at once](https://github.com/gaearon/react-dnd/issues/14)
* [Even when source is removed, letting another drag source "represent it" (e.g. card disappeared from one Kanban list, reappeared in another one)](https://github.com/gaearon/react-dnd/pull/64#issuecomment-76118757)

Turns out, these problems are much easier to solve when DOM is thrown out of the window.

## What's the API like?

[Tests](https://github.com/gaearon/dnd-core/tree/master/src/__tests__) should give you some idea. You register drag sources and drop targets, hook up a backend (you can use barebone `TestBackend` or implement a fancy real one yourself), and your drag sources and drop targets magically begin to interact.

![](http://i.imgur.com/6l8CpxZ.png)


text:
"""
Created on Tue May 17 01:01:31 2016

@author: Ghareeb
"""

from PythonStarterApp import app
import os

if 'VCAP_APP_PORT' in os.environ:
    appPort = os.environ['VCAP_APP_PORT']
else:
    appPort = 5000

if 'VCAP_APP_HOST' in os.environ:
    appHost = os.environ['VCAP_APP_HOST']
else:
    appHost = '0.0.0.0'

if __name__ == '__main__':
    app.run(host=appHost,port=appPort, debug=False, threaded=True)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 7: 420 (1931)

#### Original name
Buellia substellulans Zahlbr.

### Remarks
null


text:
{% extends "utils/_layout" %}

{% import "_includes/forms" as forms %}

{% macro table(heading, data) %}
	{% if data %}

{{ heading }}

			{% for key, value in data %}

					{{ key|raw }}
					{{ value|nl2br|raw }}

			{% endfor %}

	{% endif %}
{% endmacro %}

{% from _self import table %}

{% block content %}

		<select onchange="Craft.redirectTo('utils/logs/'+this.value);">
			{% for fileName in logFileNames %}
				<option{% if fileName == currentLogFileName %} selected{% endif %}>{{ fileName }}</option>
			{% endfor %}
		</select>

	{% for logEntries in logEntriesByRequest %}

		{% if not loop.first %}
{% endif %}

		{% for logEntry in logEntries %}

			{% if currentLogFileName == 'phperrors.log' %}

					{{ logEntry.message|raw }}

			{% else %}

{{ logEntry.dateTime.localeDate() ~ ' ' ~ logEntry.dateTime.localeTime() }}

						Level
						{{ logEntry.level }}

						Category
						{{ logEntry.category }}

					{% if logEntry.message %}

							Message
							{{ logEntry.message }}

					{% endif %}

				{{ table('Get Variables', logEntry.get) }}
				{{ table('Post Variables', logEntry.post) }}
				{{ table('Cookies', logEntry.cookie) }}
				{{ table('Session Data', logEntry.session) }}
				{{ table('Server Variables', logEntry.server) }}

				{% if logEntry.profile %}

Profile

						{% for step in logEntry.profile %}

{{ step|join('
')|raw }}

						{% endfor %}

				{% endif %}

			{% endif %}

		{% endfor %}
	{% endfor %}

{% endblock %}


text:
namespace gpu {
class CommandBufferStub;
class GpuChannel;
}

namespace media {

class MediaGpuChannel {
 public:
  MediaGpuChannel(gpu::GpuChannel* channel,
                  const AndroidOverlayMojoFactoryCB& overlay_factory_cb);
  MediaGpuChannel(const MediaGpuChannel&) = delete;
  MediaGpuChannel& operator=(const MediaGpuChannel&) = delete;
  ~MediaGpuChannel();

 private:
  void BindCommandBufferMediaReceiver(
      gpu::CommandBufferStub* stub,
      mojo::GenericPendingAssociatedReceiver receiver);

  const raw_ptr<gpu::GpuChannel> channel_;
  AndroidOverlayMojoFactoryCB overlay_factory_cb_;
  mojo::UniqueAssociatedReceiverSet<mojom::GpuAcceleratedVideoDecoderProvider>
      accelerated_video_decoder_providers_;
};

}  // namespace media

#endif  // MEDIA_GPU_IPC_SERVICE_MEDIA_GPU_CHANNEL_H_


text:
namespace cpptimer {

    std::shared_ptr<Timer> Timer::CreateWithListener(const std::shared_ptr<TimerListener> & listener) {
        return std::make_shared<TimerImpl>(listener);
    }

    TimerImpl::TimerImpl(const std::shared_ptr<TimerListener> & listener):
            io_service_(),
            timer_(io_service_, boost::posix_time::seconds(1)) {
        listener_ = listener;
    }

    void TimerImpl::StartTimer(int32_t seconds) {
        time_remaining_ = seconds;
        io_service_.reset();
        timer_.async_wait(boost::bind(&TimerImpl::TimerTick, this, boost::asio::placeholders::error));
        boost::thread th([&] { io_service_.run(); });
    }

    void TimerImpl::TimerTick(const boost::system::error_code& e) {
        if(e != boost::asio::error::operation_aborted) {
            time_remaining_--;
            std:: cout << "C++: TimerTick() with " << std::to_string(time_remaining_) << " seconds remaining.\n";
            if (time_remaining_ > 0) {
                timer_.expires_from_now(boost::posix_time::seconds(1));
                timer_.async_wait(boost::bind(&TimerImpl::TimerTick, this, boost::asio::placeholders::error));
                listener_->TimerTicked(time_remaining_);
            } else {
                listener_->TimerEnded();
            }
        }
    }

}


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

 * Implement REST API server for items

[Unreleased]: https://github.com/bubblebox/server/tree/master


text:
#include "CLucene/_ApiHeader.h"
#include "_TermInfo.h"

CL_NS_DEF(index)

TermInfo::TermInfo(){
//Func - Constructor
//Pre  - true
//Post - Instance has been created

	docFreq     = 0;
	freqPointer = 0;
	proxPointer = 0;
  skipOffset = 0;
}

TermInfo::~TermInfo(){
//Func - Destructor.
//Pre  - true
//Post - Instance has been destroyed
}

TermInfo::TermInfo(const int32_t df, const int64_t fp, const int64_t pp){
//Func - Constructor.
//Pre  - df >= 0, fp >= 0 pp >= 0
//Post - An instance has been created with FreqPointer = fp, proxPointer=pp and docFreq= df

    CND_PRECONDITION(df >= 0, "df contains negative number");
    CND_PRECONDITION(fp >= 0, "fp contains negative number");
    CND_PRECONDITION(pp >= 0, "pp contains negative number");

    freqPointer = fp;
    proxPointer = pp;
	  docFreq     = df;
    skipOffset = 0;
}

TermInfo::TermInfo(const TermInfo* ti) {
//Func - Constructor.
//       Initialises this instance by copying the values of another TermInfo ti
//Pre  - ti is a reference to another TermInfo
//       ti->docFreq >= 0
//       ti->freqPointer >= 0
//       ti->proxPointer >= 0
//Post - Values of ti have been copied to the values of this Instance.

    CND_PRECONDITION(ti->docFreq     >= 0, "ti->docFreq contains negative number");
    CND_PRECONDITION(ti->freqPointer >= 0, "ti->freqPointer contains negative number");
    CND_PRECONDITION(ti->proxPointer >= 0, "ti->proxPointer contains negative number");

	docFreq     = ti->docFreq;
	freqPointer = ti->freqPointer;
	proxPointer = ti->proxPointer;
  skipOffset  = ti->skipOffset;
}

void TermInfo::set(const int32_t df, const int64_t fp, const int64_t pp, int32_t so) {
//Func - Sets a new document frequency, a new freqPointer and a new proxPointer
//Pre  - df >= 0, fp >= 0 pp >= 0
//Post - The new document frequency, a new freqPointer and a new proxPointer
//       have been set

    CND_PRECONDITION(df >= 0, "df contains negative number");
    CND_PRECONDITION(fp >= 0, "fp contains negative number");
    CND_PRECONDITION(pp >= 0, "pp contains negative number");

	docFreq     = df;
	freqPointer = fp;
	proxPointer = pp;
    skipOffset  = so;
}

void TermInfo::set(const TermInfo* ti) {
//Func - Sets a new document frequency, a new freqPointer and a new proxPointer
//       by copying these values from another instance of TermInfo
//Pre  - ti is a reference to another TermInfo
//       ti->docFreq >= 0
//       ti->freqPointer >= 0
//       ti->proxPointer >= 0
//Post - Values of ti have been copied to the values of this Instance.

    CND_PRECONDITION(ti->docFreq     >= 0, "ti->docFreq contains negative number");
    CND_PRECONDITION(ti->freqPointer >= 0, "ti->freqPointer contains negative number");
    CND_PRECONDITION(ti->proxPointer >= 0, "ti->proxPointer contains negative number");

	docFreq     = ti->docFreq;
	freqPointer = ti->freqPointer;
	proxPointer = ti->proxPointer;
    skipOffset =  ti->skipOffset;
}
CL_NS_END


text:
// Template Source: BaseEntityRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests;

import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.MobileAppContentFile;
import com.microsoft.graph.models.FileEncryptionInfo;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequestBuilder;
import com.microsoft.graph.models.MobileAppContentFileCommitParameterSet;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Mobile App Content File Request Builder.
 */
public class MobileAppContentFileRequestBuilder extends BaseRequestBuilder<MobileAppContentFile> {

    /**
     * The request builder for the MobileAppContentFile
     *
     * @param requestUrl     the request URL
     * @param client         the service client
     * @param requestOptions the options for this request
     */
    public MobileAppContentFileRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        super(requestUrl, client, requestOptions);
    }

    /**
     * Creates the request
     *
     * @param requestOptions the options for this request
     * @return the MobileAppContentFileRequest instance
     */
    @Nonnull
    public MobileAppContentFileRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
        return buildRequest(getOptions(requestOptions));
    }

    /**
     * Creates the request with specific requestOptions instead of the existing requestOptions
     *
     * @param requestOptions the options for this request
     * @return the MobileAppContentFileRequest instance
     */
    @Nonnull
    public MobileAppContentFileRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        return new com.microsoft.graph.requests.MobileAppContentFileRequest(getRequestUrl(), getClient(), requestOptions);
    }

    /**
     * Commits a file of a given app.
     * @return the request builder
     * @param parameters the parameters for the service method
     */
    @Nonnull
    public MobileAppContentFileCommitRequestBuilder commit(@Nonnull final MobileAppContentFileCommitParameterSet parameters) {
        return new MobileAppContentFileCommitRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.commit"), getClient(), null, parameters);
    }

    /**
     * Renews the SAS URI for an application file upload.
     * @return the request builder
     */
    @Nonnull
    public MobileAppContentFileRenewUploadRequestBuilder renewUpload() {
        return new MobileAppContentFileRenewUploadRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.renewUpload"), getClient(), null);
    }
}


text:
package org.jfrog.artifactory.client.model.repository.settings;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.jfrog.artifactory.client.model.SnapshotVersionBehavior;
import org.jfrog.artifactory.client.model.repository.LocalRepoChecksumPolicyType;
import org.jfrog.artifactory.client.model.repository.PomCleanupPolicy;
import org.jfrog.artifactory.client.model.repository.RemoteRepoChecksumPolicyType;

/**
 * @author Ivan Vasylivskyi (ivanvas@jfrog.com)
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public interface MavenRepositorySettings extends RepositorySettings {

    // ** local ** //

    Integer getMaxUniqueSnapshots();

    Boolean getHandleReleases();

    Boolean getHandleSnapshots();

    Boolean getSuppressPomConsistencyChecks();

    SnapshotVersionBehavior getSnapshotVersionBehavior();

    LocalRepoChecksumPolicyType getChecksumPolicyType();

    // ** remote ** //

    Boolean getFetchJarsEagerly();

    Boolean getFetchSourcesEagerly();

    RemoteRepoChecksumPolicyType getRemoteRepoChecksumPolicyType();

    Boolean getListRemoteFolderItems();

    Boolean getRejectInvalidJars();

    // ** virtual ** //

    Boolean getForceMavenAuthentication();

    PomCleanupPolicy getPomRepositoryReferencesCleanupPolicy();

    String getKeyPair();

}


text:
<?php

final class PhutilModuleUtilsTestCase extends PhutilTestCase {

  public function testGetCurrentLibraryName() {
    $this->assertEqual('phutil', phutil_get_current_library_name());
  }

}


text:
<?php

namespace ZendTest\Cache\Storage;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Cache\Exception\RuntimeException;
use Zend\Cache\Storage\Plugin\PluginInterface;
use Zend\Cache\Storage\PluginManager;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\Test\CommonPluginManagerTrait;

class PluginManagerTest extends TestCase
{
    use CommonPluginManagerTrait;

    protected function getPluginManager()
    {
        return new PluginManager(new ServiceManager());
    }

    protected function getV2InvalidPluginException()
    {
        return RuntimeException::class;
    }

    protected function getInstanceOf()
    {
        return PluginInterface::class;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Package gameshop.advance.ui.swing.factory</title>
<meta name="date" content="2015-02-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
gameshop.advance.ui.swing.factory

Packages that use gameshop.advance.ui.swing.factory

Package
Description

gameshop.advance.ui.swing.factory

Classes in gameshop.advance.ui.swing.factory used by gameshop.advance.ui.swing.factory

Class and Description

UIFactory

Classe Factory per la generazione degli elementi delle schermate dell'interfaccia.

UIStyleSingleton

Classe che definisce lo stile degli elementi delle varie schermate.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package vspk

import "github.com/nuagenetworks/go-bambou/bambou"

// EgressACLTemplateIdentity represents the Identity of the object
var EgressACLTemplateIdentity = bambou.Identity{
	Name:     "egressacltemplate",
	Category: "egressacltemplates",
}

// EgressACLTemplatesList represents a list of EgressACLTemplates
type EgressACLTemplatesList []*EgressACLTemplate

// EgressACLTemplatesAncestor is the interface of an ancestor of a EgressACLTemplate must implement.
type EgressACLTemplatesAncestor interface {
	EgressACLTemplates(*bambou.FetchingInfo) (EgressACLTemplatesList, *bambou.Error)
	CreateEgressACLTemplates(*EgressACLTemplate) *bambou.Error
}

// EgressACLTemplate represents the model of a egressacltemplate
type EgressACLTemplate struct {
	ID                             string `json:"ID,omitempty"`
	ParentID                       string `json:"parentID,omitempty"`
	ParentType                     string `json:"parentType,omitempty"`
	Owner                          string `json:"owner,omitempty"`
	Name                           string `json:"name,omitempty"`
	LastUpdatedBy                  string `json:"lastUpdatedBy,omitempty"`
	Active                         bool   `json:"active"`
	DefaultAllowIP                 bool   `json:"defaultAllowIP"`
	DefaultAllowNonIP              bool   `json:"defaultAllowNonIP"`
	DefaultInstallACLImplicitRules bool   `json:"defaultInstallACLImplicitRules"`
	Description                    string `json:"description,omitempty"`
	EntityScope                    string `json:"entityScope,omitempty"`
	PolicyState                    string `json:"policyState,omitempty"`
	Priority                       int    `json:"priority,omitempty"`
	PriorityType                   string `json:"priorityType,omitempty"`
	AssociatedLiveEntityID         string `json:"associatedLiveEntityID,omitempty"`
	ExternalID                     string `json:"externalID,omitempty"`
}

// NewEgressACLTemplate returns a new *EgressACLTemplate
func NewEgressACLTemplate() *EgressACLTemplate {

	return &EgressACLTemplate{}
}

// Identity returns the Identity of the object.
func (o *EgressACLTemplate) Identity() bambou.Identity {

	return EgressACLTemplateIdentity
}

// Identifier returns the value of the object's unique identifier.
func (o *EgressACLTemplate) Identifier() string {

	return o.ID
}

// SetIdentifier sets the value of the object's unique identifier.
func (o *EgressACLTemplate) SetIdentifier(ID string) {

	o.ID = ID
}

// Fetch retrieves the EgressACLTemplate from the server
func (o *EgressACLTemplate) Fetch() *bambou.Error {

	return bambou.CurrentSession().FetchEntity(o)
}

// Save saves the EgressACLTemplate into the server
func (o *EgressACLTemplate) Save() *bambou.Error {

	return bambou.CurrentSession().SaveEntity(o)
}

// Delete deletes the EgressACLTemplate from the server
func (o *EgressACLTemplate) Delete() *bambou.Error {

	return bambou.CurrentSession().DeleteEntity(o)
}

// Metadatas retrieves the list of child Metadatas of the EgressACLTemplate
func (o *EgressACLTemplate) Metadatas(info *bambou.FetchingInfo) (MetadatasList, *bambou.Error) {

	var list MetadatasList
	err := bambou.CurrentSession().FetchChildren(o, MetadataIdentity, &list, info)
	return list, err
}

// CreateMetadata creates a new child Metadata under the EgressACLTemplate
func (o *EgressACLTemplate) CreateMetadata(child *Metadata) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// EgressACLEntryTemplates retrieves the list of child EgressACLEntryTemplates of the EgressACLTemplate
func (o *EgressACLTemplate) EgressACLEntryTemplates(info *bambou.FetchingInfo) (EgressACLEntryTemplatesList, *bambou.Error) {

	var list EgressACLEntryTemplatesList
	err := bambou.CurrentSession().FetchChildren(o, EgressACLEntryTemplateIdentity, &list, info)
	return list, err
}

// CreateEgressACLEntryTemplate creates a new child EgressACLEntryTemplate under the EgressACLTemplate
func (o *EgressACLTemplate) CreateEgressACLEntryTemplate(child *EgressACLEntryTemplate) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// GlobalMetadatas retrieves the list of child GlobalMetadatas of the EgressACLTemplate
func (o *EgressACLTemplate) GlobalMetadatas(info *bambou.FetchingInfo) (GlobalMetadatasList, *bambou.Error) {

	var list GlobalMetadatasList
	err := bambou.CurrentSession().FetchChildren(o, GlobalMetadataIdentity, &list, info)
	return list, err
}

// CreateGlobalMetadata creates a new child GlobalMetadata under the EgressACLTemplate
func (o *EgressACLTemplate) CreateGlobalMetadata(child *GlobalMetadata) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// VMs retrieves the list of child VMs of the EgressACLTemplate
func (o *EgressACLTemplate) VMs(info *bambou.FetchingInfo) (VMsList, *bambou.Error) {

	var list VMsList
	err := bambou.CurrentSession().FetchChildren(o, VMIdentity, &list, info)
	return list, err
}

// CreateVM creates a new child VM under the EgressACLTemplate
func (o *EgressACLTemplate) CreateVM(child *VM) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// Jobs retrieves the list of child Jobs of the EgressACLTemplate
func (o *EgressACLTemplate) Jobs(info *bambou.FetchingInfo) (JobsList, *bambou.Error) {

	var list JobsList
	err := bambou.CurrentSession().FetchChildren(o, JobIdentity, &list, info)
	return list, err
}

// CreateJob creates a new child Job under the EgressACLTemplate
func (o *EgressACLTemplate) CreateJob(child *Job) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// Containers retrieves the list of child Containers of the EgressACLTemplate
func (o *EgressACLTemplate) Containers(info *bambou.FetchingInfo) (ContainersList, *bambou.Error) {

	var list ContainersList
	err := bambou.CurrentSession().FetchChildren(o, ContainerIdentity, &list, info)
	return list, err
}

// CreateContainer creates a new child Container under the EgressACLTemplate
func (o *EgressACLTemplate) CreateContainer(child *Container) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// EventLogs retrieves the list of child EventLogs of the EgressACLTemplate
func (o *EgressACLTemplate) EventLogs(info *bambou.FetchingInfo) (EventLogsList, *bambou.Error) {

	var list EventLogsList
	err := bambou.CurrentSession().FetchChildren(o, EventLogIdentity, &list, info)
	return list, err
}

// CreateEventLog creates a new child EventLog under the EgressACLTemplate
func (o *EgressACLTemplate) CreateEventLog(child *EventLog) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}


text:
"""Pog: a command line Azkaban client."""

from azkaban import __version__
from setuptools import setup

setup(
    name='azkaban',
    version=__version__,
    description='Azkaban CLI',
    long_description=open('README.rst').read(),
    author='Matthieu Monsch',
    author_email='monsch@alum.mit.edu',
    url='http://github.com/mtth/azkaban/',
    license='MIT',
    py_modules=['azkaban'],
    classifiers=[
      'Development Status :: 4 - Beta',
      'Intended Audience :: Developers',
      'License :: OSI Approved :: MIT License',
      'Programming Language :: Python',
    ],
    install_requires=[
      'docopt',
      'requests>=2.0.1',
      'PyYAML',
    ],
    # entry_points={'console_scripts': []},
)


text:
/// CreateFriendListCommand
/// ============================
/// Creates the tile that represents the user's friends and their scores
/// Compares user score to friend's scores

using System;
using System.Collections;
using UnityEngine;
using strange.extensions.context.api;
using strange.extensions.command.impl;
using strange.extensions.dispatcher.eventdispatcher.api;

namespace strange.examples.multiplecontexts.social
{
	public class CreateFriendListCommand : Command
	{

		[Inject(ContextKeys.CONTEXT_VIEW)]
		public GameObject contextView{get;set;}

		[Inject(ContextKeys.CONTEXT_DISPATCHER)]
		public IEventDispatcher dispatcher{get;set;}

		//Remember back in StartCommand when I said we'd need the userVO again?
		[Inject]
		public UserVO userVO{get;set;}

		public override void Execute()
		{
			ArrayList list = data as ArrayList;

			int highScore = 0;
			int aa = list.Count;
			for (int a = 0; a < aa; a++)
			{
				UserVO vo = list[a] as UserVO;

				GameObject go = UnityEngine.Object.Instantiate(Resources.Load("GameTile")) as GameObject;
				go.AddComponent<UserTileView>();
				go.transform.parent = contextView.transform;
				UserTileView view = go.GetComponent<UserTileView>() as UserTileView;
				view.setUser(vo);

				Vector3 pos = new Vector3(.2f + (.1f * a), .1f, (Camera.main.farClipPlane - Camera.main.nearClipPlane)/2f);
				Vector3 dest = Camera.main.ViewportToWorldPoint(pos);
				view.SetTilePosition(dest);

				highScore = Math.Max(highScore, vo.highScore);
			}

			string msg;
			if (userVO.currentScore > highScore)
			{
				msg = "Score of " + userVO.currentScore + " is the new High Score!!!";
			}
			else if (userVO.currentScore > userVO.highScore)
			{
				msg = "Score of " + userVO.currentScore + " is a personal best!";
			}
			else
			{
				msg = "Score of " + userVO.currentScore + " is nothing special.";
			}

			GameObject award = new GameObject();
			award.transform.parent = contextView.transform;
			award.AddComponent<AwardView>();

			dispatcher.Dispatch(SocialEvent.REWARD_TEXT, msg);

		}
	}
}


text:
(function () {
    var $chartDataSelect = $('#chartDataSelect');
    var $seriesTypeSelect = $('#seriesTypeSelect');
    var $scaleTypeSelect = $('#scaleTypeSelect');
    var $indicatorTypeSelect = $('#indicatorTypeSelect');
    var $indicatorSettingsModal = $('#indicatorSettingsModal');
    var $resetBtn = $('#resetButton');
    var $addIndicatorBtn = $('#addIndicatorButton');
    var $indicatorNavPanel = $('#indicatorNavPanel');
    var $indicatorForm = $('#indicatorForm');
    var $loader = $('#loader');

    var appSettingsCache = {};
    appSettingsCache['data'] = {};
    appSettingsCache['chartType'] = $seriesTypeSelect.val();
    appSettingsCache['scale'] = $scaleTypeSelect.val();
    appSettingsCache['indicators'] = {};

    var chartContainer = 'chart-container';

    var indicatorsSettings = {
        name: '',
        plotIndex: 0,
        defaultSettings: {},
        seriesType: [
            'area',
            'column',
            'jump-line',
            'line',
            'marker',
            'spline',
            'spline-area',
            'step-area',
            'step-line',
            'stick'
        ]
    };

    var chart;
    var dataTable;

    var inputHtml =
        '
' +
        '
' +
        '' +
        '<input type="number" class="form-control" id="">' +
        '
' +
        '
';

    var selectHtml =
        '
' +
        '
' +
        '' +
        '<select class="form-control select show-tick" id=""></select>' +
        '
' +
        '
';

    var app = {
        createChart: createChart,
        removeChart: removeChart
    };

    // this Sample will properly work only if upload it to a server and access via http or https
    if (window.location.protocol === 'file:') {
        $loader.hide();
        $('.wrapper').hide();
        $('#warning').modal({
            backdrop: 'static',
            keyboard: false
        });
    }

    // get indicators from file indicators.xml
    $.get("indicators.xml", function (data) {
        $(data).find('indicator').each(function (index, item) {
            var indicatorName = $(this).attr('type');
            var description;
            var $option = $('<option></option>');

            // create option and append to indicator type select
            $option.attr({
                'value': indicatorName,
                'data-abbr': $(this).find('abbreviation').text(),
                'data-full-text': $(this).find('title').text()
            }).text($(this).find('title').text());

            if ($(this).find('[name="plotIndex"]').length) {
                $option.attr('data-plot-index', $(this).find('[name="plotIndex"]').attr('value'));
            }

            $indicatorTypeSelect.append($option);

            indicatorsSettings['defaultSettings'][indicatorName] = {};

            // set indicator settings to indicator object
            $(item).find('defaults').children().each(function () {
                var prop = $(this).attr('name');
                var value = $(this).attr('value');

                switch ($(this).attr('type')) {
                    case 'number':
                        value = +value;
                        break;
                    case 'array':
                        value = JSON.parse(value);
                        break;
                }

                indicatorsSettings['defaultSettings'][indicatorName][prop] = value;
            });

            // description from xml
            description = $(item).find('description').text();

            // save indicator overview
            indicatorsSettings['defaultSettings'][indicatorName]['overview'] = {};
            indicatorsSettings['defaultSettings'][indicatorName]['overview']['title'] = $(item).find('title').text();
            indicatorsSettings['defaultSettings'][indicatorName]['overview']['description'] = description;
        });

        // sort option in select
        var options = $indicatorTypeSelect.find('option').sort(function (a, b) {
            return a.value.toUpperCase().localeCompare(b.value.toUpperCase())
        });
        $indicatorTypeSelect.append(options);

        // init selectpicker
        $indicatorTypeSelect.selectpicker();
    });

    $(window).on('resize', initHeightChart);

    anychart.onDocumentReady(function () {
        // To work with the data adapter you need to reference the data adapter script file from AnyChart CDN
        // (https://cdn.anychart.com/releases/v8/js/anychart-data-adapter.min.js)
        // Load JSON data and create a chart by JSON data.
        anychart.data.loadJsonFile($chartDataSelect.find('option:selected').data().json, function (data) {
            appSettingsCache['data'][$chartDataSelect.find('option:selected').text().toLowerCase().trim()] = data;
            // init, create chart
            app.createChart(chartContainer);
        });

        // event to set data to chart
        $chartDataSelect.on('change', function () {
            var name = $(this).find('option:selected').text().toLowerCase().trim();

            if (!~Object.keys(appSettingsCache['data']).indexOf(name)) {
                // To work with the data adapter you need to reference the data adapter script file from AnyChart CDN
                // (https://cdn.anychart.com/releases/v8/js/anychart-data-adapter.min.js)
                // Load JSON data and create a chart by JSON data.
                anychart.data.loadJsonFile($(this).find('option:selected').data().json, function (data) {
                    appSettingsCache['data'][name] = data;
                    dataTable.addData(data);
                    chart.plot().getSeries(0).name(name.toUpperCase());
                });
            } else {
                dataTable.addData(appSettingsCache['data'][name]);
                chart.plot().getSeries(0).name(name.toUpperCase());
            }
        });

        // event to set chart type
        $seriesTypeSelect.on('change', function () {
            var type = $(this).val();

            // set chart type
            chart.plot().getSeries(0).seriesType(type);
            // save chart type
            appSettingsCache['chartType'] = type;
        });

        // event to show modal indicator settings
        $indicatorTypeSelect.on('change', function () {

            if ($(this).val()) {
                if ($(this).val().length === 1) {
                    updateTextForIndicatorTypeSelect($indicatorTypeSelect);
                }
            }

            if ($(this).val() === null || $(this).val().length < Object.keys(appSettingsCache.indicators).length) {

                app.removeChart();

                if ($(this).val() !== null) {
                    for (var keyIndicator in appSettingsCache.indicators) {
                        if (!~$(this).val().indexOf(keyIndicator)) {
                            delete appSettingsCache.indicators[keyIndicator]
                        }
                    }
                } else {
                    appSettingsCache.indicators = {};
                }

                app.createChart(chartContainer, true);

                return
            }

            for (var i = 0; i < $(this).val().length; i++) {
                if (!~Object.keys(appSettingsCache.indicators).indexOf($(this).val()[i])) {
                    // set indicator name
                    indicatorsSettings.name = $(this).val()[i];
                    break;
                }
            }

            // set plot index
            indicatorsSettings.plotIndex = $(this).find('option[value="' + indicatorsSettings.name + '"]').data().plotIndex;

            if (indicatorsSettings.plotIndex !== 0) {
                indicatorsSettings.plotIndex = chart.getPlotsCount();
            }

            // create html if form (input/select)
            createHtmlToIndicatorForm();
            // set default indicator settings to input/select
            setDefaultIndicatorSettings();

            // show indicator settings modal
            $indicatorSettingsModal.modal('show');
            // hide dropdown menu, select
            $indicatorNavPanel.find('.select.open').removeClass('open');
        });

        // event to change scale
        $scaleTypeSelect.on('change', function () {
            app.removeChart();
            // save scale type
            appSettingsCache['scale'] = $(this).val();
            app.createChart(chartContainer, true);
        });

        // remove selected class, if indicator not selected
        $indicatorSettingsModal.on('hidden.bs.modal', function () {
            var lastAddedIndicator;

            for (var i = 0; i < $indicatorTypeSelect.val().length; i++) {
                if (!~Object.keys(appSettingsCache.indicators).indexOf($indicatorTypeSelect.val()[i])) {
                    // set indicator name
                    lastAddedIndicator = $indicatorTypeSelect.val()[i];
                    break;
                }
            }

            if (!lastAddedIndicator) {
                // update select text/title
                updateTextForIndicatorTypeSelect($indicatorTypeSelect);
                return false
            }

            var indexOption = $indicatorTypeSelect.find('[value="' + lastAddedIndicator + '"]').index();

            // unselect option
            $indicatorTypeSelect.find('[value="' + lastAddedIndicator + '"]').removeAttr('selected');
            // remove selected class
            $indicatorTypeSelect.prev('.dropdown-menu').find('li[data-original-index="' + indexOption + '"]').removeClass('selected');
            // update select text/title
            updateTextForIndicatorTypeSelect($indicatorTypeSelect);
        });

        // init selectpicker to all select in indicator settings modal
        $indicatorSettingsModal.on('show.bs.modal', function () {
            $indicatorForm.find('.select').selectpicker();
        });

        // reset all settings
        $resetBtn.on('click', function (e) {
            e.preventDefault();

            app.removeChart();
            // reset saved settings
            appSettingsCache['indicators'] = {};
            appSettingsCache['scale'] = 'linear';
            appSettingsCache['chartType'] = 'line';

            // select msft data
            $chartDataSelect.val(1).selectpicker('refresh');
            // select series type
            $seriesTypeSelect.val('candlestick').selectpicker('refresh');
            // reset indicators select
            $indicatorTypeSelect.val('').selectpicker('refresh');
            // select chart scale
            $scaleTypeSelect.val('linear').selectpicker('refresh');

            // init, create chart
            app.createChart(chartContainer);
        });

        // event to add indicator
        $addIndicatorBtn.on('click', function () {
            var mapping = dataTable.mapAs({'value': 1, 'volume': 1, 'open': 1, 'high': 2, 'low': 3, 'close': 4});
            // var keys = Object.keys(indicatorsSettings.defaultSettings[indicatorsSettings.name]);
            var indicator = indicatorsSettings.defaultSettings[indicatorsSettings.name];
            var settings = [mapping];
            var indicatorName = indicatorsSettings.name;

            // for slow/fast stochastic
            if (~indicatorName.toLowerCase().indexOf('stochastic')) {
                indicatorName = 'stochastic';
            }

            for (key in indicator) {
                if (key !== 'overview' && key !== 'plotIndex') {
                    var val = $('#' + key).val();
                    val = val == 'true' || val == 'false' ? val == 'true' : val;
                    settings.push(val);
                }
            }

            // save settings for indicator
            appSettingsCache['indicators'][indicatorsSettings.name] = {};
            appSettingsCache['indicators'][indicatorsSettings.name]['settings'] = settings;
            appSettingsCache['indicators'][indicatorsSettings.name]['plotIndex'] = indicatorsSettings.plotIndex;

            var plot = chart.plot(indicatorsSettings.plotIndex);
            plot[indicatorName].apply(plot, settings);
            // adding extra Y axis to the right side
            plot.yAxis(1).orientation('right');
            // hide indicator settings modal
            $indicatorSettingsModal.modal('hide');
        });
    });

    function initHeightChart() {
        var creditsHeight = 10;
        $('#chart-container').height($(window).height() - $indicatorNavPanel.outerHeight() - creditsHeight);
    }

    function createChart(container, updateChart) {
        var dataName = $chartDataSelect.find('option:selected').text().trim();
        var seriesType = $seriesTypeSelect.val();

        // create data table on loaded data
        dataTable = anychart.data.table();

        var series;

        // map loaded data
        var mapping = dataTable.mapAs({'value': 1, 'volume': 1, 'open': 1, 'high': 2, 'low': 3, 'close': 4});

        // create stock chart
        chart = anychart.stock();

        // create plot on the chart
        var plot = chart.plot(0);

        dataTable.addData(appSettingsCache['data'][dataName.toLowerCase()]);

        if (updateChart) {
            var indicatorName;
            var indicatorPlot;
            var indicatorSettings = [];

            // create line series
            series = plot[appSettingsCache['chartType']](mapping);
            series.name(dataName.toUpperCase());

            plot.yScale(appSettingsCache['scale']);

            for (var keyIndicator in appSettingsCache['indicators']) {
                indicatorName = keyIndicator;

                if (appSettingsCache['indicators'].hasOwnProperty(keyIndicator)) {
                    indicatorSettings = appSettingsCache['indicators'][keyIndicator]['settings'];
                    indicatorSettings[0] = mapping;
                }

                // for slow/fast stochastic
                if (~indicatorName.toLowerCase().indexOf('stochastic')) {
                    indicatorName = 'stochastic';
                }

                if (appSettingsCache['indicators'].hasOwnProperty(keyIndicator)) {
                    indicatorPlot = chart.plot(appSettingsCache['indicators'][keyIndicator]['plotIndex']);
                    indicatorPlot[indicatorName].apply(indicatorPlot, indicatorSettings);
                    // adding extra Y axis to the right side
                    indicatorPlot.yAxis(1).orientation('right');
                }
            }

        } else {
            // create line series
            series = plot[seriesType](mapping);
            series.name(dataName.toUpperCase());
        }

        series.stroke('2px #64b5f6');

        // adding extra Y axis to the right side
        var yAxis = plot.yAxis(1);
        yAxis.orientation('right');
        // setting chart padding to fit both Y axes
        chart.padding(10, 50, 20, 50);

        // create scroller series with mapped data
        chart.scroller().line(mapping);

        // set chart selected date/time range
        chart.selectRange('2004-11-14', '2007-11-15');

        // set container id for the chart
        chart.container(container);

        // initiate chart drawing
        chart.draw();

        // create range picker
        var rangePicker = anychart.ui.rangePicker();
        // init range picker
        rangePicker.render(chart);

        // create range selector
        var rangeSelector = anychart.ui.rangeSelector();
        // init range selector
        rangeSelector.render(chart);

        chart.listen('chartDraw', function () {
            initHeightChart();
            setTimeout(function () {
                $loader.hide();
            }, 100);
        });

    }

    function removeChart() {
        if (chart) {
            chart.dispose();
            chart = null;
        }
    }

    function createHtmlToIndicatorForm() {
        var $indicatorFormGroup;
        var indicatorSettings = indicatorsSettings.defaultSettings[indicatorsSettings.name];
        var $option;
        var i = 0;

        $('#indicatorSettingsModalTitle').text(indicatorsSettings.defaultSettings[indicatorsSettings.name].overview.title);

        // empty form
        $indicatorForm.empty();
        // create row
        $indicatorForm.append('

');
        var $indicatorFormRow = $indicatorForm.find('.row');

        for (var key in indicatorSettings) {
            if (indicatorSettings.hasOwnProperty(key) && key !== 'overview' && key !== 'plotIndex') {

                if (typeof indicatorSettings[key] === 'string') {
                    $indicatorFormRow.append(selectHtml);
                    $indicatorFormGroup = $('#indicatorFormGroup');
                    $indicatorFormGroup.find('select').attr('id', key);
                    $indicatorFormGroup.find('label').attr('for', key).text(getInputLabelText(key));

                    for (i = 0; i < indicatorsSettings.seriesType.length; i++) {
                        $option = $('<option></option>');
                        $option.val(indicatorsSettings.seriesType[i].toLowerCase());
                        $option.text(getInputLabelText(indicatorsSettings.seriesType[i]));
                        $indicatorFormGroup.find('select').append($option);
                    }

                    $indicatorFormGroup.removeAttr('id');

                } else if (typeof indicatorSettings[key] === 'number') {
                    $indicatorFormRow.append(inputHtml);
                    $indicatorFormGroup = $('#indicatorFormGroup');
                    $indicatorFormGroup.find('input').attr('id', key);

                    $indicatorFormGroup.removeAttr('id').find('label').attr('for', key).text(getInputLabelText(key));

                } else if (typeof indicatorSettings[key] === 'object') {
                    $indicatorFormRow.append(selectHtml);
                    $indicatorFormGroup = $('#indicatorFormGroup');
                    $indicatorFormGroup.find('select').attr('id', key);
                    $indicatorFormGroup.find('label').attr('for', key).text(getInputLabelText(key));

                    for (i = 0; i < indicatorSettings[key].length; i++) {
                        $option = $('<option></option>');
                        $option.val(indicatorSettings[key][i].toLowerCase());
                        $option.text(indicatorSettings[key][i]);
                        $indicatorFormGroup.find('select').append($option);
                    }

                    $indicatorFormGroup.removeAttr('id');
                }
            }
        }

        // col class to form el
        setColClass($indicatorForm);
        // indicator overview text
        $indicatorForm.find($("[class*='col-sm-']")).last().after('

');
        $indicatorForm.find('#overviewText').append(indicatorsSettings.defaultSettings[indicatorsSettings.name].overview.description);
    }

    function setDefaultIndicatorSettings() {

        var indicatorSettings = indicatorsSettings.defaultSettings[indicatorsSettings.name];

        for (var key in indicatorSettings) {
            if (indicatorSettings.hasOwnProperty(key) && key !== 'overview' && key !== 'plotIndex') {
                $('#' + key).val(indicatorSettings[key]);
            }
        }
    }
})();


text:
<dom-module id="x-custom">
  <template>

[[user]] says:

[[message]]

  </template>

</dom-module>


text:
use super::output_vec;
use crate::run::OwnedRun;
use livesplit_core::run::parser::{composite::ParsedRun, TimerKind};
use std::{io::Write, os::raw::c_char};

/// type
pub type ParseRunResult = Option<ParsedRun<'static>>;
/// type
pub type OwnedParseRunResult = Box<ParseRunResult>;

/// drop
#[no_mangle]
pub extern "C" fn ParseRunResult_drop(this: OwnedParseRunResult) {
    drop(this);
}

/// Returns <TRUE> if the Run got parsed successfully. <FALSE> is returned otherwise.
#[no_mangle]
pub extern "C" fn ParseRunResult_parsed_successfully(this: &ParseRunResult) -> bool {
    this.is_some()
}

/// Moves the actual Run object out of the Result. You may not call this if the
/// Run wasn't parsed successfully.
#[no_mangle]
pub extern "C" fn ParseRunResult_unwrap(this: OwnedParseRunResult) -> OwnedRun {
    Box::new((*this).unwrap().run)
}

/// Accesses the name of the Parser that parsed the Run. You may not call this
/// if the Run wasn't parsed successfully.
#[no_mangle]
pub extern "C" fn ParseRunResult_timer_kind(this: &ParseRunResult) -> *const c_char {
    output_vec(|f| write!(f, "{}", this.as_ref().unwrap().kind).unwrap())
}

/// Checks whether the Parser parsed a generic timer. Since a generic timer can
/// have any name, it may clash with the specific timer formats that
/// livesplit-core supports. With this function you can determine if a generic
/// timer format was parsed, instead of one of the more specific timer formats.
#[no_mangle]
pub extern "C" fn ParseRunResult_is_generic_timer(this: &ParseRunResult) -> bool {
    matches!(
        this,
        Some(ParsedRun {
            kind: TimerKind::Generic(_),
            ..
        })
    )
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ @LANG136 }}</title>
<link rel="stylesheet" href="{{ @CONSTRUCTR_BASE_URL}}/CONSTRUCTR-CMS/ASSETS/css/constructr_css_merged.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

	<include href="{{ @NAVIGATION }}" />
	<form action="{{ @CONSTRUCTR_BASE_URL }}/constructr/uploads" method="get" enctype="application/x-www-form-urlencoded">

				search
				<input placeholder="{{ @LANG137 }}" name="needle" id="needle" type="text" value="{{ @ORIGIN_NEEDLE }}" required="required">
				<check if="{{ @ORIGIN_NEEDLE }} != ''">
					<true>{{ @LANG343 }}</true>
				</check>

	</form>

{{ @FILES_COUNTR }} {{ @LANG138 }} | <input type="checkbox" id="pix" checked="checked" /> {{ @LANG139 }}   <input type="checkbox" id="files" checked="checked" /> {{ @LANG140 }} | {{ @LANG141 }} +

            <check if="{{ @NEW }} == 'success'">

{{ @LANG142 }}

            </check>
            <check if="{{ @NEW }} == 'no-success'">

{{ @LANG143 }}

            </check>
            <check if="{{ @DELETE }} == 'success'">

{{ @LANG144 }}

            </check>
            <check if="{{ @DELETE }} == 'no-success'">

{{ @LANG145 }}

            </check>
            <check if="{{ @EDIT }} == 'success'">

{{ @LANG352 }}

            </check>
            <check if="{{ @EDIT }} == 'no-success'">

{{ @LANG353 }}

            </check>

	<check if="{{ @PAGINATION_FILES }}">
		<true>

		            {{ @LANG146 }}
		            {{ @LANG147 }}
		            {{ @LANG148 }}

		            <repeat group="{{ @PAGINATION_FILES }}" value="{{ @PAGINATION_FILE }}">
		            	<check if="{{ strrchr(@PAGINATION_FILE,'#') }} == '#true'">
		            		<true>

		            		</true>
		            		<false>

		            		</false>
		            	</check>
			            	<check if="{{ strrchr(@PAGINATION_FILE,'#') }} == '#true'">
			            		<true>

			            		</true>
			            		<false>
			            			{{ str_replace('#false','',@PAGINATION_FILE) }}
			            		</false>
			            	</check>
			                {{ @CONSTRUCTR_BASE_URL }}/UPLOADS/{{ str_replace('#false','',str_replace('#true','',@PAGINATION_FILE)) }}
			                <nobr>
			                	mode_edit

			                	open_in_new

			                	delete
			                </nobr>

			        </repeat>

		</true>
	</check>
	<check if="{{ @SHOW_PAGINATION }} == 'true'">
		<true>

					{{ html_entity_decode(@PAGINATION_STRING) }}

		</true>
	</check>

ConstructrCMS Version {{ @CONSTRUCTR_VERSION }}


text:
package com.manolovn.sample.point;

import com.manolovn.trianglify.generator.point.CircularPointGenerator;
import com.manolovn.trianglify.generator.point.PointGenerator;
import com.manolovn.trianglify.generator.point.RegularPointGenerator;

/**
 * Point generator factory
 *
 * @author manolovn
 */
public class PointGeneratorFactory {

    public enum Type {
        REGULAR("regular"),
        CIRCULAR("circular");

        Type(String type) {

        }
    }

    public static PointGenerator from(String stringType) {
        Type type = Type.valueOf(stringType);
        switch (type) {
            case CIRCULAR:
                return new CircularPointGenerator();
            case REGULAR:
            default:
                return new RegularPointGenerator();
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 3/2/17
 * Time: 9:01 AM
 */

namespace Stk\AdhesionBundle\Forms;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;

class UploadType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('attachement', FileType::class, [
                'label' => 'Fichier excel:'
            ]);
    }

}


text:
"""A wrapper to pass a node without its type information."""

from typing import Any, Dict

from tfx.dsl.components.base import base_node

class NodeWrapper(base_node.BaseNode):
  """Wrapper of a node.

  The wrapper is needed for container entrypoint to deserialize a component
  wihtout knowning it's original python class. This enables users
  to use container base component without re-compiling the tfx base image every
  time they change the component and spec definitions.
  """

  def __init__(self, node: base_node.BaseNode):
    self.executor_spec = node.executor_spec
    self.driver_class = node.driver_class
    self._type = node.type
    self._id = node.id
    self._inputs = node.inputs
    self._outputs = node.outputs
    self._exec_properties = node.exec_properties

  @property
  def type(self) -> str:
    return self._type

  @property
  def id(self) -> str:
    return self._id

  @property
  def inputs(self) -> Dict[str, Any]:
    return self._inputs

  @property
  def outputs(self) -> Dict[str, Any]:
    return self._outputs

  @property
  def exec_properties(self) -> Dict[str, Any]:
    return self._exec_properties


text:
package core

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
	"net/http"
)

// UpdateDrgRouteRulesRequest wrapper for the UpdateDrgRouteRules operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/UpdateDrgRouteRules.go.html to see an example of how to use UpdateDrgRouteRulesRequest.
type UpdateDrgRouteRulesRequest struct {

	// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the DRG route table.
	DrgRouteTableId *string `mandatory:"true" contributesTo:"path" name:"drgRouteTableId"`

	// Request to update one or more route rules in the DRG route table.
	UpdateDrgRouteRulesDetails `contributesTo:"body"`

	// Unique Oracle-assigned identifier for the request.
	// If you need to contact Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`

	// Metadata about the request. This information will not be transmitted to the service, but
	// represents information that the SDK will consume to drive retry behavior.
	RequestMetadata common.RequestMetadata
}

func (request UpdateDrgRouteRulesRequest) String() string {
	return common.PointerString(request)
}

// HTTPRequest implements the OCIRequest interface
func (request UpdateDrgRouteRulesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {

	return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}

// BinaryRequestBody implements the OCIRequest interface
func (request UpdateDrgRouteRulesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {

	return nil, false

}

// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request UpdateDrgRouteRulesRequest) RetryPolicy() *common.RetryPolicy {
	return request.RequestMetadata.RetryPolicy
}

// UpdateDrgRouteRulesResponse wrapper for the UpdateDrgRouteRules operation
type UpdateDrgRouteRulesResponse struct {

	// The underlying http response
	RawResponse *http.Response

	// The []DrgRouteRule instance
	Items []DrgRouteRule `presentIn:"body"`

	// Unique Oracle-assigned identifier for the request. If you need to contact
	// Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}

func (response UpdateDrgRouteRulesResponse) String() string {
	return common.PointerString(response)
}

// HTTPResponse implements the OCIResponse interface
func (response UpdateDrgRouteRulesResponse) HTTPResponse() *http.Response {
	return response.RawResponse
}


text:
<?php

namespace Kazoo\Tests\Common;

use \PHPUnit_Framework_TestCase;

use \Kazoo\SDK;

use \Kazoo\AuthToken\ApiKey;
use \Kazoo\AuthToken\User;
use \Kazoo\AuthToken\Exception\Unauthenticated;
use \Kazoo\Api\Exception\RateLimit;

class FunctionalTest extends \PHPUnit_Framework_TestCase
{
    private $sdk;

    public function setUp() {
        @session_start();

        if(empty($GLOBALS['api_key'])){
            $auth_token = new User($GLOBALS['auth_username'], $GLOBALS['auth_password'], $GLOBALS['auth_realm']);
        } else {
            $auth_token = new ApiKey($GLOBALS['api_key']);
        }

        if(empty($GLOBALS['base_url'])){
            $options = array();
        } else {
            $options = array('base_url' => $GLOBALS['base_url']);
        }

        try {
            $this->sdk = new SDK($auth_token, $options);
        } catch (RateLimit $e) {
            $this->markTestSkipped('API limit reached. Skipping to prevent unnecessary failure.');
        } catch (Unauthenticated $e) {
            $this->markTestSkipped('Test requires authentication. Skipping to prevent unnecessary failure.');
        }
    }

    public function getSDK() {
        return $this->sdk;
    }

    public function testVerify() {
        $this->assertTrue(TRUE);
    }
}


text:
package pg

import (
	"database/sql/driver"
	"encoding/json"
	"reflect"
	"strconv"
	"time"

	"github.com/yobert/pg/pgutil"
)

type valueAppender func([]byte, reflect.Value) []byte

var valueAppenders = [...]valueAppender{
	reflect.Bool:          appendBoolValue,
	reflect.Int:           appendIntValue,
	reflect.Int8:          appendIntValue,
	reflect.Int16:         appendIntValue,
	reflect.Int32:         appendIntValue,
	reflect.Int64:         appendIntValue,
	reflect.Uint:          appendUintValue,
	reflect.Uint8:         appendUintValue,
	reflect.Uint16:        appendUintValue,
	reflect.Uint32:        appendUintValue,
	reflect.Uint64:        appendUintValue,
	reflect.Uintptr:       nil,
	reflect.Float32:       appendFloatValue,
	reflect.Float64:       appendFloatValue,
	reflect.Complex64:     nil,
	reflect.Complex128:    nil,
	reflect.Array:         nil,
	reflect.Chan:          nil,
	reflect.Func:          nil,
	reflect.Interface:     nil,
	reflect.Map:           nil,
	reflect.Ptr:           nil,
	reflect.Slice:         nil,
	reflect.String:        appendStringValue,
	reflect.Struct:        appendStructValue,
	reflect.UnsafePointer: nil,
}

func appendBoolValue(dst []byte, v reflect.Value) []byte {
	return appendBool(dst, v.Bool())
}

func appendIntValue(dst []byte, v reflect.Value) []byte {
	return strconv.AppendInt(dst, v.Int(), 10)
}

func appendUintValue(dst []byte, v reflect.Value) []byte {
	return strconv.AppendUint(dst, v.Uint(), 10)
}

func appendFloatValue(dst []byte, v reflect.Value) []byte {
	return appendFloat(dst, v.Float())
}

func appendStringValue(dst []byte, v reflect.Value) []byte {
	return appendString(dst, v.String())
}

func appendStructValue(dst []byte, v reflect.Value) []byte {
	switch v.Type() {
	case timeType:
		return appendTimeValue(dst, v)
	}
	b, err := json.Marshal(v.Interface())
	if err != nil {
		panic(err)
	}
	return appendStringBytes(dst, b)
}

func appendTimeValue(dst []byte, v reflect.Value) []byte {
	dst = append(dst, '\'')
	dst = pgutil.AppendTime(dst, v.Interface().(time.Time))
	dst = append(dst, '\'')
	return dst
}

func appendAppenderValue(dst []byte, v reflect.Value) []byte {
	return v.Interface().(QueryAppender).AppendQuery(dst)
}

func appendDriverValuerValue(dst []byte, v reflect.Value) []byte {
	return appendDriverValuer(dst, v.Interface().(driver.Valuer))
}

func isEmptyValue(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
		return v.Len() == 0
	case reflect.Bool:
		return !v.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return v.Int() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return v.Uint() == 0
	case reflect.Float32, reflect.Float64:
		return v.Float() == 0
	case reflect.Interface, reflect.Ptr:
		return v.IsNil()
	}
	return false
}


text:
title: Development Team Evaluation Explained
keywords:
  - clean code
  - job happiness
  - work life balance
  - testing
  - automation
  - agile
  - enterprise
  - deliver value
---

Explanation for the [Development Team Evaluation](/2018/05/31/development-team-evaluation/) questions.

## What is your source control branching strategy?
This is the first question for a very good reason. If the answer is _"we don't have source control"_ you better run for your life.
Widely adopted patterns such as feature branches or single branch development are generally a sign of maturity.
A team struggling with their branching strategy is clearly in need of technical expertise.

## How do you know what is your team working on?
> What needs to be done?
> What has already been completed?

Mature teams actively track their work _-generally with an [Issue Tracking software](https://en.wikipedia.org/wiki/Issue_tracking_system)-_.
This practice increases productivity. Problems arise when work is not tracked: features are forgotten, employees burn out, chaos reigns.

## How do you assign new work?
Sharing is caring. Agile teams with strong engineering practices share responsibilities across their members. No single engineer is responsible for a single product. Multiple engineers collaborate on the same task. This collaboration reduces silos and increases the [Bus Factor](https://en.wikipedia.org/wiki/Bus_factor).

## How long does it take you to go from an idea into something your customers can use?
There is not a right answer here. Feature sizes can greatly vary _even_ on the same team.
Shorter cycle times indicate good organizational health.

## How frequently do you do deployments?
Frequent deployments indicate a high level of confidence in the release and monitoring process.

## How many bugs have you had in the last quarter?
> How many of those were regressions?

A mature team will rarely have bugs and *NEVER* will have regressions.
The absence of bugs indicates strong engineering practices.

## What sort of testing do you do?
There is no correct answer for this question either. Mature teams will rely heavily on automated unit tests.
Avoid places that see no value in tests.

## When was the last time you reviewed the vulnerabilities of your system?
Security is important for any product in any organization. Mature teams understand this and incorporate security oriented practices into their software development lifecycle.

## Do you know whom to contact in case there's a problem?
A team with strong Operational Integrity will have clearly defined policies and SLAs around incident responses.

## When was your last production incident?
> Did you resolve it?
>How long did it took to get resolved?

A mature team will rarely have production incidents. If there is any sort of problem it will get resolved immediately.


text:
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
--------------------------------------------------------------------
-- |
-- Copyright :  (c) McGraw Hill Financial 2014-2015
-- License   :  BSD2
-- Maintainer:  Stephen Compall <scompall@nocandysw.com>
-- Stability :  experimental
-- Portability: non-portable
--
-- State and helpers for loading modules in the REPL
--------------------------------------------------------------------

module Ermine.Console.Module
  ( moduleLoader, testLoader, preludeTestLoader
  ) where

import Control.Applicative
import Control.Lens
import Control.Monad (liftM)
import Control.Monad.Error.Class
-- import Control.Monad.IO.Class
import Control.Monad.State.Class
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import Data.Traversable (forM)
import Data.Foldable (foldl', forM_)
import Data.Monoid (mempty, (<>))
import Data.Text (Text, unpack)
import Ermine.Loader.Core (Loader, contramapName, fanoutIdLoaderM,
                           load, loaded, thenM, thenM')
import Ermine.Loader.Filesystem (filesystemLoader, explainLoadRefusal,
                                 Freshness)
-- import Ermine.Loader.MapCache (loadCached)
import Ermine.Parser.Module
-- import Ermine.Parser.State
import Ermine.Pretty hiding (string, int, integer, (</>))
import Ermine.Syntax.Module (Import, Module, ModuleHead, importModule,
                             moduleHeadImports, moduleHeadText)
import Ermine.Syntax.ModuleName (ModuleName, moduleName, mkModuleName_)
import Ermine.Syntax.Name
import System.FilePath ((</>))
import Text.Parser.Combinators (eof)
import Text.Parser.Token (TokenParsing, someSpace)
import Text.Trifecta.Parser
import Text.Trifecta.Result

-- TODO s11 remove
import Control.Monad.State hiding (forM, forM_, liftM)
import Control.Monad.Trans.Except
import Ermine.Loader.MapCache

-- | From a loader that loads the raw 'Text' of a module, produce a
-- 'Module' loader using the cache in state.
moduleLoader :: forall e m. (MonadError Doc m,
                             MonadState (HashMap ModuleName (e, Module)) m)
             => Loader e m ModuleName Text
             -> Loader e m ModuleName Module
moduleLoader l = fanoutIdLoaderM lemh `thenM'` afterModuleHead
  where lemh :: Loader e m ModuleName (ModuleHead (Import Text) Text)
        lemh = l `thenM` parseModuleHead
        dep :: ModuleName -> m (ModuleHead (Import Text) (e, Text))
        dep = liftM strength . (lemh^.load)
        importSet :: [ModuleHead (Import Text) (e, Text)] -> m ()
        importSet mhs = do
          preceding <- get
          -- Here we finally use the invariant of 'pickImportPlan':
          -- the 'Module's referenced by 'Import's *must* already be
          -- in the state.
          let precImp i = (i, snd $ preceding HM.! (i^.importModule))
          emods <- mhs `forM` \mh ->
              (mh^.moduleHeadText._1,)
              `liftM` parseModuleRemainder (bimap precImp snd mh)
          put (foldl' (\hm em@(_, md) -> HM.insert (md^.moduleName) em hm)
                      preceding emods)
        afterModuleHead (e, (n, mh)) = do
          already <- get
          impss <- pickImportPlan dep already n
                 . strength $ (e, mh)
          impss `forM_` importSet
          gets (HM.! n)

-- TODO s11: remove or pull out to tests

testLoader :: String -> String -> IO (Either Doc Module)
testLoader loadDir =
  let l :: ModuleName
        -> ExceptT Doc (StateT (HashMap ModuleName (Freshness, Module)) IO) Module
      l = loadCached . moduleLoader
        . loaded (withExceptT (pretty . unpack . explainLoadRefusal))
        . contramapName (view name)
        $ filesystemLoader loadDir ".e"
  in flip evalStateT mempty . runExceptT . l . mkModuleName_

preludeTestLoader :: String -> IO (Either Doc Module)
preludeTestLoader = testLoader ("stdlib" </> "Prelude")

-- end s11 remove

-- | Make a plan to import dependencies, based on importing a single
-- dependency.  Include all the module heads and remaining bodies in
-- the plan.
--
-- Invariant: For each element of the result, every 'Import'
-- referenced by each 'ModuleHead' appears in a previous element of
-- the result.
pickImportPlan :: MonadError Doc m
               => (ModuleName -> m (ModuleHead (Import g) txt))
                  -- ^ load a module head by name
               -> HashMap ModuleName a -- ^ already-loaded Modules
               -> ModuleName           -- ^ initial module name
               -> ModuleHead (Import g) txt -- ^ initial module head
               -> m [[ModuleHead (Import g) txt]]
pickImportPlan dep hm n fstMH = do
  graph <- fetchGraphM deps (const . dep) (HM.singleton n fstMH)
  topSort graph deps &
    either (throwError . reportCircle) (return . fmap (fmap snd))
  where deps :: ModuleHead (Import g) a -> [ModuleName]
        deps = filter (\mn -> not (HM.member mn hm))
             . toListOf (moduleHeadImports.folded.importModule)
        reportCircle circ = "Circular dependency detected: "
                         <> pretty (circ <&> pretty . unpack . (^.name))

-- Why isn't this defined?
strength :: Functor f => (a, f b) -> f (a, b)
strength (a, fb) = (a,) <$> fb

-- TODO: Replace 'mempty' in parseModuleHead and parseModuleRemainder
-- with an appropriate Delta reflecting the input file and (to-be)
-- saved value in the ModuleHead, respectively.

parseModuleHead :: MonadError Doc m => Text -> m (ModuleHead (Import Text) Text)
parseModuleHead = asMError . parseString (phrase moduleHead) mempty . unpack

parseModuleRemainder :: MonadError Doc m
                     => ModuleHead (Import Text, Module) Text
                     -> m Module
parseModuleRemainder mh =
  mh ^. moduleHeadText
    & unpack
    & parseString (phrase (wholeModule mh)) mempty
    & asMError

phrase :: TokenParsing m => m a -> m a
phrase ma = optional someSpace *> ma <* eof

asMError :: MonadError Doc m => Result a -> m a
asMError (Success a) = return a
asMError (Failure doc) = throwError doc