text:
from yapsy.IPlugin import IPlugin
from yapsy.PluginManager import PluginManager
from django.template import loader, Context
from django.db.models import Count
from server.models import *
from django.shortcuts import get_object_or_404
import server.utils as utils

mem_4_gb = 4 * 1024 * 1024
mem_415_gb = 4.15 * 1024 * 1024
mem_775_gb = 7.75 * 1024 * 1024
mem_8_gb = 8 * 1024 * 1024

class Memory(IPlugin):
    def plugin_type(self):
        return 'builtin'

    def widget_width(self):
        return 4

    def get_description(self):
        return 'Installed RAM'

    def widget_content(self, page, machines=None, theid=None):
        # The data is data is pulled from the database and passed to a template.

        # There are three possible views we're going to be rendering to - front, bu_dashbaord and group_dashboard. If page is set to bu_dashboard, or group_dashboard, you will be passed a business_unit or machine_group id to use (mainly for linking to the right search).
        if page == 'front':
            t = loader.get_template('plugins/traffic_lights_front.html')

        if page == 'bu_dashboard':
            t = loader.get_template('plugins/traffic_lights_id.html')

        if page == 'group_dashboard':
            t = loader.get_template('plugins/traffic_lights_id.html')

        try:
            mem_ok = machines.filter(memory_kb__gte=mem_8_gb).count()
        except:
            mem_ok = 0
        try:
            mem_warning = machines.filter(memory_kb__range=[mem_4_gb, mem_775_gb]).count()
        except:
            mem_warning = 0

        try:
            mem_alert = machines.filter(memory_kb__lt=mem_4_gb).count()
        except:
            mem_alert = 0

        c = Context({
            'title': 'Memory',
            'ok_label': '8GB +',
            'ok_count': mem_ok,
            'warning_label': '4GB +',
            'warning_count': mem_warning,
            'alert_label': '< 4GB',
            'alert_count': mem_alert,
            'plugin': 'Memory',
            'theid': theid,
            'page': page
        })
        return t.render(c)

    def filter_machines(self, machines, data):
        if data == 'ok':
            machines = machines.filter(memory_kb__gte=mem_8_gb)
            title = 'Machines with more than 8GB memory'

        elif data == 'warning':
            machines = machines.filter(memory_kb__range=[mem_4_gb, mem_775_gb])
            title = 'Machines with between 4GB and 8GB memory'

        elif data == 'alert':
            machines = machines.filter(memory_kb__lt=mem_4_gb)
            title = 'Machines with less than 4GB memory'

        else:
            machines = None
            title = None

        return machines, title


text:
#include "cardcreator_app.h"

#include <set>
#include <sdl.h>

#include <utils/filesystem/filesystem.h>
#include <game_utils/tween/tween_utils.h>

#include "component_framework/EntityManager.h"
#include "component_framework/EventManager.h"
#include "component_framework/gcomponents.h"
#include "component_framework/SystemManager.h"
#include "component_framework/ComponentUpdator.h"
#include "component_framework/EntitySerializer.h"

#include "misc_utils/debug_layer.h"
#include "misc_utils/config_ui.h"
#include "misc_utils/simple_profiler.h"

#include <utils/imagetoarray/imagetoarray.h>

#include "resize_image.h"
#include "global_data.h"

//---------------------------------------------------------------------------------------
#ifdef WIN32
#include <SDL_syswm.h>

void MoveWindowTo( int x, int y )
{
	SDL_SysWMinfo i;
	SDL_VERSION( &i.version );
	if ( SDL_GetWMInfo ( &i) ) {
		HWND hwnd = i.window;
		SetWindowPos( hwnd, HWND_TOP, x, y,  0, 0,          // Ignores size arguments.
                 SWP_FRAMECHANGED );
	}
}
#undef LoadImage
#endif // WIN32

template< class T >
inline void SWAP_RED_AND_BLUE( T& color )
{
	T red = 0;
	T blue = 0;

	red = 0x00ff0000 & color;
	blue = 0x000000ff & color;

	red = red >> 16;
	blue = blue << 16;

	color = ( color & 0xff00ff00 ) | red | blue;
}

struct Page
{
	Page()
	{

	}

	void Init( int pixel_size_x, int pixel_size_y, int card_count_x, int card_count_y, int border_size = 4 )
	{
		card_count = 0;
		types::ivector2 pagesize( 2480, 3508 );
		data.Resize( pagesize.x, pagesize.y );
		data.SetEverythingTo( 0xFFFFFFFF );

		size.Set( pixel_size_x, pixel_size_y );
		border_buffer.Set( border_size, border_size );

		types::ivector2 start_pos =( pagesize - types::ivector2( card_count_x * ( size.x + border_buffer.x ), card_count_y * ( size.y + border_buffer.y ) ) );
		start_pos.x *= 0.5f;
		start_pos.y *= 0.5f;

		types::ivector2 pos = start_pos;
		for( int y = 0; y < card_count_y; ++y )
		{
			for( int x = 0; x < card_count_x; ++x )
			{
				points.push_back( pos );
				pos.x += size.x + border_buffer.x;
			}

			pos.x = start_pos.x;
			pos.y += size.y + border_buffer.y;
		}
	}

	void Clear()
	{
		card_count = 0;
		data.SetEverythingTo( 0xFFFFFFFF );
	}

	ceng::CArray2D< Uint32 > data;
	int card_count;
	std::vector< types::ivector2 > points;
	types::ivector2	 size;
	types::ivector2 border_buffer;

	void AddCardToPage( const ceng::CArray2D< Uint32 >& image )
	{
		types::ivector2 image_pos = ( types::ivector2( image.GetWidth(), image.GetHeight() ) - size ) * 0.5f;
		types::ivector2 page_pos = points[ card_count ];
		for( int y = -border_buffer.y; y < size.y + border_buffer.y; ++y )
		{
			for( int x = -border_buffer.x; x < size.x + border_buffer.x; ++x )
			{
				if( x >= 0 && y >= 0 && x < size.x && y < size.y )
				{
					data.At( x + page_pos.x, y + page_pos.y ) = image.At( x + image_pos.x, y + image_pos.y );
					SWAP_RED_AND_BLUE( data.At( x + page_pos.x, y + page_pos.y ) );
				}
				else
				{
					data.At( x + page_pos.x, y + page_pos.y ) = 0xFFe8e8e8;
				}
			}
		}

		card_count++;
	}

	bool IsFull() { if( card_count >= (int)points.size() ) return true; else return false; }
};

void LoadCSVFile( const std::string& csv_file, std::vector< std::map< std::string, std::string > >& result );

void ParseCards( const std::string& filename, const std::string& output_prefix = "output/test_case_",  const types::ivector2& pixel_size = types::ivector2( 550, 550 ), const types::ivector2& card_page_count = types::ivector2( 4, 6 ), int border = 4 )
{
	std::vector< std::map< std::string, std::string > > values;
	LoadCSVFile( filename, values );

	// void	LoadImage( const std::string& filename, ceng::CArray2D< poro::types::Uint32 >& out_array2d, bool include_alpha );
	Page p;
	p.Init( pixel_size.x, pixel_size.y, card_page_count.x, card_page_count.y, border );
	int pagec = 0;

	for( std::size_t i = 0; i < values.size(); ++i )
	{
		int count = ceng::CastFromString< int >(values[i]["count"]);
		std::string filename = values[i]["filename"];

		if( filename.empty() )
			continue;

		ceng::CArray2D< poro::types::Uint32 > image;
		LoadImage( filename, image, true );

		if( image.GetWidth() <= 0 || image.GetHeight() <= 0 )
		{
			std::cout << "Error couldn't load image: " << filename << std::endl;
		}
		else
		{
			for( int j = 0; j < count; ++j )
			{
				p.AddCardToPage( image );
				if( p.IsFull() )
				{
					SaveImage( output_prefix + ceng::CastToString( pagec ) + ".png", p.data );
					pagec++;
					p.Clear();
				}
			}
		}
	}

	// last case
	SaveImage( output_prefix + ceng::CastToString( pagec ) + ".png", p.data );
	pagec++;
	p.Clear();

}

//

void ParseCards( std::vector< std::pair< std::string, int > >& filenames, const std::string& output_prefix = "output/test_case_",
				const types::ivector2& pixel_size = types::ivector2( 550, 550 ),
				const types::ivector2& card_page_count = types::ivector2( 4, 6 ),
				const types::ivector2& resize_size = types::ivector2( 550, 550 ),
				int border_size = 3,
				bool rotate = false )
{

	// void	LoadImage( const std::string& filename, ceng::CArray2D< poro::types::Uint32 >& out_array2d, bool include_alpha );

	Page p;
	p.Init( pixel_size.x, pixel_size.y, card_page_count.x, card_page_count.y, border_size );
	int pagec = 0;

	for( std::size_t i = 0; i < filenames.size(); ++i )
	{
		int count = filenames[i].second;
		std::string filename = filenames[i].first;

		if( filename.empty() )
			continue;

		ceng::CArray2D< poro::types::Uint32 > image;
		LoadImage( filename, image, true );
		if( image.GetWidth() <= 0 || image.GetHeight() <= 0 )
		{
			std::cout << "Error couldn't load image: " << filename << std::endl;
		}
		else
		{
			// if we need to rotate
			if( rotate )
			{
				ceng::CArray2D< poro::types::Uint32 > rotated_image;
				ImageRotate90( image, rotated_image );
				image = rotated_image;
			}

			// if we need to resize
			if( true )
			{
				ceng::CArray2D< poro::types::Uint32 > resized_image;
				// 1095, 958 );
				ImageResize( image, resized_image, resize_size.x, resize_size.y );
				image = resized_image;
			}

			for( int j = 0; j < count; ++j )
			{
				p.AddCardToPage( image );
				if( p.IsFull() )
				{
					SaveImage( output_prefix + ceng::CastToString( pagec ) + ".png", p.data );
					pagec++;
					p.Clear();
				}
			}
		}
	}

	// last case
	SaveImage( output_prefix + ceng::CastToString( pagec ) + ".png", p.data );
	pagec++;
	p.Clear();

}

