text:
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Cecil;

namespace Stratis.SmartContracts.CLR.Compilation
{
    /// <summary>
    /// Resolver for .NET Core assemblies used in a
    /// <see cref="Mono.Cecil.ModuleDefinition"/>
    /// </summary>
    public class DotNetCoreAssemblyResolver : IAssemblyResolver
    {
        //ref: https://github.com/jbevain/cecil/issues/306

        private static readonly string BaseDirectory = System.AppContext.BaseDirectory;
        private static readonly string RuntimeDirectory = Path.GetDirectoryName(typeof(object).Assembly.Location);

        private readonly Dictionary<string, AssemblyDefinition> libraries;

        public DotNetCoreAssemblyResolver()
        {
            this.libraries = new Dictionary<string, AssemblyDefinition>();
        }

        // IAssemblyResolver API

        public AssemblyDefinition Resolve(AssemblyNameReference name)
        {
            return this.Resolve(name, new ReaderParameters() { AssemblyResolver = this });
        }

        public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            AssemblyDefinition def;
            if (!this.libraries.TryGetValue(name.Name, out def))
            {
                string path = Path.Combine(BaseDirectory, $"{name.Name}.dll");

                if (File.Exists(path))
                {
                    def = AssemblyDefinition.ReadAssembly(path, parameters);
                    this.libraries.Add(name.Name, def);
                }
                else
                {
                    path = Path.Combine(RuntimeDirectory, $"{name.Name}.dll");
                    if (File.Exists(path))
                    {
                        def = AssemblyDefinition.ReadAssembly(path, parameters);
                        this.libraries.Add(name.Name, def);
                    }
                    else
                    {
                        path = $"{name.Name}.dll";
                        if (File.Exists(path))
                        {
                            def = AssemblyDefinition.ReadAssembly(path, parameters);
                            this.libraries.Add(name.Name, def);
                        }
                    }
                }
            }
            return def;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            foreach (AssemblyDefinition def in this.libraries.Values)
            {
                def.Dispose();
            }
        }

        public void Dispose()
        {
            this.Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }

    public static class AssemblyResolverExtensions
    {
        public static AssemblyDefinition Resolve(this IAssemblyResolver resolver, string fullName)
        {
            return resolver.Resolve(fullName, new ReaderParameters() { AssemblyResolver = resolver });
        }

        public static AssemblyDefinition Resolve(this IAssemblyResolver resolver, string fullName, ReaderParameters parameters)
        {
            if (fullName == null)
            {
                throw new ArgumentNullException(nameof(fullName));
            }
            return resolver.Resolve(AssemblyNameReference.Parse(fullName), parameters);
        }

    }
}


text:
@implementation NSArray (AKTArray)
- (id)objectMaybeAtIndex:(NSUInteger)index {
    if (index<self.count) {
        return self[index];
    }
    return nil;
}
@end

@implementation NSMutableArray (AKTArray)
- (void)addOptionalObject:(id)object {
    if (object) {
        [self addObject:object];
    }
}

- (void)insertOptionalObjet:(id)object maybeAtIndex:(NSUInteger)index {
    if (object
        && (index<=self.count)) {
        [self insertObject:object atIndex:index];
    }
}

- (void)removeObjectMaybeAtIndex:(NSUInteger)index {
    if (index<self.count) {
        [self removeObjectAtIndex:index];
    }
}
@end

redpajama_set_name: RedPajamaGithub


text:
@interface THPlayerView ()
@property (strong, nonatomic) THOverlayView *overlayView;                   // 1
@end

@implementation THPlayerView

+ (Class)layerClass {                                                       // 2
    return [AVPlayerLayer class];
}

