text:
#ifndef INC_FUDGEPROTO_AST
#define INC_FUDGEPROTO_AST

#include "constants.hpp"
#include "memoryutil.hpp"
#include <algorithm>
#include <deque>
#include <list>
#include <map>
#include <vector>
#include <stdexcept>
#include <string>

namespace fudgeproto {

class identifier : public refcounted
{
    public:
        identifier ( const std::string & first );
        ~identifier ( );

        identifier * clone ( ) const;

        inline size_t size ( ) const { return m_elements.size ( ); }
        inline const std::string & at ( size_t index ) const { return m_elements [ index ]; }
        inline const std::string & operator[] ( size_t index ) const { return at ( index ); }

        void append ( const std::string & element );
        void extend ( const identifier & source );
        void prepend ( const std::string & element );
        void prepend ( const identifier & source );
        void pop ( );
        void clear ( );

        std::string asString ( const std::string & separator ) const;

        bool equals ( const identifier & id ) const;

        static identifier * createAndConsume ( char * source );
        static identifier * prependAndConsume ( identifier * id, char * source );
        static identifier * createFromString ( const std::string & source,
                                               const std::string & separator,
                                               bool ignoreEmpty = true );

    private:
        identifier ( );

        std::deque<std::string> m_elements;
};

class definition : public refcounted
{
    protected:
        definition ( identifier * id );

    public:
        virtual ~definition ( );

        virtual void addContent ( definition * ) = 0;

        inline bool hasId ( ) const { return m_id; }
        inline const identifier & id ( ) const { return *m_id; }
        inline std::string idString ( ) const { return m_id ? m_id->asString ( "." ) : "NULL"; }

        void setIdentifier ( identifier * id );
        void resetIdentifier ( identifier * id );

        static definition * setIdentifierAndConsume ( definition * target, char * source );
        static definition * setIdentifierAndConsume ( definition * target, identifier * source );

    private:
        definition ( );         // Not implemented

        identifier * m_id;
};

class fieldtype
{
    public:
        fieldtype ( int type );
        fieldtype ( identifier * id );
        fieldtype ( const fieldtype & source );
        fieldtype & operator= ( const fieldtype & source );
        ~fieldtype ( );

        inline fudgeproto_type type ( ) const { return m_type; }
        inline const identifier & name ( ) const { return *m_id; }

        bool isComplex ( ) const;
        bool isInteger ( ) const;
        bool isFloating ( ) const;

        void resetIdentifier ( const identifier * id );

        const definition & def ( ) const;
        void setDefinition ( const definition * def );

    private:
        fudgeproto_type m_type;
        const identifier * m_id;
        const definition * m_definition;
};

class fieldconstraint
{
    public:
        fieldconstraint ( int bound );

        void append ( int bound );

        inline const std::vector<int> & bounds ( ) const { return m_bounds; }

    private:
        std::vector<int> m_bounds;
};

class literalvalue : public refcounted
{
    public:
        literalvalue ( int value );
        literalvalue ( double value );
        literalvalue ( const std::string & value );
        literalvalue ( bool value );
        ~literalvalue ( );

        inline fudgeproto_type type ( ) const { return m_type; }

        bool getBool ( ) const;
        double getDouble ( ) const;
        int getInt ( ) const;
        const std::string & getString ( ) const;

        bool isCompatibleType ( fudgeproto_type type ) const;

        static literalvalue * createAndConsume ( char * value );

    private:
        fudgeproto_type m_type;
        union
        {
            int integer;
            double dprecision;
            bool boolean;
            std::string * string;
        } m_value;
};

template<class T>
class generic_list : public refcounted
{
    public:
        typedef std::list<T *> valuetype;

        ~generic_list ( )
        {
            std::for_each ( m_content.begin ( ), m_content.end ( ), refcounted::dec );
        }

        void prepend ( T * value )
        {
            if ( ! value ) throw std::runtime_error ( "Cannot prepend NULL value to list" );

            refcounted::inc ( value );
            m_content.push_front ( value );
        }

        static generic_list * createAndConsume ( T * value )
        {
            if ( ! value ) throw std::runtime_error ( "Cannot create a list with a NULL value" );

            generic_list<T> * list ( new generic_list<T> );
            list->prepend ( value );
            refcounted::dec ( value );
            return list;
        }

        static generic_list * prependAndConsume ( generic_list * list, T * value )
        {
            if ( ! list ) throw std::runtime_error ( "Cannot prepend to a NULL list" );
            if ( ! value ) throw std::runtime_error ( "Cannot prepend a list with a NULL value" );

            list->prepend ( value );
            refcounted::dec ( value );
            return list;
        }

        inline const valuetype & content ( ) const { return m_content; }
        inline size_t size ( ) const { return m_content.size ( ); }

    private:
        valuetype m_content;
};

typedef generic_list<identifier> identifier_list;

class enumdef : public definition
{
    public:
        enumdef ( );
        enumdef ( identifier * id );

        inline void addContent ( definition * ) { throw std::runtime_error ( "Cannot add content to an enum" ); }

        inline size_t size ( ) const { return m_pairs.size ( ); }
        inline const std::pair<std::string, int32_t> & operator[] ( size_t index ) const { return m_pairs [ index ]; }

        void append ( const std::string & key );
        void append ( const std::string & key, int32_t value );

        static enumdef * appendAndConsume ( enumdef * enumeration, char * key, int32_t value, bool hasValue );

    private:
        typedef std::pair<std::string, int32_t> pair;
        std::vector<pair> m_pairs;
};

class fielddef : public definition
{
    public:
        fielddef ( identifier * id,
                   const fieldtype & type,
                   fudgeproto_modifier modifier,
                   const std::vector<int> & constraints,
                   literalvalue * defvalue );
        ~fielddef ( );

        inline void addContent ( definition * ) { throw std::runtime_error ( "Cannot add content to a field" ); }

        inline fieldtype & type ( ) { return m_type; }
        inline const fieldtype & type ( ) const { return m_type; }
        inline fudgeproto_modifier modifier ( ) const { return m_modifier; }
        inline const std::vector<int> & constraints ( ) const { return m_constraints; }
        inline bool hasOrdinal ( ) const { return m_ordinal; }
        inline int ordinal ( ) const { return *m_ordinal; }
        inline bool hasDefValue ( ) const { return m_defvalue; }
        inline const literalvalue & defValue ( ) const { return *m_defvalue; }
        inline bool isOptional ( ) const { return m_modifier & FUDGEPROTO_MODIFIER_OPTIONAL; }

        inline bool isCollection ( ) const { return ! m_constraints.empty ( ); }

        void setOrdinal ( int ordinal );

        static fielddef * createAndConsume ( char * name,
                                             fieldtype * type,
                                             int modifier,
                                             fieldconstraint * constraints,
                                             int ordinal,
                                             literalvalue * defvalue );

        static fudgeproto_modifier cleanModifier ( int modifier );

    private:
        fieldtype m_type;
        fudgeproto_modifier m_modifier;
        std::vector<int> m_constraints;
        int * m_ordinal;
        literalvalue * m_defvalue;
};

class messagedef : public definition
{
    public:
        messagedef ( );
        messagedef ( identifier * id, bool isExtern = false );
        ~messagedef ( );

        inline bool isExtern ( ) const { return m_extern; }

        inline const std::vector<const identifier *> & parents ( ) const { return m_parents; }
        inline const std::list<enumdef *> & enums ( ) const { return m_enums; }
        inline const std::list<fielddef *> & fields ( ) const { return m_fields; }
        inline const std::list<messagedef *> messages ( ) const { return m_messages; }

        void addContent ( definition * content );
        void addParents ( const identifier_list & parents );

        void replaceParent ( size_t index, const identifier * parent );

        inline std::string originalIdString ( ) const { return m_originalId ? m_originalId->asString ( "." ) : idString ( ); }

        void saveOriginalId ( );

        static messagedef * addContentAndConsume ( messagedef * message, definition * definition );
        static messagedef * addParentsAndConsume ( messagedef * message, identifier_list * parents );

    private:
        bool m_extern;
        identifier * m_originalId;
        std::vector<const identifier *> m_parents;
        std::list<enumdef *> m_enums;
        std::list<fielddef *> m_fields;
        std::list<messagedef *> m_messages;
};

class namespacedef: public definition
{
    public:
        namespacedef ( );
        namespacedef ( identifier * id );
        namespacedef & operator= ( const namespacedef & source );
        ~namespacedef ( );

        void addContent ( definition * content );
        void clear ( );
        void removeContentIf ( bool ( *predicate ) ( const definition & ) );

        inline const std::list<definition *> & content ( ) const { return m_content; }

        static namespacedef * createAndConsume ( identifier * id );
        static namespacedef * addContentAndConsume ( namespacedef * ns, definition * content );
        static void assignAndConsume ( namespacedef & target, namespacedef * source );

    private:
        std::list<definition *> m_content;
};

}

#endif


text:
from __future__ import division, print_function, unicode_literals

from numpy import linalg as LA

def unitvec(vec):
    return (1.0 / LA.norm(vec, ord=2)) * vec

redpajama_set_name: RedPajamaGithub


text:
import { currentURL, visit } from '@ember/test-helpers';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { login } from 'open-event-frontend/tests/helpers/custom-helpers';

module('Acceptance | explore', function(hooks) {
  setupApplicationTest(hooks);

  test('visiting /explore without login', async function(assert) {
    await visit('/explore');
    assert.equal(currentURL(), '/explore');
  });

  test('visiting /explore with login', async function(assert) {
    await login(assert);
    await visit('/explore');
    assert.equal(currentURL(), '/explore');
  });
});


text:
'use strict';

/**
 * 登录路由中间件
 * Generic require login routing middleware
 */
exports.requiresLogin = function (req, res, next) {
    if (!req.isAuthenticated()) {
        return res.send(401, 'User is not authorized');
    }
    next();
};

/**
 * 管理路由中间件
 * Generic require Admin routing middleware
 * 简单的角色管理检测 - 后期会加入完善的权限管理系统
 * Basic Role checking - future release with full permission system
 */
exports.requiresAdmin = function (req, res, next) {
    if (!req.isAuthenticated() || !req.user.hasRole('admin')) {
        return res.send(401, 'User is not authorized');
    }
    next();
};


text:
static FMDatabase *db = nil;

@interface MUDatabase ()
+ (NSString *) filePath;
+ (void) moveOldDatabases;
@end

@implementation MUDatabase

+ (NSString *) filePath {
    NSArray *libraryDirectories = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
                                                                      NSUserDomainMask,
                                                                      YES);
    NSString *library = [libraryDirectories objectAtIndex:0];
    [[NSFileManager defaultManager] createDirectoryAtPath:library withIntermediateDirectories:YES attributes:nil error:nil];
    return [library stringByAppendingPathComponent:@"mumble.sqlite"];
}

+ (void) moveOldDatabases {
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                       NSUserDomainMask,
                                                                       YES);
    NSString *docs = [documentDirectories objectAtIndex:0];

    NSError *err = nil;
    NSFileManager *manager = [NSFileManager defaultManager];

    // Hide the SQLite database from the iTunes document inspector.
    NSString *oldPath = [docs stringByAppendingPathComponent:@"mumble.sqlite"];
    NSString *newPath = [docs stringByAppendingPathComponent:@".mumble.sqlite"];
    if (![manager fileExistsAtPath:newPath] && [manager fileExistsAtPath:oldPath]) {
        if (![manager moveItemAtPath:oldPath toPath:newPath error:&err]) {
            NSLog(@"MUDatabase: unable to move file to new spot (mumble.sqlite -> .mumble.sqlite)");
        }
    }

    // Attempt to move an old database to the new location.
    NSString *correctPath = [MUDatabase filePath];
    if (![manager fileExistsAtPath:correctPath]) {
        oldPath = newPath;
        newPath = correctPath;
        if (![manager fileExistsAtPath:newPath] && [manager fileExistsAtPath:oldPath]) {
            if (![manager moveItemAtPath:oldPath toPath:newPath error:&err]) {
                NSLog(@"MUDatabase: Unable to move file to new spot (~/Documents -> ~/Library)");
            }
        }
    }
}