//---------------------------------------------------------------------------------------

#define CONFIG_MARCHING_HOLES(list_) \
	list_(bool,			display_libtess2,					true,		NULL ) \
	list_(bool,			display_poly2tri,					false,		NULL ) \
	list_(float,		camera_zoom,						6.0f,		MetaData( 1.f, 20.f ) ) \
	list_(int,			stat_fps_count,						0,			NULL ) \

DEFINE_CONFIG_UI( ConfigMarchingHoles, CONFIG_MARCHING_HOLES )

namespace {

	ConfigMarchingHoles g_config;
	types::vector2 camera_offset( -114, 14 );
}
// ----------------------------------------------------------------------------

CardCreatorApp::CardCreatorApp()
{
}

//-----------------------------------------------------------------------------

void LoadCSVFile( const std::string& csv_file, std::vector< std::map< std::string, std::string > >& result )
{
	std::vector< std::string > input;
	ceng::ReadFileToVector( csv_file, input );

	if( input.empty() )
		return;

	std::vector< std::string > labels = ceng::StringSplit( ",", input[0] );
	result.resize( input.size() - 1 );
	for( std::size_t i = 1; i < input.size(); ++i )
	{
		std::vector< std::string > data = ceng::StringSplit( ",", input[i] );
		for( std::size_t j = 0; j < data.size(); ++j )
		{
			result[ i - 1 ][ labels[j] ] = data[j];
		}
	}
}

void LoadDeckFile( const std::string& csv_file, std::vector< std::pair< std::string, int > >& result )
{
	std::vector< std::map< std::string, std::string > > values;
	LoadCSVFile( csv_file, values );

	for( std::size_t i = 0; i < values.size(); ++i )
	{
		int count = 0;
		if( values[i]["count"].empty() == false )
			count = ceng::CastFromString< int >(values[i]["count"]);
		std::string filename = values[i]["filename"];

		if( filename.empty() == false && count > 0 )
			result.push_back( std::make_pair( filename, count ) ) ;
	}
}

//-----------------------------------------------------------------------------

void CardCreatorApp::Init()
{
	DefaultApplication::Init();
	Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 0.15f, 0.15f, 0.15f, 1.f ) );

	/*ParseCards( "data/king/hexes.csv", "output/king_hex_", types::ivector2( 376, 326 ), types::ivector2( 6, 10 ), 0  );
	Poro()->Exit();
	return;*/

	// ParseCards( "zombie_game/combat_deck.txt", "zombie_game/output/combat_" );
	/*ParseCards( "data/rebellion.txt", "output/king_", types::ivector2( 712, 1010 ), types::ivector2( 3, 3 ), 3  );

	Poro()->Exit();
	return;*/
	// ParseCards( "space_cards.txt", "output/space_cards_", types::ivector2( 550, 550 ), types::ivector2( 4, 6 ) );
	// test
	// LoadCSVFile( "data/nomoremeat.csv" );

	// --- components ----
	GComponents::Init();
	SGF::EventManager* mEventManager = GComponents::eventManager;
	SGF::EntityManager* mEntityManager = GComponents::entityManager;

	// -- debug stuff ---

	mDebugLayer.reset( new DebugLayer );
	mDebugLayer->SetManagers( mEventManager, mEntityManager );

	// ----- sprite containers ----

	mSpriteContainer = new as::Sprite;

	mCardContainer = new as::Sprite;
	mOverlay = new as::Sprite;

	// -- create card crafting ---
	mSpriteContainer->addChild( mCardContainer );
	mSpriteContainer->addChild( mOverlay );

	mSpriteContainer->SetScale( 1.0f, 1.0f );

	// -- overlay sprite
	as::Sprite* overlay = as::LoadSprite( "data/templates/poker_overlay.png" );
	mOverlay->addChild( overlay );

	as::Sprite* new_card = new as::Sprite;
	mCardContainer->addChild( new_card );
	GD.mSprite = new_card;

	MoveWindowTo( 0, 0 );

	LoadEntity( GD.GetConfig().entity_xml_file, mEntityManager );

	if( GD.GetConfig().parse_automatically )
	{
		std::vector< std::pair< std::string, int > > filenames = DoAllTheCards();

		// write the filenames and card counts out
		if( GD.GetConfig().deck_output.empty() == false )
		{
			// count,filename
			std::fstream fout( GD.GetConfig().deck_output.c_str(), std::ios::out );
			fout << "count,filename" << std::endl;
			for( int i = 0; i < filenames.size(); ++i )
			{
				fout << filenames[i].second << "," << filenames[i].first << std::endl;
			}
		}

		// 1095, 958 );
		if( GD.GetConfig().create_grid )
		{
			ParseCards( filenames,
				GD.GetConfig().grid_output_prefix,
				GD.GetConfig().grid_single_image_size,
				GD.GetConfig().grid_number_on_page,
				GD.GetConfig().grid_single_image_resize,
				GD.GetConfig().grid_border_size,
				GD.GetConfig().grid_rotate_90 );
		}
	}

	if( GD.GetConfig().create_grid_from_file.empty() == false )
	{
		std::vector< std::pair< std::string, int > > filenames;
		LoadDeckFile( GD.GetConfig().create_grid_from_file, filenames );

		ParseCards( filenames,
				GD.GetConfig().grid_output_prefix,
				GD.GetConfig().grid_single_image_size,
				GD.GetConfig().grid_number_on_page,
				GD.GetConfig().grid_single_image_resize,
				GD.GetConfig().grid_border_size,
				GD.GetConfig().grid_rotate_90 );
	}
}

// ----------------------------------------------------------------------------

void CardCreatorApp::Update( float dt )
{
	UpdateGTweens( dt );

	if( mDebugLayer.get() )
		mDebugLayer->Update( dt );

	if( Poro()->GetKeyboard()->IsKeyDown( SDLK_LEFT ) )	camera_offset.x++;
	if( Poro()->GetKeyboard()->IsKeyDown( SDLK_RIGHT ) ) camera_offset.x--;
	if( Poro()->GetKeyboard()->IsKeyDown( SDLK_UP ) )	camera_offset.y++;
	if( Poro()->GetKeyboard()->IsKeyDown( SDLK_DOWN ) )	camera_offset.y--;

	if( mSpriteContainer )
		mSpriteContainer->Update( dt );

	SGF::SystemManager::GetSingletonPtr()->Process( dt );
}

// ----------------------------------------------------------------------------

void CardCreatorApp::Draw( poro::IGraphics* graphics )
{
	if( mDebugLayer.get() )
		mDebugLayer->Draw( graphics );

	if( mSpriteContainer )
		as::DrawSprite( mSpriteContainer, graphics );

}

// ----------------------------------------------------------------------------

types::vector2 TransformMouseForSprite( as::Sprite* sprite, const types::vector2& mouse_pos )
{
	using namespace as;
	std::vector< const DisplayObjectContainer* > parents;
	sprite->getParentTree( parents );

	as::types::xform xform;
	for( int i = (int)parents.size() - 1; i > 0; --i )
	{
		cassert( parents[ i ] );
		const Sprite* parent = dynamic_cast< const Sprite* >( parents[ i ] );
		if( parent )
			xform = ceng::math::Mul( xform, parent->GetXForm() );
	}

	// xform = ceng::math::Mul( xform, this->GetXForm() );

	return ceng::math::MulT( xform, mouse_pos );
}

void CardCreatorApp::MouseMove(const poro::types::vec2& p)
{
}

void CardCreatorApp::MouseButtonDown(const poro::types::vec2& p, int button)
{
	if( button == poro::Mouse::MOUSE_BUTTON_LEFT )
	{
		types::vector2 mouse_pos = TransformMouseForSprite( mCardContainer, types::vector2( p ) );
		std::vector< as::Sprite* > sprites = mCardContainer->FindSpritesAtPoint( mouse_pos );
		std::cout << "sprites.size()" << sprites.size() << std::endl;

		/*SGF::Entity* e = mEntityManager->GetClosestEntity(types::vector2( p ));

		if ( e != NULL )
			mDebugLayer->SetEntity(e);
			*/
	}
}

void CardCreatorApp::MouseButtonUp(const poro::types::vec2& pos, int button)
{
}

//=============================================================================

void CardCreatorApp::OnKeyDown( int key, poro::types::charset unicode )
{
	if( key == SDLK_0 )
		mOverlay->SetAlpha( 0.f );
	else if( key >= SDLK_1 && key <= SDLK_9 )
	{
		float value = ( ( key - SDLK_1 ) + 1 ) / 10.f;
		mOverlay->SetAlpha( value );
	}

	if( key == SDLK_SPACE )
		DoAllTheCards();
		// SaveTheCard( "output/test_card.png" );
}

