text:
module.exports = (function(){
    'use strict';

    var config = require('../config');
    var utils = require('../utils');

    return {
        getLatest: function(count, callback){
            var options = {}
            options.count = count;
            options.method = 'GET';
            options.uri = config.uri.GET_LATEST_NOTIFICATIONS;

            utils.exec(options, callback);
        },
        readAll: function(callback){
            var options = {};
            options.method = 'POST';
            options.uri = config.uri.READ_ALL_NOTIFICATIONS;

            utils.exec(options, callback);
        }
    }
})();


text:
% E. Dunham -- Resume
% Contents Copyright (C) 2014 - 2016, E. Dunham

% LaTeX code for rendering the resume is distributed under the MIT license.
% See LICENSE.txt. It means you can use the code for whatever you want,
% including your own resume, but I'm not liable if it catches your computer on
% fire.

% Template originally developed by E. Dunham
% https://github.com/edunham/resume/blob/master/resume.tex

\documentclass[11pt]{article} % Set default font size to 11pt
\input{preamble}
\begin{document}

\centerline{{\Huge \bf Megan Goossens}}
\bigskip

\contact{goossenm@oregonstate.edu}
        {}
        {github.com/MaraJade}
        {Cottage Grove, Oregon}

\heading{Skills}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\skill{Software Development}
      {Python, C, HTML/CSS/Javascript, Ruby, PHP}

\skill{Collaboration Software}
      {IRC, Git \& GitHub, Sphinx}

\heading{Employment}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{description}

\squish
\experience{Iron Horse Contracting, Inc}
           {Jumper}
           {11/2017 - 12/2017}

Assisted with the delivery of packages for FedEx customers

\squish
\experience{IEQ Technology, Inc.}
           {Web Developer}
           {12/2016 - 05/2017}

Developed PHP webapps

Maintained and updated PHP websites

Created themes for wordpress websites

Data Entry

\experience{OSU Open Source Lab}
           {Student Developer}
           {06/2014 - 08/2016}

Met with clients to determine design of APIs for mobile apps

Designed and implemented APIs in Django and NodeJS

Built webapps in Flask

Created plugins for Github and Fenestra in Ruby

\experience{OSU Central Web Services}
           {Student Developer}
           {03/2012 - 06/2014}

Met with clients to determine themeing of websites

Created themes for Drupal websites

Developed modules for Drupal

\end{description}

\heading{Leadership}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{description}
\squish
\experience{OSU Linux Users Group}
           {Webmaster}
           {2013 - 2014}

Maintained and updated group website, assisted with weekly meetings and events

\experience{OSU Chess Club}
           {Treasurer}
           {2013 - 2014}

Tracked fees and other monetary transactions

Assisted with weekly meetings and events

\end{description}

\heading{Academics}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{description}
\squish
\experience{Oregon State University}
           {}
           {2011-Present}

Upper-division coursework in Computer Science including Operating Systems,\\
Software Engineering, and Analysis of Algorithms.

\experience{Senior Capstone}
           {}
           {2015-2016}

Worked with Apache Software Foundation to improve community building website
Django prototype

\end{description}
\end{document}

redpajama_set_name: RedPajamaGithub


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

class GalleryItemTest < Test::Unit::TestCase
  fixtures :gallery_items

  # Replace this with your real tests.
  def test_truth
    assert true
  end
end


text:
import {ParamMetadata, PipeMethods} from "@tsed/platform-params";
import {Inject, Injectable} from "@tsed/di";
import {NotFound} from "@tsed/exceptions";
import {PersonModel} from "../models/PersonModel";
import {PersonsService} from "../models/PersonsService";

@Injectable()
export class PersonPipe implements PipeMethods<string, Promise<PersonModel>> {
  @Inject()
  personsService: PersonsService;