// Initialize the database.
+ (void) initializeDatabase {
    NSLog(@"Initializing database with SQLite version: %@", [FMDatabase sqliteLibVersion]);

    // Attempt to move old databases if we find ones
    // in our old locations.
    [MUDatabase moveOldDatabases];

    NSString *dbPath = [MUDatabase filePath];
    db = [[FMDatabase alloc] initWithPath:dbPath];
    if (!db)
        return;

    if ([db open]) {
        NSLog(@"MUDatabase: Initialized database at %@", dbPath);
    } else {
        NSLog(@"MUDatabase: Could not open database at %@", dbPath);
        [db release];
        db = nil;
        return;
    }

    [db executeUpdate:@"CREATE TABLE IF NOT EXISTS `favourites` "
                      @"(`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                      @" `name` TEXT,"
                      @" `hostname` TEXT,"
                      @" `port` INTEGER DEFAULT 64738,"
                      @" `username` TEXT,"
                      @" `password` TEXT)"];

    [db executeUpdate:@"CREATE TABLE IF NOT EXISTS `cert` "
                      @"(`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                      @" `hostname` TEXT,"
                      @" `port` INTEGER,"
                      @" `digest` TEXT)"];
    [db executeUpdate:@"CREATE UNIQUE INDEX IF NOT EXISTS `cert_host_port`"
                      @" on `cert`(`hostname`,`port`)"];
    [db executeUpdate:@"CREATE TABLE IF NOT EXISTS `usernames` "
                      @"(`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                      @" `hostname` TEXT,"
                      @" `port` INTEGER,"
                      @" `username` TEXT)"];
    [db executeUpdate:@"CREATE UNIQUE INDEX IF NOT EXISTS `usernames_host_port`"
                      @" on `usernames`(`hostname`,`port`)"];
    [db executeUpdate:@"CREATE TABLE IF NOT EXISTS `tokens` "
                      @"(`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                      @" `hostname` TEXT,"
                      @" `port` INTEGER,"
                      @" `tokens` BLOB)"];
    [db executeUpdate:@"CREATE UNIQUE INDEX IF NOT EXISTS `tokens_host_port`"
                      @" on `tokens`(`hostname`,`port`)"];
    [db executeUpdate:@"VACUUM"];

    if ([db hadError]) {
        NSLog(@"MUDatabase: Error: %@ (Code: %i)", [db lastErrorMessage], [db lastErrorCode]);
    }
}

// Tear down the database
+ (void) teardown {
    [db release];
}

// Store a single favourite
+ (void) storeFavourite:(MUFavouriteServer *)favServ {
    // If the favourite already has a primary key, update the currently stored entity
    if ([favServ hasPrimaryKey]) {
        [db executeUpdate:@"UPDATE `favourites` SET `name`=?, `hostname`=?, `port`=?, `username`=?, `password`=? WHERE `id`=?",
            [favServ displayName],
            [favServ hostName],
            [NSString stringWithFormat:@"%lu", (unsigned long)[favServ port]],
            [favServ userName],
            [favServ password],
            [NSNumber numberWithInteger:[favServ primaryKey]]];
    // If it isn't already stored, store it and update the object's pkey.
    } else {
        // We're already inside a transaction if we were called from within
        // storeFavourites. If that isn't the case, make sure we start a new
        // transaction.
        BOOL newTransaction = ![db inTransaction];
        if (newTransaction)
            [db beginTransaction];
        [db executeUpdate:@"INSERT INTO `favourites` (`name`, `hostname`, `port`, `username`, `password`) VALUES (?, ?, ?, ?, ?)",
            [favServ displayName],
            [favServ hostName],
            [NSString stringWithFormat:@"%lu", (unsigned long)[favServ port]],
            [favServ userName],
            [favServ password]];
        FMResultSet *res = [db executeQuery:@"SELECT last_insert_rowid()"];
        [res next];
        [favServ setPrimaryKey:[res intForColumnIndex:0]];
        if (newTransaction)
            [db commit];
    }
}

// Delete a particular favourite
+ (void) deleteFavourite:(MUFavouriteServer *)favServ {
    NSAssert([favServ hasPrimaryKey], @"Cannot delete a FavouriteServer not originated from the database.");
    [db executeUpdate:@"DELETE FROM `favourites` WHERE `id`=?", [NSNumber numberWithInteger:[favServ primaryKey]]];
}

// Save favourites
+ (void) storeFavourites:(NSArray *)favourites {
    [db beginTransaction];
    for (MUFavouriteServer *favServ in favourites) {
        [MUDatabase storeFavourite:favServ];
    }
    [db commit];
}

// Fetch all favourites
+ (NSMutableArray *) fetchAllFavourites {
    NSMutableArray *favs = [[NSMutableArray alloc] init];
    FMResultSet *res = [db executeQuery:@"SELECT `id`, `name`, `hostname`, `port`, `username`, `password` FROM `favourites`"];
    while ([res next]) {
        MUFavouriteServer *fs = [[MUFavouriteServer alloc] init];
        [fs setPrimaryKey:[res intForColumnIndex:0]];
        [fs setDisplayName:[res stringForColumnIndex:1]];
        [fs setHostName:[res stringForColumnIndex:2]];
        [fs setPort:[res intForColumnIndex:3]];
        [fs setUserName:[res stringForColumnIndex:4]];
        [fs setPassword:[res stringForColumnIndex:5]];
        [favs addObject:fs];
        [fs release];
    }
    [res close];
    return [favs autorelease];
}

#pragma mark -
#pragma mark Certificate verification

+ (void) storeDigest:(NSString *)hash forServerWithHostname:(NSString *)hostname port:(NSInteger)port {
    [db executeUpdate:@"REPLACE INTO `cert` (`hostname`,`port`,`digest`) VALUES (?,?,?)",
           hostname, [NSNumber numberWithInteger:port], hash];

}

+ (NSString *) digestForServerWithHostname:(NSString *)hostname port:(NSInteger)port {
    FMResultSet *result = [db executeQuery:@"SELECT `digest` FROM `cert` WHERE `hostname` = ? AND `port` = ?",
                                 hostname, [NSNumber numberWithInteger:port]];
    if ([result next]) {
        return [result stringForColumnIndex:0];
    }
    return nil;
}

#pragma mark -
#pragma mark Username rememberer

+ (void) storeUsername:(NSString *)username forServerWithHostname:(NSString *)hostname port:(NSInteger)port {
    [db executeUpdate:@"REPLACE INTO `usernames` (`hostname`,`port`,`username`) VALUES (?,?,?)",
        hostname, [NSNumber numberWithInteger:port], username];
}

+ (NSString *) usernameForServerWithHostname:(NSString *)hostname port:(NSInteger)port {
    FMResultSet *result = [db executeQuery:@"SELECT `username` FROM `usernames` WHERE `hostname` = ? AND `port` = ?",
                           hostname, [NSNumber numberWithInteger:port]];
    if ([result next]) {
        return [result stringForColumnIndex:0];
    }
    return nil;
}

#pragma mark -
#pragma mark Access tokens

+ (void) storeAccessTokens:(NSArray *)tokens forServerWithHostname:(NSString *)hostname port:(NSInteger)port {
    NSData *tokensJSON = nil;
    if (tokens != nil) {
        NSError *err = nil;
        tokensJSON = [NSJSONSerialization dataWithJSONObject:tokens options:0 error:&err];
        if (err != nil) {
            NSLog(@"MUDatabase#storeAccessTokens:forServerWithHostname:port: %@", err);
            return;
        }
    }
    [db executeUpdate:@"REPLACE INTO `tokens` (`hostname`,`port`,`tokens`) VALUES (?,?,?)",
        hostname, [NSNumber numberWithInteger:port], tokensJSON];
}

+ (NSArray *) accessTokensForServerWithHostname:(NSString *)hostname port:(NSInteger)port {
    FMResultSet *result = [db executeQuery:@"SELECT `tokens` FROM `tokens` WHERE `hostname` = ? AND `port` = ?",
                           hostname, [NSNumber numberWithInteger:port]];
    if ([result next]) {
        NSError *err = nil;
        NSData *tokensJSON = [result dataForColumnIndex:0];
        NSArray *tokens = [NSJSONSerialization JSONObjectWithData:tokensJSON options:0 error:&err];
        if (err != nil) {
            NSLog(@"MUDatabase#accessTokensForServerWithHostname:port: %@", err);
            return nil;
        }
        return tokens;
    }
    return nil;
}

@end


text:
<!DOCTYPE html>

	<form th:action="@{/login}" method="POST">

				Por favor, faça o login.

				O usuário e/ou senha não conferem

					<input type="text" class="form-control  input-lg" placeholder="Seu usuário" autofocus="autofocus" name="username"/>

					<input type="password" class="form-control  input-lg" placeholder="Sua senha" name="password"/>

					<button type="submit" class="btn  btn-primary  btn-lg  aw-btn-full-width">Entrar</button>

	</form>


text:
package collector

import (
	"context"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/go-kit/log"
	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
	"github.com/smartystreets/goconvey/convey"
)

func TestScrapeClientStat(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("error opening a stub database connection: %s", err)
	}
	defer db.Close()

	mock.ExpectQuery(sanitizeQuery(userstatCheckQuery)).WillReturnRows(sqlmock.NewRows([]string{"Variable_name", "Value"}).
		AddRow("userstat", "ON"))

	columns := []string{"CLIENT", "TOTAL_CONNECTIONS", "CONCURRENT_CONNECTIONS", "CONNECTED_TIME", "BUSY_TIME", "CPU_TIME", "BYTES_RECEIVED", "BYTES_SENT", "BINLOG_BYTES_WRITTEN", "ROWS_READ", "ROWS_SENT", "ROWS_DELETED", "ROWS_INSERTED", "ROWS_UPDATED", "SELECT_COMMANDS", "UPDATE_COMMANDS", "OTHER_COMMANDS", "COMMIT_TRANSACTIONS", "ROLLBACK_TRANSACTIONS", "DENIED_CONNECTIONS", "LOST_CONNECTIONS", "ACCESS_DENIED", "EMPTY_QUERIES"}
	rows := sqlmock.NewRows(columns).
		AddRow("localhost", 1002, 0, 127027, 286, 245, float64(2565104853), 21090856, float64(2380108042), 767691, 1764, 8778, 1210741, 0, 1764, 1214416, 293, 2430888, 0, 0, 0, 0, 0)
	mock.ExpectQuery(sanitizeQuery(clientStatQuery)).WillReturnRows(rows)

	ch := make(chan prometheus.Metric)
	go func() {
		if err = (ScrapeClientStat{}).Scrape(context.Background(), db, ch, log.NewNopLogger()); err != nil {
			t.Errorf("error calling function on test: %s", err)
		}
		close(ch)
	}()

	expected := []MetricResult{
		{labels: labelMap{"client": "localhost"}, value: 1002, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 0, metricType: dto.MetricType_GAUGE},
		{labels: labelMap{"client": "localhost"}, value: 127027, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 286, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 245, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: float64(2565104853), metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 21090856, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: float64(2380108042), metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 767691, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 1764, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 8778, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 1210741, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 0, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 1764, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 1214416, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 293, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 2430888, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 0, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 0, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 0, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 0, metricType: dto.MetricType_COUNTER},
		{labels: labelMap{"client": "localhost"}, value: 0, metricType: dto.MetricType_COUNTER},
	}
	convey.Convey("Metrics comparison", t, func() {
		for _, expect := range expected {
			got := readMetric(<-ch)
			convey.So(expect, convey.ShouldResemble, got)
		}
	})

	// Ensure all SQL queries were executed
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled exceptions: %s", err)
	}
}