void CardCreatorApp::OnKeyUp( int key, poro::types::charset unicode )
{
}

//=============================================================================

// returns a list of filenames
std::vector< std::pair< std::string, int > > CardCreatorApp::DoAllTheCards()
{
	std::vector< std::pair< std::string, int > > result;
	std::vector< std::map< std::string, std::string > > data_set;
	LoadCSVFile( GD.GetConfig().csv_file, data_set );

	GD.isCrafting = false;

	for( std::size_t i = 0; i < data_set.size(); ++i )
	{
		std::map< std::string, std::string >::iterator j;
		int number_of_cards = 1;
		for( j = data_set[i].begin(); j != data_set[i].end(); ++j )
		{
			GD.SetData( j->first, j->second );
			if( j->first == "number_of_cards" ) number_of_cards = ceng::CastFromString< int >( j->second );
		}

		// --- card data has been set
		// disable overlay, set color to white
		mOverlay->SetVisibility( 0 );
		mOverlay->SetAlpha( 0 );
		Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 1, 1, 1, 1 ) );

		UpdateStep();

		// --- save the card

		std::string name = data_set[i]["name"];
		if( name.empty() )
			name = ceng::CastToString( i );

		SaveTheCard( GD.GetConfig().output_folder + name + ".png" );

		result.push_back( std::make_pair( GD.GetConfig().output_folder + name + ".png", number_of_cards ) );

		// put the count and the name into something

		// ---
	}

	GD.isCrafting = true;
	Poro()->GetGraphics()->SetFillColor( poro::GetFColor( 0.15f, 0.15f, 0.15f, 1.f ) );
	return result;
}

void CardCreatorApp::SaveTheCard( const std::string& filename )
{
	// this needs to be somewhere else...
	// Poro()->GetGraphics()->SaveScreenshot( filename, 0, 0, 825, 1125 );
	// hexes
	// Poro()->GetGraphics()->SaveScreenshot( filename, 0, 0, 1200, 1050 );
	Poro()->GetGraphics()->SaveScreenshot( filename, 0, 0, GD.GetConfig().screenshot_size.x, GD.GetConfig().screenshot_size.y );

}

//=============================================================================

void CardCreatorApp::UpdateStep()
{
	for( int i = 0; i < 2; ++i )
	{
		float dt = 1.f / 60.f;

		SetComponentRefresh( true );
		SGF::SystemManager::GetSingletonPtr()->Process( dt );

		Poro()->GetApplication()->Update( dt );

		Poro()->GetGraphics()->BeginRendering();
		Poro()->GetApplication()->Draw(Poro()->GetGraphics());
		Poro()->GetGraphics()->EndRendering();
	}
}

//=============================================================================

redpajama_set_name: RedPajamaGithub


text:
layout: log
title: 19 AUG 2019
date: 2019-08-19
---

### work

- i implemented a few small fixes on the product i work on that were a consequence of fast implementation and even faster QA. unfortunately, one of my fixes unveiled a much larger, systemic issue with a feature my team built a just over a year ago. i swore it worked when it was implemented. 👀👀👀

### non-work

- i read a bit of _Feeling Good_ by David D. Burns over lunch. i'm currently in the middle of learning about different cognition patterns that lead to and contribute to a depressed mood.
- elias and i ad libbed a stir fry for dinner. the vegetables ended up getting pretty soggy this attempt, but it was otherwise pretty good.

### exercise

- i had a really great bike ride to work. the weather was beautiful. however, i opted to have elias pick me up in the afternoon due to an oppressive heat index and an all-uphill ride back to my place.
- i'll probably end up doing a quick run when the sun goes down.

### errata

- my rabbit, smalls, celebrated his 9th birthday last week!
- i'm currently hunting for new leggings to replace a few pairs that have pilled and have never really liked. additionally, i'm looking for a pair of joggers for fall.


text:
{{ '<' . '?xml version="1.0" encoding="utf-8"?>' }}

<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
    <channel>
        <title>{{ trans('feeds.title') }}</title>
        <link>{{ trans('feeds.link') }}</link>
        <atom:link href="{{ Request::url() }}" rel="self"></atom:link>
        <description>{{ trans('feeds.sub_title') }}</description>
        <language>{{ trans('feeds.language') }}</language>
        <lastBuildDate>{{ Carbon\Carbon::now()->toRSSString() }}</lastBuildDate>

@foreach($tricks as $trick)
        <item>
            <title>{{ $trick->title }}</title>
            <link>{{ route('tricks.show', [$trick->id, $trick->slug]) }}</link>
            <guid>{{ route('tricks.show', [$trick->id, $trick->slug]) }}</guid>
            <description><![CDATA[{{{ $trick->prettyDescription }}}]]></description>
            <pubDate>{{ $trick->created_at->toRSSString() }}</pubDate>
        </item>
@endforeach
    </channel>
</rss>


text:
require_relative "file_reference"
require_relative "locale"

class ABBYY::Cloud
  module Models
    class FileLink < FileReference
      attribute :name,        type: Types::Strict::String
      attribute :language,    type: Types::Locale
      attribute :is_deleted,  type: Types::Form::Bool
      attribute :chars_count, type: Types::Coercible::Int, optional: true
      attribute :words_count, type: Types::Coercible::Int, optional: true
      attribute :pages_count, type: Types::Coercible::Int, optional: true
    end

    # Registers type Types::FileLink
    Types.register_type FileLink
  end
end


text:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var passportLocal = require('passport-local');
var passportHttp = require('passport-http');
var models = require('../data-access-layer/models');
var encryptor = require('../lib/helpers/encryptor');

function loggedIn(req, res, next) {
    if (req.user) {
        next();
    } else {
        res.redirect('/login');
    }
}

/* GET home page. */
passport.use(new passportLocal.Strategy({
    usernameField: 'email',
    passwordField: 'password',
    session: false
}, function (email, password, done) {
    models.User.findOne({ where: { email: email } }).then(function (user) {
        if (!user) {
            done(null, false);
        }
        if (encryptor(password) === user.password) {
            done(null, user);
        }
        done(null, false);
    });
}));
passport.use(new passportHttp.BasicStrategy(function (username, password, done) {
    if (username === 'admin' && password === 'admin') {
        done(null, { id: username, name: username });
    } else {
        done(null, null);
    }
}));
passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});
router.get('/', function(req, res, next) {
    res.render('index', {
        isAuthenticated: req.isAuthenticated(),
        user: req.user,
        title: 'Inspired Actions'
    });
});
router.get('/login', function (req, res, next) {
    if (req.isAuthenticated()) {
        return res.redirect('/');
    }
    res.render('login', {
        title: 'Log In'
    });
});
router.post('/login', passport.authenticate('local', { failureRedirect: '/login' }), function (req, res, next) {
    res.redirect('/');
});
router.get('/logout', function (req, res, next) {
    req.session.destroy();
    res.redirect('/');
});
router.get('/sign-up', function (req, res, next) {
    if (req.isAuthenticated()) {
        return res.redirect('/');
    }
    res.render('sign-up', {
        title: 'Sign Up'
    });
});
router.post('/sign-up', function (req, res, next) {

    models.User.findOne({ where: { email: req.body.email } }).then(function (user) {
        if (user !== null) {
            return res.render('sign-up', {
                error: "User exists"
            });
        } else {
            return models.User.create({ email: req.body.email, name: req.body.name, surname: req.body.surname, password: encryptor(req.body.password) }).then(function () {
                res.redirect('/');
            });
        }
    });
});
router.get('/admin', passport.authenticate('basic', { session: false }), function (req, res, next) {
    res.render('admin-page');
});
router.post('/query', function (req, res, next) {
    var query = req.body.query;

    models.sequelize.query(query).then(function (data) {
        res.json(data);
    });
});
router.get('/my-page', loggedIn, function (req, res, next) {
    return models.Category.findAll().then(function (categories) {
        return models.Level.findAll().then(function (levels) {
            return models.UsersSkill.findAll({
                include: [
                    { model: models.User, where: { id: req.user.id } },
                    { model: models.SkillsLevel, include: [
                        { model: models.Skill },
                        { model: models.SkillLevel }
                    ] }
                ]}).then(function (results) {
                    var skills = [];
                    for (var i in results) {
                        var skill = {};
                        skill['name'] = results[i]['SkillsLevel']['Skill']['name'];
                        skill['level'] = results[i]['SkillsLevel']['SkillLevel']['name'];
                        skill['levelID'] = results[i]['SkillsLevel']['SkillLevel']['id'];
                        skills.push(skill);
                    }
                    return res.render('my-page', {
                        title: 'My Profile',
                        isAuthenticated: req.isAuthenticated(),
                        user: req.user,
                        categories: categories,
                        levels: levels,
                        skills: skills
                    });
            });
        });
    });
});
router.post('/update-profile-settings', function (req, res, next) {
    var id = req.body.id
        , name = req.body.name
        , surname = req.body.surname
        , email = req.body.email;
    models.User.update({
        name: name,
        surname: surname,
        email: email
    }, {
        where: { id: id }
    }).then(function () {
        return res.json({ result: "Account settings updated" });
    }).catch(function (err) {
        return res.send(err.message);
    });
});
router.post('/update-profile-target-position', function (req, res, next) {
    return models.PositionsLevel
        .findOrCreate({ where: { LevelId: req.body.level, PositionId: req.body.position } })
        .then(function (value) {
            return models.User.update({
                PositionsLevelId: value[0].id
            }, {
                where: { id: req.user.id }
            })
                .then(function () {
                    return res.json({ result: "Target Updated" });
                });
        });
});
router.get('/get-positions/:categoryId', function (req, res, next) {
    var categoryId = req.params.categoryId;

    return models.Position.findAll({ where: { categoryId: categoryId } }).then(function (values) {
        return res.json(values);
    });
});
router.post('/add-new-skill', function (req, res, next) {
    var newSkill = req.body.skill;

    return models.Skill.create({ name: newSkill, GroupId: 1 }).then(function (skill) {
        return models.SkillsLevel.create({ SkillId: skill.id, SkillLevelId: 1 }).then(function (skillLevel) {
            return models.UsersSkill.create({ UserId: req.user.id, SkillsLevelId: skillLevel.id }).then(function () {
                return res.json({
                    name: skill.name,
                    level: 'Novice'
                });
            })
        });
    });
});
router.post('/remove-skill', function (req, res, next) {
    var skill = req.body.skill
        , skillLevel = req.body.skillLevel;

    return models.Skill.findOne({ where: { name: skill } }).then(function (skill) {
        return models.SkillsLevel.findOne({ SkillId: skill.id, SkillLevelId: skillLevel }).then(function (skillsLevel) {
            return models.UsersSkill.findOne({ UserId: req.user.id, SkillsLevelId: skillsLevel.id }).then(function (value) {
                value.destroy();
                return res.json({Success: true});
            });
        });
    });
});
router.get('/all-courses', function (req, res, next) {
    return models.Course.findAll().then(function (courses) {
        return res.render('all-courses', {
            isAuthenticated: req.isAuthenticated(),
            user: req.user,
            courses: courses
        });
    });
});