  async transform(id: string, metadata: ParamMetadata): Promise<PersonModel> {
    const person = await this.personsService.findOne(id);

    if (!person) {
      throw new NotFound("Person not found");
    }

    return person;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

    <TITLE>Dolphin Platform Core API Overview</TITLE>

This is the documentation of the public core API of Dolphin Platform.

The Dolphin Platform is a framework that implements the presentation model pattern and provides a modern way to create enterprise applications.
    The Platform provides several client implementations that all can be used in combination with a general sever API. By doing so you can create enterprise application with a single server and several desktop, web and mobile client implementations. Here the Dolphin Platforms define a mechanism to automatically snchronize models between the server and the client.

This module contains the public and general API of the Dolphin Platform core API that is used on server and client side.

You can find the documentation of the different modules here.

Additional information can be found on the Dolphin Platform website.


text:
static NSArray *networkFactories = nil;
static NSArray *dataStoreFactories = nil;

@implementation BMFDefaultFactory

+ (void) initialize {
	dataStoreFactories = [BMFDataStoreFactory availableFactories];
}

#pragma mark Network

- (id) loaderWithUrlString:(NSString *) urlString parameters:(NSDictionary *) parameters sender:(id) sender {
	BMFAFURLSessionLoader *loader = [BMFAFURLSessionLoader new];

	loader.url = [NSURL URLWithString:urlString];
	loader.parameters = parameters;

	return loader;
}

- (id) loaderOperationWithUrlString:(NSString *) urlString parameters:(NSDictionary *) parameters sender:(id) sender {
	return [[BMFLoaderOperation alloc] initWithLoader:[self loaderWithUrlString:urlString parameters:parameters sender:sender]];
}

- (id) fileLoaderWithUrl:(NSURL *) fileURL {
	BMFFileLoader *loader = [BMFFileLoader new];
	loader.fileUrl = fileURL;
	return loader;
}

- (id) fileLoaderOperationWithUrl:(NSURL *) fileURL sender:(id) sender {
	return [[BMFLoaderOperation alloc] initWithLoader:[self fileLoaderWithUrl:fileURL]];
}

- (id<BMFTaskProtocol>) dataLoadTask:(NSString *) urlString parameters:(NSDictionary *) parameters sender:(id) sender {

	BMFOperation *loadOperation = [self loaderOperationWithUrlString:urlString parameters:parameters sender:sender];

	id<BMFTaskProtocol> task = [[BMFOperationsTask alloc] initWithOperations:@[ loadOperation ]];
	return task;
}

- (id<BMFTaskProtocol>) imageLoadTask:(NSString *) urlString parameters:(NSDictionary *) parameters sender:(id) sender {

	BMFOperation *loadOperation = [self loaderOperationWithUrlString:urlString parameters:parameters sender:sender];

	BMFOperation *serializeOperation = [self imageSerializerOperation:sender];

	id<BMFTaskProtocol> task = [[BMFOperationsTask alloc] initWithOperations:@[ loadOperation, serializeOperation ]];

	return task;
}

#pragma mark Serializers
- (id<BMFSerializerProtocol>) jsonSerializer:(id)sender {
	return [BMFJSONSerializer new];
}

- (id<BMFSerializerProtocol>) imageSerializer:(id)sender{
	return [BMFImageSerializer new];
}

- (BMFOperation *) jsonSerializerOperation:(id)sender {
	return [[BMFSerializerOperation alloc] initWithSerializer:[self jsonSerializer:(id)sender]];
}

- (BMFOperation *) imageSerializerOperation:(id)sender {
	return [[BMFSerializerOperation alloc] initWithSerializer:[self imageSerializer:(id)sender]];
}

#pragma mark Data Stores

- (id<BMFDataReadProtocol>) dataStoreWithParameter:(id) input sender:(id) sender {
	for (id<BMFDataStoresFactoryProtocol> factory in dataStoreFactories) {
		id object = [factory dataStoreWithParameter:input sender:sender];
		if (object) return object;
	}

	return nil;
}

- (id<BMFDataReadProtocol>) dataStoreWithParameters:(NSArray *) parameters sender:(id) sender {
	if (parameters.count==1) return [self dataStoreWithParameter:parameters.firstObject sender:sender];

	for (id<BMFDataStoresFactoryProtocol> factory in dataStoreFactories) {
		id object = [factory dataStoreWithParameters:parameters sender:sender];
		if (object) return object;
	}

	return nil;
}

@end


text:
import _ from 'lodash';
import { BlockchainMonitor } from '../lib/blockchainmonitor';
import logger from '../lib/logger';

const config = require('../config');
const bcm = new BlockchainMonitor();
bcm.start(config, err => {
  if (err) throw err;

  logger.info('Blockchain monitor started');
});


text:
Ingresá

                Mail
                <input type="text" class="form-control" ng-model="loginCtrl.loginForm.mail" placeholder="Mail...">

                Contraseña
                <input type="password" class="form-control"
                       ng-model="loginCtrl.loginForm.password"
                       ng-keyup="loginCtrl.passwordEnter($event);"
                       placeholder="Contraseña...">

                Recuperar Contraseña

                <button class="btn-big" ng-click="loginCtrl.login();">Aceptar</button>
                <button class="btn-big" ng-click="loginCtrl.createUsuario();">Nuevo Usuario</button>

{{loginCtrl.message}}


text:
<?php
class Kwf_Component_Cache_FullPage_Test extends Kwc_TestAbstract
{
    public function setUp()
    {
        parent::setUp('Kwf_Component_Cache_FullPage_Root');
    }

    /*
    test1 -> embeds test2 -> links test4
          -> links test3
    */

    private function _getViewCacheCount()
    {
        $s = new Kwf_Model_Select();
        $s->whereEquals('deleted', false);
        return Kwf_Component_Cache::getInstance()->getModel()->countRows($s);
    }

    public function testEmbedContent()
    {
        $html = $this->_root->getChildComponent('_test1')->render(null, true);
        $this->assertContains('content2', $html);
        $this->assertContains('/test3"', $html);

        $this->assertEquals(7, $this->_getViewCacheCount());
        /*
        - root_test1:page
        - root_test1:master
        - root_test1:component
        - root_test2:component       [delete]
        - root_test4:componentLink
        - root_test3:componentLink
        - root_test1:fullPage        [delete]
        */

        $row = Kwf_Model_Abstract::getInstance('Kwf_Component_Cache_FullPage_Test2_Model')->getRow('root_test2');
        $row->test = 'foo2';
        $row->save();
        $this->_process();

        $this->assertEquals(5, $this->_getViewCacheCount());
        $html = $this->_root->getChildComponent('_test1')->render(null, true);
        $this->assertContains('foo2', $html);
        $this->assertContains('/test3"', $html);
        $this->assertEquals(7, $this->_getViewCacheCount());
    }

    public function testLinkTargetContentsChanged()
    {
        $html = $this->_root->getChildComponent('_test1')->render(null, true);
        $this->_root->getChildComponent('_test3')->render(null, true);
        $this->assertContains('content2', $html);
        $this->assertContains('/test3"', $html);
        $this->assertEquals(7+4, $this->_getViewCacheCount());

        $row = Kwf_Model_Abstract::getInstance('Kwf_Component_Cache_FullPage_Test3_Model')->getRow('root_test3');
        $row->test = 'foo3';
        $row->save();
        $this->_process();
        /*
        - root_test1:page
        - root_test1:master
        - root_test1:component
        - root_test2:component
        - root_test4:componentLink
        - root_test3:componentLink
        - root_test1:fullPage

        - root_test3:page
        - root_test3:master
        - root_test3:component       [delete]
        - root_test3:fullPage        [delete]
        */
/*
$s = new Kwf_Model_Select();
foreach (Kwf_Component_Cache::getInstance()->getModel('includes')->getRows($s) as $row) {
    echo $row->component_id.':'.$row->type.' -> '.$row->target_id;
    echo "\n";
}
echo "\n";

$s = new Kwf_Model_Select();
foreach (Kwf_Component_Cache::getInstance()->getModel()->getRows($s) as $row) {
    echo $row->component_id.':'.$row->type;
    if ($row->deleted) echo " [deleted]";
    echo "\n";
}
*/

        $this->assertEquals(7+4-2, $this->_getViewCacheCount());
        $html = $this->_root->getChildComponent('_test1')->render(null, true);
        $this->assertContains('content2', $html);
        $this->assertContains('/test3"', $html);
        $this->assertEquals(7+4-2, $this->_getViewCacheCount());
    }

    public function testLinkTargetChanged1()
    {
        $html = $this->_root->getChildComponent('_test1')->render(null, true);
        $this->assertContains('content2', $html);
        $this->assertContains('/test3"', $html);
        $this->assertEquals(7, $this->_getViewCacheCount());
        /*
        - root_test1:page
        - root_test1:master
        - root_test1:component
        - root_test2:component
        - root_test4:componentLink
        - root_test3:componentLink   [delete]
        - root_test1:fullPage        [delete]
        */

        Kwf_Events_Dispatcher::fireEvent(new Kwf_Component_Event_Page_UrlChanged('Kwf_Component_Cache_FullPage_Test3_Component', $this->_root->getChildComponent('_test3')));
        $this->_process();

        $this->assertEquals(5, $this->_getViewCacheCount());
        $html = $this->_root->getChildComponent('_test1')->render(null, true);
        $this->assertContains('content2', $html);
        $this->assertContains('/test3"', $html);
        $this->assertEquals(7, $this->_getViewCacheCount());
    }

    public function testLinkTargetChanged2()
    {
        $html = $this->_root->getChildComponent('_test1')->render(null, true);
        $this->assertContains('content2', $html);
        $this->assertContains('/test3"', $html);
        $this->assertEquals(7, $this->_getViewCacheCount());
        /*
        - root_test1:page
        - root_test1:master
        - root_test1:component
        - root_test2:component
        - root_test4:componentLink   [delete]
        - root_test3:componentLink
        - root_test1:fullPage        [deleted]
        */

        $this->_root->getChildComponent('_test2')->render(null, true);

        /*
        - root_test2:page
        - root_test2:master
        - root_test2:fullPage        [delete]
        */
        $this->assertEquals(7+3, $this->_getViewCacheCount());

        $this->_root->getChildComponent('_test3')->render(null, true);
        /*
        - root_test3:page
        - root_test3:master
        - root_test3:component
        - root_test3:fullPage
        */
        $this->assertEquals(7+3+4, $this->_getViewCacheCount());

        $this->_root->getChildComponent('_test4')->render(null, true);
        /*
        - root_test4:page
        - root_test4:master
        - root_test4:component
        - root_test4:fullPage        [delete]
        */
        $this->assertEquals(7+3+4+4, $this->_getViewCacheCount());

        Kwf_Events_Dispatcher::fireEvent(new Kwf_Component_Event_Page_UrlChanged('Kwf_Component_Cache_FullPage_Test4_Component', $this->_root->getChildComponent('_test4')));
        $this->_process();

        $this->assertEquals(7+3+4+4 - 4, $this->_getViewCacheCount());

        $html = $this->_root->getChildComponent('_test1')->render(null, true);
        $this->assertContains('content2', $html);
        $this->assertContains('/test3"', $html);
        $this->assertEquals(7+3+4+4 - 4 +2, $this->_getViewCacheCount());

        $this->_root->getChildComponent('_test2')->render(null, true);
        $this->assertEquals(7+3+4+4 - 4 +2+1, $this->_getViewCacheCount());

        $this->_root->getChildComponent('_test3')->render(null, true);
        $this->assertEquals(7+3+4+4 - 4 +2+1, $this->_getViewCacheCount());

        $this->_root->getChildComponent('_test4')->render(null, true);
        $this->assertEquals(7+3+4+4 - 4 +2+1+1, $this->_getViewCacheCount());
    }
}


text:
	// utilities
var pick = require('broccoli-static-compiler'),
	merge = require('broccoli-merge-trees'),
	env = require('broccoli-env').getEnv();
	// filters
	transpileES6 = require('broccoli-es6-transpiler'),
	transpileES6Modules = require('broccoli-es6-module-transpiler'),
	clean = require('./broccoli/clean-transpiled');

function copy( path ) {
	return pick( path, { srcDir: '/', destDir: '/' + path } );
}

function makeGlobals ( globals ) {
	return globals.reduce( function( obj, global ) {
		obj[ global ] = true;
		return obj;
	}, {} )
}

var globals = ['define', 'Promise'];

function transpile ( tree ) {

	return transpileES6( tree, {
		globals: makeGlobals( globals )
	});

}

function fullTranspile ( tree ) {

	tree = transpileES6Modules( tree, {
		moduleName: function(filePath) {
			return filePath.replace(/.js$/, '');
  		}
	});

	tree = transpile( tree );

	return clean( tree );
}

var src = pick('src', {
		srcDir: '/',
		files: [ '**/*.js' ],
		destDir: '/src'
	});
src = fullTranspile( src )

globals = globals.concat( [
	'QUnit', '_modules', 'test', 'start', 'asyncTest',
	'ok', 'equal', 'notEqual',  'deepEqual', 'expect', 'throws' ] );

globals = globals.concat( [ 'simulant', 'HTMLDocument', 'jQuery', 'MouseEvent' ] );

var test = transpile( copy( 'test' ) );

var out = [ src, test ];
if ( env !== 'production' ) { out = out.concat( [ copy( 'sandbox' ) ] ); }

module.exports = merge( out );


text:
import { orderBy, groupBy } from 'lodash'

function OverviewController ($scope, $stateParams, $filter, dataFactory) {
  'ngInject'

  this.currentMonth = new Date($stateParams.year, $stateParams.month - 1)

  const previousMonth = new Date(this.currentMonth)
  previousMonth.setMonth(this.currentMonth.getMonth() - 1)
  this.previousMonthLinkParams = {
    year: $filter('date')(previousMonth, 'yyyy'),
    month: $filter('date')(previousMonth, 'MM')
  }

  const nextMonth = new Date(this.currentMonth)
  nextMonth.setMonth(this.currentMonth.getMonth() + 1)
  this.nextMonthLinkParams = {
    year: $filter('date')(nextMonth, 'yyyy'),
    month: $filter('date')(nextMonth, 'MM')
  }

  this.monthExpenses = null
  this.expensesByDay = null

  const fetchExpenses = () => {
    dataFactory.findExpensesByMonth(this.currentMonth).then(expenses => {
      if (expenses.length > 0) {
        const orderedExpenses = orderBy(expenses, 'date', 'desc')

        this.expensesByDay = groupBy(orderedExpenses, expense => {
          const date = new Date(expense.date)
          return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
        })
      }

      this.monthExpenses = expenses
          .map(val => val.amount)
          .reduce((prev, curr) => prev + curr, 0)
    })
  }

  fetchExpenses()

  const unsubscribeExpenseUpdates = dataFactory.onExpenseUpdate(fetchExpenses)
  $scope.$on('$destroy', unsubscribeExpenseUpdates)
}

export default OverviewController


text:
const _ = require('lodash');

const {gen: tcg} = require('testcheck');

const {conform} = require('./conform');
const {explainData} = require('./explainData');
const isValid = require('./isValid');
const {gen} = require('./gen');

const describe = require('./util/describe');

function nilable(predicate) {
    return {
        conform: value => _.isNull(value) ? null : conform(predicate, value),
        unform: _.identity,
        gen: () => tcg.null.then(() => _.random(10) < 2 ? tcg.null : gen(predicate)),
        describe: () => [nilable.name, ...describe([predicate])],
        explain: function*(value, {via}) {
            if (!(_.isNull(value) || isValid(predicate, value))) {
                yield explainData(predicate, value, {path: ['pred'], via}).problems[0];

                yield {
                    path: ['null'],
                    pred: 'isNull',
                    val: value,
                    via,
                    'in': []
                };
            }
        }
    };
}

module.exports = nilable;


text:
from datetime import datetime

from django.core.urlresolvers import reverse
from django_webtest import WebTest

from ..factories._accounts import UserFactory
from ..factories._openings import OpeningFactory
from ..factories._companies import CompanyFactory

from openings.models import Opening
from tests.utils import subdomain_get

class OpeningsViewsTests(WebTest):

    def setUp(self):
        self.user = UserFactory()

    def test_arriving_on_opening_creation_page(self):
        url = reverse('openings:create_opening')
        response = subdomain_get(self.app, url, user=self.user)
        self.assertEqual(response.status_code, 200)

    def test_opening_creation(self):
        url = reverse('openings:create_opening')

        page = subdomain_get(self.app, url, user=self.user)
        form = page.forms[0]

        form['title'] = 'Software Developer'
        form['description'] = 'Fait des logiciels.'
        form['is_private'] = ''
        form['country'] = 'FR'
        form['city'] = 'Cannes'
        response = form.submit().follow()

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Opening created.")

        opening_created = Opening.objects.get()

        self.assertEqual(opening_created.company, self.user.company)
        self.assertEqual(opening_created.title, 'Software Developer')

    def test_opening_creation_invalid(self):
        url = reverse('openings:create_opening')

        page = subdomain_get(self.app, url, user=self.user)
        form = page.forms[0]
        form['title'] = 'Software Developer'
        form['description'] = ''
        form['is_private'] = ''
        form['country'] = 'FR'
        form['city'] = 'Cannes'
        response = form.submit()

        self.assertEqual(response.status_code, 200)

        self.assertEqual(Opening.objects.count(), 0)

    def test_opening_edit(self):
        opening = OpeningFactory(title='DevOps', company=self.user.company)
        url = reverse('openings:update_opening', args=(opening.id,))

        page = subdomain_get(self.app, url, user=self.user)
        form = page.forms[0]
        form['title'] = 'Software Developer'
        response = form.submit().follow()

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'Software Developer')
        self.assertNotContains(response, 'DevOps')