- (id)initWithPlayer:(AVPlayer *)player {
    self = [super initWithFrame:CGRectZero];                                // 3
    if (self) {
        self.backgroundColor = [UIColor blackColor];
        self.autoresizingMask = UIViewAutoresizingFlexibleHeight |
                                UIViewAutoresizingFlexibleWidth;

        [(AVPlayerLayer *) [self layer] setPlayer:player];                  // 4

        [[NSBundle mainBundle] loadNibNamed:@"THOverlayView"                // 5
                                      owner:self
                                    options:nil];

        [self addSubview:_overlayView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.overlayView.frame = self.bounds;
}

- (id <THTransport>)transport {
    return self.overlayView;
}

@end


text:
package myProject.servlets.test.db;

import myProject.db.DB;
import myProject.util.RequestResponseHelper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//http://infinite-peak-27151.herokuapp.com/ExecuteQueryServlet?query=select * from MAIN_TABLE
//select * from AVATAR_TABLE_NAME
//select * from MAIN_TABLE, AVATAR_TABLE_NAME where LOGIN != 'zz' and AVATAR_ID_COLUMN = 'treww';
//select * from AVATAR_TABLE_NAME where AVATAR_ID_COLUMN = 'treww';
public class ExecuteQueryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryString = req.getParameter("query");
        resp.getWriter().println("got query = " + queryString);
        int i = 1;
        try (Connection connection = DB.getConnection()) {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(queryString);
            while (resultSet.next()) {
                try {
                    do {
                        String string = resultSet.getString(i++);
                        resp.getWriter().println(resultSet.getMetaData().getColumnName(i - 1) + " = " + string + " | ");
                    } while (true);
                } catch (SQLException sqlException) {
                    //Do nothing
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


text:
package org.elasticsearch.xpack.sql.action;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.xpack.sql.proto.Mode;
import org.elasticsearch.xpack.sql.proto.RequestInfo;
import org.elasticsearch.xpack.sql.proto.SqlVersion;

import java.io.IOException;
import java.util.Objects;

import static org.elasticsearch.action.ValidateActions.addValidationError;

/**
 * Base request for all SQL-related requests.
 * <p>
 * Contains information about the client mode that can be used to generate different responses based on the caller type.
 */
public abstract class AbstractSqlRequest extends ActionRequest implements ToXContent {

    private RequestInfo requestInfo;

    protected AbstractSqlRequest() {
        this.requestInfo = new RequestInfo(Mode.PLAIN);
    }

    protected AbstractSqlRequest(RequestInfo requestInfo) {
        this.requestInfo = requestInfo;
    }

    protected AbstractSqlRequest(StreamInput in) throws IOException {
        super(in);
        Mode mode = in.readEnum(Mode.class);
        String clientId = in.readOptionalString();
        String clientVersion = in.readOptionalString();
        requestInfo = new RequestInfo(mode, clientId, clientVersion);
    }

    @Override
    public ActionRequestValidationException validate() {
        ActionRequestValidationException validationException = null;
        if (requestInfo == null || requestInfo.mode() == null) {
            validationException = addValidationError("[mode] is required", validationException);
        }
        return validationException;
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeEnum(requestInfo.mode());
        out.writeOptionalString(requestInfo.clientId());
        out.writeOptionalString(requestInfo.version() == null ? null : requestInfo.version().toString());
    }

    public RequestInfo requestInfo() {
        return requestInfo;
    }

    public void requestInfo(RequestInfo requestInfo) {
        this.requestInfo = requestInfo;
    }

    public Mode mode() {
        return requestInfo.mode();
    }

    public void mode(Mode mode) {
        this.requestInfo.mode(mode);
    }

    public void mode(String mode) {
        this.requestInfo.mode(Mode.fromString(mode));
    }

    public String clientId() {
        return requestInfo.clientId();
    }

    public void clientId(String clientId) {
        this.requestInfo.clientId(clientId);
    }

    public void version(String clientVersion) {
        requestInfo.version(clientVersion);
    }

    public SqlVersion version() {
        return requestInfo.version();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        AbstractSqlRequest that = (AbstractSqlRequest) o;
        return Objects.equals(requestInfo, that.requestInfo);
    }

    @Override
    public int hashCode() {
        return requestInfo.hashCode();
    }

}


text:
export = BackupEventReader;
declare function BackupEventReader(): void;
declare class BackupEventReader {
    peekEvent(): any;
    popEvent(): any;
}
declare namespace BackupEventReader {
    const BACKUP_DONE: number;
    const BACKUP_INVALID: number;
    const DB_DROPPED: number;
    const BACKUP_RESTORED: number;
    const BACKUP_FAIL: number;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-test</artifactId>
        <version>8.0-SNAPSHOT</version>
        <relativePath>../..</relativePath>
    </parent>
    <artifactId>vaadin-test-jsp-integration</artifactId>
    <name>vaadin-test-jsp-integration</name>
    <packaging>war</packaging>

    <dependencies>

        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-client-compiled</artifactId>
        </dependency>

        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-uitest-common</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
require 'base64'

unless ARGV.length == 1
  puts "Please pass 1 string to decrypt"
  exit (1)
end

puts Base64.decode64(ARGV[0])


text:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Seminar</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

Department of Mathematics

Indian Institute of Science

Bangalore 560 012

GRADUATE SEMINAR

 Speaker

:

    Prof. Phoolan Prasad

    Affiliation

:

IISc, (Graduate Seminar)

 Subject Area

:

Mathematics

 Venue

:

Lecture Hall I, Dept of Mathematics

 Time

:

4.00
pm

Date

:

    Tuesday, 18th April, 2006

    Event Title1

    :

" Extended Lemma on Bicharacteristics "

    Abstract

     Courant and Hilbert (1962) has an
    important result "Lemma on Bicharacteristic Directions" which is quoted
    frequently in the theory of wave propagation in multi-dimensions. We first
    state a general criterion for a vector to be a ray vector and use it to show
    that a bicharacteristic direction gives a ray direction. Next we generalize
    the lemma to include some additional equations i.e., the full ray equations
    and thecompatibility condition along the bicharacteristics.


text:
from datetime import timedelta

from django.core.management import BaseCommand, CommandError

from timers.models import Timer

class Command(BaseCommand):
    help = (
        'Change a timer\'s nth interval start/end time by the given number '
        'of minutes.'
        'Usage:\n'
        '  ./manage.py change_interval <timer> <n> (start|end) (+|-) <minutes>'
    )

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            'timer',
            help='The name of the timer whose nth interval should be changed.',
        )
        parser.add_argument(
            'n',
            type=int,
            help='The nth most recent interval to adjust; 0 = most recent.',
        )
        parser.add_argument(
            'start_or_end',
            choices=('start', 'end'),
            help='Whether to adjust the start or end of the interval.',
        )
        parser.add_argument(
            'plus_or_minus',
            choices=('+', '-'),
            help='Whether to adjust the interval forward or backward.',
        )
        parser.add_argument(
            'delta',
            type=int,
            help='Number of minutes to add or subtract.',
        )

    def handle(self, **options):
        timer_name = options['timer']
        n = int(options['n'])

        s_or_e = options['start_or_end']
        adjust_start = s_or_e == 'start'

        p_or_m = options['plus_or_minus']
        later = p_or_m == '+'
        back_or_forward = 'forward' if p_or_m == '+' else 'back'

        delta = int(options['delta'])

        try:
            timer = Timer.objects.get(name=timer_name)
        except Timer.DoesNotExist:
            raise CommandError(
                'Could not find a Timer name "{0}".'
                .format(timer_name)
            )
        except Timer.MultipleObjectsReturned:
            raise CommandError(
                'Found multiple timers named "{0}"... sorry!'
                .format(timer_name)
            )

        try:
            interval = timer.interval_set.all()[n]
        except IndexError:
            raise CommandError('Could not find the requested interval.')

        self.stdout.write(
            'Would adjust the "{timer}" interval[{n}] '
            '{start_or_end} time {back_or_forward} by {delta} minutes.'
            .format(
                timer=timer_name,
                n=n,
                start_or_end=s_or_e,
                back_or_forward=back_or_forward,
                delta=delta,
            )
        )

        self.stdout.write(
            'Current interval timespan...\n'
            '   start: {0}\n'
            '     end: {1}\n'
            '  length: {2}\n'
            .format(interval.start, interval.end, interval.length)
        )

        diff = timedelta(minutes=delta)
        if adjust_start:
            if later:
                interval.start += diff
            else:
                interval.start -= diff
        else:
            if later:
                interval.end += diff
            else:
                interval.end -= diff

        self.stdout.write(
            'New interval timespan...\n'
            '   start: {0}\n'
            '     end: {1}\n'
            '  length: {2}'
            .format(interval.start, interval.end, interval.length)
        )

        confirm = input('Save this change (y/n)? ')
        if confirm == 'y':
            interval.save()


text:
ficdl-ruby
==========

ficdl in ruby.  A learning exercise.


text:
BSLS_IDENT_RCSID(bblscm_version_cpp,"$Id$ $CSID$")

namespace BloombergLP {

#define BBL_VERSION_PATCH 0

#define STRINGIFY2(a) #a
#define STRINGIFY(a) STRINGIFY2(a)

#define BBLSCM_VERSION_STRING "BLP_LIB_BBL_BBL_" STRINGIFY(BBL_VERSION_MAJOR) \
                                             "." STRINGIFY(BBL_VERSION_MINOR) \
                                             "." STRINGIFY(BBL_VERSION_PATCH)

const char *bblscm::Version::s_ident = "$Id: " BBLSCM_VERSION_STRING " $";
const char *bblscm::Version::s_what  = "@(#)"  BBLSCM_VERSION_STRING;

const char *bblscm::Version::BBLSCM_S_VERSION    = BBLSCM_VERSION_STRING;
const char *bblscm::Version::s_dependencies      = "";
const char *bblscm::Version::s_buildInfo         = "";
const char *bblscm::Version::s_timestamp         = "";
const char *bblscm::Version::s_sourceControlInfo = "";

}  // close enterprise namespace

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


text:
package model

import (
	"testing"

	"github.com/boltdb/bolt"
	"github.com/stretchr/testify/assert"
	"time"
	"flag"
)

func TestNewHeartbeat(t *testing.T) {
	assert := assert.New(t)

	hb := NewHeartbeat("ApiKeyID555")
	assert.NotNil(hb)
	assert.NotNil(hb.ID)
	assert.NotNil(hb.CreatedAt)
}

func TestListHeartbeats(t *testing.T) {
	RunInTestDb(t, func(t *testing.T, db *bolt.DB) {
		assert := assert.New(t)

		// should be empty
		heartbeats, err := ListHeartbeats(db, "foo")
		assert.NoError(err)
		assert.NotNil(heartbeats)
		assert.True(len(*heartbeats) == 0)

		// add a heartbeat
		h1 := NewHeartbeat("APIKeyID1")
		err = h1.Save(db, "foo")
		assert.NoError(err)

		// should be one Heartbeat
		heartbeats, err = ListHeartbeats(db, "foo")
		assert.NoError(err)
		assert.NotNil(heartbeats)
		assert.True(len(*heartbeats) == 1)
		assert.Equal(*h1, (*heartbeats)[h1.ID])

		// add another Heartbeat
		h2 := NewHeartbeat("APIKeyID2")
		err = h2.Save(db, "foo")
		assert.NoError(err)

		// should be two heartbeats
		heartbeats, err = ListHeartbeats(db, "foo")
		assert.NoError(err)
		assert.NotNil(heartbeats)
		assert.True(len(*heartbeats) == 2)
		assert.Equal(*h1, (*heartbeats)[h1.ID])
		assert.Equal(*h2, (*heartbeats)[h2.ID])
	})
}

func TestLatestHeartbeats(t *testing.T) {
	flag.Lookup("logtostderr").Value.Set("true")

	RunInTestDb(t, func(t *testing.T, db *bolt.DB) {
		assert := assert.New(t)

		// should be empty
		heartbeats, err := LatestHeartbeatPerApiKey(db, "foo")
		assert.NoError(err)
		assert.NotNil(heartbeats)
		assert.True(len(*heartbeats) == 0)

		// add a heartbeat
		h1 := NewHeartbeat("APIKeyID1")
		h1.ExecutedAt = time.Now().Add(-10 * time.Minute)
		err = h1.Save(db, "foo")
		assert.NoError(err)

		// should be one Heartbeat
		heartbeats, err = LatestHeartbeatPerApiKey(db, "foo")
		assert.NoError(err)
		assert.NotNil(heartbeats)
		assert.True(len(*heartbeats) == 1)
		assert.Equal(*h1, (*heartbeats)[h1.ID])

		// add another heartbeat with the same api key
		h2 := NewHeartbeat("APIKeyID1")
		h2.ExecutedAt = time.Now()
		err = h2.Save(db, "foo")
		assert.NoError(err)

		// should be still be just one heartbeats, but should be the latest one i.e. h2
		heartbeats, err = LatestHeartbeatPerApiKey(db, "foo")
		assert.NoError(err)
		assert.NotNil(heartbeats)
		assert.True(len(*heartbeats) == 1)
		assert.Equal(*h2, (*heartbeats)[h2.ID])

		// add another heartbeat with the another api key
		h3 := NewHeartbeat("APIKeyID2")
		h3.ExecutedAt = time.Now()
		err = h3.Save(db, "foo")
		assert.NoError(err)

		// should be two heartbeats
		heartbeats, err = LatestHeartbeatPerApiKey(db, "foo")
		assert.NoError(err)
		assert.NotNil(heartbeats)
		assert.True(len(*heartbeats) == 2)
		assert.Equal(*h2, (*heartbeats)[h2.ID])
		assert.Equal(*h3, (*heartbeats)[h3.ID])
	})
}


text:
.coloreditor {
  width: 642px;
  display: inline-block;
}
.coloreditor button {
  outline: none;
}
.coloreditor-result {
  min-height: 40px;
  word-break: break-all;
  padding: 12px;
  padding-bottom: 10px;
  box-sizing: border-box;
  background: #F7F7F7;
  font-family: monospace;
  border-bottom-left-radius: 3px;
  border-bottom-right-radius: 3px;
}
.coloreditor-result:after {
  content: ".";
  clear: both;
  display: block;
  visibility: hidden;
  height: 0px;
}
.coloreditor-result .coloreditor-code {
  border: 1px solid #d1cacd;
  background: #FFFEFE;
  padding: 12px;
  min-height: 30px;
  max-height: 150px;
  overflow-y: scroll;
}
.coloreditor-result .highlight {
  background: #E2E2E2;
  border-radius: 3px;
  display: inline-block;
  padding: 0 3px;
  margin: 0 2px;
  box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.22);
}
.coloreditor-editable {
  min-height: 80px;
  max-height: 150px;
  overflow: scroll;
  padding: 12px;
  box-sizing: border-box;
  background: #29160f;
  color: #fff;
  font-family: Arial;
  font-size: 18px;
  outline: none;
  word-break: break-all;
}
.coloreditor-buttons {
  padding: 8px;
  background: #F7F7F7;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
}
.coloreditor-buttons ul {
  padding: 0;
  margin: 0;
}
.coloreditor-buttons li {
  list-style: none;
  margin: 0;
  padding: 0;
  display: inline-block;
  vertical-align: top;
  margin-right: 5px;
}
.coloreditor-buttons li:last-child {
  margin-right: 0;
}
.coloreditor-formatbutton,
.coloreditor-colorbutton {
  display: block;
  width: 25px;
  height: 25px;
  border: none;
  background: #f9f9f9;
  color: #444;
  text-align: center;
  line-height: 25px;
  padding: 0;
  box-sizing: border-box;
  font-size: 15px;
  box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.1);
  border-radius: 3px;
  text-transform: uppercase;
  -webkit-transition: background 0.2s, box-shadow 0.3s, -webkit-transform 0.2s, opacity 0.2s;
  transition: background 0.2s, box-shadow 0.3s, transform 0.2s, opacity 0.2s;
}
.coloreditor-formatbutton:hover,
.coloreditor-colorbutton:hover {
  box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.25);
}
.coloreditor-formatbutton:active,
.coloreditor-colorbutton:active {
  -webkit-transform: translate(0, 2px);
  -ms-transform: translate(0, 2px);
  transform: translate(0, 2px);
}
.coloreditor-formatbutton:hover {
  background: #ffffff;
}
.coloreditor-colorbutton {
  background: transparent;
}
.coloreditor-colorbutton:hover {
  opacity: 0.75;
  box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.25);
}
.coloreditor-prefix {
  float: right;
  padding-top: 5px;
}
.coloreditor-prefix button {
  border: 1px solid rgba(209, 202, 205, 0);
  border: none;
  background: transparent;
  height: 26px;
  padding: 0 12px;
  margin-left: 1px;
  margin: 0;
  color: #555;
  -webkit-transition: color 0.2s, background 0.1s, box-shadow 0.2s, -webkit-transform 0.1s;
  transition: color 0.2s, background 0.1s, box-shadow 0.2s, transform 0.1s;
  border-radius: 3px;
  margin-left: 6px;
}
.coloreditor-prefix button:hover {
  color: #111;
  background: rgba(209, 202, 205, 0.3);
}
.coloreditor-prefix button.active {
  background: #f9f9f9;
  color: #111;
  box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.1);
}
.coloreditor-prefix button:active {
  -webkit-transform: translate(0, 2px);
  -ms-transform: translate(0, 2px);
  transform: translate(0, 2px);
}