module.exports = router;


text:
// -*- c++ -*-

// +--------------------------------------------------------------------+
// | This file is part of WaveletTL - the Wavelet Template Library      |
// |                                                                    |
// | Copyright (c) 2002-2009                                            |
// | Thorsten Raasch, Manuel Werner, Ulrich Friedrich                   |
// +--------------------------------------------------------------------+
#ifndef _WAVELETTL_TFRAME_SUPPORT_H
#define	_WAVELETTL_TFRAME_SUPPORT_H

#include <list>
#include <set>
#include <algebra/infinite_vector.h>
#include <cube/tframe_index.h>

namespace WaveletTL
{

    template <class IFRAME, unsigned int DIM> class TensorFrame;

    /*
     * For a given interval frame IFRAME, compute a cube
     * 2^{-j_}<a_,b_> = 2^{-j_1}[a_1,b_1]x...x2^{-j_n}[a_n,b_n]
     * which contains the support of a single primal cube quark
     * or quarklet psi_lambda.
     */

    template <class IFRAME, unsigned int DIM>
    void support(const TensorFrame<IFRAME,DIM>& frame,
                 const typename TensorFrame<IFRAME,DIM>::Index& lambda,
                 typename TensorFrame<IFRAME,DIM>::Support& supp);

    template <class IFRAME, unsigned int DIM>
    void support(const TensorFrame<IFRAME,DIM>& frame,
                 const int& lambda_num,
                 typename TensorFrame<IFRAME,DIM>::Support& supp);

    template <class IFRAME, unsigned int DIM>
    bool intersect_supports(const TensorFrame<IFRAME,DIM>& frame,
  			  const typename TensorFrame<IFRAME,DIM>::Index& lambda,
			  const typename TensorFrame<IFRAME,DIM>::Index& mu);

    /*
     * For a given interval frame, compute a cube
     * 2^{-j_}<a_,b_> = 2^{-j_1}[a_1,b_1]x...x2^{-j_n}[a_n,b_n]
     * representing the intersection of the support cubes
     * corresponding to the indices lambda and mu.
     * Function returns true if a nontrivial intersection
     * exists, false otherwise. In the latter case 'supp'
     * has no meaningful value.
     */

    template <class IFRAME, unsigned int DIM>
    bool intersect_supports(const TensorFrame<IFRAME,DIM>& frame,
  			  const typename TensorFrame<IFRAME,DIM>::Index& lambda,
			  const typename TensorFrame<IFRAME,DIM>::Support& supp_mu,
			  typename TensorFrame<IFRAME,DIM>::Support& supp);

    template <class IFRAME, unsigned int DIM>
    bool intersect_supports(const TensorFrame<IFRAME,DIM>& frame,
			  const int& lambda_num,
			  const typename TensorFrame<IFRAME,DIM>::Support& supp_mu,
			  typename TensorFrame<IFRAME,DIM>::Support& supp);

    template <class IFRAME, unsigned int DIM>
    bool intersect_supports(const TensorFrame<IFRAME,DIM>& frame,
			  const typename TensorFrame<IFRAME,DIM>::Index& lambda,
			  const typename TensorFrame<IFRAME,DIM>::Index& mu,
			  typename TensorFrame<IFRAME,DIM>::Support& supp);

    template <class IFRAME, unsigned int DIM>
    bool intersect_supports(const TensorFrame<IFRAME,DIM>& frame,
			  const int& lambda_num,
			  const int& mu_num,
			  typename TensorFrame<IFRAME,DIM>::Support& supp);

    /*
     * For a given quarklet \psi_\lambda, compute all quarks OR quarklets
     * \psi_\nu with level |\nu|=j (multiindex), such that the respective supports
     * have a nontrivial intersection.
     */

    template <class IFRAME, unsigned int DIM>
    void intersecting_quarklets(const TensorFrame<IFRAME,DIM>& frame,
			     const typename TensorFrame<IFRAME,DIM>::Index& lambda,
			     const typename TensorFrameIndex<IFRAME,DIM>::level_type& j,
                             std::list<int>& intersecting,
                             const typename TensorFrameIndex<IFRAME,DIM>::polynomial_type& p);

    template <class IFRAME, unsigned int DIM>
    void intersecting_quarklets(const TensorFrame<IFRAME,DIM>& frame,
			     const int& lambda_num,
			     const typename TensorFrameIndex<IFRAME,DIM>::level_type& j,
			     std::list<int>& intersecting,
                             const typename TensorFrameIndex<IFRAME,DIM>::polynomial_type& p);

/*!
    Decide whether the support of a given (primal) generator/quarklet \psi_\lambda
    intersects the singular support of another (primal) generator/quarklet \psi_\nu.
  */
  template <class IFRAME, unsigned int DIM>
  bool intersect_singular_support(const TensorFrame<IFRAME,DIM>& frame,
				  const typename TensorFrame<IFRAME,DIM>::Index& lambda,
				  const typename TensorFrame<IFRAME,DIM>::Index& nu);
}

#include <cube/tframe_support.cpp>

#endif	/* _WAVELETTL_TFRAME_SUPPORT_H */


text:
package android.media;

/**
 * An AudioMixPortConfig describes a possible configuration of an output or input mixer.
 * It is used to specify a sink or source when creating a connection with
 * AudioManager.connectAudioPatch().
 * An AudioMixPortConfig is obtained from AudioMixPort.buildConfig().
 * @hide
 */

public class AudioMixPortConfig extends AudioPortConfig {

    AudioMixPortConfig(AudioMixPort mixPort, int samplingRate, int channelMask, int format,
                AudioGainConfig gain) {
        super((AudioPort)mixPort, samplingRate, channelMask, format, gain);
    }

    /**
     * Returns the audio mix port this AudioMixPortConfig is issued from.
     */
    public AudioMixPort port() {
        return (AudioMixPort)mPort;
    }
}


text:
class Browser;

class BookmarkSubMenuModel : public ui::SimpleMenuModel {
 public:
  BookmarkSubMenuModel(ui::SimpleMenuModel::Delegate* delegate,
                       Browser* browser);
  virtual ~BookmarkSubMenuModel();

 private:
  void Build(Browser* browser);

  DISALLOW_COPY_AND_ASSIGN(BookmarkSubMenuModel);
};

#endif  // defined(TOOLKIT_USES_GTK) && !defined(TOOLKIT_VIEWS)

#endif  // CHROME_BROWSER_UI_TOOLBAR_BOOKMARK_SUB_MENU_MODEL_H_


text:
//Problem 2. Concatenate text files

//Write a program that concatenates two text files into another text file.

using System;
using System.IO;
using System.Text;

class ConcatenateTxtFiles
{
    static void Main()
    {
        Encoding encodingCyr = Encoding.GetEncoding(1251);
        try
        {
            var fileOne = new StreamReader(@"..\..\fileOne.txt", encodingCyr);
            var fileTwo = new StreamReader(@"..\..\fileTwo.txt", encodingCyr);
            var result = new StreamWriter(@"..\..\resultFile.txt", false, encodingCyr);

            string fileOneRead = string.Empty;
            string fileTwoRead = string.Empty;
            string resultWrite = string.Empty;

            using (fileOne)
            {
               fileOneRead = fileOne.ReadToEnd();
            }
            using (fileTwo)
            {
                fileTwoRead = fileTwo.ReadToEnd();
            }
            using (result)
            {
                result.WriteLine(fileOneRead);
                result.WriteLine(fileTwoRead);
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}


text:
<?php

namespace spec\Booster\Storage;

use League\Flysystem\Filesystem as FlySystem;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class FlyDataStoreSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Booster\Storage\FlyDataStore');
    }

    function it_should_request_data_from_filesystem(FlySystem $filesystem)
    {
        $filesystem->read('booster.json')->shouldBeCalled();

        $this->getByName('booster');
    }

    function let(FlySystem $filesystem)
    {
        $this->beConstructedWith($filesystem);
    }
}


text:
package com.amazonaws.services.directconnect.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * Container for the parameters to the DescribeLags operation.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeLagsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The ID of the LAG.
     *