    def test_cant_edit_other_company_opening(self):
        opening = OpeningFactory(title='DevOps', company=CompanyFactory())
        url = reverse('openings:update_opening', args=(opening.id,))
        subdomain_get(self.app, url, user=self.user, status=404)

    def test_opening_delete(self):
        opening = OpeningFactory(title='DevOps', company=self.user.company)
        url = reverse('openings:delete_opening', args=(opening.id,))

        response = subdomain_get(self.app, url, user=self.user)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.request.path,
            reverse('openings:list_openings')
        )
        self.assertNotContains(response, 'DevOps')
        self.assertContains(response, 'Opening deleted.')

    def test_opening_listing(self):
        url = reverse('openings:list_openings')
        opening = OpeningFactory(title='DevOps', company=self.user.company)
        response = subdomain_get(self.app, url, user=self.user)
        self.assertContains(response, opening.title)

    def test_opening_detail_view(self):
        opening = OpeningFactory(title='DevOps', company=self.user.company)
        url = reverse('openings:detail_opening', args=(opening.id,))
        response = subdomain_get(self.app, url, user=self.user)
        self.assertContains(response, opening.title)

    def test_close_opening_valid(self):
        opening = OpeningFactory(title='DevOps', company=self.user.company)
        url = reverse('openings:publish_opening', args=(opening.id,))
        subdomain_get(self.app, url, user=self.user)

        self.assertEqual(
            Opening.objects.filter(published_date__isnull=True).count(), 0
        )

    def test_publish_opening(self):
        opening = OpeningFactory(company=self.user.company)
        url = reverse('openings:publish_opening', args=(opening.id,))
        subdomain_get(self.app, url, user=self.user)

        self.assertIsNotNone(Opening.objects.get().published_date)

    def test_unpublish_opening(self):
        opening = OpeningFactory(
            company=self.user.company, published_date=datetime.now()
        )
        url = reverse('openings:publish_opening', args=(opening.id,))
        subdomain_get(self.app, url, user=self.user)

        self.assertIsNone(Opening.objects.get().published_date)

    def test_publish_another_company_opening(self):
        opening = OpeningFactory(
            company=self.user.company, published_date=datetime.now()
        )
        user2 = UserFactory()
        url = reverse('openings:publish_opening', args=(opening.id,))
        subdomain_get(self.app, url, user=user2, status=404)