text:
<?php
/**
 * Cross - a micro PHP 5 framework
 *
 * @link        http://www.crossphp.com
 * @license     MIT License
 */
namespace Cross\DB\Connecter;

use Cross\Exception\CoreException;
use Exception;
use PDO;

/**
 * @Auth: wonli <wonli@live.com>
 * Class PgSQLConnecter
 * @package Cross\DB\Connecter
 */
class PgSQLConnecter extends BaseConnecter
{
    /**
     * 数据库连接实例
     *
     * @var object
     */
    private static $instance;

    /**
     * 默认连接参数
     *
     * @var array
     */
    private static $options = array();

    /**
     * 创建PgSQL的PDO连接
     *
     * @param string $dsn dsn
     * @param string $user 数据库用户名
     * @param string $password 数据库密码
     * @param array $options
     * @throws CoreException
     */
    private function __construct($dsn, $user, $password, array $options = array())
    {
        try {
            $this->pdo = new PDO($dsn, $user, $password, parent::getOptions(self::$options, $options));
        } catch (Exception $e) {
            throw new CoreException($e->getMessage());
        }
    }

    /**
     * @see MysqlModel::__construct
     * @param string $dsn
     * @param string $user
     * @param string $password
     * @param array $option
     * @return mixed
     */
    static function getInstance($dsn, $user, $password, array $option = array())
    {
        //同时建立多个连接时候已dsn的md5值为key
        $key = md5($dsn);
        if (!isset(self::$instance[$key])) {
            self::$instance [$key] = new self($dsn, $user, $password, $option);
        }

        return self::$instance [$key];
    }

    /**
     * 返回PDO连接的实例
     *
     * @return PDO
     */
    public function getPDO()
    {
        return $this->pdo;
    }

    /**
     * 获取表的主键名
     *
     * @param string $table_name
     * @return bool
     */
    public function getPK($table_name)
    {
        $table_info = $this->getMetaData($table_name, false);
        foreach ($table_info as $info) {
            if ($info['contype'] == 'p') {
                return $info['column_name'];
            }
        }
        return false;
    }