     *

     * Example: dxlag-abc123
     *

     *

     * Default: None
     *

     */
    private String lagId;

    /**
     *

     * The ID of the LAG.
     *

     *

     * Example: dxlag-abc123
     *

     *

     * Default: None
     *

     *
     * @param lagId
     *        The ID of the LAG.

     *

     *        Example: dxlag-abc123
     *

     *

     *        Default: None
     */

    public void setLagId(String lagId) {
        this.lagId = lagId;
    }

    /**
     *

     * The ID of the LAG.
     *

     *

     * Example: dxlag-abc123
     *

     *

     * Default: None
     *

     *
     * @return The ID of the LAG.

     *

     *         Example: dxlag-abc123
     *

     *

     *         Default: None
     */

    public String getLagId() {
        return this.lagId;
    }

    /**
     *

     * The ID of the LAG.
     *

     *

     * Example: dxlag-abc123
     *

     *

     * Default: None
     *

     *
     * @param lagId
     *        The ID of the LAG.

     *

     *        Example: dxlag-abc123
     *

     *

     *        Default: None
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeLagsRequest withLagId(String lagId) {
        setLagId(lagId);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getLagId() != null)
            sb.append("LagId: ").append(getLagId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeLagsRequest == false)
            return false;
        DescribeLagsRequest other = (DescribeLagsRequest) obj;
        if (other.getLagId() == null ^ this.getLagId() == null)
            return false;
        if (other.getLagId() != null && other.getLagId().equals(this.getLagId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getLagId() == null) ? 0 : getLagId().hashCode());
        return hashCode;
    }

    @Override
    public DescribeLagsRequest clone() {
        return (DescribeLagsRequest) super.clone();
    }

}


text:
import unittest
import seed_database

class parseIntoProbabilityHashTests(unittest.TestCase):

  def testKeySetting(self):
    string2 = "This apple is red."
    one = "this apple"
    two = "apple is"
    three = "is red"
    outcome = {one: 1, two: 1, three: 1}
    probabilityHash2 = seed_database.parseIntoProbabilityHash(string2)
    self.assertEqual(probabilityHash2, outcome)

  def testIncrementingValue(self):
    string = "How are you doing today, my friend? Are you happy or are you sad? How are your kids doing today?"
    probabilityHash = seed_database.parseIntoProbabilityHash(string)
    self.assertEqual(probabilityHash["are you"], 3)

  def test_formatting_hash_method(self):
    string1 = "hello there"
    string2 = "goodbye there"
    hash = {"hello there": 1}
    result1 = seed_databse.format_hash(hash, string1)
    self.assertEqual(result1, {"hello there": 2})
    result2 = seed_databse.format_hash(hash, string2)
    self.assertEqual(result2, {"hello there": 1, "goodbye there": 1})

def main():
    unittest.main()

if __name__ == '__main__':
  main()


text:
<!doctype html>

  <meta charset="utf-8">

  <link rel=stylesheet href="node_modules/codemirror/lib/codemirror.css">

  <link rel="stylesheet" href="node_modules/codemirror/addon/hint/show-hint.css">

  <link rel="stylesheet" href="node_modules/codemirror/addon/dialog/dialog.css">

  <link rel=stylesheet href="doc/docs.css">
  <title>Tern</title>

  The crowd-funding campaign has reached its goal! Let's get the stretch goals as well.

Tern. Intelligent JavaScript editing

A tern is a small sea bird. It darts over the waves, looking for
fish below the surface. When it spots one, it dives into the water,
vanishes for an instant, and bursts out again with its prey in its
beak.

Tern is a piece of software. It dives into the muddy depths of a
JavaScript system to locate the information that it was asked for.
Combined with an editor plug-in, it can make the life of a JavaScript
programmer a lot more pleasant.

Demo

This editor is hooked up to Tern. The drop-down in the top right
corner lists the commands and keyboard shortcuts available. Output and
function argument hints will appear in the bar below the editor.

  <select id="commands">
    <option>commands...</option>
    <option value=complete>Autocomplete (ctrl-space)</option>
    <option value=jumptodef>Jump to definition (alt-.)</option>
    <option value=findtype>Find type of (ctrl-i)</option>
    <option value=rename>Rename variable (ctrl-q)</option>
    <option value=addfile>Add a new file</option>
    <option value=delfile>Remove this file</option>
  </select>
  <form>

    <textarea id=code name=code>
// Use ctrl-space to complete something
co
document.body.a

// Put the cursor in or after an expression, press ctrl-i to
// find its type

var foo = ["array", "of", "strings"];
var bar = foo.slice(0, 2).join("").split("a")[0];

// Works for locally defined types too.

function CTor() { this.size = 10; }
CTor.prototype.hallo = "hallo";

var baz = new CTor;
baz.

// You can press ctrl-q when the cursor is on a variable name to
// rename it. Try it with CTor...

// When the cursor is in an argument list, the arguments are
// shown below the editor.

[1].reduce(  );

// And a little more advanced code...

(function(exports) {
  exports.randomElt = function(arr) {
    return arr[Math.floor(arr.length * Math.random())];
  };
  exports.strList = "foo".split("");
  exports.intList = exports.strList.map(function(s) { return s.charCodeAt(0); });
})(window.myMod = {});

var randomStr = myMod.randomElt(myMod.strList);
var randomInt = myMod.randomElt(myMod.intList);

// A test of the requirejs plug-in. Check the 'test_dep.js' tab,
// notice that the test variable.

requirejs(["test_dep.js"], function(test) {
  var word = test.capitalize(test.garble("coconut"));
  console.log(word);
});
</textarea></form>

define(function() {
  return {
    capitalize: function(word) {
      return word.charAt(0).toUpperCase() + word.slice(1);
    },
    garble: function(word) {
      return word.replace(/[auiyoe]/g, function() {
        return "auiyoe".charAt(Math.floor(Math.random() * 6));
      });
    }
  };
});

What is the status of the project?

Tern is not yet finished. The core works well enough to be useful,
but a lot of work is still to be done: testing, documenting, fixing
bugs, and writing editor plug-ins.

Tern is open source software, under an MIT license. You can find
the code on Github.
Documentation does not exist yet, but is being worked on.

How does it work?

Tern parses and analyzes a program on the fly, using a simple form
of type inference along with a lot of heuristics and dirty tricks to
approximate the types of the variables and expressions in the
program.

The type inference algorithm is roughly based on
the algorithm used in
Mozilla's SpiderMonkey engine. It deviates from their approach in
several ways, because, on the one hand, it does not have access to
run-time information, and, on the other hand, it does not have to be
entirely precise, and can use approximations in some cases.

Once you know the type of a thing, it is easy to provide a
meaningful list of property completions, or display a function type as
a set of parameter hints.

Tern can be run in two ways — as a JavaScript library, for
integration in JavaScript-based systems like the demo above, or as an
HTTP server, for use with desktop editor plug-ins.

Is this new?

I am under the impression that the approach I'm taking here has
never before been applied to JavaScript editing assistance.

Microsoft's Visual Studio's JavaScript Intellisense comes the
closest, in terms of power. It uses a completely different approach
(actually running the code, instead of doing type inference), and has
some different strengths and weaknesses.

But that is a proprietary system tied to a single IDE. If the
crowd-funding succeeds, Tern will be an open system that can (and
will) be plugged into a variety of editors and IDEs.

Does it scale?

So is this a clever toy that works in a little text input like the
one above, or something that can be applied when working on real, big,
multi-file, multi-dependency projects?

I've tried to keep big codebases in mind as I built this. These are
the strategies Tern uses to stay responsive in the face of huge bulks
of code:

The parser it uses
  (Acorn) is heavily
  optimized.

The type inference algorithm is designed to be lightweight (its
  other use, in the SpiderMonkey compiler, is similarly
  performance-critical).

Tern runs as a server (or instance) which reuses as much
  information as possible between queries, and tries to time
  recomputation work so that it doesn't hold up the interface.

When editing large files, there is a mechanism for re-evaluating
  only a small slice of the file, using information from a previous
  evaluation run as context.

It is possible to automatically 'condense' a JavaScript library
  to a simple JSON document that holds its type information, and then
  load only that information when analysing code that uses the
  library. (You can hand-edit such documents to fix inference mistakes
  or add information.)

- Marijn Haverbeke


text:
'use strict';

var chai = require('chai');
var sinonChai = require('sinon-chai');
chai.should();
chai.use(sinonChai);

var Promise = require('bluebird');

var templateTools = require('../template-tools');
var mockModel = require('./mock-model');

describe('gulp-angular index js template', function () {
  var model, indexJs, indexEs6, indexCoffee, indexTs;

  before(function() {
    return Promise.all([
      templateTools.load('src/app/_index.module.js'),
      templateTools.load('src/app/_index.module.es6'),
      templateTools.load('src/app/_index.module.coffee'),
      templateTools.load('src/app/_index.module.ts')
    ]).then(function(modules) {
      indexJs = modules[0];
      indexEs6 = modules[1];
      indexCoffee = modules[2];
      indexTs = modules[3];
    });
  });

  beforeEach(function() {
    model = mockModel();
  });

  it('should name the module as the app name and add modules dependencies in the module declaration', function() {
    model.appName = 'testAppName';
    model.modulesDependencies = 'test value';
    var testJs = /angular\n {4}\.module\('testAppName', \[test value\]\)/;
    var testEs6 = /angular\.module\('testAppName', \[test value\]\)/;
    var testTs = /angular\.module\('testAppName', \[test value\]\)/;
    var testCoffee = /angular\.module 'testAppName', \[test value\]/;
    var result = indexJs(model);
    result.should.match(testJs);
    result = indexEs6(model);
    result.should.match(testEs6);
    result = indexCoffee(model);
    result.should.match(testCoffee);
    result = indexTs(model);
    result.should.match(testTs);
  });

  it('should not add the router config for no router', function() {
    model.props.router.key = 'noRouter';
    var result = indexEs6(model);
    result.should.not.match(/\.config\(routerConfig\)/);
    result.should.not.match(/RouterController/);
    result = indexTs(model);
    result.should.not.match(/\.config\(routerConfig\)/);
    result.should.not.match(/RouterController/);
  });

  it('should add the router config when a router is chosen', function() {
    model.props.router.key = 'not-none';
    var result = indexEs6(model);
    result.should.match(/\.config\(routerConfig\)/);
    result.should.not.match(/RouterController/);
    result = indexTs(model);
    result.should.match(/\.config\(routerConfig\)/);
    result.should.not.match(/RouterController/);
  });

  it('should add the router controller for the angular new router', function() {
    model.props.router.key = 'new-router';
    var result = indexEs6(model);
    result.should.match(/\.controller\('RouterController', RouterController\)/);
    result = indexTs(model);
    result.should.match(/\.controller\('RouterController', RouterController\)/);
  });

});


text:
@import url("../../../../../core/components/com_citations/site/assets/css/citations.css");

	#content-header .content-header-left h2 {
		padding: 0;
	}
	.citation-author {
		padding:0 0 15px 0;
	}
	.citation-citation {
		margin: 0 0 30px 0;
	}
	.citation-abstract {
		padding:0 0 20px 0;
	}


text:
/**
 * Created by numminorihsf on 15.02.16.
 */

function mapObjectFromArray(prefix, val, rec){
  if (val === null) return prefix + '
' + syncWrapper.null(val) + '
';
  if (val instanceof Array) return prefix + '
' + syncWrapper.array(val, rec+1) + '
';
  if (val.toString === Object.prototype.toString) return prefix + '
' + syncWrapper.object(val, rec+1) + '
';
  return prefix + '

' + val.toString() + '

';
}

function mapObjectFromObject(prefix, key, val, rec){
  if (val === null) return prefix + '
' + key + ':' + syncWrapper.null(val) + '
';
  if (val instanceof Array) return prefix + '
' + key + ':' + syncWrapper.array(val, rec+1) + '
';
  if (val.toString === Object.prototype.toString) return prefix + '
' + key + ':' + syncWrapper.object(val, rec+1) + '
';
  return prefix + '
' + key + ':
' + val.toString() + '

';
}

var syncWrapper = {
  string: function(data){
    return ''+data+'';
  },
  number: function(data){
    return ''+data.toString()+'';
  },
  boolean: function(data){
    return ''+(data ? 'true' : 'false')+'';
  },
  "function": function(){
    return '';
  },
  "undefined": function(){
    return '';
  },
  "null": function(){
    return 'null';
  },
  "array": function(data, rec){
    rec = rec || 1;
    var prefix = '';
    var lastPre = '';
    var i = rec;
    while (i-- > 0){
      lastPre = prefix;
      prefix += ' ';
    }
    var arrayMap = data.map(function(val){
      var type = typeof val;
      switch (type) {
        case 'string':
          return prefix + '
' + syncWrapper.string(val) + '
';
        case 'number':
          return prefix + '
' + syncWrapper.number(val) + '
';
        case 'boolean':
          return prefix + '
' + syncWrapper.boolean(val) + '
';
        case 'function':
          return prefix + '
' + syncWrapper.function(val) + '
';
        case 'undefined':
          return prefix + '
' + syncWrapper.undefined(val) + '
';
        default:
          return mapObjectFromArray(prefix, val, rec);
      }
    }).join('\n');
    return '
\n' + arrayMap + '\n' + lastPre+ '
';
  },
  "object": function(data, rec){
    rec = rec || 1;
    var prefix = '';
    var lastPre = '';
    var i = rec;
    while (i-- > 0){
      lastPre = prefix;
      prefix += ' ';
    }
    var objectMap = Object.keys(data).map(function(key){
      var val = data[key];
      var type = typeof val;
      switch (type) {
        case 'string':
          return prefix + '
' + key + ':' + syncWrapper.string(val) + '
';
        case 'number':
          return prefix + '
' + key + ':' + syncWrapper.number(val) + '
';
        case 'boolean':
          return prefix + '
' + key + ':' + syncWrapper.boolean(val) + '
';
        case 'function':
          return prefix + '
' + key + ':' + syncWrapper.function(val) + '
';
        case 'undefined':
          return prefix + '
' + key + ':' + syncWrapper.undefined(val) + '
';
        default:
          return mapObjectFromObject(prefix, key, val, rec);
      }
    }).join('\n');
    return '
\n'+objectMap+'\n' + lastPre + '
';
  }
};

var formats = require('../../both-formatter/text/html')(syncWrapper);

module.exports = function(data, cb){
  var type = typeof data;
  formats[type](data, cb);
};


text:
<!DOCTYPE html>