text:
<?php
class pagesController extends controller {
    public function recreatePages() {
		$res = new response();
		if($this->getModel()->recreatePages()) {
			$res->addMessage(lang::_('Pages was recreated'));
		} else {
			$res->pushError($this->getModel()->getErrors());
		}
		$res->ajaxExec();
	}
}
?>


text:
from lib.common import helpers

class Module:

    def __init__(self, mainMenu, params=[]):

        self.info = {
            'Name': 'Invoke-ReverseDNSLookup',

            'Author': ['DarkOperator'],

            'Description': ('Performs a DNS Reverse Lookup of a given IPv4 IP Range.'),

            'Background' : True,

            'OutputExtension' : None,

            'NeedsAdmin' : False,

            'OpsecSafe' : True,

            'MinPSVersion' : '2',

            'Comments': [
                'https://github.com/darkoperator/Posh-SecMod/blob/master/Discovery/Discovery.psm1'
            ]
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent' : {
                'Description'   :   'Agent to run module on.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'Range' : {
                'Description'   :   "Range to perform reverse DNS on.",
                'Required'      :   False,
                'Value'         :   ''
            },
            'CIDR' : {
                'Description'   :   "CIDR to perform reverse DNS on.",
                'Required'      :   False,
                'Value'         :   ''
            }
        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        for param in params:
            # parameter format is [Name, Value]
            option, value = param
            if option in self.options:
                self.options[option]['Value'] = value

    def generate(self):

        # read in the common module source code
        moduleSource = self.mainMenu.installPath + "/data/module_source/situational_awareness/Network/Invoke-ReverseDNSLookup.ps1"

        try:
            f = open(moduleSource, 'r')
        except:
            print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
            return ""

        moduleCode = f.read()
        f.close()

        script = moduleCode

        script += "Invoke-ReverseDNSLookup"

        for option,values in self.options.iteritems():
            if option.lower() != "agent":
                if values['Value'] and values['Value'] != '':
                    if values['Value'].lower() == "true":
                        # if we're just adding a switch
                        script += " -" + str(option)
                    else:
                        script += " -" + str(option) + " " + str(values['Value'])

        # only return objects where HostName is not an IP (i.e. the address resolves)
        script += " | % {try{$entry=$_; $ipObj = [System.Net.IPAddress]::parse($entry.HostName); if(-not [System.Net.IPAddress]::tryparse([string]$_.HostName, [ref]$ipObj)) { $entry }} catch{$entry} } | Select-Object HostName, AddressList | ft -autosize | Out-String | %{$_ + \"`n\"}"

        return script


text:
package org.onepf.opfiab.samsung;

import android.content.Context;
import android.support.annotation.NonNull;

import org.json.JSONException;
import org.onepf.opfiab.model.billing.Purchase;
import org.onepf.opfiab.samsung.model.SamsungVerification;
import org.onepf.opfiab.util.OPFIabUtils;
import org.onepf.opfiab.verification.PurchaseVerifier;
import org.onepf.opfiab.verification.VerificationResult;
import org.onepf.opfutils.OPFLog;
import org.onepf.opfutils.OPFUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class SamsungPurchaseVerifier implements PurchaseVerifier {

    protected static final int TIMEOUT = 3000;
    protected static final String VERIFY_URL
            = "https://iap.samsungapps.com/iap/appsItemVerifyIAPReceipt.as?protocolVersion=2.0"
            + "&purchaseID=";

    @NonNull
    protected final Context context;
    @NonNull
    protected final BillingMode billingMode;

    public SamsungPurchaseVerifier(@NonNull final Context context,
                                   @NonNull final BillingMode billingMode) {
        this.context = context;
        this.billingMode = billingMode;
    }

    @NonNull
    @Override
    public VerificationResult verify(@NonNull final Purchase purchase) {
        if (!OPFUtils.isConnected(context)) {
            OPFLog.e("Can't verify purchase, no connection.");
            return VerificationResult.ERROR;
        }
        try {
            final HttpURLConnection connection = (HttpURLConnection)
                    new URL(VERIFY_URL + purchase.getToken()).openConnection();
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            connection.connect();
            final int responseCode = connection.getResponseCode();
            OPFLog.d("Verify response code: " + responseCode);
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return VerificationResult.ERROR;
            }
            final String body = OPFIabUtils.toString(connection.getInputStream());
            final SamsungVerification verification = new SamsungVerification(body);
            OPFLog.d("Samsung verification: " + verification);
            return verification.isStatus()  && verification.getMode() == this.billingMode
                    ? VerificationResult.SUCCESS : VerificationResult.FAILED;
        } catch (IOException | JSONException exception) {
            OPFLog.e("", exception);
        }
        return VerificationResult.ERROR;
    }
}