text:
import {Routes, RouterModule } from '@angular/router';

/* Import components for use in routing */
import { AppComponent } from './app.component';

const routes : Routes = [
  { path: '', component: AppComponent }
];

export const routing = RouterModule.forRoot(routes);


text:
define(['sugar-web/graphics/palette'], function(palette) {

	var speedpalette = {};

	speedpalette.SpeedPalette = function(invoker, primaryText) {
		palette.Palette.call(this, invoker, primaryText);
		this.getPalette().id = "speedpalette";
		this.speedEvent = document.createEvent('CustomEvent');
		this.speedEvent.initCustomEvent('speed', true, true, {'speed': 50});

		var speedElem = document.createElement('div');
		speedElem.innerHTML = `

			  speed:<input id="speedvalue" type="range" step="10" style="width:70%;margin:3%;margin-left:28%;margin-top:22px;"></input>

		`;
		this.setContent([speedElem]);

		invoker.addEventListener('click', function(e) {
			document.getElementById("speedlabel").innerHTML = (document.getElementById("speed-button").title) + ":";
			document.getElementById("speedvalue").value = 100-((app.blinkTime-500)/10);
		});

		var that = this;
		this.speedScale = document.querySelector('#speedvalue');
		this.speedScale.oninput = function() {
			that.speedEvent.detail.speed = 100-this.value;
			that.getPalette().dispatchEvent(that.speedEvent);
		}
	};

	var addEventListener = function(type, listener, useCapture) {
		return this.getPalette().addEventListener(type, listener, useCapture);
	};

	speedpalette.SpeedPalette.prototype = Object.create(palette.Palette.prototype, {
		addEventListener: {
			value: addEventListener,
			enumerable: true,
			configurable: true,
			writable: true
		}
	});

	return speedpalette;
});


text:
namespace XRoadLib.Soap;

public abstract class FaultCode
{
    protected enum FaultCodeType
    {
        Server,
        Client,
        [UsedImplicitly] VersionMismatch,
        [UsedImplicitly] MustUnderstand
    }

    public string Value { get; }

    protected FaultCode(FaultCodeType type, string value)
    {
        Value = string.IsNullOrWhiteSpace(value) ? type.ToString() : $"{type}.{value}";
    }
}


text:
layout: post
title: TrelloExport 1.9.34
tags: trello chrome excel markdown html opml
---

New features for Excel and HTML exports!

## What's new for TrelloExport 1.9.34?

Versions 1.9.33 and .34, released today, bring some new features:

- new data field dateLastActivity exported ([issue #18](https://github.com/trapias/TrelloExport/issues/18))
- new data field numberOfComments exported ([issue #19](https://github.com/trapias/TrelloExport/issues/19))
- new option to choose which columns to export to Excel ([issue #17](https://github.com/trapias/TrelloExport/issues/17))
- can set a custom css for HTML export
- can check/uncheck all columns to export

### Excel columns chooser

You can now choose which columns to export to the final Excel spreadsheet:

![Choose columns to export]({{ site.baseurl }}/images/TrelloExport_1.9.34_excelcolumns.png)

### HTML custom stylesheet

Perhaps not the better way, but it is now possible to use a custom stylesheet when exporting to HTML: just set the URL to your css file in the box before exporting.
If not specified, the [default stylesheet](https://trapias.github.io/assets/TrelloExport/default.css) will be used.

![Use a custom stylesheet]({{ site.baseurl }}/images/TrelloExport_1.9.34_css.png)

## Feedback
Your feedback is always welcome. If you have any problem please open an issue on [GitHub](https://github.com/trapias/trelloExport/issues) or contact me, I'll do my best to fix it quickly.

## Donate?
If you wish to support the development of this tool, you can now [make a donation](https://trapias.github.io/donate/).

## Download
You can now get TrelloExport from the Chrome Web Store at [this URL](https://chrome.google.com/webstore/detail/trelloexport/kmmnaeamjfdnbhljpedgfchjbkbomahp).

If you want the source version, get them on GitHub at [https://github.com/trapias/trelloExport](https://github.com/trapias/trelloExport), and follow the installation instructions in the readme.


text:
/*!
 * angular-feedback-form v0.0.1
 * https://github.com/ediri/angular-feedback-form
 * Copyright (c) 2016 ediri
 * License: MIT
 */
.feedback {
    transform: rotate(-90deg);
    border: none;
    outline: none;
    text-transform: uppercase;
    padding: 0.3em 1em;
    position: fixed;
    top: 420px;
    z-index: 1;
    left: -35px;
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;
}

.alert-float {
    position: absolute;
    width: 80%;
    left: 65px;
    top: 10px;
}


text:
package org.dashbuilder.dataset.backend;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import javax.enterprise.context.ApplicationScoped;

import org.apache.commons.lang3.StringUtils;
import org.dashbuilder.dataset.DataColumn;
import org.dashbuilder.dataset.DataSet;
import org.dashbuilder.dataset.date.Month;
import org.dashbuilder.dataset.engine.DataSetHandler;
import org.dashbuilder.dataset.engine.group.IntervalBuilder;
import org.dashbuilder.dataset.group.Interval;
import org.dashbuilder.dataset.engine.group.IntervalList;
import org.dashbuilder.dataset.group.DateIntervalType;
import org.dashbuilder.dataset.group.ColumnGroup;
import org.dashbuilder.dataset.sort.DataSetSort;
import org.dashbuilder.dataset.sort.ColumnSort;
import org.dashbuilder.dataset.sort.SortOrder;
import org.dashbuilder.dataset.sort.SortedList;
import org.dashbuilder.dataset.date.Quarter;

import static org.dashbuilder.dataset.group.DateIntervalType.*;

/**
 * Interval builder for date columns which generates intervals depending on the underlying data available.
 */
@ApplicationScoped
public class BackendIntervalBuilderDynamicDate implements IntervalBuilder {

    public IntervalList build(DataSetHandler handler, ColumnGroup columnGroup) {
        IntervalDateRangeList results = new IntervalDateRangeList(columnGroup);
        DataSet dataSet = handler.getDataSet();
        List values = dataSet.getColumnById(columnGroup.getSourceId()).getValues();
        if (values.isEmpty()) {
            return results;
        }

        // Sort the column dates.
        DataSetSort sortOp = new DataSetSort();
        sortOp.addSortColumn(new ColumnSort(columnGroup.getSourceId(), SortOrder.ASCENDING));
        DataSetHandler sortResults = handler.sort(sortOp);
        List<Integer> sortedRows = sortResults.getRows();
        if (sortedRows == null || sortedRows.isEmpty()) {
            return results;
        }

        // Get the lower & upper limits (discard nulls).
        SortedList sortedValues = new SortedList(values, sortedRows);
        Date minDate = null;
        Date maxDate = null;
        for (int i = 0; minDate == null && i < sortedValues.size(); i++) {
            minDate = (Date) sortedValues.get(i);
        }
        for (int i = sortedValues.size()-1; maxDate == null && i >= 0; i--) {
            maxDate = (Date) sortedValues.get(i);
        }

        // If min/max are equals then return a single interval.
        DateIntervalType intervalType = calculateIntervalSize(minDate, maxDate, columnGroup);
        if (minDate == null || minDate.compareTo(maxDate) == 0) {

            IntervalDateRange interval = new IntervalDateRange(0, intervalType, minDate, maxDate);
            for (int row = 0; row < sortedValues.size(); row++) interval.getRows().add(row);

            results.add(interval);
            results.setIntervalType(columnGroup.getIntervalSize());
            results.setMinValue(minDate);
            results.setMaxValue(maxDate);
            return results;
        }

        // Create the intervals according to the min/max dates.
        Calendar c = firstIntervalDate(intervalType, minDate, columnGroup);
        int index = 0;
        int counter = 0;
        while (c.getTime().compareTo(maxDate) <= 0) {
            Date intervalMinDate = c.getTime();

            // Create the next interval
            nextIntervalDate(c, intervalType, 1);
            Date intervalMaxDate = c.getTime();
            IntervalDateRange interval = new IntervalDateRange(counter++, intervalType, intervalMinDate, intervalMaxDate);
            results.add(interval);

            // Add the target rows
            boolean stop = false;
            while (!stop) {
                if (index >= sortedValues.size()) {
                    stop = true;
                } else {
                    Date dateValue = (Date) sortedValues.get(index);
                    Integer row = sortedRows.get(index);
                    if (dateValue == null) {
                        index++;
                    } else if (dateValue.before(intervalMaxDate)) {
                        interval.getRows().add(row);
                        index++;
                    } else {
                        stop = true;
                    }
                }
            }
        }

        // Reverse intervals if requested
        boolean asc = columnGroup.isAscendingOrder();
        if (!asc) Collections.reverse( results );

        // Return the results
        results.setIntervalType(intervalType.toString());
        results.setMinValue(minDate);
        results.setMaxValue(maxDate);
        return results;
    }

    public IntervalList build(DataColumn dataColumn) {
        ColumnGroup columnGroup = dataColumn.getColumnGroup();
        Date minDate = (Date) dataColumn.getMinValue();
        Date maxDate = (Date) dataColumn.getMaxValue();
        DateIntervalType intervalType = DateIntervalType.getByName(dataColumn.getIntervalType());

        IntervalDateRangeList results = new IntervalDateRangeList(columnGroup);
        Calendar c = firstIntervalDate(intervalType, minDate, columnGroup);
        int counter = 0;
        while (c.getTime().compareTo(maxDate) <= 0) {
            Date intervalMinDate = c.getTime();

            // Create the next interval
            nextIntervalDate(c, intervalType, 1);
            Date intervalMaxDate = c.getTime();
            IntervalDateRange interval = new IntervalDateRange(counter++, intervalType, intervalMinDate, intervalMaxDate);
            results.add(interval);
        }

        // Reverse intervals if requested
        boolean asc = columnGroup.isAscendingOrder();
        if (!asc) Collections.reverse( results );

        // Return the results
        results.setIntervalType(intervalType.toString());
        results.setMinValue(minDate);
        results.setMaxValue(maxDate);
        return results;
    }

    public DateIntervalType calculateIntervalSize(Date minDate, Date maxDate, ColumnGroup columnGroup) {

        // Calculate the interval type used according to the constraints set.
        int maxIntervals = columnGroup.getMaxIntervals();
        if (maxIntervals < 1) maxIntervals = 15;
        DateIntervalType intervalType = YEAR;
        long millis = (maxDate.getTime() - minDate.getTime());
        for (DateIntervalType type : values()) {
            long nintervals = millis / getDurationInMillis(type);
            if (nintervals < maxIntervals) {
                intervalType = type;
                break;
            }
        }

        // Ensure the interval mode obtained is always greater or equals than the preferred interval size.
        DateIntervalType intervalSize = null;
        if (!StringUtils.isBlank(columnGroup.getIntervalSize())) {
            intervalSize = getByName(columnGroup.getIntervalSize());
        }
        if (intervalSize != null && compare(intervalType, intervalSize) == -1) {
            intervalType = intervalSize;
        }
        return intervalType;
    }

    protected Calendar firstIntervalDate(DateIntervalType intervalType, Date minDate, ColumnGroup columnGroup) {
        Calendar c = GregorianCalendar.getInstance();
        c.setLenient(false);
        c.setTime(minDate);
        if (YEAR.equals(intervalType)) {
            c.set(Calendar.MONTH, 0);
            c.set(Calendar.DAY_OF_MONTH, 1);
            c.set(Calendar.HOUR, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
        }
        if (QUARTER.equals(intervalType)) {
            int currentMonth = c.get(Calendar.MONTH);
            int firstMonthYear = columnGroup.getFirstMonthOfYear().getIndex();
            int rest = Quarter.getPositionInQuarter(firstMonthYear, currentMonth+1);
            c.add(Calendar.MONTH, rest * -1);
            c.set(Calendar.DAY_OF_MONTH, 1);
            c.set(Calendar.HOUR, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
        }
        if (MONTH.equals(intervalType)) {
            c.set(Calendar.DAY_OF_MONTH, 1);
            c.set(Calendar.HOUR, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
        }
        if (DAY.equals(intervalType) || DAY_OF_WEEK.equals(intervalType) || WEEK.equals(intervalType)) {
            c.set(Calendar.HOUR, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
        }
        if (HOUR.equals(intervalType)) {
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
        }
        if (MINUTE.equals(intervalType)) {
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
        }
        if (SECOND.equals(intervalType)) {
            c.set(Calendar.MILLISECOND, 0);
        }
        return c;
    }

    protected void nextIntervalDate(Calendar c, DateIntervalType intervalType, int intervals) {

        if (MILLENIUM.equals(intervalType)) {
            c.add(Calendar.YEAR, 1000 * intervals);
        }
        if (CENTURY.equals(intervalType)) {
            c.add(Calendar.YEAR, 100 * intervals);
        }
        if (DECADE.equals(intervalType)) {
            c.add(Calendar.YEAR, 10 * intervals);
        }
        if (YEAR.equals(intervalType)) {
            c.add(Calendar.YEAR, intervals);
        }
        if (QUARTER.equals(intervalType)) {
            c.add(Calendar.MONTH, 3 * intervals);
        }
        if (MONTH.equals(intervalType)) {
            c.add(Calendar.MONTH, intervals);
        }
        if (WEEK.equals(intervalType)) {
            c.add(Calendar.DAY_OF_MONTH, 7 * intervals);
        }
        if (DAY.equals(intervalType) || DAY_OF_WEEK.equals(intervalType)) {
            c.add(Calendar.DAY_OF_MONTH, intervals);
        }
        if (HOUR.equals(intervalType)) {
            c.add(Calendar.HOUR_OF_DAY, intervals);
        }
        if (MINUTE.equals(intervalType)) {
            c.add(Calendar.MINUTE, intervals);
        }
        if (SECOND.equals(intervalType)) {
            c.add(Calendar.SECOND, intervals);
        }
    }

    public Interval locate(DataColumn column, Integer intervalIndex) {
        ColumnGroup columnGroup = column.getColumnGroup();
        Date columnMinDate = (Date) column.getMinValue();
        String type = column.getIntervalType();

        if (columnGroup == null) return null;
        if (columnMinDate == null) return null;
        if (type == null) return null;

        // Calculate the interval min. date.
        DateIntervalType intervalType = DateIntervalType.getByName(type);
        Calendar c = firstIntervalDate(intervalType, columnMinDate, columnGroup);
        nextIntervalDate(c, intervalType, intervalIndex);
        Date intervalMinDate = c.getTime();

        // Calculate the interval max. date.
        nextIntervalDate(c, intervalType, 1);
        Date intervalMaxDate = c.getTime();

        // Build & return the selected interval
        return new IntervalDateRange(intervalIndex, intervalType, intervalMinDate, intervalMaxDate);
    }

    private static SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    /**
     * A list containing date range intervals.
     */
    public class IntervalDateRangeList extends IntervalList {

        public IntervalDateRangeList(ColumnGroup columnGroup) {
            super(columnGroup);
        }

        public Interval locateInterval(Object value) {
            Date d = (Date) value;
            for (Interval interval : this) {
                IntervalDateRange dateRange = (IntervalDateRange) interval;
                if (d.equals(dateRange.getMinDate()) || (d.after(dateRange.getMinDate()) && d.before(dateRange.getMaxDate()))) {
                    return interval;
                }
            }
            return null;
        }
    }

    /**
     * A date interval holding dates belonging to a given range.
     */
    public class IntervalDateRange extends Interval {

        public IntervalDateRange(int index, DateIntervalType intervalType, Date minDate, Date maxDate) {
            super(calculateName(intervalType, minDate));
            super.setMinValue(minDate);
            super.setMaxValue(maxDate);
            super.setIndex(index);
            super.setType(intervalType.toString());
        }

        public Date getMinDate() {
            return (Date) minValue;
        }

        public Date getMaxDate() {
            return (Date) maxValue;
        }
    }

    public static String calculateName(DateIntervalType intervalType, Date d) {
        if (d == null) return null;

        Locale l = Locale.getDefault();
        if (MILLENIUM.equals(intervalType) || CENTURY.equals(intervalType)
            || DECADE.equals(intervalType) || YEAR.equals(intervalType)) {
            SimpleDateFormat format  = new SimpleDateFormat("yyyy", l);
            return format.format(d);
        }
        if (QUARTER.equals(intervalType) || MONTH.equals(intervalType)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM", l);
            return format.format(d);
        }
        if (WEEK.equals(intervalType) || DAY.equals(intervalType) || DAY_OF_WEEK.equals(intervalType)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            return format.format(d);
        }
        if (HOUR.equals(intervalType)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH");
            return format.format(d);
        }
        if (MINUTE.equals(intervalType)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return format.format(d);
        }
        if (SECOND.equals(intervalType)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format.format(d);
        }
        return format.format(d);
    }
}


text:
    <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
    <title>hasHashCode</title>
<link href="../../../images/logo-icon.svg" rel="icon" type="image/svg"><link href="../../styles/style.css" rel="Stylesheet"><link href="../../styles/logo-styles.css" rel="Stylesheet"><link href="../../styles/jetbrains-mono.css" rel="Stylesheet"><link href="../../styles/main.css" rel="Stylesheet">

assertk/assertk.assertions/hasHashCode

<button class="platform-tag platform-selector common-like" data-active="" data-filter=":assertk:dokkaHtmlPartial/commonMain">common</button>

has<wbr>Hash<wbr>Code

fun Assert<Any>.hasHashCode(hashCode: Int)
Content copied to clipboard

Asserts the value has the expected hash code from it's hashCode.

© 2021 CopyrightGenerated by dokka


text:
package gov.va.med.lom.vistabroker.patient.data;

import java.io.Serializable;

public class OrderDialogResolved implements Serializable {

  private String inputId;      // can be dialog IEN or '#ORIFN'
  private int quickLevel;      // 0=dialog,1=auto,2=verify,8=reject,9=cancel
  private String responseId;   // DialogID + ';' + $H
  private String dialogIen;    // pointer to 101.41 for dialog (may be quick order IEN)
  private char dialogType;     // type of dialog (Q or D)
  private int formId;          // windows form to display
  private String displayGroup; // pointer to 100.98, display group for dialog
  private String showText;     // text to show for verify or rejection
  private String qoKeyVars;    // from entry action of quick order

  public String getInputId() {
    return inputId;
  }
  public void setInputId(String inputId) {
    this.inputId = inputId;
  }
  public int getQuickLevel() {
    return quickLevel;
  }
  public void setQuickLevel(int quickLevel) {
    this.quickLevel = quickLevel;
  }
  public String getResponseId() {
    return responseId;
  }
  public void setResponseId(String responseId) {
    this.responseId = responseId;
  }
  public String getDialogIen() {
    return dialogIen;
  }
  public void setDialogIen(String dialogIen) {
    this.dialogIen = dialogIen;
  }
  public char getDialogType() {
    return dialogType;
  }
  public void setDialogType(char dialogType) {
    this.dialogType = dialogType;
  }
  public int getFormId() {
    return formId;
  }
  public void setFormId(int formId) {
    this.formId = formId;
  }
  public String getDisplayGroup() {
    return displayGroup;
  }
  public void setDisplayGroup(String displayGroup) {
    this.displayGroup = displayGroup;
  }
  public String getShowText() {
    return showText;
  }
  public void setShowText(String showText) {
    this.showText = showText;
  }
  public String getQoKeyVars() {
    return qoKeyVars;
  }
  public void setQoKeyVars(String qoKeyVars) {
    this.qoKeyVars = qoKeyVars;
  }

}


text:
EMAIL_READY="/var/.email_ready"
SEND_FW="/var/.email_fwlog"
SEND_PC="/var/.email_pclog"
SEND_AW="/var/.email_awlog"
SEND_ALL="/var/.email_alllog"

FW_LOG_CACHE="/var/.fw_log_cache"
PC_LOG_CACHE="/var/.pc_log_cache"
AW_LOG_CACHE="/var/.aw_log_cache"

FWLOG_PATTERN="UTOPIA: FW"
PCLOG_PATTERN="Blocked_"
AWLOG_PATTERN="\.warn\ |\.alert\ "

FW_LOG="/var/log/kernel"
PC_LOG="/var/log/kernel"
AW_LOG="/var/log/messages"

FW_LAST_LOG=${FWLOG_PATTERN}
PC_LAST_LOG=${PCLOG_PATTERN}
AW_LAST_LOG=${AWLOG_PATTERN}

VERSION_FILE="/etc/versions"

if [ ! -f $VERSION_FILE ]; then
    PRODUCT_NAME="Docsis Gateway"
elif [ `head -n1 $VERSION_FILE | grep -wc "dpc3939"` -eq 1 ]; then
    PRODUCT_NAME="dpc3939"
elif [ `head -n1 $VERSION_FILE | grep -wc "dpc3939b"` -eq 1 ]; then
    PRODUCT_NAME="dpc3939b"
elif [ `head -n1 $VERSION_FILE | grep -wc "dpc3848"` -eq 1 ]; then
    PRODUCT_NAME="dpc3848"
elif [ `head -n1 $VERSION_FILE | grep -wc "dpc3848"` -eq 1 ]; then
    PRODUCT_NAME="dpc3848"
else
    PRODUCT_NAME="Docsis Gateway"
fi

if [ $# -eq 0 ]; then
    sleepInterval=12
else
    sleepInterval=$1
fi

rm -rf "${FW_LOG_CACHE}"
rm -rf "${PC_LOG_CACHE}"
rm -rf "${AW_LOG_CACHE}"

while [ 1 ]; do

    ##wait until email notification SB APIs are ready
    while [ ! -e "${EMAIL_READY}" ];do
        sleep 5
    done

    ##send interval
    sleep $sleepInterval

    psCnt=`ps | grep -F "email_notification_monitor.sh" | wc -l`
    while [ $psCnt -gt 3 ]; do
        sleep 3
        psCnt=`ps | grep -F "email_notification_monitor.sh" | wc -l`
    done

    ##-------------------------FW LOGS--------------------------------------------------
    ##collect firewall logs only if its GUI option is set to yes
    if [ -e "${SEND_FW}" -o -e "${SEND_ALL}" ]; then

        match=`grep -F -c "${FW_LAST_LOG}" ${FW_LOG}`

        if [ $match -ne 0 ]; then
            ##1. if ${FW_LAST_LOG} is FWLOG_PATTERN, then append all the entries in the log file
            ##2. if ${FW_LAST_LOG} is the last line of logs which has been sent, then append all the entries AFTER this line
            if [ "${FW_LAST_LOG}" != "${FWLOG_PATTERN}" ]; then
                awk -v pat="${FW_LAST_LOG}" 'f; $0 == pat {f=1}' "${FW_LOG}" | grep -F "${FWLOG_PATTERN}" >> ${FW_LOG_CACHE}

            else
                grep -F "${FWLOG_PATTERN}" "${FW_LOG}" >> ${FW_LOG_CACHE}
            fi
        elif [ "${FW_LAST_LOG}" != "${FWLOG_PATTERN}" ]; then
            ##if no entries are found
            ##1. Maybe after the last email has been sent, ${FW_LAST_LOG} is flushed in the log file. We need to find the new entries by ${FWLOG_PATTERN}
            FW_LAST_LOG="${FWLOG_PATTERN}"

            match2=`grep -F -c "${FW_LAST_LOG}" ${FW_LOG}`

            if [ $match2 -ne 0 ]; then
                ##1.1 if new entries are found by ${FWLOG_PATTERN}, append them to log cache file.
                grep -F "${FWLOG_PATTERN}" "${FW_LOG}" >> ${FW_LOG_CACHE}
            fi
        fi

        ##if found new log entries
        ##1. save the last line for tracking
        ##2. send logs
        ##3. clean log cache file
        if [ -s "${FW_LOG_CACHE}" ]; then
            FW_LAST_LOG=`tail -n 1 ${FW_LOG_CACHE}`;

            (((cat /var/ssmtp_msg; echo "Subject: $PRODUCT_NAME Firewall Logs"; echo; echo; uuencode ${FW_LOG_CACHE} USGv2_Firewall_Logs_`date +%Y_%m_%d_%H_%M_%S`.txt) | ssmtp `awk -F ': ' 'NR==1{print $2}' /var/ssmtp_msg`) && (echo -n > ${FW_LOG_CACHE}))
        fi
    fi

    ##Not using array here since we may want to apply different log sending strategy for different log types. Repeat same code block.
    ##-------------------------PC LOGS--------------------------------------------------
    ##collect parental control logs only if its GUI option is set to yes
    if [ -e "${SEND_PC}" -o -e "${SEND_ALL}" ]; then

        match=`grep -F -c "${PC_LAST_LOG}" ${PC_LOG}`

        if [ $match -ne 0 ]; then
            ##1. if ${PC_LAST_LOG} is PCLOG_PATTERN, then append all the entries in the log file
            ##2. if ${PC_LAST_LOG} is the last line of logs which has been sent, then append all the entries AFTER this line
            if [ "${PC_LAST_LOG}" != "${PCLOG_PATTERN}" ]; then
                awk -v pat="${PC_LAST_LOG}" 'f; $0 == pat {f=1}' "${PC_LOG}" | grep -F "${PCLOG_PATTERN}" >> ${PC_LOG_CACHE}
            else
                grep -F "${PCLOG_PATTERN}" "${PC_LOG}" >> ${PC_LOG_CACHE}
            fi
        elif [ "${PC_LAST_LOG}" != "${PCLOG_PATTERN}" ]; then
            ##if no entries are found
            ##1. Maybe after the last email has been sent, ${PC_LAST_LOG} is flushed in the log file. We need to find the new entries by ${PCLOG_PATTERN}
            PC_LAST_LOG="${PCLOG_PATTERN}"

            match2=`grep -F -c "${PC_LAST_LOG}" ${PC_LOG}`

            if [ $match2 -ne 0 ]; then
                ##1.1 if new entries are found by ${PCLOG_PATTERN}, append them to log cache file.
                grep -F "${PCLOG_PATTERN}" "${PC_LOG}" >> ${PC_LOG_CACHE}
            fi
        fi

        ##if found new log entries
        ##1. save the last line for tracking
        ##2. send logs
        ##3. clean log cache file
        if [ -s "${PC_LOG_CACHE}" ]; then
            PC_LAST_LOG=`tail -n 1 ${PC_LOG_CACHE}`;

            BLKURL_CNT=`syscfg get ManagedSiteBlockCount`
            INDEX=1

            while [ $INDEX -le $BLKURL_CNT ]; do
                SITE=`syscfg get pcms_$INDEX site`
                METHOD=`syscfg get pcms_$INDEX method`

                if [ $METHOD == "URL" ]; then
                    sed -i 's,LOG_SiteBlocked_'"${INDEX}"'_DROP,Block URL '"$SITE"' ,g' "${PC_LOG_CACHE}"
                else
                    sed -i 's,LOG_SiteBlocked_'"${INDEX}"'_DROP,Block Keyword '"$SITE"' ,g' "${PC_LOG_CACHE}"
                fi
                let INDEX=$INDEX+1
            done

            BLKSERV_CNT=`syscfg get ManagedServiceBlockCount`
            INDEX=1

            while [ $INDEX -le $BLKSERV_CNT ]; do
                SERV=`syscfg get pcmse_$INDEX desc`
                sed -i "s/LOG_ServiceBlocked_${INDEX}_DROP/Block Service $SERV /g" ${PC_LOG_CACHE}
                let INDEX=$INDEX+1
            done

            (((cat /var/ssmtp_msg; echo "Subject: $PRODUCT_NAME Parental Control Logs"; echo; echo; uuencode ${PC_LOG_CACHE} USGv2_ParentalControl_Logs_`date +%Y_%m_%d_%H_%M_%S`.txt) | ssmtp `awk -F ': ' 'NR==1{print $2}' /var/ssmtp_msg`) && (echo -n > ${PC_LOG_CACHE}))
        fi
    fi

    ##-------------------------AW LOGS--------------------------------------------------
    ##collect alerts and warnings logs only if its GUI option is set to yes
    if [ -e "${SEND_AW}" -o -e "${SEND_ALL}" ]; then

        if [ "${AW_LAST_LOG}" = "${AWLOG_PATTERN}" ]; then
            match=`grep -E -c "${AW_LAST_LOG}" ${AW_LOG}`
        else
            match=`grep -F -c "${AW_LAST_LOG}" ${AW_LOG}`
        fi

        if [ $match -ne 0 ]; then
            ##1. if ${AW_LAST_LOG} is AWLOG_PATTERN, then append all the entries in the log file
            ##2. if ${AW_LAST_LOG} is the last line of logs which has been sent, then append all the entries AFTER this line
            if [ "${AW_LAST_LOG}" != "${AWLOG_PATTERN}" ]; then
                awk -v pat="${AW_LAST_LOG}" 'f; $0 == pat {f=1}' "${AW_LOG}" | grep -E "${AWLOG_PATTERN}" >> ${AW_LOG_CACHE}
            else
                grep -E "${AWLOG_PATTERN}" "${AW_LOG}" >> ${AW_LOG_CACHE}
            fi
        elif [ "${AW_LAST_LOG}" != "${AWLOG_PATTERN}" ]; then
            ##if no entries are found
            ##1. Maybe after the last email has been sent, ${AW_LAST_LOG} is flushed in the log file. We need to find the new entries by ${AWLOG_PATTERN}
            AW_LAST_LOG="${AWLOG_PATTERN}"

            match2=`grep -E -c "${AW_LAST_LOG}" ${AW_LOG}`

            if [ $match2 -ne 0 ]; then
                ##1.1 if new entries are found by ${AWLOG_PATTERN}, append them to log cache file.
                grep -E "${AWLOG_PATTERN}" "${AW_LOG}" >> ${AW_LOG_CACHE}
            fi
        fi

        ##if found new log entries
        ##1. save the last line for tracking
        ##2. send logs
        ##3. clean log cache file
        if [ -s "${AW_LOG_CACHE}" ]; then
            AW_LAST_LOG=`tail -n 1 ${AW_LOG_CACHE}`;

            (((cat /var/ssmtp_msg; echo "Subject: $PRODUCT_NAME Alerts and Warnings Logs"; echo; echo; uuencode ${AW_LOG_CACHE} USGv2_AlertsOrWarnings_Logs_`date +%Y_%m_%d_%H_%M_%S`.txt) | ssmtp `awk -F ': ' 'NR==1{print $2}' /var/ssmtp_msg`) && (echo -n > ${AW_LOG_CACHE}))
        fi
    fi

done


text:
import abc
import typing
import hashlib

import furl

from waterbutler.core import utils
from waterbutler.server import settings

class BaseMetadata(metaclass=abc.ABCMeta):
    """The BaseMetadata object provides the base structure for all metadata returned via
    WaterButler.  It also implements the API serialization methods to turn metadata objects
    into primitive data structures suitable for serializing.

    The basic metadata response looks like::

        {
          "path": "",
          "name": "",
          "kind": "",
          "provider": "",
          "materialized": "",
          "provider": "",
          "etag": "",
          "extra": {}
        }
    """

    def __init__(self, raw: dict) -> None:
        self.raw = raw

    def serialized(self) -> dict:
        """Returns a dict of primitives suitable for serializing into JSON.

        .. note::

            This method determines the output of API v0 and v1.

        :rtype: dict
        """
        return {
            'extra': self.extra,
            'kind': self.kind,
            'name': self.name,
            'path': self.path,
            'provider': self.provider,
            'materialized': self.materialized_path,
            'etag': hashlib.sha256('{}::{}'.format(self.provider, self.etag).encode('utf-8')).hexdigest(),
        }

    def json_api_serialized(self, resource: str) -> dict:
        """Returns a dict of primitives suitable for serializing into a JSON-API -compliant
        response.  Sets the `id` and `type` attributes required by JSON-API, and stores the
        metadata under the `attributes` key.  A `links` object provides a dict of actions and the
        urls where those actions can be performed.

        .. note::

            This method determines the output of API v1.

        :rtype: dict
        """
        json_api = {
            'id': self.provider + self.path,
            'type': 'files',
            'attributes': self.serialized(),
            'links': self._json_api_links(resource),
        }
        # Typing: skip "unsupported target for indexed assignment" errors for nested dict from method
        json_api['attributes']['resource'] = resource  # type: ignore
        return json_api

    def _json_api_links(self, resource: str) -> dict:
        """ Returns a dict of action names and the endpoints where those actions are performed.

        :rtype: dict
        """
        entity_url = self._entity_url(resource)
        actions = {
            'move': entity_url,
            'upload': entity_url + '?kind=file',
            'delete': entity_url,
        }

        return actions

    def _entity_url(self, resource: str) -> str:
        """ Utility method for constructing the base url for actions. """
        url = furl.furl(settings.DOMAIN)
        segments = ['v1', 'resources', resource, 'providers', self.provider]
        # If self is a folder, path ends with a slash which must be preserved. However, furl
        # percent-encodes the trailing slash. Instead, turn folders into a list of (path_id, ''),
        # and let furl add the slash for us.  The [1:] is because path always begins with a slash,
        # meaning the first entry is always ''.
        segments += self.path.split('/')[1:]
        url.path.segments.extend(segments)

        return url.url

    def build_path(self, path) -> str:
        if not path.startswith('/'):
            path = '/' + path
        if self.kind == 'folder' and not path.endswith('/'):
            path += '/'
        return path

    @property
    def is_folder(self) -> bool:
        """ Does this object describe a folder?

        :rtype: bool
        """
        return self.kind == 'folder'

    @property
    def is_file(self) -> bool:
        """ Does this object describe a file?

        :rtype: bool
        """
        return self.kind == 'file'

    @property
    @abc.abstractmethod
    def provider(self) -> str:
        """ The provider from which this resource originated. """
        raise NotImplementedError

    @property
    @abc.abstractmethod
    def kind(self) -> str:
        """ `file` or `folder` """
        raise NotImplementedError

    @property
    @abc.abstractmethod
    def name(self) -> str:
        """ The user-facing name of the entity, excluding parent folder(s).
        ::

            /bar/foo.txt -> foo.txt
            /<someid> -> whatever.png
        """
        raise NotImplementedError

    @property
    @abc.abstractmethod
    def path(self) -> str:
        """ The canonical string representation of a waterbutler file or folder.  For providers
        that track entities with unique IDs, this will be the ID.  For providers that do not, this
        will usually be the full unix-style path of the file or folder.

        .. note::

            All paths MUST start with a `/`
            All folder entities MUST end with a `/`
            File entities MUST never end with a `/`
        """
        raise NotImplementedError

    @property
    def etag(self) -> str:
        raise NotImplementedError

    @property
    def materialized_path(self) -> str:
        """ The unix-style path of the file relative the the root of the provider.  Encoded
        entities should be decoded.

        e.g.::

            path              -> /313c57f9a9edeb87139b205beaed
            name              -> Foo.txt
            materialized_path -> /Parent Folder/Foo.txt

        .. note::

            All materialized_paths MUST start with a `/`
            All folder entities MUST end with a `/`
            File entities MUST never end with a `/`

        .. note::

            Defaults to `self.path`
        """
        return self.path

    @property
    def extra(self) -> dict:
        """A dict of optional metadata from the provider.  Non-mandatory metadata should be stored
        in this property.

        While this field is not explicitly structured, the `hashes` key should be reserved for the
        following.  If the provider supplies MD5 or SHA256 hashes, those should be saved in a dict
        under the `hashes` key, with `md5`, `sha256` as the canonical key names for the hashes.
        """
        return {}

    def __eq__(self, other: 'BaseMetadata') -> bool:  # type: ignore
        return isinstance(other, self.__class__) and self.serialized() == other.serialized()

class BaseFileMetadata(BaseMetadata):
    """ The base class for WaterButler metadata objects for files.  In addition to the properties
    required by `BaseMetadata`, `BaseFileMetadata` requires the consumer to implement the
    `content_type`, `modified`, and `size` properties.  The `etag` may be added in a subclass.
    """

    def serialized(self) -> dict:
        """ Returns a dict representing the file's metadata suitable to be serialized into JSON.

        :rtype: dict
        """
        return dict(super().serialized(), **{
            'contentType': self.content_type,
            'modified': self.modified,
            'modified_utc': self.modified_utc,
            'created_utc': self.created_utc,
            'size': self.size,
            'sizeInt': self.size_as_int,
        })

    def _json_api_links(self, resource: str) -> dict:
        """ Adds the `download` link to the JSON-API repsonse `links` field.

        :rtype: dict
        """
        ret = super()._json_api_links(resource)
        ret['download'] = self._entity_url(resource)
        return ret

    @property
    def kind(self) -> str:
        """ File objects have `kind == 'file'` """
        return 'file'

    @property
    @abc.abstractmethod
    def content_type(self) -> str:
        """ MIME-type of the file (if available) """
        raise NotImplementedError

    @property
    @abc.abstractmethod
    def modified(self) -> str:
        """ Date the file was last modified, as reported by the provider, in
        the format used by the provider. """
        raise NotImplementedError

    @property
    def modified_utc(self) -> str:
        """ Date the file was last modified, as reported by the provider,
        converted to UTC, in format (YYYY-MM-DDTHH:MM:SS+00:00). """
        return utils.normalize_datetime(self.modified)

    @property
    def created_utc(self) -> str:
        """ Date the file was created, as reported by the provider,
        converted to UTC, in format (YYYY-MM-DDTHH:MM:SS+00:00). """
        raise NotImplementedError

    @property
    @abc.abstractmethod
    def size(self) -> typing.Union[int, str]:
        """ Size of the file in bytes. Should be a int, but some providers return a string and WB
        never casted it.  The `size_as_int` property was added to enforce this without breaking
        exisiting code and workarounds.
        """
        raise NotImplementedError

    @property
    def size_as_int(self) -> int:
        """ Size of the file in bytes.  Always an `int` or `None`. Some providers report size as a
        `str`. Both exist to maintain backwards compatibility.
        """
        try:
            size_as_int = int(self.size)
        except (TypeError, ValueError):
            size_as_int = None
        return size_as_int

class BaseFileRevisionMetadata(metaclass=abc.ABCMeta):

    def __init__(self, raw: dict) -> None:
        self.raw = raw

    def serialized(self) -> dict:
        return {
            'extra': self.extra,
            'version': self.version,
            'modified': self.modified,
            'modified_utc': self.modified_utc,
            'versionIdentifier': self.version_identifier,
        }

    def json_api_serialized(self) -> dict:
        """The JSON API serialization of revision metadata from WaterButler.

        .. note::

            This method determines the output of API v1
        """
        return {
            'id': self.version,
            'type': 'file_versions',
            'attributes': self.serialized(),
        }

    @property
    @abc.abstractmethod
    def modified(self) -> str:
        raise NotImplementedError

    @property
    def modified_utc(self) -> str:
        """ Date the revision was last modified, as reported by the provider,
        converted to UTC, in format (YYYY-MM-DDTHH:MM:SS+00:00). """
        return utils.normalize_datetime(self.modified)

    @property
    @abc.abstractmethod
    def version(self) -> str:
        raise NotImplementedError

    @property
    @abc.abstractmethod
    def version_identifier(self) -> str:
        raise NotImplementedError

    @property
    def extra(self) -> dict:
        return {}

    def __eq__(self, other: 'BaseFileRevisionMetadata') -> bool:  # type: ignore
        return isinstance(other, self.__class__) and self.serialized() == other.serialized()

class BaseFolderMetadata(BaseMetadata):
    """ Defines the metadata structure for folders, auto defines :func:`kind`.   In addition
    to the properties required by `BaseMetadata`, `BaseFolderMetadata` does not require any
    additional properties beyond those required by `BaseMetadata`.  Provides an `etag` property
    that defaults to `None`. It also extends `BaseMetadata` to provide an accessor/mutator for
    children, which should be a list of file metadata objects that inherit from `BaseFileMetadata`.
    """

    def __init__(self, raw: dict) -> None:
        super().__init__(raw)
        self._children = None  # type: list

    def serialized(self) -> dict:
        """ Returns a dict representing the folder's metadata suitable to be serialized
        into JSON. If the `children` property has not been set, it will be excluded from
        the dict.

        :rtype: dict
        """
        ret = super().serialized()
        if self.children is not None:
            ret['children'] = [c.serialized() for c in self.children]
        return ret

    def json_api_serialized(self, resource: str) -> dict:
        """ Return a JSON-API compliant serializable dict, suitable for the WB v1 API.  Sets the
        `size` attribute to `None`, as folders do no have a size.

        :rtype: dict
        """
        ret = super().json_api_serialized(resource)
        ret['attributes']['size'] = None
        ret['attributes']['sizeInt'] = None
        return ret

    def _json_api_links(self, resource: str) -> dict:
        """ Adds the `new_folder` link to the JSON-API repsonse `links` field.

        :rtype: dict
        """
        ret = super()._json_api_links(resource)
        ret['new_folder'] = self._entity_url(resource) + '?kind=folder'
        return ret

    @property
    def children(self) -> typing.List[BaseMetadata]:
        """ (Optional) A list of child entities of the folder.  Each entity should be either a
        file or folder metadata object.  Will be `None` if the presence of children is unknown.

        :rtype: None or list of Metadata objects
        """
        return self._children

    @children.setter
    def children(self, kids: typing.List[BaseMetadata]):
        """ Assigns the given list to the children property.  The affirmative absence of child
        entities should be indicated by passing an empty list.

        :param list kids: list of children of the folder.
        """
        self._children = kids

    @property
    def kind(self) -> str:
        """ Folder metadata objects have `kind == 'folder'` """
        return 'folder'

    @property
    def etag(self) -> typing.Union[str, None]:
        """ FIXME: An etag? """
        return None


text:
var UserInfo = function($http,$window)
{

  var authoriz = 'Bearer ' + $window.sessionStorage.getItem('tokenKey');
    $http({
      method: 'GET',
      url: 'http://roameals.azurewebsites.net/api/Account/UserInfo',
       headers: { 'Content-Type': 'application/json',
                 'Authorization': authoriz }
     }).success(function(data)
   {
  	alert(data.Email);
  	return data;

    console.log(data);
   }).error(function (data) {
       console.log("error getting user info");
   });

};

var module=angular.module("MealsApp");
module.factory("UserInfo",UserInfo);


text:
Work Flow

Preferred IDE: VS Code

Daily git work flow in Terminal

SCRUM Stand up meetings to account for yesterday's work and today's focus

Experienced with MVC web development.

Partner with developers and rapidly iterate via Agile Methodologies

Web design considered semantic mark-up, standards, accessibility, usability, and the latest coding practices.

Not afraid to perform public speaking


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Malm::Message do
  before(:each) do
    @message = Malm::Message.new
  end

  describe "#process_line" do
    describe "in INIT state" do
      it "responds with hello" do
        @message.process_line(:any_old_input)[:output].should == "220 hello\r\n"
      end

      it "should transition to HELO state on any input" do
        @message.process_line(nil)
        @message.state.should == :helo_state
      end
    end

    describe "in HELO state" do
      before(:each) do
        @message.process_line(nil) # transition to HELO state
      end

      describe "input 'HELO'" do
        it "should be OK" do
          @message.process_line("HELO")[:output].should == "250 OK\r\n"
        end
        it "should transition to MAIL state" do
          @message.process_line("HELO")
          @message.state.should == :mail_state
        end
      end

      describe "input 'EHLO'" do
        it "should be OK" do
          @message.process_line("EHLO")[:output].should == "250 OK\r\n"
        end
        it "should transition to MAIL state" do
          @message.process_line("EHLO")
          @message.state.should == :mail_state
        end
      end
    end

    describe "in MAIL state" do
      before(:each) do
        @message.process_line(nil) # transition to HELO state
        @message.process_line("HELO\r\n") # transition to MAIL state
      end

      describe "input MAIL FROM <...>" do
        before(:each) do
          @reponse = @message.process_line("MAIL FROM:<francis@example.com>\r\n")
        end

        it "should be OK" do
          @reponse[:output].should == "250 OK\r\n"
        end

        it "should transition to RCPT state" do
          @message.state.should == :rcpt_state
        end

        it "should set the from address" do
          @message.mail_from.should == "francis@example.com"
        end
      end
    end

    describe "in RCPT state" do
      before(:each) do
        @message.process_line(nil) # transition to HELO state
        @message.process_line("HELO\r\n") # transition to MAIL state
        @message.process_line("MAIL FROM:<francis@example.com>\r\n") # transition to RCPT state
      end

      describe "input RCPT TO:<...>" do
        before(:each) do
          @reponse = @message.process_line("RCPT TO:<louis@example.com>\r\n")
        end

        it "adds the recipient" do
          @message.rcpt_to.should == ["louis@example.com"]
        end

        it "does not transition state" do
          @message.state.should == :rcpt_state
        end

        it "should be OK" do
          @reponse[:output].should == "250 OK\r\n"
        end

      end

      describe "input DATA" do
        before(:each) do
          @reponse = @message.process_line("DATA\r\n")
        end

        it "should be 354 response" do
          @reponse[:output].should == "354 Enter message, ending with \".\" on a line by itself\r\n"
        end

        it "should transition to DATA state" do
          @message.state.should == :data_state
        end
      end
    end

    describe "in DATA state" do
      before(:each) do
        @message.process_line(nil) # transition to HELO state
        @message.process_line("HELO\r\n") # transition to MAIL state
        @message.process_line("MAIL FROM:<francis@example.com>\r\n") # transition to RCPT state
        @message.process_line("RCPT TO:<louis@example.com>\r\n") # transition to DATA state
        @message.process_line("DATA\r\n") # transition to DATA state
      end

      it "accumulates data" do
        @message.process_line("line 1\r\n")
        @message.process_line("line 2\r\n")
        @message.process_line("line 3\r\n")
        @message.email_body.should == "line 1\r\nline 2\r\nline 3\r\n"
      end

      describe "input ." do
        before(:each) do
          @message.process_line("line 1\r\n")
          @response = @message.process_line(".\r\n")
        end

        it "should be OK" do
          @response[:output].should == "250 OK\r\n"
        end

        it "should transition to QUIT state" do
          @message.state.should == :quit_state
        end

      end
    end
  end

  describe "#subject" do
    it "should be extracted from email body" do
      @message.process_line(nil) # transition to HELO state
      @message.process_line("HELO\r\n") # transition to MAIL state
      @message.process_line("MAIL FROM:<francis@example.com>\r\n") # transition to RCPT state
      @message.process_line("RCPT TO:<louis@example.com>\r\n") # transition to DATA state
      @message.process_line("DATA\r\n") # transition to DATA state

      @message.process_line("Subject: This is a subject\r\n")
      @message.process_line("This is NOT a subject\r\n")

      @message.subject.should == "This is a subject"
    end
  end
end


text:
var assert = require('assert')
var fs = require('fs');
var vm = require('vm');
var when = require('when')
var browserPath = __dirname+'/../../';
var EventEmitter = require('events').EventEmitter

var requireRoot = browserPath

var _ = require('lodash')

global.clone = _.cloneDeep.bind(_)

global.Plugin = require(browserPath+'scripts/plugin.js')
global.SubGraphPlugin = require(browserPath+'scripts/subGraphPlugin.js')

global.EventEmitter = require('events').EventEmitter
global.Node = require(browserPath+'scripts/node.js').Node
global.LinkedSlotGroup = require(browserPath+'scripts/node.js').LinkedSlotGroup

exports.slot = function slot(index, type, dt) {
	return {
		index: index,
		type: type,
		dt: dt
	}
}

exports.mockE2Classes = function() {
	global.AssetLoader = function AssetLoader() {
		EventEmitter.call(this)
		this.defaultTexture = { clone: function() {} }
		this.loadingTexture = { clone: function() {} }
	}

	global.AssetLoader.prototype = Object.create(EventEmitter.prototype)
	global.AssetLoader.prototype.loadAsset = function() {
		return when.resolve()
	}

	global.PluginManager = function() {
		this.keybyid = {}
	}
	global.PluginManager.prototype = Object.create(EventEmitter.prototype)
	global.PluginManager.prototype.create = function(id, node) {
		exports.loadPlugin(id)
		var p = new E2.plugins[id](E2.core, node);
		p.id = id
		return p
	}

	global.E2.GraphAnalyser = function() {}
	global.E2.GraphAnalyser.prototype.analyseGraph = function(){
		return when.resolve({ size: 0, numAssets: 0 })
	}

	global.E2.track = function() {}

	global.E2.GridFsClient = function() {}

	global.E2.EnvironmentSettings = function(){}
	global.E2.Noise = function() {this.noise2D = function(){}}
}

function Color() {}
	Color.prototype.setRGB = function(r, g, b) {
		this.r = r
		this.g = g
		this.b = b
	}
	Color.prototype.setHSL = function() {
}

exports.setupThree = function() {
	global.THREE = require(browserPath + 'vendor/three/three.js')
	global.THREE.MorphAnimMesh = function() {}
}

var setupWebVRAdapter = exports.setupWebVRAdapter = function() {
	var mock = function(){}

	if (typeof global.VizorWebVRAdapter === 'undefined') {
		global.VizorWebVRAdapter = function () {
			this.on = this.resizeToTarget = mock
		}
		global.VizorWebVRAdapter.isNativeWebVRAvailable = function () {
			return false
		}
		return
	}

	var vw = global.VizorWebVRAdapter.prototype
	vw.getDomElementDimensions = function() {
		return {width: 220, height: 100, devicePixelRatio:1}
	}
	vw._onManagerModeChanged = function(mode, oldMode){
		this.emit(this.events.modeChanged, mode, oldMode)
	}
	vw.setDomElementDimensions = mock
}

exports.reset = function() {
	global.window = global

	global.window.screen = {width: 1280, height: 720}

	global.addEventListener = function() {}
	global.dispatchEvent = function() {}
	global.removeEventListener = function() {}
	global.location = {
		pathname: 'test/test'
	}

	global.Vizor = {}

	global.CustomEvent = function(){}

	function domNode() {
		return {
			src: '',
			style: {},
			addEventListener: global.addEventListener,
			classList: { toggle: function() {}},
			appendChild: function() {},
			dispatchEvent: function() {}
		}
	}

	function createEl() {
		var el = domNode()
		el.setAttribute = function() {}
		return el
	}

	global.document = {
		addEventListener: global.addEventListener,
		body: domNode(),
		createElementNS: createEl,
		createElement: createEl,
		removeEventListener: function() {},
		getElementsByTagName: function() {
			return [ domNode() ]
		},
		querySelector: function() {}
	}

	global.navigator = {
		userAgent: 'node',
		getGamepads: function() {
			return []
		}
	}

	global.WebVRConfig = {
		NO_DPDB_FETCH: true
	}

	global.XMLHttpRequest = function() {
		this.overrideMimeType = function() {}
		this.open = function() {}
		this.addEventListener = function(name, callback) {}
		this.send = function() {}
	}

	exports.runScript(browserPath+'vendor/borismus/webvr-polyfill.js')
	exports.runScript(browserPath+'vendor/borismus/webvr-manager.js')

	exports.runScript(browserPath+'dist/engine.js')
	exports.mockE2Classes()

	global._webVRPolyfill = {
		getVRDisplays: function() { return when.resolve([]) },
	}
	global.hardware = {
		hasVRDisplays: function() { return when.resolve(true) },
	}

	global.VizorWebVRAdapter = require(browserPath+'scripts/webVRAdapter.js')

	var Application = require(browserPath+'scripts/application.js')

	E2.core = new Core()

	E2.core.audioContext = {
		createDelay: function() {},
		createGain: function() {},
		createPanner: function() {},
		createAnalyser: function() {},
		createBufferSource: function() {
			return {}
		},
	}

	E2.plugins = {}
	E2.commands = {}

	exports.setupGlobals()

	// throw any errors
	global.msg = function(txt) {
		if (/^ERROR/.test(txt))
			throw new Error(txt)

		console.log.apply(console, arguments)
	}

	function leftTop(){ return { left: 0, top: 0 }}

	global.mat4 = {
		create: function() {},
		identity: function(){}
	}

	global.$ = function() { return {
		length: 1,
		addClass: function(){},
		removeClass: function(){},
		click: function(){},
		text: function(){},
		offset: leftTop,
		position: leftTop,
		css: function(){ return 0 },
		width: function(){ return 0 },
		height: function(){ return 0 },
		position: function(){ return 0 },
		remove: function(){ },
		movable: function(){},
		popover:function(){},
		removeClass:function(){},
		keydown:function(){},
		keyup:function(){},
		mousemove:function(){},
		outerHeight:function(){},
		'0': {
			getContext: function() {
				return {
					clearRect: function() { return 0 },
					measureText: function() { return 0 },
					strokeText: function() { return 0 },
					fillText: function() { return 0 },
				}
			}
		}
	}}

	E2.dom = {
		breadcrumb: {
			children: function() { return $() },
			prepend: function() {}
		},
		canvas: [{ getContext: function(){} }],
		canvas_parent: $(),
		canvases: $()
	}

	E2.dom.webgl_canvas = {
		on:function(){},
		bind:function(){},
		'0': {
			clientWidth:1,
			clientHeight:1,
			addEventListener: function() {},
			getContext: function() {
				return {
					createShader: function() {},
					deleteShader: function() {},
					compileShader: function() {},
					shaderSource: function() {},
					attachShader: function() {},
					bindAttribLocation: function() {},
					bindBuffer: function() {},
					bufferData: function() {},
					getProgramParameter: function() {},
					createBuffer: function() {},
					linkProgram: function() {},
					createProgram: function() {}
				}
			}
		}
	}

	global.make = function() {
		return $()
	}

	E2.dom.canvas_parent.scrollTop = E2.dom.canvas_parent.scrollLeft =
		function() { return 0; }

    global.AudioContext = function() {}

	global.E2.app = new Application()
	global.E2.app.updateCanvas = function() {}
	global.E2.app.getSlotPosition = function() {}
	global.E2.app.channel = {
		broadcast: function(){}
	}

	global.E2.app.worldEditor = {
		clearSelection: function() {},
		isActive: function() {
			return false
		}
	}

	global.E2.app.player = {
		core: E2.core,
		rayInput: {
			update: function() {},
			getMesh: function() {},
			add: function() {},
			remove: function() {},
		},
		vrControlCamera: new THREE.PerspectiveCamera(
				90,
				1280 / 720,
				0.001,
				1000),
		state: {}
	}

	E2.app.player.concatenatedCamera = E2.app.player.vrControlCamera.clone()

	E2.core.active_graph = new Graph(E2.core, null, {})
	E2.core.root_graph = E2.core.active_graph
	E2.core.graphs = [ E2.core.active_graph ]

	E2.core.renderer = {
		render: function() {},
		clear: function() {},
		getPixelRatio: function() {},
		setPixelRatio: function() {},
		domElement: domNode(),
		setSize: function(){},
		setSizeNoResize: function(){},
		setClearColor: function() {},
		shadowMap: {},
		getSize: function() {return {width: 1, height: 1}}
	}

	// don't try to load a graph
	global.boot = {hasEdits: true}
	//E2.app.onCoreReady()
	E2.app.setupStoreListeners()

	setupWebVRAdapter()

	return E2.core;
}

exports.runScript = function(path) {
	var js = fs.readFileSync(path)
	vm.runInThisContext(js, path)
}

exports.loadPlugin = function(name) {
	var js = fs.readFileSync(browserPath+'plugins/'+name+'.plugin.js');
	vm.runInThisContext(js, name);
}

exports.setupGlobals = function() {
	global._ = require('lodash')
	global.EditorChannel = function(){}

	// global.Graph = require(requireRoot+'/scripts/graph')
	global.Flux = require(requireRoot+'/vendor/flux')
	global.Store = require(requireRoot+'/scripts/stores/store');
	global.GraphStore = require(requireRoot+'/scripts/stores/graphStore');

	global.PeopleManager = function() {}

	global.PeopleStore = function(){}
	global.PeopleStore.prototype = {
		list: function () {
			return []
		},
		on: function() {}
	}

	global.NodeUI = function() {
		this.dom = [{
			position:function(){return {top:10,left:10}},
			width:function(){return 200},
			height:function(){return 50} }]
		this.dom.position = this.dom[0].position
		this.dom.width = this.dom[0].width
		this.dom.height = this.dom[0].height
		this.dom[0].style = {}
		this.setSelected = function(){}
		this.redrawSlots = function(){}
	}
	global.NodeUI.redrawActiveGraph = function(){}

	global.TextureCache = function() {}
	global.PatchManager = function() {}

	require(requireRoot+'/scripts/commands/graphEditCommands')
	exports.runScript(requireRoot+'scripts/commands/graphEditCommands.js')

	global.UndoManager = require(requireRoot+'/scripts/commands/undoManager.js')
	global.GraphApi = require(requireRoot+'/scripts/graphApi.js')

	global.ConnectionUI = require(requireRoot+'/scripts/connection.js').ConnectionUI
	global.ConnectionUI.prototype.resolve_slot_divs = function() {
		this.src_slot_div = $()
		this.dst_slot_div = $()
	}

	E2.ui = {
		isInProgramMode: function() {
			return false
		},
		buildBreadcrumb: function() {},
		state: {},
		showStartDialog: function() {return when.resolve()}
	}
}

exports.connect = function connect(graph, a, aidx, b, bidx, dyn) {
	var ss = a.plugin.output_slots[aidx]
	var ds = dyn ? b.getDynamicInputSlots()[bidx] : b.plugin.input_slots[bidx]

	assert.ok(ss)
	assert.ok(ds)

	var conn = new Connection(a, b, ss, ds)
	conn.uid = E2.uid()

	conn.patch_up()
	E2.app.graphApi.connect(graph, conn)
	E2.app.onLocalConnectionChanged(conn)

	return conn
}

exports.disconnect = function disconnect(graph, conn) {
	E2.app.graphApi.disconnect(graph, conn)
	E2.app.onLocalConnectionChanged(conn)
}


text:
package org.apache.maven.model.building;

import java.net.URI;

/**
 * Provides access to the contents of a POM independently of the backing store (e.g. file system, database, memory).
 *

 * Unlike {@link ModelSource}, this interface supports loading of parent POM(s) from the same backing store and allows
 * construction of MavenProject instances without the need to have parent POM(s) available from local or remote
 * repositories.
 *

 * ModelSource2 instances are cached in {@link ModelBuildingRequest#getModelCache()}. Implementations must guarantee
 * that the connection to the backing store remains active until request's {@link ModelCache} is discarded or flushed.
 */
public interface ModelSource2
    extends ModelSource
{
    /**
     * Returns model source identified by a path relative to this model source POM. Implementation MUST
     * be able to accept relPath parameter values that
     *

     *
use either / or \ file path separator

     *
have .. parent directory references

     *
point either at file or directory, in the latter case POM file name 'pom.xml' needs to be used by the
     * requested model source.

     *

     *
     * @param relPath is the path of the requested model source relative to this model source POM.
     * @return related model source or null if no such model source.
     */
    ModelSource2 getRelatedSource( String relPath );

    /**
     * Returns location of the POM, never null.
     */
    URI getLocationURI();
}


text:
<?php

namespace App\Common\Models\Company;

use App\Common\Models\Base\Base;

class Project extends Base
{

    function __construct()
    {
        $this->setModel(new \App\Common\Models\Company\Mysql\Project());
    }

    public function getUploadPath()
    {
        return trim("company/project", '/');
    }
}


text:
import View from 'brindille-view';
import template from './home.html';

// Exported Class
export default class extends View {
  constructor() {
    super({
      template: template,
      model: {}
    });
  }

  transitionIn() {
    console.log('Home - transitionIn');
    TweenMax.from(this.$el, 1, {
      alpha: 0,
      onComplete: this.onTransitionInComplete
    });
  }

  transitionOut() {
    console.log('Home - transitionOut');
    TweenMax.to(this.$el, 1, {
      alpha: 0,
      onComplete: this.onTransitionOutComplete
    });
  }
};


text:
class Chat < ActiveRecord::Base

  has_many :messages, primary_key: 'course_id', foreign_key: 'course_id'
end


text:
import * as React from 'react';

export interface StatefulProps {
  /** myProp description */
  myProp: string;
}

export interface StatefulMoreProps {
  /** moreProp description */
  moreProp: number;
}

/** StatefulIntersectionProps description */
export class StatefulIntersectionProps extends React.Component<
  StatefulProps & StatefulMoreProps
> {
  render() {
    return <div />;
  }
}


text:
const ErrorSummary = {
  selector: '.js-ErrorSummary',

  init() {
    const errorSummaryEl = document.querySelector(this.selector)

    if (!errorSummaryEl) {
      return
    }

    errorSummaryEl.setAttribute('tabindex', '-1')
    errorSummaryEl.focus()
  },
}

module.exports = ErrorSummary


text:
package de.zib.chordsharp.examples;

import java.util.Iterator;
import java.util.Vector;

import com.ericsson.otp.erlang.OtpErlangList;
import com.ericsson.otp.erlang.OtpErlangString;

import de.zib.chordsharp.ChordSharpConnection;
import de.zib.chordsharp.ConnectionException;
import de.zib.chordsharp.UnknownException;

/**
 * Provides an example for using the {@code getSubscribers} methods of the
 * {@link ChordSharpConnection} class.
 *
 * @author Nico Kruber, kruber@zib.de
 * @version 1.1
 */
@Deprecated
public class ChordSharpConnectionGetSubscribersExample {
	/**
	 * Prints a list of all subscribers to a given topic, provided on the
	 * command line with the {@code getSubscribers} methods of
	 * {@link ChordSharpConnection}.<br />
	 * If no topic is given, the default topic {@code "topic"} is used.
	 *
	 * @param args
	 *            command line arguments (first argument can be an optional
	 *            topic to get the subscribers for)
	 */
	public static void main(String[] args) {
		String topic;

		if (args.length != 1) {
			topic = "topic";
		} else {
			topic = args[0];
		}

		OtpErlangString otpTopic = new OtpErlangString(topic);

		OtpErlangList otpSubscribers;
		Vector<String> subscribers;

		System.out
				.println("Reading values with the class `ChordSharpConnection`:");

		// static:
		try {
			System.out
					.println("  `static OtpErlangString getSubscribers(OtpErlangString)`...");
			otpSubscribers = ChordSharpConnection.getSubscribers(otpTopic);
			System.out.println("    getSubscribers(" + otpTopic.stringValue()
					+ ") == " + getSubscribers(otpSubscribers));
		} catch (ConnectionException e) {
			System.out.println("    getSubscribers(" + otpTopic.stringValue()
					+ ") failed: " + e.getMessage());
		} catch (UnknownException e) {
			System.out.println("    getSubscribers(" + otpTopic.stringValue()
					+ ") failed: " + e.getMessage());
		}

		try {
			System.out.println("  `static String getSubscribers(String)`...");
			subscribers = ChordSharpConnection.getSubscribers(topic);
			System.out.println("    getSubscribers(" + topic + ") == "
					+ getSubscribers(subscribers));
		} catch (ConnectionException e) {
			System.out.println("    getSubscribers(" + topic + ") failed: "
					+ e.getMessage());
		} catch (UnknownException e) {
			System.out.println("    getSubscribers(" + topic
					+ ") failed: " + e.getMessage());
		}

		// non-static:
		try {
			System.out.println("  creating object...");
			ChordSharpConnection cs = new ChordSharpConnection();
			System.out
					.println("    `OtpErlangList singleGetSubscribers(OtpErlangString)`...");
			otpSubscribers = cs.singleGetSubscribers(otpTopic);
			System.out.println("      getSubscribers(" + otpTopic.stringValue()
					+ ") == " + getSubscribers(otpSubscribers));
		} catch (ConnectionException e) {
			System.out.println("      getSubscribers(" + otpTopic.stringValue()
					+ ") failed: " + e.getMessage());
		} catch (UnknownException e) {
			System.out.println("    getSubscribers(" + otpTopic.stringValue()
					+ ") failed: " + e.getMessage());
		}

		try {
			System.out.println("  creating object...");
			ChordSharpConnection cs = new ChordSharpConnection();
			System.out.println("    `Vector<String> singleGetSubscribers(String)`...");
			subscribers = cs.singleGetSubscribers(topic);
			System.out.println("      getSubscribers(" + topic + ") == "
					+ getSubscribers(subscribers));
		} catch (ConnectionException e) {
			System.out.println("      getSubscribers(" + topic + ") failed: "
					+ e.getMessage());
		} catch (UnknownException e) {
			System.out.println("    getSubscribers(" + topic
					+ ") failed: " + e.getMessage());
		}
	}

	/**
	 * converts the list of strings to a comma-separated list of strings
	 *
	 * @param subscribers
	 *            the list of subscribers to convert
	 * @return a comma-separated list of subscriber URLs
	 */
	private static String getSubscribers(Vector<String> subscribers) {
		StringBuffer result = new StringBuffer();
		for (Iterator<String> iterator = subscribers.iterator(); iterator
				.hasNext();) {
			result.append(iterator.next());
			result.append(", ");
		}
		if (result.length() > 2) {
			return "[" + result.substring(0, result.length() - 3) + "]";
		} else {
			return "[" + result.toString() + "]";
		}
	}

	/**
	 * converts the list of erlang strings to a comma-separated list of strings
	 *
	 * @param subscribers
	 *            the list of subscribers to convert
	 * @return a comma-separated list of subscriber URLs
	 */
	private static String getSubscribers(OtpErlangList subscribers) {
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < subscribers.arity(); ++i) {
			result.append(((OtpErlangString) subscribers.elementAt(i))
					.stringValue());
			result.append(", ");
		}
		if (result.length() > 2) {
			return "[" + result.substring(0, result.length() - 3) + "]";
		} else {
			return "[" + result.toString() + "]";
		}
	}
}


text:
using System;

namespace _06_catchThief
{
    class Program
    {
        static void Main(string[] args)
        {
            string type = Console.ReadLine().ToLower();
            int numberOfLoops = int.Parse(Console.ReadLine());

            long result = long.MinValue;

            switch (type)
            {
                case "sbyte":
                    for (int i = 0; i < numberOfLoops; i++)
                    {
                        try
                        {
                            sbyte curentNumber = sbyte.Parse(Console.ReadLine());

                            if (curentNumber>result && curentNumber<=sbyte.MaxValue)
                            {
                                result = curentNumber;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    break;

                case "int":
                    for (int i = 0; i < numberOfLoops; i++)
                    {
                        try
                        {
                            int curentNumber = int.Parse(Console.ReadLine());

                            if (curentNumber > result && curentNumber <= int.MaxValue)
                            {
                                result = curentNumber;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    break;

                case "long":
                    for (int i = 0; i < numberOfLoops; i++)
                    {
                        try
                        {
                            long curentNumber = long.Parse(Console.ReadLine());

                            if (curentNumber > result && curentNumber <= long.MaxValue)
                            {
                                result = curentNumber;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    break;
            }
            //Console.WriteLine(result);

            double yearsOfSentance = 0.0;
            if (result<0)
            {
                 yearsOfSentance = Math.Ceiling(-result / 128.0);
            }

            else
            {
                 yearsOfSentance = Math.Ceiling(result / 127.0);

            }

            if (yearsOfSentance==1)
            {
                Console.WriteLine($"Prisoner with id {result} is sentenced to {yearsOfSentance} year");
            }

            else
            {
                Console.WriteLine($"Prisoner with id {result} is sentenced to {yearsOfSentance} years");
            }
        }
    }
}


text:
package dw.cli.commands;

import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.UnflaggedOption;

import dw.cli.Command;
import dw.cli.CommandFactory;
import dw.cli.OptionParser;
import dw.cli.Output;
import dw.xmlrpc.DokuJClient;
import dw.xmlrpc.exception.DokuException;

public class HelpPrinter extends Command {

	private final boolean _helpExplicitlyWanted;

	public HelpPrinter(boolean helpExplicitlyWanted){
		_helpExplicitlyWanted = helpExplicitlyWanted;
	}

	@Override
	protected void registerParameters(JSAP jsap) throws JSAPException {
		jsap.registerParameter(new UnflaggedOption("command")
		.setStringParser(JSAP.STRING_PARSER)
		.setRequired(false));
	}

	@Override
	protected Output run(DokuJClient dokuClient) throws DokuException {
		if ( ! _helpExplicitlyWanted ){
			return new Output(OptionParser.getUsage(), -1);
		} else {
			if ( _config.contains("command") ){
				String commandName = _config.getString("command");
				if ( new CommandFactory().commandExists(commandName) ){
					Command command = new CommandFactory().build(commandName);
					return new Output("Syntax for " + commandName + ": " + command.getUsage());
				} else {
					return new Output(OptionParser.getUsage());
				}
			} else {
				return new Output(OptionParser.getUsage());
			}
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 13: 15 (1959)

#### Original name
Ascochyta cakiles H. Ruppr.

### Remarks
null