    <title>process.cwd documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../highlight.css" />

            property

                Function

                |

                .process.cwd

                    cwd (
                    ) {

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


text:
/*jslint browser:true, indent:2*/

/*global suite, test, suiteSetup, setup, suiteTeardown, teardown*/ // Mocha
/*global assert, chai*/ // Chai
/*global $*/ // jQuery
/*global angular*/ // Angular

(function () {
  'use strict';

  var app;

  app = angular.module('app', []);

  app.directive('counter', [
    function () {
      return {
        restrict: 'E',
        replace: true,
        template: '<button ng-click="increment()">{{count}}</button>',
        scope: true,
        link: function ($scope) {
          $scope.count = 0;
          $scope.increment = function () {
            $scope.count += 1;
          };
        }
      }
    }
  ]);

  suite('Angular.JS', function () {
    var fixture$;

    suiteSetup(function () {
      $(document.body).append('<counter id="angular-fixture"></counter>');
      angular.bootstrap(document.body, ['app']);
      fixture$ = $('#angular-fixture');
    });

    test('initial directive state is correct', function () {
      assert.isTrue(fixture$.hasClass('ng-scope'));
      assert.equal(fixture$.text(), '0');
    });

    test('directive reacts as expected to events', function () {
      fixture$.trigger('click');
      assert.equal(fixture$.text(), '1');
    });

  });

}());


text:
using System.Data;
using GNF.Domain.Entities;

namespace GNF.DapperUow.Repositories
{
    /// <summary>
    /// Represents that the implemented classes are repositories.
    /// </summary>
    /// <typeparam name="TEntity">The type of the aggregate root on which the repository operations
    /// should be performed.</typeparam>
    public interface IRepositoryWithTransaction<TEntity>:IRepository<TEntity>
        where TEntity : IEntity
    {
        /// <summary>
        /// DB事务对象
        /// </summary>
        IDbTransaction DbTransaction { get; }

        /// <summary>
        /// 设置DB事务对象,设置后ConnectionString会为空
        /// </summary>
        /// <param name="dbTransaction"></param>
        IRepositoryWithTransaction<TEntity> SetDbTransaction(IDbTransaction dbTransaction);
    }
}


text:
using FirstFloor.ModernUI.Presentation;
using FirstFloor.ModernUI.Windows.Controls;
using FirstFloor.ModernUI.Windows.Media;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace FirstFloor.ModernUI.Windows.Navigation
{
    /// <summary>
    /// The default link navigator with support for loading frame content, external link navigation using the default browser and command execution.
    /// </summary>
    public class DefaultLinkNavigator
        : ILinkNavigator
    {
        private CommandDictionary commands = new CommandDictionary();
        private string[] externalSchemes = new string[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps, Uri.UriSchemeMailto };

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultLinkNavigator"/> class.
        /// </summary>
        public DefaultLinkNavigator()
        {
            // register all ApperanceManager commands
            this.Commands.Add(new Uri("cmd://accentcolor"), AppearanceManager.Current.AccentColorCommand);
            this.Commands.Add(new Uri("cmd://darktheme"), AppearanceManager.Current.DarkThemeCommand);
            this.Commands.Add(new Uri("cmd://largefontsize"), AppearanceManager.Current.LargeFontSizeCommand);
            this.Commands.Add(new Uri("cmd://lighttheme"), AppearanceManager.Current.LightThemeCommand);
            this.Commands.Add(new Uri("cmd://settheme"), AppearanceManager.Current.SetThemeCommand);
            this.Commands.Add(new Uri("cmd://smallfontsize"), AppearanceManager.Current.SmallFontSizeCommand);

            // register navigation commands
            this.commands.Add(new Uri("cmd://browseback"), NavigationCommands.BrowseBack);
            this.commands.Add(new Uri("cmd://refresh"), NavigationCommands.Refresh);

            // register application commands
            this.commands.Add(new Uri("cmd://copy"), ApplicationCommands.Copy);
        }

        /// <summary>
        /// Gets or sets the schemes for external link navigation.
        /// </summary>
        /// <remarks>
        /// Default schemes are http, https and mailto.
        /// </remarks>
        public string[] ExternalSchemes
        {
            get { return this.externalSchemes; }
            set { this.externalSchemes = value; }
        }

        /// <summary>
        /// Gets or sets the navigable commands.
        /// </summary>
        public CommandDictionary Commands
        {
            get { return this.commands; }
            set { this.commands = value; }
        }

        /// <summary>
        /// Performs navigation to specified link.
        /// </summary>
        /// <param name="uri">The uri to navigate to.</param>
        /// <param name="source">The source element that triggers the navigation. Required for frame navigation.</param>
        /// <param name="parameter">An optional command parameter or navigation target.</param>
        public virtual void Navigate(Uri uri, FrameworkElement source = null, string parameter = null)
        {
            if (uri == null) {
                throw new ArgumentNullException("uri");
            }

            // first check if uri refers to a command
            ICommand command;
            if (this.commands != null && this.commands.TryGetValue(uri, out command)) {
                // note: not executed within BBCodeBlock context, Hyperlink instance has Command and CommandParameter set
                if (command.CanExecute(parameter)) {
                    command.Execute(parameter);
                }
                else {
                    // do nothing
                }
            }
            else if (uri.IsAbsoluteUri && this.externalSchemes != null && this.externalSchemes.Any(s => uri.Scheme.Equals(s, StringComparison.OrdinalIgnoreCase))) {
                // uri is external, load in default browser
                Process.Start(uri.AbsoluteUri);
                return;
            }
            else {
                // perform frame navigation
                if (source == null) {   // source required
                    throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, ModernUI.Resources.NavigationFailedSourceNotSpecified, uri));
                }

                // use optional parameter as navigation target to identify target frame (_self, _parent, _top or named target frame)
                var frame = NavigationHelper.FindFrame(parameter, source);
                if (frame == null) {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, ModernUI.Resources.NavigationFailedFrameNotFound, uri, parameter));
                }

                // delegate navigation to the frame
                frame.Source = uri;
            }
        }
    }
}