text:
package com.novoda.merlin.registerable.connection;

public interface ConnectListener extends Connectable {
}


text:
package org.ooc.compiler;

import java.util.Collection;

import org.ooc.backends.ProjectInfo;
import org.ooc.compiler.libraries.LibraryManager;
import org.ooc.errors.MaxedOutPassLimit;
import org.ooc.errors.SourceContext;
import org.ooc.parsers.SourceParser;
import org.ubi.CompilationFailedError;

/**
 * ooc's public interface to compile
 *
 * @author Amos Wenger
 */
public class Compiler {

	protected final SourceParser parser;

	protected FileContentProvider provider;

	/**
	 * @see LibraryManager
	 */
	public final static LibraryManager libManager = new LibraryManager();

	/**
	 * Default constructor.
	 */
	public Compiler() {

		this.provider = new FileContentProvider(null);
		this.parser = new SourceParser(provider);

	}

	/**
	 * Compile sourceName, with all specified build properties, and return 0 on
	 * success, and a non-zero value on failure. The specified projInfo will be
	 * filled with information (e.g. executables, modules) about the compilation.
	 * @param props the build properties
	 * @param sourceName the full name of the source to build e.g. "my.package.MyClass"
	 * @param projInfo a project info that will contain everything there is to know
	 * about the compilation (e.g. executables/modules, dependencies, etc.)
	 * @return 0 on success, any other value if there's any problem
	 * @throws Exception
	 */
	public synchronized int compile(ProjectInfo projInfo, String sourceName) throws Exception {

		BuildProperties props = projInfo.props;
		provider.setSourcePath(props.sourcePath);

		try {

			SourceContext mainSource = parser.parse(projInfo, sourceName, true);
			if(!mainSource.isAssembled()) {
				System.out.println(mainSource.source.getInfo().fullName+" failed to compile, abandoning.");
				return 1;
			}

			projInfo.addSourceRecursive(mainSource);

	        if(props.backend != null) {

	        	libManager.resolveLibraries("gc", projInfo);
	        	return props.backend.compile(projInfo, props);

	        }

	        return 0;

		} catch(MaxedOutPassLimit e) {

			return 1;

		} catch(CompilationFailedError e) {

			System.err.println(e.getMessage());
			return 1;

		}

    }

	/**
	 * Clear the source cache
	 */
	public void clearCache() {

		parser.clearCache();

	}