    /**
     * 获取最后插入时的ID
     *
     * @return mixed
     */
    public function lastInsertId()
    {
        $sql = "SELECT LASTVAL() as insert_id";
        try {
            $data = $this->pdo->query($sql)->fetch(PDO::FETCH_ASSOC);;
            return $data['insert_id'];
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 获取表的字段信息
     *
     * @param string $table
     * @param bool $fields_map
     * @return array
     */
    function getMetaData($table, $fields_map = true)
    {
        $sql = "select a.column_name, a.is_nullable, a.column_default, p.contype from (
                    select i.column_name, i.is_nullable, i.column_default, i.ordinal_position, c.oid
                    from information_schema.columns i left join pg_class c on c.relname=i.table_name
                    where i.table_name='{$table}'
                ) a left join pg_constraint p on p.conrelid=a.oid and a.ordinal_position = ANY (p.conkey)";

        try {
            $data = $this->pdo->query($sql);
            if ($fields_map) {
                $result = array();
                $data->fetchAll(PDO::FETCH_FUNC, function ($column_name, $is_null, $column_default, $con_type) use (&$result) {
                    $auto_increment = preg_match("/nextval\((.*)\)/", $column_default);
                    $result[$column_name] = array(
                        'primary' => $con_type == 'p',
                        'auto_increment' => $auto_increment,
                        'default_value' => $auto_increment ? '' : strval($column_default),
                        'not_null' => $is_null == 'NO',
                    );
                });
                return $result;
            } else {
                return $data->fetchAll(PDO::FETCH_ASSOC);
            }
        } catch (Exception $e) {
            return array();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="pl">
<context>
    <name>MConfig</name>
    <message>
        <location filename="../mconfig.cpp" line="185"/>
        <location filename="../mconfig.cpp" line="261"/>
        <location filename="../mconfig.cpp" line="293"/>
        <location filename="../mconfig.cpp" line="319"/>
        <location filename="../mconfig.cpp" line="341"/>
        <location filename="../mconfig.cpp" line="364"/>
        <location filename="../mconfig.cpp" line="837"/>
        <location filename="../mconfig.cpp" line="866"/>
        <location filename="../mconfig.cpp" line="890"/>
        <location filename="../mconfig.cpp" line="898"/>
        <location filename="../mconfig.cpp" line="905"/>
        <source>none</source>
        <translation>żadne</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="376"/>
        <source>The user configuration will be repaired. Please close all other applications now. When finished, please logout or reboot. Are you sure you want to repair now?</source>
        <translation>Konfiguracja użytkownika zostanie naprawiona. Proszę wybierz teraz wszystkie pozostałe aplikacje, gdy skończysz wyloguj się lub uruchom ponownie komputer. Czy jesteś pewien, że chcesz przeprowadzić teraz naprawę?</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="377"/>
        <location filename="../mconfig.cpp" line="507"/>
        <location filename="../mconfig.cpp" line="615"/>
        <location filename="../mconfig.cpp" line="670"/>
        <location filename="../mconfig.cpp" line="697"/>
        <source>Yes</source>
        <translation>Tak</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="377"/>
        <location filename="../mconfig.cpp" line="507"/>
        <location filename="../mconfig.cpp" line="615"/>
        <location filename="../mconfig.cpp" line="670"/>
        <location filename="../mconfig.cpp" line="697"/>
        <source>No</source>
        <translation>Nie</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="417"/>
        <location filename="../mconfig.cpp" line="428"/>
        <source>Autologin options</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="418"/>
        <source>Autologin has been disabled for the '%1' account.</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="429"/>
        <source>Autologin has been enabled for the '%1' account.</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="438"/>
        <source>Xfce settings</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="439"/>
        <source> Your current Xfce settings have been backed up in a hidden folder called .restore in your home folder (~/.restore/)</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="460"/>
        <location filename="../mconfig.cpp" line="483"/>
        <source>Panel settings</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="461"/>
        <location filename="../mconfig.cpp" line="484"/>
        <source> Your current panel settings have been backed up in a hidden folder called .restore in your home folder (~/.restore/)</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="502"/>
        <source>You must specify a 'copy to' destination. You cannot copy to the desktop you are logged in to.</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="506"/>
        <source>Before copying, close all other applications. Be sure the copy to destination is large enough to contain the files you are copying. Copying between desktops may overwrite or delete your files or preferences on the destination desktop. Are you sure you want to proceed?</source>
        <translation>Przed kopiowaniem zamknij wszystkie inne aplikacje. Upewnij się, że ścieżka "kopiuj do" posiada wystarczającą przestrzeń dyskową by pomieścić wszystkie kopiowane pliki. Kopiowanie pomiędzy pulpitami może nadpisać lub skasować wszystkie Twoje pliki i konfiguracje na pulpicie docelowym. Czy chcesz kontynuować?</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="528"/>
        <source>Synchronizing desktop...</source>
        <translation>Synchronizacja pulpitu...</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="530"/>
        <source>Copying desktop...</source>
        <translation>Kopiowanie pulpitu...</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="553"/>
        <source>The user name needs to be at least 2 characters long. Please select a longer name before proceeding.</source>
        <translation>Nazwa użytkownika musi mieć przynajmniej dwa znaki. Proszę wybierz dłuższą nazwę, by kontynuować.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="557"/>
        <source>The user name needs to be lower case and it
cannot contain special characters or spaces.
Please choose another name before proceeding.</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="566"/>
        <source>Sorry that name is in use. Please select a different name.</source>
        <translation>Przepraszam, ta nazwa jest już wykorzystywana. Wybierz inną.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="571"/>
        <source>The user password entries do not match.  Please try again.</source>
        <translation>Hasła nie pasują do siebie. Spróbuj ponownie.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="576"/>
        <source>The user password needs to be at least 2 characters long. Please select a longer name before proceeding.</source>
        <translation>Hasło użytkownika musi mieć przynajmniej dwa znaki. Proszę wybierz dłuższe hasło. by kontynuować. </translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="604"/>
        <source>The user was added ok.</source>
        <translation>Użytkownik został dodany.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="608"/>
        <source>Failed to add the user.</source>
        <translation>Błąd dodawania użytkownika.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="613"/>
        <source>This action cannot be undone. Are you sure you want to delete user %1?</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="626"/>
        <source>The user has been deleted.</source>
        <translation>Użytkownik został usunięty. </translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="629"/>
        <source>Failed to delete the user.</source>
        <translation>Błąd usuwania użytkownika.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="642"/>
        <source>The group name needs to be at least 2 characters long. Please select a longer name before proceeding.</source>
        <translation>Nazwa grupy musi mieć przynajmniej dwa znaki. Proszę wybierz dłuższą nazwę, by kontynuować.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="646"/>
        <source>The group name needs to be lower case and it
cannot contain special characters or spaces.
Please choose another name before proceeding.</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="655"/>
        <source>Sorry that group name already exists. Please select a different name.</source>
        <translation>Przepraszam, ale ta nazwa grupy już istnieje. Wybierz inną.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="662"/>
        <source>The system group was added ok.</source>
        <translation>Dodano grupę systemową.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="665"/>
        <source>Failed to add the system group.</source>
        <translation>Błąd dodawania grupy systemowej.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="668"/>
        <source>This action cannot be undone. Are you sure you want to delete group %1?</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="675"/>
        <source>The group has been deleted.</source>
        <translation>Grupa systemowa została usunięta. </translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="678"/>
        <source>Failed to delete the group.</source>
        <translation>Błąd usuwania grupy systemowej.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="696"/>
        <source>Are you sure you want to make these changes?</source>
        <translation>Czy jesteś pewien, że chcesz wprowadzić zmiany?</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="702"/>
        <source>The changes have been applied.</source>
        <translation>Zmiany zostały wprowadzone.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="705"/>
        <source>Failed to apply group changes</source>
        <translation>Błąd wprowadzania zmian grup systemowych.</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="789"/>
        <source>Synchronizing desktop...ok</source>
        <translation>Synchronizacja pulpitu... OK</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="791"/>
        <source>Copying desktop...ok</source>
        <translation>Kopiowanie pulpitu... OK</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="795"/>
        <source>Synchronizing desktop...failed</source>
        <translation>Synchronizacja pulpitu... BŁĄD</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="797"/>
        <source>Copying desktop...failed</source>
        <translation>Kopiowanie pulpitu... BŁĄD</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1002"/>
        <source>Baobab installation</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1003"/>
        <source>Wait while Baobab is installing...</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1071"/>
        <source>About MX User Manager</source>
        <translation>O MX Zarządzanie użytkownikiem</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1072"/>
        <location filename="../mconfig.cpp" line="1079"/>
        <location filename="../mconfig.cpp" line="1086"/>
        <source>MX User Manager</source>
        <translation>MX Zarządzanie użytkownikiem</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1074"/>
        <source>Simple user configuration for MX Linux</source>
        <translation>Proste narzędzie konfiguracji użytkownika dla dystrybucji MX Linux</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1075"/>
        <source>Copyright (c) MX Linux</source>
        <translation>Copyright (c) MX Linux </translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1076"/>
        <location filename="../mconfig.cpp" line="1079"/>
        <source>License</source>
        <translation>Licencja</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1077"/>
        <source>Cancel</source>
        <translation>Anuluj</translation>
    </message>
    <message>
        <location filename="../mconfig.cpp" line="1086"/>
        <source>Help</source>
        <translation>Pomoc</translation>
    </message>
</context>
<context>
    <name>MEConfig</name>
    <message>
        <location filename="../meconfig.ui" line="26"/>
        <source>MX User Manager</source>
        <translation>MX Zarządzanie użytkownikiem</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="62"/>
        <source>Add/Remove User</source>
        <translation>Dodaj/Usuń użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="65"/>
        <source>Add a new user</source>
        <translation>Dodaj nowego użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="92"/>
        <source>Add User Account</source>
        <translation>Dodaj konto użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="119"/>
        <location filename="../meconfig.ui" line="154"/>
        <source>Password for new user</source>
        <translation>Hasło dla nowego użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="122"/>
        <source>Confirm user password:</source>
        <translation>Potwierdź hasło użytkownika:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="135"/>
        <source>Enter password for new user</source>
        <translation>Podaj hasło dla nowego użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="157"/>
        <source>User password:</source>
        <translation>Hasło użytkownika:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="170"/>
        <location filename="../meconfig.ui" line="1174"/>
        <source>Enter username of new user</source>
        <translation>Podaj nazwę nowego użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="176"/>
        <source>username</source>
        <translation>nazwa użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="189"/>
        <location filename="../meconfig.ui" line="1193"/>
        <source>Username of new user</source>
        <translation>Nowa nazwa użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="192"/>
        <source>User login name:</source>
        <translation>Login użytkownika:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="205"/>
        <source>Reenter password for new user</source>
        <translation>Wprowadź ponownie hasło użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="240"/>
        <source>Delete User Account</source>
        <translation>Usuń konto użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="267"/>
        <source>Also delete the user's home directory</source>
        <translation>Usuń również jego katalog domowy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="270"/>
        <source>Delete user home directory</source>
        <translation>Usuń katalog domowy użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="286"/>
        <location filename="../meconfig.ui" line="308"/>
        <location filename="../meconfig.ui" line="1239"/>
        <location filename="../meconfig.ui" line="1261"/>
        <location filename="../meconfig.ui" line="1328"/>
        <location filename="../meconfig.ui" line="1341"/>
        <source>Select user to delete</source>
        <translation>Wybierz użytkownika do usunięcia</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="295"/>
        <source>User to delete:</source>
        <translation>Użytkownik do usunięcia:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="323"/>
        <source>Options</source>
        <translation>Opcje</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="326"/>
        <source>Repair a user configuration</source>
        <translation>Napraw konfigurację użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="360"/>
        <location filename="../meconfig.ui" line="1301"/>
        <source>Modify User Account</source>
        <translation>Zmień konto użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="372"/>
        <location filename="../meconfig.ui" line="388"/>
        <location filename="../meconfig.ui" line="933"/>
        <location filename="../meconfig.ui" line="949"/>
        <source>Select user to repair</source>
        <translation>Wybierz użytkownika do naprawy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="375"/>
        <location filename="../meconfig.ui" line="1350"/>
        <source>User to change:</source>
        <translation>Użytkownik do zmiany:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="410"/>
        <source>Restore Defaults</source>
        <translation>Przywróć domyślne</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="431"/>
        <source>Restore browser configs to MX defaults</source>
        <translation>Przywróć ustawienia przeglądarki do domyślnego zestawu MX</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="437"/>
        <source>Mozilla (Iceweasel or Firefox) configs</source>
        <translation>Konfiguracja programu Mozilla (Iceweasel/Firefox)</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="440"/>
        <source>Alt+X</source>
        <translation>Alt+X</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="447"/>
        <source>Restore group memberships to MX defaults</source>
        <translation>Przywróć domyślny przydział uczestników do grup.</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="453"/>
        <source>Group memberships</source>
        <translation>Przydział użytkowników do grup</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="456"/>
        <source>Alt+G</source>
        <translation>Alt+G</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="463"/>
        <source>Restore APT sources to MX defaults</source>
        <translation>Przywróć domyślny zestaw źródeł oprogramowania APT </translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="466"/>
        <source>Restore APT sources</source>
        <translation>Przywróć źródła oprogramowania APT</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="473"/>
        <source>Restore Xfce defaults</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="483"/>
        <source>Change Autologin Settings</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="489"/>
        <source>Log in automatically</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="496"/>
        <source>Require password to log in</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="506"/>
        <source>Select Panel Options</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="512"/>
        <source>Display default panel horizontally</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="519"/>
        <source>Restore default configuration</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="529"/>
        <source>Restore backed up configuration</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="544"/>
        <source>Copy/Sync</source>
        <translation>Kopiuj/synchronizuj</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="571"/>
        <source>Copy Between Desktops</source>
        <translation>Kopiuj pomiędzy pulpitami</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="598"/>
        <source>Select to copy and then delete differences</source>
        <translation>Wybierz by skopiować, a potem usunąć różnice</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="601"/>
        <source>Sync</source>
        <translation>Synchronizacja</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="617"/>
        <location filename="../meconfig.ui" line="693"/>
        <source>Select desktop to copy from</source>
        <translation>Wybierz pulpit źródłowy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="626"/>
        <source>Copy from:</source>
        <translation>Kopia z (pulpit źródłowy):</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="639"/>
        <location filename="../meconfig.ui" line="661"/>
        <source>Select desktop to copy to</source>
        <translation>Wybierz pulpit docelowy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="648"/>
        <source>Copy to:</source>
        <translation>Kopia do (pulpit docelowy):</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="674"/>
        <source>Select to only copy files</source>
        <translation>Wybierz by skopiować tylko pliki</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="677"/>
        <source>Copy only</source>
        <translation>Kopiuj tylko</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="736"/>
        <source>Select to copy/sync Shared</source>
        <translation>Wybierz by skopiować/zsynchronizować tylko Współdzielone</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="739"/>
        <source>Shared folder</source>
        <translation>Folder współdzielony</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="752"/>
        <source>Select to copy/sync entire home</source>
        <translation>Wybierz by skopiować/zsynchronizować cały katalog domowy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="755"/>
        <source>Entire home</source>
        <translation>Cały katalog domowy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="771"/>
        <source>Select to copy/sync the browser configuration</source>
        <translation>Wybierz by skopiować/zsynchronizować konfigurację użytkownika</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="774"/>
        <source>Mozilla (Firefox or Iceweasel) configs</source>
        <translation>Konfiguracja programu Mozilla (Iceweasel/Firefox)</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="787"/>
        <source>Select to copy/sync Documents</source>
        <translation>Wybierz by skopiować/zsynchronizować Dokumenty</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="790"/>
        <source>Documents folder</source>
        <translation>Katalog dokumentów</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="797"/>
        <source>What to copy/sync:</source>
        <translation>Co kopiować/zsynchronizować:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="813"/>
        <source>Progress</source>
        <translation>Postęp</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="843"/>
        <location filename="../meconfig.ui" line="859"/>
        <source>Status of the changes</source>
        <translation>Status zmian</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="862"/>
        <source>Status:</source>
        <translation>Status:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="878"/>
        <source>Progress of the changes</source>
        <translation>Postęp zmian</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="915"/>
        <source>Free Up Space</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="921"/>
        <source>Free disk space for user</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="936"/>
        <source>User account:</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="959"/>
        <source>Folders to clean</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="965"/>
        <source>Delete /tmp files</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="975"/>
        <source>Delete ~/.thumbnails</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="985"/>
        <source>Delete ~/.cache</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="998"/>
        <source>Clear APT cache</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1004"/>
        <source>autoclean (only removes old cache files that can no longer be downloaded)</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1014"/>
        <source>clean (delete all cache files)</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1024"/>
        <source>Delete logs</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1030"/>
        <source>delete old logs (delete .gz, .old, and .1 log files)</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1043"/>
        <source>delete all logs</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1059"/>
        <source>Empty Trash</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1068"/>
        <source>selected user Trash</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1078"/>
        <source>empty Trash for all users</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1088"/>
        <source>Graphical tool for analysing disk usage</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1094"/>
        <source>Run Baobab</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1135"/>
        <source>Add/Remove Groups</source>
        <translation>Dodaj/Usuń grupy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1147"/>
        <source>Add Group</source>
        <translation>Dodaj grupę</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1180"/>
        <source>groupname</source>
        <translation>Nazwa grupy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1196"/>
        <source>Group name:</source>
        <translation>Nazwa grupy:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1212"/>
        <source>Delete Group</source>
        <translation>Usuń grupę</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1248"/>
        <source>Group to delete:</source>
        <translation>Grupa do usunięcia:</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1289"/>
        <source>Group Membership</source>
        <translation>Przynależność użytkowników do grupy</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1386"/>
        <source>Groups user belongs to (change the groups by selecting/deselecting the appropriate boxes):</source>
        <translation>Grupy do których przynależy użytkownik (zmień je poprzez zaznaczenie lub odznaczenie właściwych pól):</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1409"/>
        <source>*Please doublecheck your selections before applying, assigning wrong group memberships can break your system.  Use Repair tab to restore the original memberships if you made a mistake.</source>
        <translation>*Proszę upewnij się, że wybrałeś właściwie przed zapisaniem zmian. Wybór błędnych grup może zepsuć Twój system. Jeśli popełnisz błąd, użyj zakładki Naprawa by przywrócić oryginalne przynależności grup.</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1472"/>
        <source>Apply any changes</source>
        <translation>Zastosuj wszystkie zmiany</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1475"/>
        <source>Apply</source>
        <translation>Zastosuj</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1482"/>
        <source>Alt+A</source>
        <translation>Alt+A</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1489"/>
        <source>Cancel any changes then quit</source>
        <translation>Cofnij wszelkie zmiany i wyjdź</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1492"/>
        <source>Close</source>
        <translation>Zamknij</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1499"/>
        <source>Alt+N</source>
        <translation>Alt+N</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1537"/>
        <source>Display help </source>
        <translation>Wyświetl pomoc</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1540"/>
        <source>Help</source>
        <translation>Pomoc</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1547"/>
        <source>Alt+H</source>
        <translation>Alt+H</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1554"/>
        <source>About this application</source>
        <translation>O programie</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1557"/>
        <source>About...</source>
        <translation>O...</translation>
    </message>
    <message>
        <location filename="../meconfig.ui" line="1564"/>
        <source>Alt+B</source>
        <translation>Alt+B</translation>
    </message>
</context>
<context>
    <name>QApplication</name>
    <message>
        <location filename="../main.cpp" line="41"/>
        <source>You must run this program as root.</source>
        <translation>Musisz uruchomić ten program jako administrator. </translation>
    </message>
</context>
</TS>


text:
%Notes by Harsh Mistry
%CS 370
%Based on Template From  https://www.cs.cmu.edu/~ggordon/10725-F12/template.tex

\documentclass[twoside]{article}
\setlength{\oddsidemargin}{0.25 in}
\setlength{\evensidemargin}{-0.25 in}
\setlength{\topmargin}{-0.6 in}
\setlength{\textwidth}{6.5 in}
\setlength{\textheight}{8.5 in}
\setlength{\headsep}{0.75 in}
\setlength{\parindent}{0 in}
\setlength{\parskip}{0.1 in}
\usepackage{amsmath,amsfonts,graphicx}
\newcounter{lecnum}
\renewcommand{\thepage}{\thelecnum-\arabic{page}}
\renewcommand{\thesection}{\thelecnum.\arabic{section}}
\renewcommand{\theequation}{\thelecnum.\arabic{equation}}
\renewcommand{\thefigure}{\thelecnum.\arabic{figure}}
\renewcommand{\thetable}{\thelecnum.\arabic{table}}
\newcommand{\lecture}[4]{
   \pagestyle{myheadings}
   \thispagestyle{plain}
   \newpage
   \setcounter{lecnum}{#1}
   \setcounter{page}{1}

   \graphicspath{ {images/} }

%Info Box
   \begin{center}
   \framebox{
      \vbox{\vspace{2mm}
    \hbox to 6.28in { {\bf CS 370 - Numerical Computation
	\hfill Fall 2018} }
       \vspace{4mm}
       \hbox to 6.28in { {\Large \hfill  #2  \hfill} }
       \vspace{2mm}
       \hbox to 6.28in { {\it Lecturer: #3 \hfill Notes By: #4} }
      \vspace{2mm}}
   }
   \end{center}

   \markboth{Lecture #1: #2}{Lecture #1: #2}

}

\renewcommand{\cite}[1]{[#1]}
\def\beginrefs{\begin{list}%
        {[\arabic{equation}]}{\usecounter{equation}
         \setlength{\leftmargin}{2.0truecm}\setlength{\labelsep}{0.4truecm}%
         \setlength{\labelwidth}{1.6truecm}}}
\def\endrefs{\end{list}}
\def\bibentry#1{\item[\hbox{[#1]}]}

\newcommand{\fig}[3]{
			\vspace{#2}
			\begin{center}
			Figure \thelecnum.#1:~#3
			\end{center}
	}

\newtheorem{theorem}{Theorem}[lecnum]
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{ex}[theorem]{Example}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{claim}[theorem]{Claim}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{definition}[theorem]{Definition}
\newenvironment{proof}{{\bf Proof:}}{\hfill\rule{2mm}{2mm}}
\newcommand\E{\mathbb{E}}

%Start of Document
\begin{document}

\lecture{2}{Interpolation}{Christopher Batty}{Harsh Mistry}

The basic problem of Interpolation is, Given a set of data points from an (unknown) function \(y = p(x)\), can we approximate \(p\)'s value at other points

\section{Uses for Interpolation}
\begin{itemize}
\item Fitting curves to data. (Related to Regression)
\item Estimating an unknown function's properties: values, derivatives, etc
\item Interpolation plays a role in many numerical methods such as differentiation, integration, differential equations, optimization, etc
\end{itemize}

\section{Linear Interpolation}
\begin{itemize}
\item The simplest form of interpolation, given two points, find a line that best fits the points.
\item Calculate the slope between two points and produce a line equation \(y = ax + b\)
\item Linear interpolation breaks down when attempting to generalize solutions with more than 2 points
\end{itemize}

\section{Polynomial Interpolation}
\begin{theorem}
\textbf{Unisolvence Theorem} - Given \(n\) data pairs \((x_i, y_i)\), \(i = 1, \ldots, n\) with distinct \(x_i\), there is a unique polynomial \(p(x)\) of degree \(\leq n - 1\) that interpolates the data.
\end{theorem}

\begin{itemize}
\item For n points, we must find all coefficients of the polynomial
$$p(x) = c_1 + c_2x + \ldots + c_n x^{n-1}$$
\item As before, each \((x_i, y_i)\) point gives one linear equation
$$ y_i = c_1 + c_2 x_i + \ldots + c_n x_i^{n-1}$$
\item Then solve the n x n linear system which should yield \(V \vec{c} = \vec{y}\)
\item \(V\) is called a Vandermonde Matrix
\end{itemize}

\textbf{Note : } $ det V = \prod_{i < j} (x_i - x_j)  $

\section{The Monomial Basis}
$p(x) = c_1 + c_2x + \ldots + c_n x^{n-1}$ is called the monomial form and can be rewritten as
$$ p(x) = \sum_{i=1}^{n} c_i x^{i-1} $$
The sequence \(1, x, x^2, x^3\) ... is called the monomial basis. Monomial form is a sum of coefficients \(c_i\) times these basis functions.

\section{The Lagrange Basis}
\begin{itemize}
\item The Lagrange basis is a different basis for interpolating polynomials.
\item We define the Lagrange basis functions \(L_k(x)\), to construct a polynomial as
$$p(x) = y_1 L_1 (x) + y_2L_2(x) + \ldots + y_n L_n(x) = \sum_{k=1}^{n} y_k L_k(x) $$
where \(y_i\) are coefficients
\item Given \(n\) data points \((x_i, y_i)\), we define
$$ L_k(x) = \frac{(x - x_1)(\ldots)(x - x_{k-1}) (x - x_{k+1})(\ldots) (x - x_n)   }{  (x_k - x_1) (\ldots) (x_k - x_{k-1}) (x_k - x_{k+1}) (\ldots) (x_k - x_n) } $$
\end{itemize}

\subsection{Why?}
We may perfer the Lagrange basis as we can directly write down the polynomial from the Lagrange basis functions, \(L_k\), and the data points, \(x_i, y_i\). There is no need to solve a linear system.

\section{Runge's Phenomenon}

When involving a polynomial with a high degree, we often are left with excessive oscillation and wiggling. This is called Runge's Phenomenon.

\subsection{Avoiding the Phenomenon}
\begin{itemize}
\item Select data/interpolation points in a \textit{smarter} way
\item Fit even higher degree polynomials, but also constrain derivatives to somehow reduce \textit{wiggliness}
\item Fit lower degree polynomials that don't exactly interpolate, but do minimize some error measure
\item Or use piecewise polynomials
\end{itemize}

\section{Piecewise Functions and Interpolation}

\begin{itemize}
\item As we know, piecewise functions are functions with different definitions for distinct intervals of the domain
\item One option of Piecewise Interpolation, is to continually apply Liner Interpolation for each set of points, but this can result in an some what unsatisfactory interpolation which may have \textit{kinks}
\item The goal is to achieve smoothness because its beneficial for aesthetic purposes  and for mathematical applications needing derivatives
\end{itemize}

\section{Hermite Interpolation}
\begin{itemize}
\item Greater smoothness requires controlling derivatives of the polynomial.
\item \textbf{Hermite Interpolation } is the problem of fitting a polynomial given function values and derivatives.
\end{itemize}

\subsection{Closed-form solution}
If we define the Polynomial on the \(i^{th}\) interval, \(p_i(x)\) as
$$ p_i(x) = a_i + b_i (x - x_i) + c_i (x-x_i)^2 + d_i (x-x_i)^3$$
there exist direct formulas for polynomial coefficients
\begin{itemize}
\item $a_i = y_i$
\item $ b_i = S_i$
\item $c_i = \frac{3y_i^\prime - 2 S_i - S_{i+1}}{\Delta x_i}$
\item $d_i = \frac{S_{i+1} + S_i - 2 y_i^\prime}{\Delta x_i^2}$
\end{itemize}
where we define
\begin{itemize}
\item \(\Delta x_i = x_{i+1} - x_i \)
\item \(y_i^\prime = \frac{y_{i+1} - y_i}{\Delta x_i}\)
\end{itemize}

\begin{definition}
\textbf{Knots} : Points where the interpolate transitions from one polynomial/to another
\end{definition}
\begin{definition}
\textbf{Nodes} : Points where some control points/data is  specified
\end{definition}

For hermite interpolation, these two points are the same, but they can differ for other curves

\section{Cubic Splines}
Fit a cubic, \(S_i(x)\) on each interval, but now require matching first and second derivatives between intervals

Require "interpolating conditions" on each interval
$$ S_i(x_i) = y_i, \hspace{1cm} S_i(x_{i+1}) = y_{i+1} $$
and "derivative conditions" at each interior point \(x_{i+1}\)
$$ S_i^\prime(x_{i+1}) = S_{i+1}^\prime(x_{i+1})$$
$$ s_i^{\prime\prime} (x_{i+1}) = s_{i+1}^{\prime\prime} (x_{i+1})$$

\subsection{Boundary Conditions}
\begin{itemize}
\item Clamped/complete- endpoints have slope set to set value
\item Free/Natural/Variational - "curvature" goes to zero at the end points, so the curve "straightens out"
\item Periodic Boundary Conditions - start and end derivatives match each other, which gives a "wrap-around" type behaviour
\item "Not-a-Knot" boundary conditions - Last two segments on an end become the same polynomial
\end{itemize}

\subsection{Hermite v.s. Cubic Splines}
\begin{itemize}
\item Hermite Interpolation - each interpolant can be found independently
\begin{itemize}
\item Solve \(n-1\) separate systems of 4 equations
\end{itemize}
\item Cubic Spline - must solve for all polynomials together at once!
\begin{itemize}
\item Solve one system with 4(n-1) equations
\end{itemize}

\end{itemize}

\section{Spline Energy}
There is an mathematical relationship between physical splines and cubic splines.

Bending a spline by placing the "drafting ducks" introduces some stored potential energy (the bending energy)

\subsection{Real spline energy }
The shape of a spline will find the minimum snergy configuration. (The least smooth shape)

Mathematical splines also minimize an "energy". i.e a measure of the total amount of curvature

\subsection{Strategies for smooth curves}
\begin{itemize}
\item Hermite Interpolation
\begin{itemize}
\item Given values and slopes
\item Separate solve per interval
\item Continuous 1st derivatives
\end{itemize}
\item Cubic spline interpolation
\begin{itemize}
\item Given values only
\item One big solve for all coeffs.
\item Continuous 1st an 2nd derivatives
\end{itemize}
\end{itemize}

\subsection{Size and Cost}
\begin{itemize}
\item Naive cubic spline system has matrix size \((4n-4)^2\) for n points
\item Basic algorithms for linear systems take \(O(N^3)\) time for \(N\) unknowns
\end{itemize}

\subsection{Cublic splines via Hermite Interpolation}
Strategy : Use hermite interpolation as a stepping stone to build a cubic spline

\begin{enumerate}
\item Express unknown polys with closed form hermite equations
\item Treat \(s_i\) (slopes at nodes) as unknowns
\item Solve \(s_i\) that give continuous 2nd derivatives
\item Give \(s_i\) plug into closed form Hermite equations to recover polynomial coefficients : \(a_i, b_i, c_i, d_i\)
\end{enumerate}

\end{document}


text:
package io.dropwizard.jersey.errors;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;

import java.util.Objects;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ErrorMessage {
    private final int code;
    private final String message;
    private final String details;

    public ErrorMessage(String message) {
        this(500, message);
    }

    public ErrorMessage(int code, String message) {
        this(code, message, null);
    }

    @JsonCreator
    public ErrorMessage(@JsonProperty("code") int code, @JsonProperty("message") String message,
                        @JsonProperty("details") String details) {
        this.code = code;
        this.message = message;
        this.details = details;
    }

    @JsonProperty("code")
    public Integer getCode() {
        return code;
    }

    @JsonProperty("message")
    public String getMessage() {
        return message;
    }

    @JsonProperty("details")
    public String getDetails() {
        return details;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if ((obj == null) || (getClass() != obj.getClass())) {
            return false;
        }

        final ErrorMessage other = (ErrorMessage) obj;
        return Objects.equals(code, other.code)
                && Objects.equals(message, other.message)
                && Objects.equals(details, other.details);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code, message, details);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this).add("code", code)
                .add("message", message).add("details", details).toString();
    }
}


text:
package com.github.st1hy.countthemcalories.core;

public interface BasicLifecycle {

    void onStart();

    void onStop();

}


text:
package reactor.util.context;

import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static reactor.util.context.ContextTest.key;
import static reactor.util.context.ContextTest.keyValue;

public class Context2Test {

	Context2 c = new Context2(1, "A", 2, "B");

	@Test
	public void replaceKey1NewContext() throws Exception {
		Context put = c.put(1, "foo");

		assertThat(put)
				.isInstanceOf(Context2.class)
				.isNotSameAs(c);
		assertThat(put.stream().map(Map.Entry::getKey))
				.containsExactly(1, 2);
		assertThat(put.stream().map(Map.Entry::getValue))
				.containsExactly("foo", "B");
	}

	@Test
	public void replaceKey2NewContext() {
		Context put = c.put(2, "foo");

		assertThat(put)
				.isInstanceOf(Context2.class)
				.isNotSameAs(c);
		assertThat(put.stream().map(Map.Entry::getKey))
				.containsExactly(1, 2);
		assertThat(put.stream().map(Map.Entry::getValue))
				.containsExactly("A", "foo");
	}

	@Test
	public void putDifferentKeyContext3() throws Exception {
		Context put = c.put(3, "Abis");
		assertThat(put)
				.isInstanceOf(Context3.class);
		assertThat(put.stream().map(Map.Entry::getKey))
				.containsExactly(1, 2, 3);
		assertThat(put.stream().map(Map.Entry::getValue))
				.containsExactly("A", "B", "Abis");
	}

	@Test
	public void hasKey() throws Exception {
		assertThat(c.hasKey(1)).as("hasKey(1)").isTrue();
		assertThat(c.hasKey(2)).as("hasKey(2)").isTrue();
		assertThat(c.hasKey(3)).as("hasKey(3)").isFalse();
	}

	@Test
	public void removeKeys() {
		assertThat(c.delete(1))
				.as("delete(1)")
				.isInstanceOf(Context1.class)
				.has(keyValue(2, "B"))
				.doesNotHave(key(1));

		assertThat(c.delete(2))
				.as("delete(2)")
				.isInstanceOf(Context1.class)
				.has(keyValue(1, "A"))
				.doesNotHave(key(2));

		assertThat(c.delete(3)).isSameAs(c);
	}

	@Test
	public void get() {
		assertThat((String) c.get(1)).isEqualTo("A");
		assertThat((String) c.get(2)).isEqualTo("B");
	}

	@Test
	public void getUnknown() throws Exception {
		assertThatExceptionOfType(NoSuchElementException.class)
				.isThrownBy(() -> c.get(3))
				.withMessage("Context does not contain key: 3");
	}

	@Test
	public void getUnknownWithDefault() throws Exception {
		assertThat(c.getOrDefault("peeka", "boo")).isEqualTo("boo");
	}

	@Test
	public void getUnknownWithDefaultNull() throws Exception {
		Object def = null;
		assertThat(c.getOrDefault("peeka", def)).isNull();
	}

	@Test
	public void stream() throws Exception {
		assertThat(c.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))
				.hasSize(2)
				.containsOnlyKeys(1, 2)
				.containsValues("A", "B");
	}

	@Test
	void forEach() {
		Map<Object, Object> items = new HashMap<>();

		c.forEach(items::put);

		assertThat(items)
				.hasSize(2)
				.containsEntry(1, "A")
				.containsEntry(2, "B");
	}

	@Test
	void forEachThrows() {
		Map<Object, Object> items = new HashMap<>();

		BiConsumer<Object, Object> action = (key, value) -> {
			if (key.equals(2)) {
				throw new RuntimeException("Boom!");
			}
			items.put(key, value);
		};

		assertThatExceptionOfType(RuntimeException.class)
				.isThrownBy(() -> c.forEach(action))
				.withMessage("Boom!");

		assertThat(items)
				.hasSize(1)
				.containsOnlyKeys(1)
				.containsValues("A");
	}

	@Test
	public void string() throws Exception {
		assertThat(c.toString()).isEqualTo("Context2{1=A, 2=B}");
	}

	@Test
	public void ofApi() {
		assertThat(Context.of("test", 12, "value", true))
				.isInstanceOf(Context2.class)
				.hasToString("Context2{test=12, value=true}");
	}

	@Test
	public void putAllOf() {
		Context m = Context.of("A", 1, "B", 2, "C", 3);
		Context put = c.putAll(m.readOnly());

		assertThat(put).isInstanceOf(Context5.class)
		               .hasToString("Context5{1=A, 2=B, A=1, B=2, C=3}");
	}

	@Test
	public void putAllReplaces() {
		Context m = Context.of(c.key1, "replaced", "A", 1);
		Context put = c.putAll(m.readOnly());

		assertThat(put).isInstanceOf(Context3.class)
		               .hasToString("Context3{1=replaced, 2=B, A=1}");
	}

	@Test
	public void putAllOfEmpty() {
		Context m = Context.empty();
		Context put = c.putAll(m.readOnly());

		assertThat(put).isSameAs(c);
	}

	@Test
	public void putNonNullWithNull() {
		Context put = c.putNonNull("putNonNull", null);

		assertThat(put).isSameAs(c);
	}

	@Test
	public void putNonNullWithValue() {
		Context put = c.putNonNull("putNonNull", "value");

		assertThat(put.getOrEmpty("putNonNull")).contains("value");
	}

	@Test
	public void size() {
		assertThat(c.size()).isEqualTo(2);
	}

	@Test
	public void putAllSelfIntoEmpty() {
		CoreContext initial = new Context0();

		Context result = ((CoreContext) c).putAllInto(initial);

		assertThat(result).isNotSameAs(initial)
		                  .isNotSameAs(c);

		assertThat(result.stream()).containsExactlyElementsOf(c.stream().collect(Collectors.toList()));
	}

	@Test
	public void putAllSelfIntoContextN() {
		CoreContext initial = new ContextN(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6);
		Context2 self = new Context2("A", 1, "B", 2);
		Context result = self.putAllInto(initial);

		assertThat(result).isNotSameAs(initial)
		                  .isNotSameAs(c);

		assertThat(result.stream().map(String::valueOf))
				.containsExactly("1=1", "2=2", "3=3", "4=4", "5=5", "6=6", "A=1", "B=2");
	}

	@Test
	public void unsafePutAllIntoShouldReplace() {
		ContextN ctx = new ContextN(Collections.emptyMap());
		ctx.accept(1, "VALUE1");
		ctx.accept(2, "VALUE2");
		ctx.accept("extra", "value");

		Context2 self = new Context2(1, "REPLACED1", 2, "REPLACED2");

		self.unsafePutAllInto(ctx);

		assertThat(ctx)
				.containsEntry(1, "REPLACED1")
				.containsEntry(2, "REPLACED2")
				.containsEntry("extra", "value")
				.hasSize(3);
	}

	@Test
	void putAllMap() {
		Map<Object, Object> map = new HashMap<>();
		map.put("A", 1);
		map.put("B", 2);
		map.put("C", 3);
		Context put = c.putAllMap(map);

		assertThat(put).isInstanceOf(Context5.class)
				.hasToString("Context5{1=A, 2=B, A=1, B=2, C=3}");
	}

	@Test
	void putAllMapEmpty() {
		Context put = c.putAllMap(Collections.emptyMap());
		assertThat(put).isSameAs(c);
	}

	@Test
	void putAllMapNullKey() {
		assertThatExceptionOfType(NullPointerException.class)
				.isThrownBy(() -> c.putAllMap(Collections.singletonMap(null, "oops")));
	}

	@Test
	void putAllMapNullValue() {
		assertThatExceptionOfType(NullPointerException.class)
				.isThrownBy(() -> c.putAllMap(Collections.singletonMap("A", null)));
	}

	@Test
	void putAllMapReplaces() {
		Map<Object, Object> map = new HashMap<>();
		map.put(c.key1, "replaced");
		map.put("A", 1);
		Context put = c.putAllMap(map);

		assertThat(put).isInstanceOf(Context3.class)
				.hasToString("Context3{1=replaced, 2=B, A=1}");
	}
}


text:
HELPER_DIR=$(cd $(dirname ${0:-}); cd ..; pwd)
# include install sh
source  $HELPER_DIR/helpers/install.sh
install_nodejs


text:
package org.estatio.module.budget.dom.partioning;

import java.math.BigDecimal;
import java.util.List;

import org.apache.isis.applib.services.factory.FactoryService;
import org.apache.isis.applib.services.repository.RepositoryService;
import org.jmock.Expectations;
import org.jmock.auto.Mock;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import org.apache.isis.applib.query.Query;
import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2;

import org.incode.module.unittestsupport.dom.repo.FinderInteraction;

import org.estatio.module.budget.dom.budgetitem.BudgetItem;
import org.estatio.module.budget.dom.keytable.KeyTable;
import org.estatio.module.budget.dom.keytable.PartitioningTable;
import org.estatio.module.charge.dom.Charge;

import static org.assertj.core.api.Assertions.assertThat;

public class PartitionItemRepository_Test {

    FinderInteraction finderInteraction;

    PartitionItemRepository partitionItemRepository;

    @Before
    public void setup() {
        partitionItemRepository = new PartitionItemRepository() {

            @Override
            protected <T> T firstMatch(Query<T> query) {
                finderInteraction = new FinderInteraction(query, FinderInteraction.FinderMethod.FIRST_MATCH);
                return null;
            }

            @Override
            protected <T> T uniqueMatch(Query<T> query) {
                finderInteraction = new FinderInteraction(query, FinderInteraction.FinderMethod.UNIQUE_MATCH);
                return null;
            }

            @Override
            protected List<PartitionItem> allInstances() {
                finderInteraction = new FinderInteraction(null, FinderInteraction.FinderMethod.ALL_INSTANCES);
                return null;
            }

            @Override
            protected <T> List<T> allMatches(Query<T> query) {
                finderInteraction = new FinderInteraction(query, FinderInteraction.FinderMethod.ALL_MATCHES);
                return null;
            }
        };
    }

    public static class FindByPartitionItem extends PartitionItemRepository_Test {

        @Test
        public void happyCase() {

            BudgetItem budgetItem = new BudgetItem();
            partitionItemRepository.findByBudgetItem(budgetItem);

            assertThat(finderInteraction.getFinderMethod()).isEqualTo(FinderInteraction.FinderMethod.ALL_MATCHES);
            assertThat(finderInteraction.getResultType()).isEqualTo(PartitionItem.class);
            assertThat(finderInteraction.getQueryName()).isEqualTo("findByBudgetItem");
            assertThat(finderInteraction.getArgumentsByParameterName().get("budgetItem")).isEqualTo((Object) budgetItem);
            assertThat(finderInteraction.getArgumentsByParameterName()).hasSize(1);
        }

    }

    public static class FindUnique extends PartitionItemRepository_Test {

        @Test
        public void happyCase() {

            Partitioning partitioning = new Partitioning();
            Charge charge = new Charge();
            BudgetItem budgetItem = new BudgetItem();
            KeyTable keyTable = new KeyTable();
            partitionItemRepository.findUnique(partitioning, charge, budgetItem, keyTable);

            assertThat(finderInteraction.getFinderMethod()).isEqualTo(FinderInteraction.FinderMethod.UNIQUE_MATCH);
            assertThat(finderInteraction.getResultType()).isEqualTo(PartitionItem.class);
            assertThat(finderInteraction.getQueryName()).isEqualTo("findUnique");
            assertThat(finderInteraction.getArgumentsByParameterName().get("partitioning")).isEqualTo((Object) partitioning);
            assertThat(finderInteraction.getArgumentsByParameterName().get("charge")).isEqualTo((Object) charge);
            assertThat(finderInteraction.getArgumentsByParameterName().get("budgetItem")).isEqualTo((Object) budgetItem);
            assertThat(finderInteraction.getArgumentsByParameterName().get("partitioningTable")).isEqualTo((Object) keyTable);
            assertThat(finderInteraction.getArgumentsByParameterName()).hasSize(4);
        }

    }

    public static class FindOrCreatePartitionItemNew extends PartitionItemRepository_Test {

        @Rule
        public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(JUnitRuleMockery2.Mode.INTERFACES_AND_CLASSES);

        @Mock
        private FactoryService mockFactoryService;

        @Mock
        private RepositoryService mockRepositoryService;

        PartitionItemRepository partitionItemRepository1;

        @Before
        public void setup() {
            partitionItemRepository1 = new PartitionItemRepository() {
                @Override
                public PartitionItem findUnique(final Partitioning partitioning, final Charge charge, final BudgetItem budgetItem, final PartitioningTable keyTable) {
                    return null;
                }
            };
            partitionItemRepository1.factoryService = mockFactoryService;
            partitionItemRepository1.repositoryService = mockRepositoryService;
        }

        @Test
        public void findOrCreateXxx() throws Exception {

            final KeyTable keyTable = new KeyTable();
            final Partitioning partitioning = new Partitioning();
            final Charge charge = new Charge();
            final BudgetItem budgetItem = new BudgetItem();
            final BigDecimal percentage = new BigDecimal("100.000000");
            final PartitionItem partitionItem = new PartitionItem();
            final BigDecimal fixedBudgetedAmount = new BigDecimal("123.45");
            final BigDecimal fixedAuditedAmount = new BigDecimal("234.56");

            // expect
            context.checking(new Expectations() {
                {
                    oneOf(mockFactoryService).instantiate(PartitionItem.class);
                    will(returnValue(partitionItem));
                    oneOf(mockRepositoryService).persist(partitionItem);
                }

            });

            // when
            PartitionItem newPartitionItem = partitionItemRepository1.findOrCreatePartitionItem(partitioning, budgetItem, charge, keyTable, percentage, fixedBudgetedAmount, fixedAuditedAmount);

            // then
            assertThat(newPartitionItem.getPartitioning()).isEqualTo(partitioning);
            assertThat(newPartitionItem.getCharge()).isEqualTo(charge);
            assertThat(newPartitionItem.getBudgetItem()).isEqualTo(budgetItem);
            assertThat(newPartitionItem.getPartitioningTable()).isEqualTo(keyTable);
            assertThat(newPartitionItem.getPercentage()).isEqualTo(percentage);
            assertThat(newPartitionItem.getFixedBudgetedAmount()).isEqualTo(fixedBudgetedAmount);
            assertThat(newPartitionItem.getFixedAuditedAmount()).isEqualTo(fixedAuditedAmount);

        }

    }

}


text:
using DGCLib_Base;
using DGCLib_Base.DomainTypes.LinearAlgebra;
using DGCLib_Misc;
using System.Collections.Generic;
using System.Linq;
using System;
using DGCLib_Base.DomainTypes;

namespace DGCLib_IK
{
    public abstract class BaseIK : IAlgorithm<Line>
    {
        [BindInGUI]
        public double[] Lengths { get; set; }

        [BindInGUI]
        public Point Target { get; set; }

        public BaseIK()
        {
            Lengths = new double[0];
            Target = new Point();
        }

        public virtual Point[] Compute()
        {
            if (Lengths.Any(o => double.IsNaN(o) || double.IsInfinity(o) || o == 0.0))
                return new Point[0];

            if (Lengths.Length == 2)
            {
                return IKUtils.GetTriangleIKPositions(Target, Lengths[0], Lengths[1], false);
            }

            return GetPositionsImpl();
        }

        protected abstract Point[] GetPositionsImpl();

        IEnumerable<Line> IAlgorithm<Line>.Compute()
        {
            var points = Compute();
            return points.Zip(points.Skip(1),(a,b)=>new Line(a, b));
        }

        private List<IGeoStructure> _debugGeo = new List<IGeoStructure>();

        protected List<IGeoStructure> DebugGeo { get { return _debugGeo; } }

        public IGeoStructure[] AdditionalGeo { get { return _debugGeo.ToArray(); } }
    }
}


text:
package main

import (
	"flag"
	"io"
	"log"
	"net"
	"ook"
	"os"
	"os/signal"
	"syscall"
)

var address = flag.String("address", "236.0.0.1:3636", "multicast to this address")
var ifaceName = flag.String("interface", "lo", "interface on which to multicast")
var verbose = flag.Bool("verbose", false, "be verbose")
var input = flag.String("input", "-", "path to file of bursts")

// Get an IPv4 address for a given interface.
func interfaceIP4(iface *net.Interface) net.IP {
	addrs, err := iface.Addrs()
	if err != nil {
		return nil
	}
	for _, n := range addrs {
		ip, _, err := net.ParseCIDR(n.String())
		if err == nil {
			if ip4 := ip.To4(); ip4 != nil {
				return ip4
			}
		}
	}
	return nil
}

func main() {
	flag.Parse()

	terminate := make(chan os.Signal)
	signal.Notify(terminate, syscall.SIGINT)

	udpAddr, err := net.ResolveUDPAddr("udp", *address)
	if err != nil {
		log.Fatalf("Unable to resolve multicasting address (%s): %s", *address, err.Error())
	}
	if *verbose {
		log.Printf("Multicasting to %s", udpAddr.String())
	}

	iface, err := net.InterfaceByName(*ifaceName)
	if err != nil {
		log.Fatalf("Unknown interface (%s): %s", *ifaceName, err.Error())
	}

	ifaceAddr := interfaceIP4(iface)
	if ifaceAddr == nil {
		log.Fatalf("Could not find an IPv4 address on the interface")
	}

	localAddr := net.UDPAddr{IP: ifaceAddr, Port: 0}

	udpConn, err := net.DialUDP("udp4", &localAddr, udpAddr)
	if err != nil {
		log.Fatalf("Failed to dial UDP: %s", err.Error())
	}

	source := func() *os.File {
		if *input == "-" {
			return os.Stdin
		} else {
			s, err := os.Open(*input)
			if err != nil {
				log.Fatalf("Failed to open input file (%s): %s", *input, err.Error())
			}
			return s
		}
	}()

	reader, err := ook.OpenFile(source)
	if err != nil {
		log.Fatalf("Failed to open input source: %s", err.Error())
	}

	for {
		burst, err := reader.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatalf("Error reading burst: %s", err.Error())
		}
		log.Printf("Read %d pulses", len(burst.Pulses))

		bytes, err := burst.Encode()
		if err != nil {
			log.Fatalf("Failed to encode burst: %s", err.Error())
		}
		log.Printf("Encodes to %d bytes", len(bytes))

		c, err := udpConn.Write(bytes)
		if err != nil {
			log.Fatalf("Failed to write burst (%s -> %s): %s", localAddr.String(), udpAddr.String(), err.Error())
		}
		if c != len(bytes) {
			log.Fatalf("Truncated burst %d != %d", c, len(bytes))
		}
	}
}


text:
<!DOCTYPE html>

    <title>CSS Transforms Test: CSS transforms scale 2 inheritance on div elements</title>
    <link rel="author" title="Delong Gao" href="mailto:gaodl@uw.edu">
    <link rel="reviewer" title="Rebecca Hauck" href="mailto:rhauck@adobe.com">
    <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#transform-property">
    <link rel="help" href="http://www.w3.org/TR/css-transforms-1/#two-d-transform-functions">

    <meta name="assert" content="While child div inherits property from its parent, scaling 2 on parent div will course the child to scale 4 and totally cover the red div. The test passes if there is a green square and no red. ">

The test passes if there is a green square and no red.


text:
<template name="devDetailNav">

      {{> backToList}}
      {{> gameTypeIndicator}}
      {{> editGameLink}}
      {{> shareGameLink}}
      {{> copyGameLink}}

</template>


text:
'use strict';

import * as chai from 'chai';
import * as sinonChai from 'sinon-chai';
import * as chaiAsPromised from 'chai-as-promised';

import * as mocks from '../../resources/mocks';
import { App } from '../../../src/app/index';
import {
  getDatabase, getDatabaseWithUrl, Database, ServerValue, enableLogging ,
} from '../../../src/database/index';
import { FirebaseApp } from '../../../src/app/firebase-app';

chai.should();
chai.use(sinonChai);
chai.use(chaiAsPromised);

const expect = chai.expect;

describe('Database', () => {
  let mockApp: App;

  beforeEach(() => {
    mockApp = mocks.app();
  });

  afterEach(() => {
    return (mockApp as FirebaseApp).delete();
  });

  describe('getDatabase()', () => {
    it('should throw when default app is not available', () => {
      expect(() => {
        return getDatabase();
      }).to.throw('The default Firebase app does not exist.');
    });

    it('should not throw given a valid app', () => {
      expect(() => {
        return getDatabase(mockApp);
      }).not.to.throw();
    });

    it('should return the same instance for a given app instance', () => {
      const db1: Database = getDatabase(mockApp);
      const db2: Database = getDatabase(mockApp);
      expect(db1).to.equal(db2);
    });
  });

  describe('getDatabaseWithUrl()', () => {
    it('should throw when default app is not available', () => {
      expect(() => {
        return getDatabaseWithUrl('https://test.firebaseio.com');
      }).to.throw('The default Firebase app does not exist.');
    });

    it('should not throw given a valid app', () => {
      expect(() => {
        return getDatabaseWithUrl('https://test.firebaseio.com', mockApp);
      }).not.to.throw();
    });

    it('should return the same instance for a given app instance', () => {
      const db1: Database = getDatabaseWithUrl('https://test.firebaseio.com', mockApp);
      const db2: Database = getDatabaseWithUrl('https://test.firebaseio.com', mockApp);
      const db3: Database = getDatabaseWithUrl('https://other.firebaseio.com', mockApp);
      expect(db1).to.equal(db2);
      expect(db1).to.not.equal(db3);
    });
  });

  it('should expose ServerValue sentinel', () => {
    expect(() => ServerValue.increment(1)).to.not.throw();
  });

  it('should expose enableLogging global function', () => {
    expect(() => {
      enableLogging(console.log);
      enableLogging(false);
    }).to.not.throw();
  });
});


text:
#include "vector.h"

#include "allocator.h"

#define INITIAL_VECTOR_CAPACITY 8

void wasm_ensure_capacity(WasmAllocator* allocator,
                                void** data,
                                size_t* capacity,
                                size_t desired_size,
                                size_t elt_byte_size) {
  if (desired_size > *capacity) {
    size_t new_capacity = *capacity ? *capacity * 2 : INITIAL_VECTOR_CAPACITY;
    while (new_capacity < desired_size)
      new_capacity *= 2;
    size_t new_byte_size = new_capacity * elt_byte_size;
    *data = wasm_realloc(allocator, *data, new_byte_size, WASM_DEFAULT_ALIGN);
    *capacity = new_capacity;
  }
}

void wasm_resize_vector(struct WasmAllocator* allocator,
                              void** data,
                              size_t* size,
                              size_t* capacity,
                              size_t desired_size,
                              size_t elt_byte_size) {
  size_t old_size = *size;
  wasm_ensure_capacity(allocator, data, capacity, desired_size, elt_byte_size);
  if (desired_size > old_size) {
    memset((void*)((size_t)*data + old_size * elt_byte_size), 0,
           (desired_size - old_size) * elt_byte_size);
  }
  *size = desired_size;
}

void* wasm_append_element(WasmAllocator* allocator,
                          void** data,
                          size_t* size,
                          size_t* capacity,
                          size_t elt_byte_size) {
  wasm_ensure_capacity(allocator, data, capacity, *size + 1, elt_byte_size);
  void* p = (void*)((size_t)*data + (*size)++ * elt_byte_size);
  memset(p, 0, elt_byte_size);
  return p;
}

void wasm_extend_elements(WasmAllocator* allocator,
                                void** dst,
                                size_t* dst_size,
                                size_t* dst_capacity,
                                const void** src,
                                size_t src_size,
                                size_t elt_byte_size) {
  wasm_ensure_capacity(allocator, dst, dst_capacity, *dst_size + src_size,
                       elt_byte_size);
  memcpy((void*)((size_t)*dst + (*dst_size * elt_byte_size)), *src,
         src_size * elt_byte_size);
  *dst_size += src_size;
}


text:
set -e

if [ -n "$TRAVIS_TAG" ] && [ "$DOCKER_VERSION" = "1.10.1" ]; then
  echo "Deploying..."
else
  echo "Skipping deploy"
  exit 0
fi

git config --global user.email "emile@vauge.com"
git config --global user.name "Emile Vauge"

# load ssh key
echo "Loading key..."
openssl aes-256-cbc -d -k "$pass" -in .travis/traefik.id_rsa.enc -out ~/.ssh/traefik.id_rsa
eval "$(ssh-agent -s)"
chmod 600 ~/.ssh/traefik.id_rsa
ssh-add ~/.ssh/traefik.id_rsa

# update traefik-library-image repo (official Docker image)
echo "Updating traefik-library-imag repo..."
git clone git@github.com:containous/traefik-library-image.git
cd traefik-library-image
./update.sh $VERSION
git add -A
echo $VERSION | git commit --file -
echo $VERSION | git tag -a $VERSION --file -
git push -q --follow-tags -u origin master > /dev/null 2>&1

# create docker image emilevauge/traefik (compatibility)
echo "Updating docker emilevauge/traefik image..."
docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS
docker tag containous/traefik emilevauge/traefik:latest
docker push emilevauge/traefik:latest
docker tag emilevauge/traefik:latest emilevauge/traefik:${VERSION}
docker push emilevauge/traefik:${VERSION}

cd ..
rm -Rf traefik-library-image/

echo "Deployed"