text:
package io.druid.server.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import io.druid.java.util.common.ISE;
import io.druid.java.util.emitter.EmittingLogger;
import io.druid.query.QueryInterruptedException;
import io.druid.server.DruidNode;
import org.eclipse.jetty.server.Response;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;

/**
 * Filter that verifies that authorization checks were applied to an HTTP request, before sending a response.
 * <p>
 * This filter is intended to help catch missing authorization checks arising from bugs/design omissions.
 */
public class PreResponseAuthorizationCheckFilter implements Filter
{
  private static final EmittingLogger log = new EmittingLogger(PreResponseAuthorizationCheckFilter.class);

  private final List<Authenticator> authenticators;
  private final ObjectMapper jsonMapper;

  public PreResponseAuthorizationCheckFilter(
      List<Authenticator> authenticators,
      ObjectMapper jsonMapper
  )
  {
    this.authenticators = authenticators;
    this.jsonMapper = jsonMapper;
  }

  @Override
  public void init(FilterConfig filterConfig)
  {

  }

  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain
  ) throws IOException, ServletException
  {
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    final HttpServletRequest request = (HttpServletRequest) servletRequest;

    if (servletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) == null) {
      handleUnauthenticatedRequest(response);
      return;
    }

    filterChain.doFilter(servletRequest, servletResponse);

    Boolean authInfoChecked = (Boolean) servletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED);
    if (authInfoChecked == null && statusIsSuccess(response.getStatus())) {
      // Note: rather than throwing an exception here, it would be nice to blank out the original response
      // since the request didn't have any authorization checks performed. However, this breaks proxying
      // (e.g. OverlordServletProxy), so this is not implemented for now.
      handleAuthorizationCheckError(
          "Request did not have an authorization check performed.",
          request,
          response
      );
    }

    if (authInfoChecked != null && !authInfoChecked && response.getStatus() != Response.SC_FORBIDDEN) {
      handleAuthorizationCheckError(
          "Request's authorization check failed but status code was not 403.",
          request,
          response
      );
    }
  }

  @Override
  public void destroy()
  {

  }

  private void handleUnauthenticatedRequest(
      final HttpServletResponse response
  ) throws IOException
  {
    // Since this is the last filter in the chain, some previous authentication filter
    // should have placed an authentication result in the request.
    // If not, send an authentication challenge.
    Set<String> supportedAuthSchemes = Sets.newHashSet();
    for (Authenticator authenticator : authenticators) {
      String challengeHeader = authenticator.getAuthChallengeHeader();
      if (challengeHeader != null) {
        supportedAuthSchemes.add(challengeHeader);
      }
    }
    for (String authScheme : supportedAuthSchemes) {
      response.addHeader("WWW-Authenticate", authScheme);
    }
    QueryInterruptedException unauthorizedError = new QueryInterruptedException(
        QueryInterruptedException.UNAUTHORIZED,
        null,
        null,
        DruidNode.getDefaultHost()
    );
    unauthorizedError.setStackTrace(new StackTraceElement[0]);
    OutputStream out = response.getOutputStream();
    sendJsonError(response, Response.SC_UNAUTHORIZED, jsonMapper.writeValueAsString(unauthorizedError), out);
    out.close();
    return;
  }

  private void handleAuthorizationCheckError(
      String errorMsg,
      HttpServletRequest servletRequest,
      HttpServletResponse servletResponse
  )
  {
    // Send out an alert so there's a centralized collection point for seeing errors of this nature
    log.makeAlert(errorMsg)
       .addData("uri", servletRequest.getRequestURI())
       .addData("method", servletRequest.getMethod())
       .addData("remoteAddr", servletRequest.getRemoteAddr())
       .addData("remoteHost", servletRequest.getRemoteHost())
       .emit();

    if (servletResponse.isCommitted()) {
      throw new ISE(errorMsg);
    } else {
      try {
        servletResponse.sendError(Response.SC_FORBIDDEN);
      }
      catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }

  private static boolean statusIsSuccess(int status)
  {
    return 200 <= status && status < 300;
  }

  public static void sendJsonError(HttpServletResponse resp, int error, String errorJson, OutputStream outputStream)
  {
    resp.setStatus(error);
    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");
    try {
      outputStream.write(errorJson.getBytes(StandardCharsets.UTF_8));
    }
    catch (IOException ioe) {
      log.error("WTF? Can't get writer from HTTP response.");
    }
  }
}