	/**
	 * @return all sources processed by this compiler
	 */
	public Collection<SourceContext> getSources() {

		return parser.getSources().values();

	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ReactiveUI;
using System.Reactive.Linq;
using VirtualSales.Models;

namespace VirtualSales.Core.Models
{
    public class PersonModel : ReactiveObject
    {
        private string _firstName;
        private string _lastName;
        private Gender? _gender;
        private DateTime? _dateOfBirth;
        private int? _numOfDependents;
        private bool _isSmoker;
        private int? _coverageAmountRequesting;
        private int? _existingCoverage;
        private int? _retirementAge;
        private int? _annualIncome;
        private int? _annualIncomeGrowthPercent;
        private string _addr1, _addr2, _city, _state, _zip;
        private readonly ObservableAsPropertyHelper<int?> _ageObservable;

        public PersonModel()
        {
            _isSmoker = false;
            this.WhenAnyValue(p => p.DateOfBirth).Select(p =>
                                                                 {
                                                                     if (!p.HasValue) return null;
                                                                     var dob = p.Value;
                                                                     var today = DateTime.Today;
                                                                     int? age = today.Year - dob.Year;
                                                                     if (dob > today.AddYears(-age.Value)) age--;
                                                                     return age;
                                                                 }).ToProperty(this, p => p.Age, out _ageObservable);
        }

        public string FirstName
        {
            get { return _firstName; }
            set { this.RaiseAndSetIfChanged(ref _firstName, value); }
        }

        public string LastName
        {
            get { return _lastName; }
            set { this.RaiseAndSetIfChanged(ref _lastName, value); }
        }

        public Gender? Gender
        {
            get { return _gender; }
            set { this.RaiseAndSetIfChanged(ref _gender, value); }
        }

        public DateTime? DateOfBirth
        {
            get { return _dateOfBirth; }
            set { this.RaiseAndSetIfChanged(ref _dateOfBirth, value); }
        }

        public int? NumOfDependents
        {
            get { return _numOfDependents; }
            set { this.RaiseAndSetIfChanged(ref _numOfDependents, value); }
        }

        public int? AnnualIncome
        {
            get { return _annualIncome; }
            set { this.RaiseAndSetIfChanged(ref _annualIncome, value); }
        }

        public int? AnnualIncomeGrowthPercent
        {
            get { return _annualIncomeGrowthPercent; }
            set { this.RaiseAndSetIfChanged(ref _annualIncomeGrowthPercent, value); }
        }

        public int? RetirementAge
        {
            get { return _retirementAge; }
            set { this.RaiseAndSetIfChanged(ref _retirementAge, value); }
        }

        public int? ExistingCoverage
        {
            get { return _existingCoverage; }
            set { this.RaiseAndSetIfChanged(ref _existingCoverage, value); }
        }

        public int? CoverageAmountRequesting
        {
            get { return _coverageAmountRequesting; }
            set { this.RaiseAndSetIfChanged(ref _coverageAmountRequesting, value); }
        }

        public bool IsSmoker
        {
            get { return _isSmoker; }
            set { this.RaiseAndSetIfChanged(ref _isSmoker, value); }
        }

        public int? Age
        {
            get { return _ageObservable.Value; }
        }

        public string Addr1
        {
            get { return _addr1; }
            set { this.RaiseAndSetIfChanged(ref _addr1, value); }
        }

        public string Addr2
        {
            get { return _addr2; }
            set { this.RaiseAndSetIfChanged(ref _addr2, value); }
        }

        public string City
        {
            get { return _city  ; }
            set { this.RaiseAndSetIfChanged(ref _city, value); }
        }

        public string State
        {
            get { return _state; }
            set { this.RaiseAndSetIfChanged(ref _state, value); }
        }

        public string Zip
        {
            get { return _zip; }
            set { this.RaiseAndSetIfChanged(ref _zip, value); }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Discord.Commands;
using Discord;

using DiscordBot.Common;

namespace DiscordBot.Modules.Public
{
    [Name("Help Commands")]
    public class HelpModule : ModuleBase<CommandContext>
    {
        public CommandService Service;

        public List<IUserMessage> HelpMessages = new List<IUserMessage>();
        public List<List<string>> HelpList = new List<List<string>>();

        public HelpModule(CommandService service)
        {
            Service = service;
        }

        [Command("help")]
        public async Task HelpAsync(string command = null)
        {
            if(command == null)
            {
                string prefix = GuildConfiguration.Load(Context.Guild.Id).Prefix;
                var builder = new EmbedBuilder()
                {
                    Color = new Color(114, 137, 218),
                    Description = "These are the commands you can use."
                };

                foreach (var module in Service.Modules)
                {
                    string description = null;
                    foreach (var cmd in module.Commands)
                    {
                        var result = await cmd.CheckPreconditionsAsync(Context);
                        if (result.IsSuccess)
                        {
                            if (cmd.Summary == "" || cmd.Summary == null)
                            {
                                description += $"{prefix}{cmd.Aliases.First()}\n";
                            }
                            else
                            {
                                description += $"{prefix}{cmd.Aliases.First()} - {cmd.Summary}\n";
                            }
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(description))
                    {
                        builder.AddField(x =>
                        {
                            x.Name = module.Name;
                            x.Value = description;
                            x.IsInline = false;
                        });
                    }
                }

                await ReplyAsync(Context.User.Mention + ", I've sent you a DM with the information you requested.");
                await Context.User.GetOrCreateDMChannelAsync().Result.SendMessageAsync("", false, builder.Build());
            }
            else
            {
                var result = Service.Search(Context, command);

                if (!result.IsSuccess)
                {
                    await ReplyAsync($"Sorry, I couldn't find a command like **{command}**.");
                    return;
                }

                string prefix = GuildConfiguration.Load(Context.Guild.Id).Prefix;
                var builder = new EmbedBuilder()
                {
                    Color = new Color(114, 137, 218),
                    Description = $"Here are some commands like **{command}**"
                };

                foreach (var match in result.Commands)
                {
                    var cmd = match.Command;

                    builder.AddField(x =>
                    {
                        x.Name = string.Join(", ", cmd.Aliases);
                        x.Value = $"Parameters: {string.Join(", ", cmd.Parameters.Select(p => p.Name))}\n" +
                                  $"Remarks: {cmd.Remarks}";
                        x.IsInline = false;
                    });
                }

                await ReplyAsync(Context.User.Mention + ", I've sent you a DM with the information you requested.");
                await Context.User.GetOrCreateDMChannelAsync().Result.SendMessageAsync("", false, builder.Build());
            }
        }
    }

}


text:
title: getPreviousSibling
name: node-functions-getprevioussibling
---

Get the previous sibling of this node. Returns a node or null.

{% highlight js %}
var node = node.getPreviousSibling();
{% endhighlight %}


text:
package com.github.davidmoten.grumpy.wms.reduction;

import java.awt.Graphics2D;
import java.awt.Rectangle;

import com.github.davidmoten.grumpy.projection.Projector;

public interface ValueRenderer<T> {
    void render(Graphics2D g, Projector projector, Rectangle region, final T t);
}


text:
/**
 * @brief A test class for OthRules
 * @details
 *
 * OthRules.winCondition is tested 3 times.
 *
 * OthRules.checkValidSet is tested 1 time(s).
 * during this test, methods:
 * 		OthRules.checkAvailableMatch
 * 		OthRules.checkVerticalDown
 * 		OthRules.checkVerticalUp
 * 		OthRules.checkRowsRight
 * 		OthRules.checkRowsLeft
 * 		OthRules.checkDiagonalUpRight
 * 		OthRules.checkDiagonalUpLeft
 * 		OthRules.checkDiagonalDownRight
 * 		OthRules.checkDiagonalDownLeft
 * 		are also called.
 *
 * 		OthRules.flipCounters is tested one time(s).
 * 		during this test, methods:
 * 		OthRules.flipVerticalDown
 * 		OthRules.flipVerticalUp
 * 		OthRules.flipRowsRight
 * 		OthRules.flipRowsLeft
 * 		OthRules.flipDiagonalUpRight
 * 		OthRules.flipDiagonalUpLeft
 * 		OthRules.flipDiagonalDownRight
 * 		OthRules.flipDiagonalDownLeft
 * 		are also called.
 *
 * @author Tom
 *
 */
public class TestOthRules {

	private static final int COLUMN = 8;
	private static final int ROW = 8;
	private static final int NO_MATCH = 0;
	private static final int PLAYER_ONE = 1;
	private static final int PLAYER_TWO = 2;
	private static final int FLIP_COL = 5;
	private static final int FLIP_ROW = 4;
	private static final int CHECK_COL = 4;
	private static final int CHECK_ROW = 4;

	private static OthGame m_othGame;
	private static OthRules m_othRules;

	public static void main(String args[]) {

		/*
		 * OthRules.winCondition Test One:
		 * Filled board of PLAYER_ONE counters
		 */
		m_othRules = new OthRules();

		OthCounter[][] m_testBoard1 = new OthCounter[COLUMN][ROW];
		for(int i = 0; i < COLUMN; i++) {
			for(int j = 0; j < ROW; j++) {
				OthCounter counter = new OthCounter(1);
				m_testBoard1[i][j] = counter;
			}
		}

		if(m_othRules.winCondition(m_testBoard1) == PLAYER_ONE) {
			System.out.println("OthRules.winCondition Test One Evaluated: Correct");
		} else {
			System.out.println("OthRules.winCondition Test One Evaluated: Incorrect");
		}

		/*
		 * OthRules.winCondition Test Two:
		 * Filled board of PLAYER_TWO counters
		 */
		m_othRules = new OthRules();

		OthCounter[][] m_testBoard2 = new OthCounter[COLUMN][ROW];
		for(int i = 0; i < COLUMN; i++) {
			for(int j = 0; j < ROW; j++) {
				OthCounter counter = new OthCounter(2);
				m_testBoard2[i][j] = counter;
			}
		}

		if(m_othRules.winCondition(m_testBoard2) == PLAYER_TWO) {
			System.out.println("OthRules.winCondition Test Two Evaluated: Correct");
		} else {
			System.out.println("OthRules.winCondition Test Two Evaluated: Incorrect");
		}

		/*
		 * OthRules.winCondition Test Two:
		 * Empty board (counters of player 0 are not visible)
		 */
		m_othRules = new OthRules();

		OthCounter[][] m_testBoard3 = new OthCounter[COLUMN][ROW];
		for(int i = 0; i < COLUMN; i++) {
			for(int j = 0; j < ROW; j++) {
				OthCounter counter = new OthCounter(0);
				m_testBoard3[i][j] = counter;
			}
		}

		if(m_othRules.winCondition(m_testBoard3) == NO_MATCH) {
			System.out.println("OthRules.winCondition Test Three Evaluated: Correct");
		} else {
			System.out.println("OthRules.winCondition Test Three Evaluated: Incorrect");
		}

		/*
		 * OthRules.checkValidSet Test One:
		 * Testing the filled board of PLAYER_ONE counters
		 * All positions filled, so no valid moves should be possible
		 */
		m_othRules = new OthRules();

		int[][] validSet1 = m_othRules.checkValidSet(m_testBoard1);
		boolean correct1 = true;
		for(int i = 0; i < COLUMN; i++) {
			for(int j = 0; j < ROW; j++) {
				if(validSet1[i][j] != 0) {
					correct1 = false;
				}
			}
		}

		if(correct1 == true) {
			System.out.println("OthRules.checkValidSet Test One Evaluated: Correct");
		} else {
			System.out.println("OthRules.checkValidSet Test One Evaluated: Incorrect");
		}

		/*
		 * OthRules.flipCounters Test One
		 * Constructs an OthGame with default counter setup,
		 * then places a specific counter at [FLIP_COL][FLIP_ROW] and tests expected result.
		 */
		m_othRules = new OthRules();
		m_othGame = new OthGame();

		m_othRules.flipCounters(m_othGame.getInPlayCounters(), FLIP_COL, FLIP_ROW, PLAYER_ONE);
		if(m_othGame.getInPlayCounters()[CHECK_COL][CHECK_ROW].getPlayer() == PLAYER_ONE) {
			System.out.println("OthRules.flipCounters Test One Evaluated: Correct");
		} else {
			System.out.println("OthRules.flipCounters Test One Evaluated: Incorrect");
		}

	}
}


text:
/**
 * Created by michael on 14.12.15.
 */
var Wunschliste = require('mongoose').model('wunschliste');

exports.getWuensche = function (req, res) {
    Wunschliste.find({}).exec(function (err, collection) {
        res.send(collection);
    })
};

exports.getWunschById = function (req, res) {
    Wunschliste.findOne({_id: req.params.id}).exec(function (err, wunsch) {
        res.send(wunsch);
    })
}

/*exports.createWunsch = function(req, res, next) {

 var userData = req.body;
 userData.username = userData.username.toLowerCase();
 userData.salt = encrypt.createSalt();
 userData.hashed_pwd = encrypt.hashPwd(userData.salt, userData.password);
 User.create(userData, function(err, user) {
 if(err) {
 if(err.toString().indexOf('E11000') > -1) {
 err = new Error('Duplicate Username');
 }
 res.status(400);
 return res.send({reason:err.toString()});
 }
 req.logIn(user, function(err) {
 if(err) {return next(err);}
 res.send(user);
 })
 })
 }*/

exports.updateWunsch = function (req, res) {
    var userUpdates = req.body;

    // use our bear model to find the bear we want
    Wunschliste.findById(userUpdates._id, function(err, wunsch) {

        if (err)
            res.send(err);

        wunsch.title  = userUpdates.title;//.name = req.body.name;  // update the bears info
        wunsch.geschenke = userUpdates.geschenke;
        wunsch.erfuellt = userUpdates.erfuellt;

        wunsch.save(function(err) {
            if (err)
                res.send(err);
            else
                res.send(wunsch);
        });

    /*    // save the bear
        wunsch.save(function(err) {
            if (err)
                res.send(err);

            res.send(wunsch);
        });
*/
    });

};


text:
using System;
using System.IO;
using System.Threading.Tasks;
using CodeMash.Exceptions;
using CodeMash.Interfaces.Client;
using CodeMash.Models.Requests;
using ServiceStack;

namespace CodeMash.Client
{
    public class CodeMashClient : ICodeMashClient
    {
        public ICodeMashSettings Settings { get; }

        public ICodeMashRequest Request { get; private set; }

        public ICodeMashResponse Response { get; private set; }

        private IServiceClient GetServiceClient(string baseUrl)
        {
            AssertSettingsAreSet();
            var client = new JsonServiceClient(string.IsNullOrWhiteSpace(baseUrl) ? CodeMashSettings.ApiUrl : baseUrl)
            {
                ResponseFilter = (res) =>
                    {
                        Response = new CodeMashResponse
                        {
                            ResponseUri = res.ResponseUri.ToString(),
                            Method = res.Method,
                            Headers = res.Headers.ToDictionary()
                        };
                    },
                RequestFilter = (req) =>
                {
                    Request = new CodeMashRequest
                    {
                        RequestUri = req.RequestUri.ToString(),
                        Host = req.Host,
                        Method = req.Method,
                        Headers = req.Headers.ToDictionary()
                    };
                }
            };

            if (Settings.ProjectId != Guid.Empty)
            {
                client.Headers.Add("X-CM-ProjectId", Settings.ProjectId.ToString());
            }

            if (!string.IsNullOrEmpty(Settings.SecretKey))
            {
                client.BearerToken = Settings.SecretKey;
            }

            return client.WithCache();
        }

        public CodeMashClient(string settingsFileName = "appsettings.json")
        {
            Settings = new CodeMashSettings(null, settingsFileName);
        }

        public CodeMashClient(string apiKey, Guid projectId, string cultureCode = null)
        {
            Settings = new CodeMashSettings(apiKey, projectId)
            {
                CultureCode = cultureCode
            };
        }

        public CodeMashClient(ICodeMashSettings settings)
        {
            Settings = settings ?? throw new ArgumentNullException(nameof(Settings), "CodeMash settings undefined.");
        }

        private void AssertSettingsAreSet()
        {
            if (Settings == null)
            {
                throw new ArgumentNullException(nameof(CodeMashSettings), "CodeMash settings are not set");
            }
        }

        private void AssertRequestIsFormed(object requestDto)
        {
            if (requestDto == null)
            {
                throw new ArgumentNullException(nameof(requestDto), "Request object is not set");
            }

            if (requestDto is RequestBase requestBaseDto)
            {
                if (string.IsNullOrEmpty(requestBaseDto.CultureCode))
                    requestBaseDto.CultureCode = Settings?.CultureCode;

                if (string.IsNullOrEmpty(requestBaseDto.Version))
                    requestBaseDto.Version = Settings?.Version;
            }
        }

        public async Task<TResponse> GetAsync<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return await CallAsync(async () => await FormGateway(requestDto, requestOptions).GetAsync<TResponse>(requestDto));
        }

        public async Task<TResponse> DeleteAsync<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return await CallAsync(async () => await FormGateway(requestDto, requestOptions).DeleteAsync<TResponse>(requestDto));
        }

        public async Task<TResponse> PostAsync<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return await CallAsync(async () => await FormGateway(requestDto, requestOptions).PostAsync<TResponse>(requestDto));
        }

        public async Task<TResponse> PutAsync<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return await CallAsync(async () => await FormGateway(requestDto, requestOptions).PutAsync<TResponse>(requestDto));
        }

        public async Task<TResponse> PatchAsync<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            var task = Task.Run(() => Patch<TResponse>(requestDto, requestOptions));

            return await task;
        }

        public TResponse Get<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return Call(() => FormGateway(requestDto, requestOptions).Get<TResponse>(requestDto));
        }

        public TResponse Delete<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return Call(() => FormGateway(requestDto, requestOptions).Delete<TResponse>(requestDto));
        }