text:
published: true
title: Harmonic Serie
tags: math
use_math: true
---
> Paradoxaly it goes toward infinity extremely slowly - [secrets of the Sum of Sums ](https://www.youtube.com/watch?v=vQE6-PLcGwU)

$ 1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + ... + \frac{1}{n} \sim \ln(n+1) \rightarrow \infty $

not related:
- [A nice sum from France solved in 3 ways!](https://www.youtube.com/watch?v=Rf_SxVjMEV4)


text:
SYNONYM

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

#### Published in
Persoonia 5(1): 102 (1967)

#### Original name
Sistotrema eluctor Donk, 1967

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:custom="http://schemas.android.com/apk/res/com.powerblock.timesheets"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:id="@+id/job_setup_table_1" >
        <!-- row 1 -->
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/main_fragment_layout_padding" >
		    <com.powerblock.timesheets.CustomSpinner
		        android:id="@+id/job_setup_cost_centre"
		        android:layout_width="@dimen/job_setup_spinner_width"
		        android:layout_height="@dimen/job_setup_spinner_height"
		        custom:entries="job_setup_cost_center"
		        android:textSize="@dimen/main_fragment_button_font"
                android:layout_marginRight="@dimen/main_fragment_layout_padding"/>
		    <com.powerblock.timesheets.CustomSpinner
		        android:id="@+id/job_setup_customer"
		        android:layout_width="@dimen/job_setup_spinner_width"
		        android:layout_height="@dimen/job_setup_spinner_height"
		        custom:entries="job_setup_customers"
		        android:textSize="@dimen/main_fragment_button_font"/>
		</LinearLayout>
		<!-- row 2 -->
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:baselineAligned="false"
            android:layout_marginBottom="@dimen/main_fragment_layout_padding">
			<com.powerblock.timesheets.CustomSpinner
			    android:id="@+id/job_setup_site_address"
		        android:layout_width="@dimen/job_setup_spinner_width"
		        android:layout_height="@dimen/job_setup_spinner_height"
			    custom:entries="job_setup_site_address"
			    android:textSize="@dimen/main_fragment_button_font"
                android:layout_marginRight="@dimen/main_fragment_layout_padding"/>
			<com.powerblock.timesheets.CustomSpinner
			    android:id="@+id/job_setup_job_owner"
		        android:layout_width="@dimen/job_setup_spinner_width"
		        android:layout_height="@dimen/job_setup_spinner_height"
			    custom:entries="job_setup_job_owner"
			    android:textSize="@dimen/main_fragment_button_font"/>

		</LinearLayout>
		<!-- row 3 -->
        <LinearLayout
            android:orientation = "horizontal"
            android:baselineAligned="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/main_fragment_layout_padding" >
			<com.powerblock.timesheets.CustomSpinner
			    android:id="@+id/job_setup_maintenance_work"
			    android:layout_width="@dimen/job_setup_spinner_width"
			    android:layout_height="@dimen/job_setup_spinner_height"
			    custom:entries="job_setup_type_of_maintenance_work"
			    android:textSize="@dimen/main_fragment_button_font"
                android:layout_marginRight="@dimen/main_fragment_layout_padding"/>
			<com.powerblock.timesheets.CustomSpinner
				android:id="@+id/job_setup_contract_work"
			    android:layout_width="@dimen/job_setup_spinner_width"
			    android:layout_height="@dimen/job_setup_spinner_height"
			    custom:entries="job_setup_type_of_contract_work"
			    android:textSize="@dimen/main_fragment_button_font"/>
		</LinearLayout>
    	<!-- row 4 -->
        <LinearLayout
            android:orientation = "horizontal"
            android:baselineAligned="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/main_fragment_layout_padding" >
			<Button
			    android:id="@+id/job_setup_description"
			    android:layout_width="@dimen/job_setup_spinner_width"
			    android:layout_height="@dimen/job_setup_spinner_height"
			    android:textSize="@dimen/main_fragment_button_font"
			    android:text="Description of works"
                android:layout_marginRight="@dimen/main_fragment_layout_padding"
                android:onClick="showDescription"/>
			<com.powerblock.timesheets.CustomSpinner
				android:id="@+id/job_setup_PIC"
			    android:layout_width="@dimen/job_setup_spinner_width"
			    android:layout_height="@dimen/job_setup_spinner_height"
			    custom:entries="job_setup_PIC"
			    android:textSize="@dimen/main_fragment_button_font"/>
		</LinearLayout>
		<!-- row 5 -->
        <LinearLayout
            android:orientation = "horizontal"
            android:baselineAligned="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/main_fragment_layout_padding" >
			<Button
				android:id="@+id/job_setup_quote_no"
			    android:layout_width="@dimen/job_setup_spinner_width"
			    android:layout_height="@dimen/job_setup_spinner_height"
			    android:textSize="@dimen/main_fragment_button_font"
			    android:text="Quote No / Work record number"
                android:layout_marginRight="@dimen/main_fragment_layout_padding"
                android:onClick="showQuoteNo"/>
			<com.powerblock.timesheets.CustomSpinner
				android:id="@+id/job_setup_personnel"
			    android:layout_width="@dimen/job_setup_spinner_width"
			    android:layout_height="@dimen/job_setup_spinner_height"
			    custom:entries="job_setup_additional_personnel"
			    android:textSize="@dimen/main_fragment_button_font"/>
	</LinearLayout>
	</LinearLayout>
</RelativeLayout>


text:
package com.badlogic.gdx.math;

import java.io.Serializable;

/** A point in a 3D grid, with integer x and y coordinates
 *
 * @author badlogic */
public class GridPoint3 implements Serializable {
	private static final long serialVersionUID = 5922187982746752830L;

	public int x;
	public int y;
	public int z;

	/** Constructs a 3D grid point with all coordinates pointing to the origin (0, 0, 0). */
	public GridPoint3 () {
	}

	/** Constructs a 3D grid point.
	 *
	 * @param x X coordinate
	 * @param y Y coordinate
	 * @param z Z coordinate */
	public GridPoint3 (int x, int y, int z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	/** Copy constructor
	 *
	 * @param point The 3D grid point to make a copy of. */
	public GridPoint3 (GridPoint3 point) {
		this.x = point.x;
		this.y = point.y;
		this.z = point.z;
	}

	/** Sets the coordinates of this 3D grid point to that of another.
	 *
	 * @param point The 3D grid point to copy coordinates of.
	 *
	 * @return this GridPoint3 for chaining. */
	public GridPoint3 set (GridPoint3 point) {
		this.x = point.x;
		this.y = point.y;
		this.z = point.z;
		return this;
	}

	/** Sets the coordinates of this GridPoint3D.
	 *
	 * @param x X coordinate
	 * @param y Y coordinate
	 * @param z Z coordinate
	 *
	 * @return this GridPoint3D for chaining. */
	public GridPoint3 set (int x, int y, int z) {
		this.x = x;
		this.y = y;
		this.z = z;
		return this;
	}

	@Override
	public boolean equals (Object o) {
		if (this == o) return true;
		if (o == null || o.getClass() != this.getClass()) return false;
		GridPoint3 g = (GridPoint3)o;
		return this.x == g.x && this.y == g.y && this.z == g.z;
	}

	@Override
	public int hashCode () {
		final int prime = 17;
		int result = 1;
		result = prime * result + this.x;
		result = prime * result + this.y;
		result = prime * result + this.z;
		return result;
	}

	@Override
	public String toString() {
		return "(" + x + ", " + y + ", " + z + ")";
	}
}


text:
package com.example.spawneddeliveryservice.models;

public class NewTransportDataModel {
    public String fromTown;
    public String toTown;
    public int availableSpace;
    public int availableKilograms;
    public String arrival;//2015-03-17 format;
    public String departure;//2015-03-17 format
    public String driverName;
    public String driverPhone;
    public String additionalContact;

    public NewTransportDataModel(String fromTown, String toTown, int availableSpace, int availableKilograms,
                                 String arrival, String departure, String driverName, String driverPhone, String additionalContact) {
        this.fromTown = fromTown;
        this.toTown = toTown;
        this.availableSpace = availableSpace;
        this.availableKilograms = availableKilograms;
        this.arrival = arrival;
        this.departure = departure;
        this.driverName = driverName;
        this.driverPhone = driverPhone;
        this.additionalContact = additionalContact;
    }
}


text:
import {Component} from '@angular/core';

@Component({
    selector: 'dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['dashboard.component.scss']
})
export class DashboardComponent {
}


text:
#pragma once

#include <tuple>

namespace phi {
namespace funcs {
template <int Arity, typename... Args>
struct IsPointerArgs {
  static_assert(Arity == sizeof...(Args), "Arity and Args not match!");
  static const bool value = false;
};

template <typename... Args>
struct IsPointerArgs<1, Args...> {
  static_assert(1 == sizeof...(Args), "Arity and Args not match!");
  static const bool value = std::is_pointer<
      typename std::tuple_element<0, std::tuple<Args...>>::type>::value;
};

// Declare a template class with a single template parameter.
template <typename>
struct FunctionTraits;

// A forwarding trait allowing functors (objects which have an operator())
// to be used with this traits class.
template <typename T>
struct FunctionTraits : public FunctionTraits<decltype(&T::operator())> {};

// A partial specialization of FunctionTraits for pointers to member functions
// and has const/non-const class member functions.
template <typename ClassType, typename ReturnType, typename... Args>
struct FunctionTraits<ReturnType (ClassType::*)(Args...) const>
    : public FunctionTraits<ReturnType(Args...)> {};
template <typename ClassType, typename ReturnType, typename... Args>
struct FunctionTraits<ReturnType (ClassType::*)(Args...)>
    : public FunctionTraits<ReturnType(Args...)> {};

// An implementation for common function.
template <typename ReturnType, typename... Args>
struct FunctionTraits<ReturnType(Args...)> {
  static const size_t arity = sizeof...(Args);
  static const bool has_pointer_args = IsPointerArgs<arity, Args...>::value;
  using ArgsTuple = std::tuple<Args...>;
};

}  // namespace funcs
}  // namespace phi


text:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Acyclicity {
    private static boolean[] visited;  // vertices that have been thoroughly checked
    private static boolean[] isOnStack;  // is vertex on the stack for current recursion call?
    private static boolean hasCycle;  // does at least one cycle exist?

    // explore using DFS
    private static void explore(List<Integer>[] adj, int v) {
        visited[v] = true;
        isOnStack[v] = true;
        for (int p : adj[v]) {
            if (!visited[p]) {
                explore(adj, p);
            } else if (isOnStack[p]) { // this vertex has been accessed once in this path; cycle found
                hasCycle = true;
                break;
            }
        }
        isOnStack[v] = false;  // re-initialize for the next recursion call
    }

    private static int acyclic(List<Integer>[] adj) {
        visited = new boolean[adj.length];
        isOnStack = new boolean[adj.length];
        for (int i = 0; i < adj.length; i++) {
            explore(adj, i);
            if (hasCycle) return 1;  // at least one cycle found
        }
        return 0;
    }

    @SuppressWarnings({"unchecked", "rawtypes"}) // supress warnings generated by generic array
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();  // number of vertices
        int m = scanner.nextInt();  // number of edges
        List<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n];
        for (int i = 0; i < n; i++) {
            adj[i] = new ArrayList<Integer>();
        }
        for (int i = 0; i < m; i++) {
            int x, y;
            x = scanner.nextInt();
            y = scanner.nextInt();
            adj[x - 1].add(y - 1);
        }
        System.out.println(acyclic(adj));
    }
}