        public TResponse Post<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return Call(() => FormGateway(requestDto, requestOptions).Post<TResponse>(requestDto));
        }

        public TResponse Put<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return Call(() => FormGateway(requestDto, requestOptions).Put<TResponse>(requestDto));
        }

        public TResponse Patch<TResponse>(object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return Call(() => FormGateway(requestDto, requestOptions).Patch<TResponse>(requestDto));
        }

        public TResponse PostFile<TResponse>(Stream fileToUpload, object requestDto, ICodeMashRequestOptions requestOptions = null)
        {
            return Call(() => FormGateway(requestDto, requestOptions).PostFileWithRequest<TResponse>(fileToUpload, requestOptions?.FileName, requestDto));
        }

        private IServiceClient FormGateway(object requestDto, ICodeMashRequestOptions requestOptions)
        {
            AssertRequestIsFormed(requestDto);

            var gateWay = GetServiceClient(requestOptions?.BaseUrl);

            if (requestOptions != null)
            {
                if (!string.IsNullOrEmpty(requestOptions.BearerToken))
                {
                    gateWay.BearerToken = requestOptions.BearerToken;
                }

                if (requestOptions.UnauthenticatedRequest)
                {
                    gateWay.BearerToken = null;
                }
            }

            return gateWay;
        }

        private async Task<TResponse> CallAsync<TResponse>(Func<Task<TResponse>> callFunc)
        {
            try
            {
                return await callFunc();
            }
            catch (WebServiceException e)
            {
                var businessException = ProcessWebServiceException(e);
                throw businessException;
            }
        }

        private TResponse Call<TResponse>(Func<TResponse> callFunc)
        {
            try
            {
                return callFunc();
            }
            catch (WebServiceException e)
            {
                var businessException = ProcessWebServiceException(e);
                throw businessException;
            }
        }

        private BusinessException ProcessWebServiceException(WebServiceException e)
        {
            var responseStatus = e.ResponseStatus;
            if (responseStatus != null)
            {
                var businessException = new BusinessException(responseStatus.Message)
                {
                    ErrorCode = responseStatus.ErrorCode,
                    StatusCode = e.StatusCode,
                    Errors = responseStatus?.Errors?.ConvertAll(x => new ValidationError
                    {
                        ErrorCode = x.ErrorCode,
                        Message = x.Message,
                        FieldName = x.FieldName
                    })
                };

                return businessException;
            }

            return new BusinessException(e.Message)
            {
                ErrorCode = e.ErrorCode,
                StatusCode = e.StatusCode
            };
        }

    }
}


text:
#ifndef _JPETANALYSISMODULE_SDARECOOFFSETCALC_H_
#define _JPETANALYSISMODULE_SDARECOOFFSETCALC_H_

#include <TCanvas.h>
#include "../../JPetUserTask/JPetUserTask.h"
class SDARecoOffsetsCalc: public JPetUserTask
{
public:
  SDARecoOffsetsCalc(const char* name);
  virtual ~SDARecoOffsetsCalc();
  virtual bool init() override;
  virtual bool exec()override;
  virtual bool terminate() override;
private:
  int fCurrentEventNumber;
  double fOffset;
  int fBadSignals;
};

#endif


text:
<?php
namespace Sharif\CalendarBundle\FormData\Transformer;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Form\DataTransformerInterface;

class LabelsTransformer implements DataTransformerInterface {
	/**
	 * @inheritdoc
	 */
	public function reverseTransform($value) {
		if($value == null) {
			return new ArrayCollection();
		} else {
			$arr = json_decode($value);
			global $kernel;
			if ('AppCache' == get_class($kernel)) {
				$kernel = $kernel->getKernel();
			}
			$doctrine = $kernel->getContainer()->get('doctrine');
			$repository =
				$doctrine->getRepository('SharifCalendarBundle:Label');

			$result = new ArrayCollection();
			foreach($arr as $id) {
				$result[] = $repository->findOneById($id);
			}
			return $result;
		}
	}

	/**
	 * @inheritdoc
	 */
	public function transform($value) {
		if($value == null) {
			return "";
		}
		return $value;
//		$arr = array();
//		foreach($value as $label) {
//			$arr[] = $label->getId();
//		}
//		return json_encode($arr);
	}
}


text:
require "test_helper"

class ConfigTest < Rugged::TestCase
  def setup
    @repo = FixtureRepo.from_rugged("testrepo.git")
  end

  def test_read_config_file
    config = @repo.config
    assert_equal 'false', config['core.bare']
    assert_nil config['not.exist']
  end

  def test_read_config_from_path
    config = Rugged::Config.new(File.join(@repo.path, 'config'))
    assert_equal 'false', config['core.bare']
  end

  def test_read_global_config_file
    config = Rugged::Config.global
    assert config['user.name'] != nil
    assert_nil config['core.bare']
  end
end

class ConfigWriteTest < Rugged::TestCase
  def setup
    @source_repo = FixtureRepo.from_rugged("testrepo.git")
    @repo = FixtureRepo.clone(@source_repo)
    @path = @repo.workdir
  end

  def test_write_config_values
    config = @repo.config
    config['custom.value'] = 'my value'

    config2 = @repo.config
    assert_equal 'my value', config2['custom.value']

    content = File.read(File.join(@repo.path, 'config'))
    assert_match(/value = my value/, content)
  end

  def test_delete_config_values
    config = @repo.config
    config.delete('core.bare')

    config2 = @repo.config
    assert_nil config2.get('core.bare')
  end
end


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

import { HttpService } from '../../shared/index';

@Injectable()
export class CardsInHandsDialogService {
    constructor(
        private httpService: HttpService
    ) { }

    getCardsInHands() {
        return this.httpService.get('/api/cards-in-hands');
    }
}


text:
package org.hackafe.syncadapter;

import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.util.Log;

/**
 * Created by groupsky on 24.06.15.
 */
public class SyncAdapter extends AbstractThreadedSyncAdapter {

    private static final String TAG = "!!!! SyncAdapter";
    private final ContentResolver mContentResolver;

    public SyncAdapter(Context context, boolean autoInitialize) {
        this(context, autoInitialize, false);
    }

    public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
        super(context, autoInitialize, allowParallelSyncs);
        Log.d(TAG, "constructor");
        mContentResolver = context.getContentResolver();
    }

    @Override
    public void onPerformSync(Account account,
                              Bundle extras,
                              String authority,
                              ContentProviderClient provider,
                              SyncResult syncResult) {
        Log.d(TAG, "onPerformSync: account=" + account +
                " extras=" + DebugUtils.toString(extras) +
                " authority=" + authority);
    }
}


text:
package eml.studio.shared.util;

import java.math.BigInteger;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import sun.misc.BASE64Decoder;

/**
 * AES Encryption and Decryption
 */
public class Aes {

    //Key (must be 16-bit, requires front-end and back-end consistency)
    private static final String KEY = "bdaictvisualabcd";

    //Algorithm
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * Aes Decryption
     *
     * @param encrypt   content
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String encrypt) {
        try {
            return aesDecrypt(encrypt, KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Aes encryption
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content) {
        try {
            return aesEncrypt(content, KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Convert byte[] to a variety of hexadecimal strings
     *
     * @param bytes byte[]
     * @param radix Convertible range,from Character.MIN_RADIX to Character.MAX_RADIX, out of range is changed to decimal
     * @return converted string
     */
    public static String binary(byte[] bytes, int radix){
        return new BigInteger(1, bytes).toString(radix);
    }

    /**
     * Base 64 encode
     *
     * @param bytes
     * @return
     */
    public static String base64Encode(byte[] bytes){
        return new String(Base64.encodeBase64(bytes));
    }

    /**
     * Base 64 decode
     *
     * @param base64Code
     * @return
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception{
        return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
    }

    /**
     * Aes Encryption
     * @param content content to be encrypted
     * @param encryptKey encryption key
     * @return
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

        return cipher.doFinal(content.getBytes("utf-8"));
    }

    /**
     * Aes Encryption for base 64 code
     *
     * @param content content to be encrypted
     * @param encryptKey encryption key
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * Aes Decryption
     *
     * @param encryptBytes byte[] to be decrypted
     * @param decryptKey decryption key
     * @return
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    /**
     * Aes Decryption for base 64 code
     *
     * @param encryptStr base 64 code to be decrypted
     * @param decryptKey decryption key
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }
}