text:
package mobi.anoda.archinamon.kernel.persefone.ui.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.google.common.collect.ImmutableList;
import java.util.List;
import mobi.anoda.archinamon.kernel.persefone.annotation.Implement;
import mobi.anoda.archinamon.kernel.persefone.ui.fragment.AbstractFragment;

/**
 * @author: Archinamon
 * @project: FavorMe
 */
public class FragmentPagerAdapter extends PagerAdapter {

    public static final String TAG = FragmentPagerAdapter.class.getSimpleName();
    private final ImmutableList<AbstractFragment> mFragmentsContainer;
    private final ImmutableList<String>           mElementTitles;
    private final FragmentManager                 mFragmentManager;
    private FragmentTransaction mCurTransaction     = null;
    private Fragment            mCurrentPrimaryItem = null;

    public FragmentPagerAdapter(FragmentActivity act, List<? extends AbstractFragment> objects) {
        mFragmentManager = act.getSupportFragmentManager();
        mFragmentsContainer = ImmutableList.copyOf(objects);
        mElementTitles = null;
    }

    public FragmentPagerAdapter(FragmentActivity act, List<? extends AbstractFragment> objects, String[] titles) {
        mFragmentManager = act.getSupportFragmentManager();
        mFragmentsContainer = ImmutableList.copyOf(objects);
        mElementTitles = ImmutableList.copyOf(titles);
    }

    public AbstractFragment getItem(int position) {
        return mFragmentsContainer.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mElementTitles != null
               ? mElementTitles.get(position)
               : "";
    }

    @Implement
    public int getCount() {
        return mFragmentsContainer.size();
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        final long itemId = getItemId(position);

        // Do we already have this fragment?
        String name = makeFragmentName(container.getId(), itemId);
        AbstractFragment fragment = (AbstractFragment) mFragmentManager.findFragmentByTag(name);
        if (fragment != null) {
            mCurTransaction.attach(fragment);
        } else {
            fragment = getItem(position);
            mCurTransaction.add(container.getId(), fragment,
                                makeFragmentName(container.getId(), itemId));
        }
        if (fragment != mCurrentPrimaryItem) {
            fragment.setMenuVisibility(false);
            fragment.setUserVisibleHint(false);
        }

        return fragment;
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            mFragmentManager.executePendingTransactions();
        }
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        mCurTransaction.detach((Fragment)object);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        AbstractFragment fragment = (AbstractFragment) object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
                mCurrentPrimaryItem.setUserVisibleHint(false);
            }

            if (fragment != null) {
                fragment.setMenuVisibility(true);
                fragment.setUserVisibleHint(true);
            }

            mCurrentPrimaryItem = fragment;
        }
    }

    @Implement
    public boolean isViewFromObject(View view, Object o) {
        return ((Fragment) o).getView() == view;
    }

    private static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }
}


text:
<?php

/**
 * @var $this  WebController
 * @var $model InitAdminForm
 */
use DreamFactory\Yii\Utility\Validate;
use Kisma\Core\Utility\Bootstrap;

Validate::register(
		'form#init-form',
		array(
			 'ignoreTitle'    => true,
			 'errorClass'     => 'error',
			 'errorPlacement' => 'function(error,element){error.appendTo(element.parent("div"));error.css("margin","-10px 0 0");}',
			 'rules'          => array(
				 'InitAdminForm[email]'          => array(
					 'required'  => true,
					 'minlength' => 5,
				 ),
				 'InitAdminForm[displayName]'    => array(
					 'required'  => true,
					 'minlength' => 5,
				 ),
				 'InitAdminForm[password]'       => array(
					 'required'  => true,
					 'minlength' => 5,
				 ),
				 'InitAdminForm[passwordRepeat]' => array(
					 'required'  => true,
					 'minlength' => 5,
					 'equalTo'   => '#InitAdminForm_password',
				 ),
			 ),
		)
);
?>
Create a System Admin User

Your DreamFactory Services Platform(tm) requires a local system administrator.

This user is a separate account that exists only
	inside your DSP. It cannot be used elsewhere, like on the dreamfactory.com site for instance.

More administrative and
	regular users can be easily added using the DSP's built-in 'Admin' application.

<form id="init-form" method="POST" action="/web/initAdmin" role="form" class="col-md-6">
	<?php
	echo '<legend>Login Credentials</legend>';

	echo Bootstrap::textFormGroup(
				  'Email Address',
				  array( 'for' => 'InitAdminForm_email' ),
				  array(
					   'id'    => 'InitAdminForm_email',
					   'name'  => 'InitAdminForm[email]',
					   'class' => 'email required',
					   'value' => $model->email
				  )
	);

	echo '
' . Bootstrap::label( array( 'class' => 'form-label', 'for' => 'InitAdminForm_password' ), 'Password' ) .
		 Bootstrap::password( array(
								   'id'    => 'InitAdminForm_password',
								   'name'  => 'InitAdminForm[password]',
								   'class' => 'password required form-control',
								   'value' => null
							  )
		 ) .
		 '
';

	echo '
' . Bootstrap::label( array( 'class' => 'form-label', 'for' => 'InitAdminForm_passwordRepeat' ),
														'Password Again'
		) .
		 Bootstrap::password( array(
								   'id'    => 'InitAdminForm_passwordRepeat',
								   'name'  => 'InitAdminForm[passwordRepeat]',
								   'class' => 'password required form-control',
								   'value' => null
							  )
		 ) .
		 '
';

	echo '<legend>User Details</legend>';

	echo '
' . Bootstrap::label( array( 'class' => 'form-label', 'for' => 'InitAdminForm_firstName' ), 'First Name' ) .
		 Bootstrap::text( array(
							   'id'    => 'InitAdminForm_firstName',
							   'name'  => 'InitAdminForm[firstName]',
							   'class' => 'required form-control',
							   'value' => $model->firstName
						  )
		 ) . '
';

	echo '
' . Bootstrap::label( array( 'class' => 'form-label', 'for' => 'InitAdminForm_lastName' ), 'Last Name' ) .
		 Bootstrap::text( array(
							   'id'    => 'InitAdminForm_lastName',
							   'name'  => 'InitAdminForm[lastName]',
							   'class' => 'required form-control',
							   'value' => $model->lastName
						  )
		 ) . '
';

	echo '
' . Bootstrap::label( array( 'class' => 'form-label', 'for' => 'InitAdminForm_displayName' ),
														'Display Name'
		) .
		 Bootstrap::text( array(
							   'id'    => 'InitAdminForm_displayName',
							   'name'  => 'InitAdminForm[displayName]',
							   'class' => 'required form-control',
							   'value' => $model->displayName,
						  )
		 ) . '
';

	?>

	<button type="submit" class="btn btn-success btn-primary">Gimme My Mojo!</button>
</form>

redpajama_set_name: RedPajamaGithub


text:
/* global describe, it, expect, before */
/* jshint expr: true */

var chai = require('chai')
  , Strategy = require('../lib/strategy')
  , server = require('./bootstrap/xmpp-server');

describe('Strategy', function() {

  describe('failing authentication with info', function() {
    var strategy = new Strategy();

    var info;

    before(function(done) {
      server.startServer(function() {
          chai.passport(strategy)
            .fail(function(i) {
              info = i;
              done();
            })
            .req(function(req) {
              req.body = {};
              req.body.jid = 'johndoe@localhost';
              req.body.password = 'public';
            })
            .authenticate();
        });
    });

    after(function(done) {
        server.stopServer(done)
    });

    it('should fail', function() {
      expect(info).to.be.an('object');
      expect(info.message).to.equal('XMPP authentication failure');
    });
  });

});


text:
<?xml version="1.0"?>
<config>
    <modules>
        <Inchoo_Shipping>
            <version>0.1.0</version>
        </Inchoo_Shipping>
    </modules>
    <global>
        <models>
            <inchoo_shipping>
                <class>Inchoo_Shipping_Model</class>
            </inchoo_shipping>
        </models>
        <helpers>
            <inchoo_shipping>
                <class>Inchoo_Shipping_Helper</class>
            </inchoo_shipping>
        </helpers>
    </global>
    <default>
        <carriers>
            <inchoo_shipping>
                <active>1</active>
                <sort_order>10</sort_order>
                <model>inchoo_shipping/carrier</model>
                <title>Inchoo Shipping Carrier</title>
                <sort_order>10</sort_order>
                <sallowspecific>1</sallowspecific>
                <express_max_weight>3</express_max_weight>
            </inchoo_shipping>
        </carriers>
    </default>
</config>


text:
/* eslint-disable @typescript-eslint/no-var-requires */
const angular = require('conventional-changelog-angular')
const debug = require('debug')('release-it:aggregate-conventional-changelog')

const whatBump = (commits) => {
  let level = undefined
  let breakings = 0
  let features = 0
  let patches = 0

  commits.forEach(commit => {
    debug(commit)

    if (commit.notes.length > 0) {
      breakings += commit.notes.length
      level = 0
    } else if (commit.type === 'feat') {
      features += 1
      if (level === 2 || level === undefined) {
        level = 1
      }
    } else if (['fix', 'patch', 'revert', 'refactor', 'docs', 'style'].includes(commit.type)) {
      patches += 1
      if (level === undefined) {
        level = 2
      }
    }
  })

  return {
    level: level,
    reason: breakings === 1
      ? `There is ${breakings} BREAKING CHANGE, ${features} features and ${patches} patches`
      : `There are ${breakings} BREAKING CHANGES, ${features} features and ${patches} patches`
  }
}

module.exports = angular.then((opts) => {
  opts.recommendedBumpOpts.whatBump = whatBump
  return opts
})


text:
Irrational Poetry

Irrational Poetry finds words hidden in irrational numbers (or streams of psuedorandom digits).

By default, Irrational Poetry generates its own stream of psuedorandom digits, but it can be configured to use a specific irrational number you supply.

Use irrational.py at the command line and specify the minimum length of words you want it to find.  It finds words of length 4 and below very quickly; finding words of length 5 and above get slower with each step.

Nine word lists of common words are provided; by changing the words in these word lists, you can change what Irrational Poetry finds.  The word lists are separated into the minimum length of words.

A small sample of words yielded from Irrational Poetry using a minimum length of 5 are:
risky widow widow short swing dozen mixed fixed prize swing dozen tight widow being swing given flower


text:
<?php
/**
 * Created by PhpStorm.
 * User: Michael
 * Date: 01/05/14
 * Time: 22:12
 */
require('../resources/include.php');

$viewSeries = new Page();
$seriesArray = $viewSeries->getComicSeries($_GET['series'],0,true);
$title = $seriesArray['comic_series']." (".$seriesArray['comic_start_year'].")";
echo $viewSeries->documentHead($title);
echo $viewSeries->menu();

echo "

";

echo "
";

echo $viewSeries->getComicSeries($_GET['series']);

echo "
";

echo "

";


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

namespace Cats.Models.Hubs
{
    partial class Receive
    {
        /// <summary>
        /// Validates this instance.
        /// </summary>
        /// <returns></returns>
        public bool Validate()
        {
            //TODO: Validate Dispatch
            return true;
        }

        /// <summary>
        /// Gets the receive by GRN.
        /// </summary>
        /// <param name="grnNo">The GRN no.</param>
        /// <returns></returns>
        public static Receive GetReceiveByGRN(string grnNo)
        {
            return null;
            //TODO:Refactor
            //CTSContext entities = new CTSContext();
            //return entities.Receives.FirstOrDefault(p => p.GRN == grnNo);
        }

        /// <summary>
        /// Updates the specified inserted.
        /// </summary>
        /// <param name="inserted">The inserted.</param>
        /// <param name="updated">The updated.</param>
        /// <param name="deleted">The deleted.</param>
        public void Update(List<ReceiveDetail> inserted, List<ReceiveDetail> updated,
            List<ReceiveDetail> deleted)
        {
            //TODO:Refactor
            //CTSContext db = new CTSContext();
            //Receive orginal = db.Receives.SingleOrDefault(p => p.ReceiveID == this.ReceiveID);
            //if (orginal != null)
            //{

            //    // CreatedDate = DateTime.Now,
            //    orginal.ReceiptDate = this.ReceiptDate;
            //    // orginal.ReceiveID = this.ReceiveID;
            //    orginal.DriverName = this.DriverName;
            //    orginal.GRN = this.GRN;
            //    orginal.PlateNo_Prime = this.PlateNo_Prime;
            //    orginal.PlateNo_Trailer = this.PlateNo_Trailer;
            //    //orginal.StackNumber = this.StackNumber;
            //    orginal.TransporterID = this.TransporterID;
            //    orginal.HubID = this.HubID;
            //   // orginal.SINumber = this.SINumber;
            //    //orginal.CommodityTypeID = this.CommodityTypeID;

            //    orginal.WayBillNo = this.WayBillNo;
            //    orginal.ResponsibleDonorID = this.ResponsibleDonorID;
            //    orginal.SourceDonorID = this.SourceDonorID;

            //    //orginal.ReceivedByStoreMan = this.ReceivedByStoreMan;
            //    //orginal.CommoditySourceID = this.CommoditySourceID;
            //    orginal.WeightBeforeUnloading = this.WeightBeforeUnloading;
            //    orginal.WeightAfterUnloading = this.WeightAfterUnloading;
            //    orginal.Remark = this.Remark;
            //    orginal.VesselName = this.VesselName;
            //    orginal.PortName = this.PortName;
            //    orginal.WeightBridgeTicketNumber = this.WeightBridgeTicketNumber;

            //    foreach (ReceiveDetail insert in inserted)
            //    {
            //        //TODO THIS should be in transaction
            //        //orginal.ReceiveDetails.Add(insert);
            //    }

            //    foreach (ReceiveDetail delete in deleted)
            //    {
            //        ReceiveDetail deletedCommodity = db.ReceiveDetails.SingleOrDefault(p => p.ReceiveDetailID == delete.ReceiveDetailID);
            //        if (deletedCommodity != null)
            //        {
            //      //      db.ReceiveDetails.DeleteObject(deletedCommodity);
            //        }
            //    }

            //    foreach (ReceiveDetail update in updated)
            //    {
            //        ReceiveDetail updatedCommodity = db.ReceiveDetails.SingleOrDefault(p => p.ReceiveDetailID == update.ReceiveDetailID);
            //        if (updatedCommodity != null)
            //        {
            //            //updatedCommodity.CommodityID = update.CommodityID;
            //            updatedCommodity.Description = update.Description;
            //            //updatedCommodity.ReceiveDetailID = update.ReceiveDetailID;
            //            //updatedCommodity.SentQuantityInMT = update.SentQuantityInMT;
            //            //updatedCommodity.ReceivedQuantityInMT = updatedCommodity.ReceivedQuantityInMT;
            //            //updatedCommodity.SentQuantityInUnit = update.SentQuantityInUnit;
            //            //updatedCommodity.UnitID = update.UnitID;
            //        }
            //    }
            //    db.SaveChanges();
            //}

        }
    }
}


text:
from django.contrib.auth.models import User
from .models import *

from django.test import TestCase, Client
from django.urls import reverse_lazy

BOT_TEST_NAME = 'BOT TEST NAME'

TEST_USER_NAME = 'USER'
TEST_USER_PW = 'USER_PW'

TEST_USER_NEW_DESCRIPTION = 'My new profile description'

NEW_PEOPLE_PROFILE_NAME = 'SOME PEOPLE'
NEW_PEOPLE_PROFILE__EDITED_DESCRIPTION = 'SOME NEW DESCRIPTION'

class Profile_Test(TestCase):
    def setUp(self):
        if not User.objects.filter( username = 'bot' ).exists():
            bot = User.objects.create_user( username = 'bot', password = '123' )
            bot_profile = bot.profile
            bot_profile.profile_type = PROFILE_TYPE_BOT
            bot_profile.name = BOT_TEST_NAME
            bot_profile.save()

    def test_Bot_profile_type(self):
        bot_profile = Profile.objects.get(name=BOT_TEST_NAME)
        self.assertEqual( bot_profile.profile_type, PROFILE_TYPE_BOT )

    def test_Bot_repo_pw(self):
        bot_profile = Profile.objects.get(name=BOT_TEST_NAME)
        self.assertFalse( bot_profile.repo_pw is None )

    def test_Bot_notifications_Zero(self):
        bot_profile = Profile.objects.get(name=BOT_TEST_NAME)
        self.assertEqual( GetUserNoticationsQ( bot_profile.user, True).count(), 0 )

    def test_Bot_profile_absolute_url(self):
        bot_profile = Profile.objects.get(name=BOT_TEST_NAME)
        self.assertEqual( bot_profile.get_absolute_url(), '/p/1/' )

    def test_Bot_profile_page(self):
        bot_profile = Profile.objects.get(name=BOT_TEST_NAME)
        c = Client()
        response = c.get( bot_profile.get_absolute_url() )
        self.assertContains(response, BOT_TEST_NAME + ' (Bot)', status_code=200 )

    def test_Bot_has_account(self):
        bot_profile = Profile.objects.get(name=BOT_TEST_NAME)
        self.assertTrue( bot_profile.has_account )

    def test_Create_Wrong_profile_type(self):
        p = Profile( profile_type = -9999 )
        with self.assertRaises(Exception):
            p.save()

class Profile_Test_Client(TestCase):
    def setUp(self):
        if not User.objects.filter( username = 'bot' ).exists():
            bot = User.objects.create_user( username = 'bot', password = '123' )
            bot_profile = bot.profile
            bot_profile.profile_type = PROFILE_TYPE_BOT
            bot_profile.name = BOT_TEST_NAME
            bot_profile.save()

        if not User.objects.filter( username = TEST_USER_NAME ).exists():
            u = User.objects.create_user( username = TEST_USER_NAME, password = TEST_USER_PW )
            u.save()

    def test_Profile_Test_Client_Root(self):
        c = Client()
        response = c.post( '/profile/view/' )
        self.assertEqual( response.status_code, 302 ) # we are not authorized - login redirect

    def test_Profile_Test_Client_Root_Wrong_Login(self):
        c = Client()
        res = c.login(username='perfect_stranger', password='yaoyao!')
        self.assertFalse( res )

    def test_Profile_View_My_Profile(self):
        u = User.objects.all()

        c = Client()

        response = c.get( reverse_lazy('my_profile_view') )
        self.assertEqual( response.status_code, 302 )

        res = c.login(username=TEST_USER_NAME, password=TEST_USER_PW )
        self.assertTrue( res )

        response = c.get( reverse_lazy('my_profile_view'), follow=True )
        self.assertEqual( response.status_code, 200 )

    def test_Edit_My_Profile( self ):
       c = Client()
       response = c.post( reverse_lazy('profiles_edit'), {  } )
       self.assertEqual( response.status_code, 302 )

       res = c.login(username=TEST_USER_NAME, password=TEST_USER_PW )
       self.assertTrue( res )

       user_profile = User.objects.get( username = TEST_USER_NAME ).profile
       self.assertEqual( user_profile.description, '' )

       response = c.post( reverse_lazy('profiles_edit'), { 'description' : TEST_USER_NEW_DESCRIPTION } )
       self.assertEqual( response.status_code, 302 )
       user_profile.refresh_from_db()
       self.assertEqual( user_profile.description, TEST_USER_NEW_DESCRIPTION  )

    def test_profile_create_and_edit(self):
        self.assertEqual( Profile.objects.count(), 2 )
        self.assertEqual( Profile.objects.filter( profile_type__in = PROFILE_TYPE_FOR_TASK ).count(), 0 )

        c = Client()
        res = c.login(username=TEST_USER_NAME, password=TEST_USER_PW )

        self.assertTrue( res )

        response = c.get( reverse_lazy('profiles_list') )
        self.assertContains(response, 'Create profile', status_code=200 )

        response = c.post( reverse_lazy('profile_create'), { 'profile_type' : PROFILE_TYPE_PEOPLE, 'name' : NEW_PEOPLE_PROFILE_NAME,  } )
        self.assertEqual( response.status_code, 302 )
        self.assertEqual( Profile.objects.filter( profile_type__in = PROFILE_TYPE_FOR_TASK ).count(), 1 )

        new_people = Profile.objects.get( name = NEW_PEOPLE_PROFILE_NAME )
        self.assertEqual( new_people.profile_type, PROFILE_TYPE_PEOPLE )
        self.assertEqual( new_people.description, '' )

        response = c.post( reverse_lazy('profile_update', args = (new_people.id,) ), { 'profile_type' : PROFILE_TYPE_PEOPLE, 'name' : NEW_PEOPLE_PROFILE_NAME, 'description' : NEW_PEOPLE_PROFILE__EDITED_DESCRIPTION } )
        self.assertEqual( response.status_code, 302 )
        new_people.refresh_from_db()
        self.assertEqual( new_people.description, NEW_PEOPLE_PROFILE__EDITED_DESCRIPTION  )


text:
<?php

class YExtend_Layout extends Yaf_Plugin_Abstract
{
    static private $instance;
    private $_layoutDir;
    private $_layoutFile;
    private $_layoutVars = array();
    private $_title = array();
    private $_js = array();
    private $_metas = array();
    private $_canonical;
    private $_layoutEnabled = true;

    private function __construct()
    {
        $config = Yaf_Application::app()->getConfig();

        $this->_layoutFile = ( !empty( $config->application->layoutFile ) ) ? $config->application->layoutFile : 'layout.phtml';
        $this->_layoutDir  = ( !empty( $config->application->layoutDir ) ) ? $config->application->layoutDir : APP_PATH . 'layout';
    }

    static public function getInstance()
    {
        if ( is_null( self::$instance ) )
        {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function __set( $name, $value )
    {
        $this->_layoutVars[ $name ] = $value;
    }

    public function disableLayout()
    {
        $this->_layoutEnabled = false;
    }

    public function addTitle( $title )
    {
        $this->_title[] = $title;
    }

    public function getTitle()
    {
        return implode( ' :: ', array_reverse( $this->_title ) );
    }

    public function addScript( $script )
    {
        if ( !in_array( $script, $this->_js ) )
        {
            $this->_js[] = $script;
        }
    }

    public function getScript()
    {
        $scripts = '';
        foreach ( $this->_js as $script)
        {
            $scripts .= '<script type="text/javascript" src="' . $script . '"></script>';
        }

        return $scripts;
    }

    public function addMeta( $key, $value, $og = false )
    {
        if ( false !== $og )
        {
            $key = 'og:' . $key;
        }
        $this->_metas[$key] = $value;
    }

    public function getMeta()
    {
        $metas = '';
        foreach ( $this->_metas as $key => $value )
        {
            $content = 'name';
            if ( 'og:' == substr( $key, 0, 3 ) )
            {
                $content = 'property';
            }
            $metas .= '<meta ' . $content . '="' . $key . '" value="' . $value . '">';
        }

        return $metas;
    }

    public function setCanonical( $url )
    {
        $this->_canonical = $url;
    }

    public function getCanonical()
    {
        return ( !empty( $this->_canonical ) ) ? '<link rel="canonical" href="' . $this->_canonical . '">' : '';
    }

    protected function getBodyId( Yaf_Request_Abstract $request )
    {
        return strtolower( $request->getControllerName() . '_' . $request->getActionName() );
    }

    public function getAnalytics()
    {
        $config = Yaf_Application::app()->getConfig();
        return $config->analytics->account;
    }

    public function postDispatch( Yaf_Request_Abstract $request, Yaf_Response_Abstract $response )
    {
        if ( $this->_layoutEnabled )
        {
            /* get the body of the response */
            $body = $response->getBody();

            /*clear existing response*/
            $response->clearBody();

            /* wrap it in the layout */
            $layout          = new Yaf_View_Simple( $this->_layoutDir );
            $layout->content = $body;
            $layout->assign( 'layout', $this->_layoutVars );
            $layout->body_id = $this->getBodyId( $request );

            /* set the response to use the wrapped version of the content */
            $response->setBody( $layout->render( $this->_layoutFile ) );
        }
    }

}


text:
'use strict';
const express = require("express");
const router = express.Router();
const path = require('path');

router.get("/", function (req, res) {
    res.send({status: !(req.modules.thread.update === true)});
});

module.exports = router;


text:
package com.microsoft.azure.management.compute;

import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.compute.implementation.ComputeManager;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;
import com.microsoft.rest.RestClient;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;

public class VirtualMachineCustomImageOperationsTest extends ComputeManagementTest {
    private static String RG_NAME = "";
    private static Region region = Region.US_WEST_CENTRAL;

    @Override
    protected void initializeClients(RestClient restClient, String defaultSubscription, String domain) {
        RG_NAME = generateRandomResourceName("javacsmrg", 15);
        super.initializeClients(restClient, defaultSubscription, domain);
    }
    @Override
    protected void cleanUpResources() {
        resourceManager.resourceGroups().deleteByName(RG_NAME);
    }
    @Test
    public void canCreateImageFromNativeVhd() throws IOException {
        final String vhdBasedImageName = generateRandomResourceName("img", 20);

        VirtualMachine linuxVM = prepareGeneralizedVmWith2EmptyDataDisks(RG_NAME,
                generateRandomResourceName("muldvm", 15),
                region,
                computeManager);
        //
        VirtualMachineCustomImage.DefinitionStages.WithCreateAndDataDiskImageOSDiskSettings
                creatableDisk = computeManager
                .virtualMachineCustomImages()
                .define(vhdBasedImageName)
                .withRegion(region)
                .withNewResourceGroup(RG_NAME)
                .withLinuxFromVhd(linuxVM.osUnmanagedDiskVhdUri(), OperatingSystemStateTypes.GENERALIZED)
                .withOSDiskCaching(linuxVM.osDiskCachingType());
        for (VirtualMachineUnmanagedDataDisk disk : linuxVM.unmanagedDataDisks().values()) {
            creatableDisk.defineDataDiskImage()
                    .withLun(disk.lun())
                    .fromVhd(disk.vhdUri())
                    .withDiskCaching(disk.cachingType())
                    .withDiskSizeInGB(disk.size() + 10) // Resize each data disk image by +10GB
                    .attach();
        }
        VirtualMachineCustomImage customImage = creatableDisk.create();
        Assert.assertNotNull(customImage.id());
        Assert.assertEquals(customImage.name(), vhdBasedImageName);
        Assert.assertFalse(customImage.isCreatedFromVirtualMachine());
        Assert.assertNull(customImage.sourceVirtualMachineId());
        Assert.assertNotNull(customImage.osDiskImage());
        Assert.assertNotNull(customImage.osDiskImage().blobUri());
        Assert.assertEquals(customImage.osDiskImage().caching(), CachingTypes.READ_WRITE);
        Assert.assertEquals(customImage.osDiskImage().osState(), OperatingSystemStateTypes.GENERALIZED);
        Assert.assertEquals(customImage.osDiskImage().osType(), OperatingSystemTypes.LINUX);
        Assert.assertNotNull(customImage.dataDiskImages());
        Assert.assertEquals(customImage.dataDiskImages().size(), linuxVM.unmanagedDataDisks().size());
        for (ImageDataDisk diskImage : customImage.dataDiskImages().values()) {
            VirtualMachineUnmanagedDataDisk matchedDisk = null;
            for (VirtualMachineUnmanagedDataDisk vmDisk : linuxVM.unmanagedDataDisks().values()) {
                if (vmDisk.lun() == diskImage.lun()) {
                    matchedDisk = vmDisk;
                    break;
                }
            }
            Assert.assertNotNull(matchedDisk);
            Assert.assertEquals(matchedDisk.cachingType(), diskImage.caching());
            Assert.assertEquals(matchedDisk.vhdUri(), diskImage.blobUri());
            Assert.assertEquals((long)matchedDisk.size() + 10, (long)diskImage.diskSizeGB());
        }
        VirtualMachineCustomImage image = computeManager
                .virtualMachineCustomImages()
                .getByResourceGroup(RG_NAME, vhdBasedImageName);
        Assert.assertNotNull(image);
        PagedList<VirtualMachineCustomImage> images = computeManager
                .virtualMachineCustomImages()
                .listByResourceGroup(RG_NAME);
        Assert.assertTrue(images.size() > 0);

        // Create virtual machine from custom image
        //
        VirtualMachine virtualMachine = computeManager.virtualMachines()
                .define(generateRandomResourceName("cusvm", 15))
                .withRegion(region)
                .withNewResourceGroup(RG_NAME)
                .withNewPrimaryNetwork("10.0.0.0/28")
                .withPrimaryPrivateIPAddressDynamic()
                .withoutPrimaryPublicIPAddress()
                .withLinuxCustomImage(image.id())
                .withRootUsername("javauser")
                .withRootPassword("12NewPA$$w0rd!")
                .withSize(VirtualMachineSizeTypes.STANDARD_D5_V2)
                .withOSDiskCaching(CachingTypes.READ_WRITE)
                .create();

        Map<Integer, VirtualMachineDataDisk> dataDisks = virtualMachine.dataDisks();
        Assert.assertNotNull(dataDisks);
        Assert.assertEquals(dataDisks.size(), image.dataDiskImages().size());
    }

    @Test
    public void canCreateImageByCapturingVM() {
        final String vmName = generateRandomResourceName("vm67-", 20);
        final String imageName = generateRandomResourceName("img", 15);

        VirtualMachine vm = prepareGeneralizedVmWith2EmptyDataDisks(RG_NAME, vmName, region, computeManager);
        //
        VirtualMachineCustomImage customImage = computeManager.virtualMachineCustomImages()
                .define(imageName)
                .withRegion(region)
                .withNewResourceGroup(RG_NAME)
                .fromVirtualMachine(vm.id())
                .create();

        Assert.assertTrue(customImage.name().equalsIgnoreCase(imageName));
        Assert.assertNotNull(customImage.osDiskImage());
        Assert.assertEquals(customImage.osDiskImage().osState(), OperatingSystemStateTypes.GENERALIZED);
        Assert.assertEquals(customImage.osDiskImage().osType(), OperatingSystemTypes.LINUX);
        Assert.assertNotNull(customImage.dataDiskImages());
        Assert.assertEquals(customImage.dataDiskImages().size(), 2);
        Assert.assertNotNull(customImage.sourceVirtualMachineId());
        Assert.assertTrue(customImage.sourceVirtualMachineId().equalsIgnoreCase(vm.id()));

        for (VirtualMachineUnmanagedDataDisk vmDisk : vm.unmanagedDataDisks().values()) {
            Assert.assertTrue(customImage.dataDiskImages().containsKey(vmDisk.lun()));
            ImageDataDisk diskImage = customImage.dataDiskImages().get(vmDisk.lun());
            Assert.assertEquals(diskImage.caching(), vmDisk.cachingType());
            Assert.assertEquals((long) diskImage.diskSizeGB(), vmDisk.size());
            Assert.assertNotNull(diskImage.blobUri());
            diskImage.blobUri().equalsIgnoreCase(vmDisk.vhdUri());
        }

        customImage = computeManager.virtualMachineCustomImages().getByResourceGroup(RG_NAME, imageName);
        Assert.assertNotNull(customImage);
        Assert.assertNotNull(customImage.inner());
        computeManager.virtualMachineCustomImages().deleteById(customImage.id());
    }

    @Test
    public void canCreateImageFromManagedDisk() {
        final String vmName = generateRandomResourceName("vm7-", 20);
        final String uname = "juser";
        final String password = "123tEst!@|ac";

        VirtualMachine nativeVm = computeManager.virtualMachines()
                .define(vmName)
                .withRegion(region)
                .withNewResourceGroup(RG_NAME)
                .withNewPrimaryNetwork("10.0.0.0/28")
                .withPrimaryPrivateIPAddressDynamic()
                .withoutPrimaryPublicIPAddress()
                .withLatestLinuxImage("Canonical", "UbuntuServer", "14.04.2-LTS")
                .withRootUsername(uname)
                .withRootPassword(password)
                .withUnmanagedDisks()                  /* UN-MANAGED OS and DATA DISKS */
                .defineUnmanagedDataDisk("disk1")
                    .withNewVhd(100)
                    .withCaching(CachingTypes.READ_ONLY)
                    .attach()
                .withNewUnmanagedDataDisk(100)
                .withSize(VirtualMachineSizeTypes.STANDARD_D5_V2)
                .withNewStorageAccount(generateRandomResourceName("stg", 17))
                .withOSDiskCaching(CachingTypes.READ_WRITE)
                .create();

        Assert.assertFalse(nativeVm.isManagedDiskEnabled());
        String osVhdUri = nativeVm.osUnmanagedDiskVhdUri();
        Assert.assertNotNull(osVhdUri);
        Map<Integer, VirtualMachineUnmanagedDataDisk> dataDisks = nativeVm.unmanagedDataDisks();
        Assert.assertEquals(dataDisks.size(), 2);

        computeManager.virtualMachines().deleteById(nativeVm.id());

        final String osDiskName = generateRandomResourceName("dsk", 15);
        // Create managed disk with Os from vm's Os disk
        //
        Disk managedOsDisk = computeManager.disks().define(osDiskName)
                .withRegion(region)
                .withNewResourceGroup(RG_NAME)
                .withLinuxFromVhd(osVhdUri)
                .create();

        // Create managed disk with Data from vm's lun0 data disk
        //
        final String dataDiskName1 = generateRandomResourceName("dsk", 15);
        VirtualMachineUnmanagedDataDisk vmNativeDataDisk1 = dataDisks.get(0);
        Disk managedDataDisk1 = computeManager.disks().define(dataDiskName1)
                .withRegion(region)
                .withNewResourceGroup(RG_NAME)
                .withData()
                .fromVhd(vmNativeDataDisk1.vhdUri())
                .create();

        // Create managed disk with Data from vm's lun1 data disk
        //
        final String dataDiskName2 = generateRandomResourceName("dsk", 15);
        VirtualMachineUnmanagedDataDisk vmNativeDataDisk2 = dataDisks.get(1);
        Disk managedDataDisk2 = computeManager.disks().define(dataDiskName2)
                .withRegion(region)
                .withNewResourceGroup(RG_NAME)
                .withData()
                .fromVhd(vmNativeDataDisk2.vhdUri())
                .create();

        // Create an image from the above managed disks
        // Note that this is not a direct user scenario, but including this as per CRP team request
        //
        final String imageName = generateRandomResourceName("img", 15);
        VirtualMachineCustomImage customImage = computeManager.virtualMachineCustomImages().define(imageName)
                .withRegion(region)
                .withNewResourceGroup(RG_NAME)
                .withLinuxFromDisk(managedOsDisk, OperatingSystemStateTypes.GENERALIZED)
                .defineDataDiskImage()
                    .withLun(vmNativeDataDisk1.lun())
                    .fromManagedDisk(managedDataDisk1)
                    .withDiskCaching(vmNativeDataDisk1.cachingType())
                    .withDiskSizeInGB(vmNativeDataDisk1.size() + 10)
                    .attach()
                .defineDataDiskImage()
                    .withLun(vmNativeDataDisk2.lun())
                    .fromManagedDisk(managedDataDisk2)
                    .withDiskSizeInGB(vmNativeDataDisk2.size() + 10)
                    .attach()
                .create();

        Assert.assertNotNull(customImage);
        Assert.assertTrue(customImage.name().equalsIgnoreCase(imageName));
        Assert.assertNotNull(customImage.osDiskImage());
        Assert.assertEquals(customImage.osDiskImage().osState(), OperatingSystemStateTypes.GENERALIZED);
        Assert.assertEquals(customImage.osDiskImage().osType(), OperatingSystemTypes.LINUX);
        Assert.assertNotNull(customImage.dataDiskImages());
        Assert.assertEquals(customImage.dataDiskImages().size(), 2);
        Assert.assertNull(customImage.sourceVirtualMachineId());

        Assert.assertTrue(customImage.dataDiskImages().containsKey(vmNativeDataDisk1.lun()));
        Assert.assertEquals(customImage.dataDiskImages().get(vmNativeDataDisk1.lun()).caching(), vmNativeDataDisk1.cachingType());
        Assert.assertTrue(customImage.dataDiskImages().containsKey(vmNativeDataDisk2.lun()));
        Assert.assertEquals(customImage.dataDiskImages().get(vmNativeDataDisk2.lun()).caching(), CachingTypes.NONE);

        for (VirtualMachineUnmanagedDataDisk vmDisk : dataDisks.values()) {
            Assert.assertTrue(customImage.dataDiskImages().containsKey(vmDisk.lun()));
            ImageDataDisk diskImage = customImage.dataDiskImages().get(vmDisk.lun());
            Assert.assertEquals((long) diskImage.diskSizeGB(), vmDisk.size() + 10);
            Assert.assertNull(diskImage.blobUri());
            Assert.assertNotNull(diskImage.managedDisk());
            Assert.assertTrue(diskImage.managedDisk().id().equalsIgnoreCase(managedDataDisk1.id())
                    || diskImage.managedDisk().id().equalsIgnoreCase(managedDataDisk2.id()));
        }
        computeManager.disks().deleteById(managedOsDisk.id());
        computeManager.disks().deleteById(managedDataDisk1.id());
        computeManager.disks().deleteById(managedDataDisk2.id());
        computeManager.virtualMachineCustomImages().deleteById(customImage.id());
    }

    private VirtualMachine prepareGeneralizedVmWith2EmptyDataDisks(String rgName,
                                                         String vmName,
                                                         Region region,
                                                         ComputeManager computeManager) {
        final String uname = "javauser";
        final String password = "12NewPA$$w0rd!";
        final KnownLinuxVirtualMachineImage linuxImage = KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS;
        final String publicIpDnsLabel = generateRandomResourceName("pip", 20);

        VirtualMachine virtualMachine = computeManager.virtualMachines()
                .define(vmName)
                .withRegion(region)
                .withNewResourceGroup(rgName)
                .withNewPrimaryNetwork("10.0.0.0/28")
                .withPrimaryPrivateIPAddressDynamic()
                .withNewPrimaryPublicIPAddress(publicIpDnsLabel)
                .withPopularLinuxImage(linuxImage)
                .withRootUsername(uname)
                .withRootPassword(password)
                .withUnmanagedDisks()
                .defineUnmanagedDataDisk("disk-1")
                    .withNewVhd(30)
                    .withCaching(CachingTypes.READ_WRITE)
                    .attach()
                .defineUnmanagedDataDisk("disk-2")
                    .withNewVhd(60)
                    .withCaching(CachingTypes.READ_ONLY)
                    .attach()
                .withSize(VirtualMachineSizeTypes.STANDARD_D5_V2)
                .withNewStorageAccount(generateRandomResourceName("stg", 17))
                .withOSDiskCaching(CachingTypes.READ_WRITE)
                .create();
        //
         deprovisionAgentInLinuxVM(virtualMachine.getPrimaryPublicIPAddress().fqdn(), 22, uname, password);
         virtualMachine.deallocate();
         virtualMachine.generalize();
        return virtualMachine;
    }
}


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

<title>com.amazonaws.services.kms (AWS SDK for Java - 1.10.27)</title>
<meta name="date" content="2015-10-15">
<link rel="stylesheet" type="text/css" href="../../../../JavaDoc.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Index

Help

        <link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/>
        <link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/>

              Search

            <form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java">

                    <input id="nav-searchfield" name="searchQuery">

                <input alt="" id="nav-search-button-inner" type="image">

              <input name="searchPath" type="hidden" value="documentation-guide" />
              <input name="this_doc_product" type="hidden" value="AWS SDK for Java" />
              <input name="this_doc_guide" type="hidden" value="API Reference" />
              <input name="doc_locale" type="hidden" value="en_us" />
            </form>

Did this page help you?

                  Yes
            No
            Tell us about it...

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.amazonaws.services.kms

Synchronous and asynchronous client classes for accessing AWSKMS.

See: Description

Interface Summary

Interface
Description

AWSKMS

Interface for accessing AWSKMS.

AWSKMSAsync

Interface for accessing AWSKMS asynchronously.

Class Summary

Class
Description

AWSKMSAsyncClient

Asynchronous client for accessing AWSKMS.

AWSKMSClient

Client for accessing AWSKMS.

Package com.amazonaws.services.kms Description

Synchronous and asynchronous client classes for accessing AWSKMS.

 AWS Key Management Service

 AWS Key Management Service (AWS KMS) is an encryption and key
 management web service. This guide describes the AWS KMS operations
 that you can call programmatically. For general information about AWS
 KMS, see the
  AWS Key Management Service Developer Guide
 .

 NOTE: AWS provides SDKs that consist of libraries and sample
 code for various programming languages and platforms (Java, Ruby,
 .Net, iOS, Android, etc.). The SDKs provide a convenient way to create
 programmatic access to AWS KMS and other AWS services. For example,
 the SDKs take care of tasks such as signing requests (see below),
 managing errors, and retrying requests automatically. For more
 information about the AWS SDKs, including how to download and install
 them, see Tools for Amazon Web Services.

 We recommend that you use the AWS SDKs to make programmatic API calls
 to AWS KMS.

 Clients must support TLS (Transport Layer Security) 1.0. We recommend
 TLS 1.2. Clients must also support cipher suites with Perfect Forward
 Secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve
 Ephemeral Diffie-Hellman (ECDHE). Most modern systems such as Java 7
 and later support these modes.

 Signing Requests

 Requests must be signed by using an access key ID and a secret access
 key. We strongly recommend that you do not use your AWS account
 access key ID and secret key for everyday work with AWS KMS. Instead,
 use the access key ID and secret access key for an IAM user, or you
 can use the AWS Security Token Service to generate temporary security
 credentials that you can use to sign requests.

 All AWS KMS operations require
  Signature Version 4
 .

 Logging API Requests

 AWS KMS supports AWS CloudTrail, a service that logs AWS API calls and
 related events for your AWS account and delivers them to an Amazon S3
 bucket that you specify. By using the information collected by
 CloudTrail, you can determine what requests were made to AWS KMS, who
 made the request, when it was made, and so on. To learn more about
 CloudTrail, including how to turn it on and find your log files, see
 the
  AWS CloudTrail User Guide
 .

 Additional Resources

 For more information about credentials and request signing, see the
 following:

  AWS Security Credentials
 - This topic provides general information about the types of
 credentials used for accessing AWS.

  AWS Security Token Service
 - This guide describes how to create and use temporary security
 credentials.

  Signing AWS API Requests
 - This set of topics walks you through the process of signing a
 request using an access key ID and a secret access key.

 Commonly Used APIs

 Of the APIs discussed in this guide, the following will prove the
 most useful for most applications. You will likely perform actions
 other than these, such as creating keys and assigning policies, by
 using the console.

 Encrypt

 Decrypt

 GenerateDataKey

 GenerateDataKeyWithoutPlaintext

Overview

Package

Class

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

            Copyright © 2013 Amazon Web Services, Inc. All Rights Reserved.


text:
package net.dongliu.apk.parser.struct.resource;

import net.dongliu.apk.parser.struct.ChunkHeader;
import net.dongliu.apk.parser.struct.ChunkType;
import net.dongliu.apk.parser.utils.Unsigned;

/**
 * @author dongliu
 */
public class TypeHeader extends ChunkHeader {

    public static final long NO_ENTRY = 0xFFFFFFFFL;

    // The type identifier this chunk is holding.  Type IDs start at 1 (corresponding to the value
    // of the type bits in a resource identifier).  0 is invalid.
    // uint8_t
    private byte id;

    // Must be 0. uint8_t
    private byte res0;
    // Must be 0. uint16_t
    private short res1;

    // Number of uint32_t entry indices that follow. uint32
    private int entryCount;

    // Offset from header where ResTable_entry data starts.uint32_t
    private int entriesStart;

    // Configuration this collection of entries is designed for.
    private ResTableConfig config;

    public TypeHeader(int headerSize, long chunkSize) {
        super(ChunkType.TABLE_TYPE, headerSize, chunkSize);
    }

    public short getId() {
        return Unsigned.toShort(id);
    }

    public void setId(short id) {
        this.id = Unsigned.toUByte(id);
    }

    public short getRes0() {
        return Unsigned.toUShort(res0);
    }

    public void setRes0(short res0) {
        this.res0 = Unsigned.toUByte(res0);
    }

    public int getRes1() {
        return Unsigned.toInt(res1);
    }

    public void setRes1(int res1) {
        this.res1 = Unsigned.toUShort(res1);
    }

    public int getEntryCount() {
        return entryCount;
    }

    public void setEntryCount(long entryCount) {
        this.entryCount = Unsigned.ensureUInt(entryCount);
    }

    public int getEntriesStart() {
        return entriesStart;
    }

    public void setEntriesStart(long entriesStart) {
        this.entriesStart = Unsigned.ensureUInt(entriesStart);
    }

    public ResTableConfig getConfig() {
        return config;
    }

    public void setConfig(ResTableConfig config) {
        this.config = config;
    }
}


text:
/** Provides dependency injection utilities for Play lifecycle. */
package play.inject;


text:
package org.jkiss.dbeaver.ext.oracle.data;

import org.jkiss.dbeaver.ext.oracle.model.OracleConstants;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.impl.jdbc.data.JDBCContentXML;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;
import org.jkiss.utils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.sql.SQLXML;

/**
 * XML content
 */
public class OracleContentXML extends JDBCContentXML {
    public OracleContentXML(DBPDataSource dataSource, SQLXML xml)
    {
        super(dataSource, xml);
    }

    @Override
    protected OracleContentXML createNewContent()
    {
        return new OracleContentXML(dataSource, null);
    }

    @Override
    public void bindParameter(
        JDBCSession session,
        JDBCPreparedStatement preparedStatement,
        DBSTypedObject columnType,
        int paramIndex)
        throws DBCException
    {
        try {
            if (storage != null) {
                try (InputStream streamReader = storage.getContentStream()) {
                    final Object xmlObject = createXmlObject(session, streamReader);

                    preparedStatement.setObject(
                        paramIndex,
                        xmlObject);
                }
            } else {
                preparedStatement.setNull(paramIndex, java.sql.Types.SQLXML);
            }
        }
        catch (SQLException e) {
            throw new DBCException(e, session.getDataSource());
        }
        catch (IOException e) {
            throw new DBCException("IO error while reading XML", e);
        }
    }

    private Object createXmlObject(JDBCSession session, InputStream stream) throws DBCException
    {
        try {
            return BeanUtils.invokeStaticMethod(
                DBUtils.getDriverClass(dataSource, OracleConstants.XMLTYPE_CLASS_NAME),
                "createXML",
                new Class[] {java.sql.Connection.class, java.io.InputStream.class},
                new Object[] {session.getOriginal(), stream});
        } catch (SQLException e) {
            throw new DBCException(e, session.getDataSource());
        } catch (Throwable e) {
            throw new DBCException("Internal error when creating XMLType", e, session.getDataSource());
        }
    }

/*
    @Override
    protected XMLType createNewOracleObject(Connection connection) throws DBCException, IOException, SQLException
    {
        final InputStream contentStream = storage.getContentStream();
        try {
            return XMLType.createXML(connection, contentStream);
        } finally {
            ContentUtils.close(contentStream);
        }
    }

    @Override
    protected DBDContentStorage makeStorageFromOpaque(DBRProgressMonitor monitor, XMLType opaque) throws DBCException
    {
        long contentLength = opaque.getLength();
        if (contentLength < 4000) {
            try {
                return new StringContentStorage(opaque.getStringVal());
            } catch (SQLException e) {
                throw new DBCException(e);
            }
        } else {
            // Create new local storage
            IFile tempFile;
            try {
                tempFile = ContentUtils.createTempContentFile(monitor, "opaque" + opaque.hashCode());
            }
            catch (IOException e) {
                throw new DBCException(e);
            }
            try {
                ContentUtils.copyReaderToFile(monitor, opaque.getClobVal().getCharacterStream(), contentLength, null, tempFile);
            } catch (Exception e) {
                ContentUtils.deleteTempFile(monitor, tempFile);
                throw new DBCException(e);
            }
            return new TemporaryContentStorage(tempFile);
        }
    }
*/
}


text:
require 'spec_helper'

describe 'Discussion Comments Snippet', :js do
  let(:user) { create(:user) }
  let(:project) { create(:project) }
  let(:snippet) { create(:project_snippet, :private, project: project, author: user) }

  before do
    project.add_maintainer(user)
    sign_in(user)

    visit project_snippet_path(project, snippet)
  end

  it_behaves_like 'discussion comments', 'snippet'
end


text:
<?php

require dirname(__FILE__) . '/libs/nette.min.php';
require dirname(__FILE__) . '/libs/Thumbnailer.php';

echo "\nThumbnailer version " . Thumbnailer::$version . "\n-----------------------\n";

$options = getopt('s:w:h:t:c:l:p:q:o:');

if (!isset($options['s'], $options['w'], $options['h'])) { ?>
Usage:
	php thumbnailer.php [options]

Options:
	-s <path>  Source directory with images. Required.
	-w ... 	   Width of thumbnail. Required.
	-h ...     Height of thumnail. Required.
	-t <path>  Thumbnails folder.
	-c ...     Prefix for thumbnails.
	-l <path>  Path to logo in alpha PNG format. Not implemented yet.
	-q ...     Quality of JPEG image.
	-o ...     Offset where to crop from top of image.
	-p ...     Position of logo. Not implementend yet.
	             1 - top left
	             2 - top right
	             3 - bottom right (default)
	             4 - bottom left

<?php
	die();
}

Debug::timer();

$tn = new Thumbnailer($options);

$tn->generate();

echo "\nDone. Total time: " . (int) Debug::timer() . " seconds\n";


text:
package textgame;

import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.JOptionPane;

public class Inventory {
	 ArrayList<Item> inventoryList = new ArrayList<Item>();

	 public Inventory() {
		 inventoryList.add(new Food("Banan", true, 10));
		 inventoryList.add(new Item("Kniv", false));
		 inventoryList.add(new Item("Nyckel", false));
	 }

	 public void show() {
		 String[] tempArray = new String[inventoryList.size()];
		 for (int i = 0; i < inventoryList.size(); i++) {
			 tempArray[i] = inventoryList.get(i).getName();
		 }

		 JOptionPane.showInputDialog(null, null, "Inventory", -1, null,
				 	tempArray, // Array of choices
				 	tempArray[0]); // Initial choice
	 }

	 public void addItem(Item item) {
		 inventoryList.add(item);
	 }
	 public Item getItem() {
		 String[] tempArray = new String[inventoryList.size()];
		 for (int i = 0; i < inventoryList.size(); i++) {
			 tempArray[i] = inventoryList.get(i).getName();
		 }

		 String item = (String) JOptionPane.showInputDialog(null, null, "Inventory", -1, null,
				 	tempArray, // Array of choices
				 	tempArray[0]); // Initial choice

	 	Item tempItem = null;
	 	for (int i = 0; i < inventoryList.size(); i++) {
			if (inventoryList.get(i).getName().equals(item)) {
				tempItem = inventoryList.get(i);
				inventoryList.remove(i);
			}
		 }

		return tempItem;
	 }
}


text:
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Runtime.InteropServices;

namespace System.Data.OleDb
{
	public sealed class OleDbDataReader : MarshalByRefObject, IDataReader, IDisposable, IDataRecord, IEnumerable
	{
		#region Fields

		private OleDbCommand command;
		private bool open;
		private ArrayList gdaResults;
		private int currentResult;
		private int currentRow;
		private bool disposed = false;

		#endregion

		#region Constructors

		internal OleDbDataReader (OleDbCommand command, ArrayList results)
		{
			this.command = command;
			open = true;
			if (results != null)
				gdaResults = results;
			else
				gdaResults = new ArrayList ();
			currentResult = -1;
			currentRow = -1;
		}

		#endregion

		#region Properties

		public int Depth {
			get {
				return 0; // no nested selects supported
			}
		}

		public int FieldCount {
			get {
				if (currentResult < 0 ||
				    currentResult >= gdaResults.Count)
					return 0;

				return libgda.gda_data_model_get_n_columns (
					(IntPtr) gdaResults[currentResult]);
			}
		}

		public bool IsClosed {
			get {
				return !open;
			}
		}

		public object this[string name] {
			get {
				int pos;

				if (currentResult == -1)
					throw new InvalidOperationException ();

				pos = libgda.gda_data_model_get_column_position (
					(IntPtr) gdaResults[currentResult],
					name);
				if (pos == -1)
					throw new IndexOutOfRangeException ();

				return this[pos];
			}
		}

		public object this[int index] {
			get {
				return (object) GetValue (index);
			}
		}

		public int RecordsAffected {
			get {
				int total_rows;

				if (currentResult < 0 ||
				    currentResult >= gdaResults.Count)
					return 0;

				total_rows = libgda.gda_data_model_get_n_rows (
					(IntPtr) gdaResults[currentResult]);
				if (total_rows > 0) {
					if (FieldCount > 0) {
						// It's a SELECT statement
						return -1;
					}
				}

				return FieldCount > 0 ? -1 : total_rows;
			}
		}

		[MonoTODO]
		public bool HasRows {
			get {
				throw new NotImplementedException ();
			}
		}

		#endregion

		#region Methods

		public void Close ()
		{
			for (int i = 0; i < gdaResults.Count; i++) {
				IntPtr obj = (IntPtr) gdaResults[i];
				libgda.FreeObject (obj);
			}

			gdaResults.Clear ();
			gdaResults = null;

			open = false;
			currentResult = -1;
			currentRow = -1;
		}

		public bool GetBoolean (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.Boolean)
				throw new InvalidCastException ();
			return libgda.gda_value_get_boolean (value);
		}

		public byte GetByte (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.Tinyint)
				throw new InvalidCastException ();
			return libgda.gda_value_get_tinyint (value);
		}

		[MonoTODO]
		public long GetBytes (int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
		{
			throw new NotImplementedException ();
		}

		[EditorBrowsableAttribute (EditorBrowsableState.Never)]
		public char GetChar (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.Tinyint)
				throw new InvalidCastException ();
			return (char) libgda.gda_value_get_tinyint (value);
		}

		[MonoTODO]
		public long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length)
		{
			throw new NotImplementedException ();
		}

		[MonoTODO]
		public OleDbDataReader GetData (int ordinal)
		{
			throw new NotImplementedException ();
		}

		public string GetDataTypeName (int index)
		{
			IntPtr attrs;
			GdaValueType type;

			if (currentResult == -1)
				return "unknown";

			attrs = libgda.gda_data_model_describe_column ((IntPtr) gdaResults[currentResult],
								       index);
			if (attrs == IntPtr.Zero)
				return "unknown";

			type = libgda.gda_field_attributes_get_gdatype (attrs);
			libgda.gda_field_attributes_free (attrs);

			return libgda.gda_type_to_string (type);
		}

		public DateTime GetDateTime (int ordinal)
		{
			IntPtr value;
			DateTime dt;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) == GdaValueType.Date) {
				GdaDate gdt;

				gdt = (GdaDate) Marshal.PtrToStructure (libgda.gda_value_get_date (value),
									typeof (GdaDate));
				return new DateTime ((int) gdt.year, (int) gdt.month, (int) gdt.day);
			} else if (libgda.gda_value_get_type (value) == GdaValueType.Time) {
				GdaTime gdt;

				gdt = (GdaTime) Marshal.PtrToStructure (libgda.gda_value_get_time (value),
									typeof (GdaTime));
				return new DateTime (0, 0, 0, (int) gdt.hour, (int) gdt.minute, (int) gdt.second, 0);
			} else if (libgda.gda_value_get_type (value) == GdaValueType.Timestamp) {
				GdaTimestamp gdt;

				gdt = (GdaTimestamp) Marshal.PtrToStructure (libgda.gda_value_get_timestamp (value),
									     typeof (GdaTimestamp));

				return new DateTime ((int) gdt.year, (int) gdt.month, (int) gdt.day,
						     (int) gdt.hour, (int) gdt.minute, (int) gdt.second,
						     (int) gdt.fraction);
			}

			throw new InvalidCastException ();
		}

		[MonoTODO]
		public decimal GetDecimal (int ordinal)
		{
			throw new NotImplementedException ();
		}

		public double GetDouble (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.Double)
				throw new InvalidCastException ();
			return libgda.gda_value_get_double (value);
		}

		[MonoTODO]
		public Type GetFieldType (int index)
		{
			IntPtr value;
			GdaValueType type;

			if (currentResult == -1)
				throw new IndexOutOfRangeException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
				index, currentRow);
			if (value == IntPtr.Zero)
				throw new IndexOutOfRangeException ();

			type = libgda.gda_value_get_type (value);
			switch (type) {
			case GdaValueType.Bigint : return typeof (long);
			case GdaValueType.Boolean : return typeof (bool);
			case GdaValueType.Date : return typeof (DateTime);
			case GdaValueType.Double : return typeof (double);
			case GdaValueType.Integer : return typeof (int);
			case GdaValueType.Single : return typeof (float);
			case GdaValueType.Smallint : return typeof (byte);
			case GdaValueType.String : return typeof (string);
			case GdaValueType.Time : return typeof (DateTime);
			case GdaValueType.Timestamp : return typeof (DateTime);
			case GdaValueType.Tinyint : return typeof (byte);
			}

			return typeof(string); // default
		}

		public float GetFloat (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.Single)
				throw new InvalidCastException ();
			return libgda.gda_value_get_single (value);
		}

		[MonoTODO]
		public Guid GetGuid (int ordinal)
		{
			throw new NotImplementedException ();
		}

		public short GetInt16 (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.Smallint)
				throw new InvalidCastException ();
			return (short) libgda.gda_value_get_smallint (value);
		}

		public int GetInt32 (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.Integer)
				throw new InvalidCastException ();
			return libgda.gda_value_get_integer (value);
		}

		public long GetInt64 (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.Bigint)
				throw new InvalidCastException ();
			return libgda.gda_value_get_bigint (value);
		}

		public string GetName (int index)
		{
			if (currentResult == -1)
				return null;

			return libgda.gda_data_model_get_column_title (
				(IntPtr) gdaResults[currentResult], index);
		}

		public int GetOrdinal (string name)
		{
			if (currentResult == -1)
				throw new IndexOutOfRangeException ();

			for (int i = 0; i < FieldCount; i++) {
				if (GetName (i) == name)
					return i;
			}

			throw new IndexOutOfRangeException ();
		}

		public DataTable GetSchemaTable ()
		{
			DataTable dataTableSchema = null;
			// Only Results from SQL SELECT Queries
			// get a DataTable for schema of the result
			// otherwise, DataTable is null reference
			if(this.FieldCount > 0) {

				IntPtr attrs;
				GdaValueType gdaType;
				long columnSize = 0;

				if (currentResult == -1) {
					// FIXME: throw an exception?
#if DEBUG_OleDbDataReader
					Console.WriteLine("Error: current result -1");
#endif
					return null;
				}

				dataTableSchema = new DataTable ();

				dataTableSchema.Columns.Add ("ColumnName", typeof (string));
				dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
				dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
				dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
				dataTableSchema.Columns.Add ("NumericScale", typeof (int));
				dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
				dataTableSchema.Columns.Add ("IsKey", typeof (bool));
				DataColumn dc = dataTableSchema.Columns["IsKey"];
				dc.AllowDBNull = true; // IsKey can have a DBNull
				dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
				dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
				dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
				dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
				dataTableSchema.Columns.Add ("DataType", typeof(Type));
				dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
				dataTableSchema.Columns.Add ("ProviderType", typeof (int));
				dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
				dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
				dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
				dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
				dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
				dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
				dataTableSchema.Columns.Add ("IsLong", typeof (bool));
				dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));

				DataRow schemaRow;
				DbType dbType;
				Type typ;

				for (int i = 0; i < this.FieldCount; i += 1 ) {

					schemaRow = dataTableSchema.NewRow ();

					attrs = libgda.gda_data_model_describe_column ((IntPtr) gdaResults[currentResult],
						i);
					if (attrs == IntPtr.Zero){
						// FIXME: throw exception
#if DEBUG_OleDbDataReader
						Console.WriteLine("Error: attrs null");
#endif
						return null;
					}

					gdaType = libgda.gda_field_attributes_get_gdatype (attrs);
					columnSize = libgda.gda_field_attributes_get_defined_size (attrs);
					libgda.gda_field_attributes_free (attrs);

					schemaRow["ColumnName"] = this.GetName(i);
					schemaRow["ColumnOrdinal"] = i + 1;

					schemaRow["ColumnSize"] = (int) columnSize;
					schemaRow["NumericPrecision"] = 0;
					schemaRow["NumericScale"] = 0;
					// TODO: need to get KeyInfo
					//if((cmdBehavior & CommandBehavior.KeyInfo) == CommandBehavior.KeyInfo) {
						// bool IsUnique, IsKey;
						// GetKeyInfo(field[i].Name, out IsUnique, out IsKey);
					//}
					//else {
						schemaRow["IsUnique"] = false;
						schemaRow["IsKey"] = DBNull.Value;
					//}
					schemaRow["BaseCatalogName"] = "";

					schemaRow["BaseColumnName"] = this.GetName(i);
					schemaRow["BaseSchemaName"] = "";
					schemaRow["BaseTableName"] = "";

					schemaRow["DataType"] = this.GetFieldType(i);

					schemaRow["AllowDBNull"] = false;

					schemaRow["ProviderType"] = (int) gdaType;
					schemaRow["IsAliased"] = false;
					schemaRow["IsExpression"] = false;
					schemaRow["IsIdentity"] = false;
					schemaRow["IsAutoIncrement"] = false;
					schemaRow["IsRowVersion"] = false;
					schemaRow["IsHidden"] = false;
					schemaRow["IsLong"] = false;
					schemaRow["IsReadOnly"] = false;

					schemaRow.AcceptChanges();

					dataTableSchema.Rows.Add (schemaRow);
				}

#if DEBUG_OleDbDataReader
				Console.WriteLine("********** DEBUG Table Schema BEGIN ************");
				foreach (DataRow myRow in dataTableSchema.Rows) {
					foreach (DataColumn myCol in dataTableSchema.Columns)
						Console.WriteLine(myCol.ColumnName + " = " + myRow[myCol]);
					Console.WriteLine();
				}
				Console.WriteLine("********** DEBUG Table Schema END ************");
#endif // DEBUG_OleDbDataReader

			}

			return dataTableSchema;
		}

		public string GetString (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new InvalidCastException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new InvalidCastException ();

			if (libgda.gda_value_get_type (value) != GdaValueType.String)
				throw new InvalidCastException ();
			return libgda.gda_value_get_string (value);
		}

		[MonoTODO]
		public TimeSpan GetTimeSpan (int ordinal)
		{
			throw new NotImplementedException ();
		}

		public object GetValue (int ordinal)
		{
			IntPtr value;
			GdaValueType type;

			if (currentResult == -1)
				throw new IndexOutOfRangeException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new IndexOutOfRangeException ();

			type = libgda.gda_value_get_type (value);
			switch (type) {
			case GdaValueType.Bigint : return GetInt64 (ordinal);
			case GdaValueType.Boolean : return GetBoolean (ordinal);
			case GdaValueType.Date : return GetDateTime (ordinal);
			case GdaValueType.Double : return GetDouble (ordinal);
			case GdaValueType.Integer : return GetInt32 (ordinal);
			case GdaValueType.Single : return GetFloat (ordinal);
			case GdaValueType.Smallint : return GetByte (ordinal);
			case GdaValueType.String : return GetString (ordinal);
			case GdaValueType.Time : return GetDateTime (ordinal);
			case GdaValueType.Timestamp : return GetDateTime (ordinal);
			case GdaValueType.Tinyint : return GetByte (ordinal);
			}

			return (object) libgda.gda_value_stringify (value);
		}

		[MonoTODO]
		public int GetValues (object[] values)
		{
			throw new NotImplementedException ();
		}

		[MonoTODO]
		IDataReader IDataRecord.GetData (int ordinal)
		{
			throw new NotImplementedException ();
		}

		IEnumerator IEnumerable.GetEnumerator ()
		{
			return new DbEnumerator (this);
		}

		public bool IsDBNull (int ordinal)
		{
			IntPtr value;

			if (currentResult == -1)
				throw new IndexOutOfRangeException ();

			value = libgda.gda_data_model_get_value_at ((IntPtr) gdaResults[currentResult],
								    ordinal, currentRow);
			if (value == IntPtr.Zero)
				throw new IndexOutOfRangeException ();

			return libgda.gda_value_is_null (value);
		}

		public bool NextResult ()
		{
			int i = currentResult + 1;
			if (i >= 0 && i < gdaResults.Count) {
				currentResult++;
				return true;
			}

			return false;
		}

		public bool Read ()
		{
			if (currentResult < 0 ||
			    currentResult >= gdaResults.Count)
				return false;

			currentRow++;
			if (currentRow <
			    libgda.gda_data_model_get_n_rows ((IntPtr) gdaResults[currentResult]))
				return true;

			return false;
		}

		#endregion

		#region Destructors

		private void Dispose (bool disposing) {
			if (!this.disposed) {
				if (disposing) {
					// release any managed resources
					command = null;
				}
				// release any unmanaged resources
				if (gdaResults != null) {
					gdaResults.Clear ();
					gdaResults = null;
				}

				// close any handles
				if (open)
					Close ();

				this.disposed = true;
			}
		}

		void IDisposable.Dispose() {
			Dispose (true);
		}

		~OleDbDataReader() {
			Dispose (false);
		}

		#endregion // Destructors

	}
}


text:
describe("Store", function () {
	var store, noop, callbackSpy;

	beforeEach(function () {
		store = new app.Store("test store");
		noop = function () {
		};
		callbackSpy = jasmine.createSpy("callback");
	});

	afterEach(function () {
		store.drop(noop);
	});

	describe("constructor", function () {
		it("calls the callback with the local store name", function () {
			new app.Store("test store", callbackSpy);

			expect(callbackSpy).toHaveBeenCalledWith({ todos: [ ] });
		});

		it("does not crash when called with no callback", function () {
			expect(function () {
				new app.Store("test store");
			}).not.toThrow();
		});

		it("shares data betweeen stores using the same name", function () {
			var storeOne = new app.Store("myStore");
			storeOne.drop(noop);
			var storeTwo = new app.Store("myStore");
			storeTwo.drop(noop);

			storeOne.save({an: "item"}, noop);
			storeTwo.findAll(callbackSpy);

			expect(callbackSpy).toHaveBeenCalledWith([
				{an: "item", id: jasmine.any(Number)}
			]);
		});

	});

	describe("save", function () {
		it("calls back when done", function () {
			var obj = {foo: "bar"};
			store.save(obj, callbackSpy);

			expect(callbackSpy).toHaveBeenCalledWith([
				{foo: "bar", id: jasmine.any(Number)}
			]);
		});

		it("can modify objects in place", function () {
			var id;
			store.save({foo: "bar"}, function (items) {
				id = items[0].id;
			});

			store.save(id, {foo: "stuff"});

			store.findAll(callbackSpy);

			expect(callbackSpy).toHaveBeenCalled();
			var callbackData = callbackSpy.mostRecentCall.args[0];
			expect(callbackData.length).toEqual(1);
			expect(callbackData[0]).toEqual({foo: "stuff", id: id});
		});
	});

	describe("findAll", function () {
		it("calls back with an empty array when empty", function () {
			store.findAll(callbackSpy);

			expect(callbackSpy).toHaveBeenCalledWith([]);
		});

		it("calls back with each item that is added", function () {
			store.save({a: "A"}, noop);
			store.save({b: "B"}, noop);
			store.save({c: "C"}, noop);

			store.findAll(callbackSpy);

//      expect(callbackSpy).toHaveBeenCalledWith([
//        {id: 1, a: "A"},
//        {id: 2, b: "B"},
//        {id: 3, c: "C"}
//      ]);

			expect(callbackSpy).toHaveBeenCalled();
			var callbackData = callbackSpy.mostRecentCall.args[0];
			expect(callbackData.length).toEqual(3);
			expect(callbackData).toContain({a: "A", id: jasmine.any(Number)});
			expect(callbackData).toContain({b: "B", id: jasmine.any(Number)});
			expect(callbackData).toContain({c: "C", id: jasmine.any(Number)});
		});

		it("does not crash when called with no arguments", function () {
			expect(function () {
				store.findAll();
			}).not.toThrow();
		});
	});

	describe("find", function () {
		it("calls back with an empty array when the store is empty", function () {
			store.find({}, callbackSpy);

			expect(callbackSpy).toHaveBeenCalledWith([]);
		});

		it("returns matching objects from the store", function () {
			store.save({foo: "bar", hello: "world"}, noop);
			store.save({foo: "bar", bye: "planet"}, noop);
			store.save({foo: "NOPE", stuff: "is cool"}, noop);

			store.find({foo: "bar"}, callbackSpy);

			expect(callbackSpy).toHaveBeenCalled();
			var callbackData = callbackSpy.mostRecentCall.args[0];
			expect(callbackData.length).toEqual(2);
			expect(callbackData).toContain({foo: "bar", hello: "world", id: jasmine.any(Number)});
			expect(callbackData).toContain({foo: "bar", bye: "planet", id: jasmine.any(Number)});
		});

		it("does not crash when called with no arguments", function () {
			expect(function () {
				store.find();
			}).not.toThrow();
		});
	});

	describe("remove", function () {
		it("removes and item from the store", function () {
			var id;
			store.save({a: "A"}, function (items) {
				id = items[0].id;
			});
			store.save({b: "B"}, noop);

			store.findAll(callbackSpy);
			var callbackData = callbackSpy.mostRecentCall.args[0];

			expect(callbackData.length).toEqual(2);

			store.remove(id, noop);
			store.findAll(callbackSpy);
			callbackData = callbackSpy.mostRecentCall.args[0];
			expect(callbackData.length).toEqual(1);
		});

	});

	describe("#dumpToEndpoint", function () {
		it("sends the contents of the db to an endpoint", function () {
			store.save({b: "B"}, noop);

			jasmine.Ajax.useMock();

			store.dumpToEndpoint();
			var request = mostRecentAjaxRequest();

			expect(request.url).toEqual("http://google.com");
			expect(request.data()).toEqual({ store: [ jasmine.any(String) ] });
		});

		it("console logs when successful", function () {
			spyOn(console, "log");
			store.save({b: "B"}, noop);

			jasmine.Ajax.useMock();

			store.dumpToEndpoint();

//		expect to see loading spinner

			var request = mostRecentAjaxRequest();

			request.response({
				status: 200,
				responseText: '{"response": {"body": "some body"}}'
			});

//		expect loading spinner to be gone
			expect(console.log).toHaveBeenCalledWith("success!")
		});
	});
});


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S10.1.5_A1.3_T4;
 * @section: 10.1.5, 15.1;
 * @assertion: Global object has properties such as built-in objects such as
 * Math, String, Date, parseInt, etc;
 * @description: Eval execution context - Other Properties;
*/

var evalStr =
'//CHECK#27\n'+
'if ( Math === null ) {\n'+
'  $ERROR("#27: Math === null");\n'+
'}\n'+
';\n';

eval(evalStr);


text:
"""Integration tests for Linode"""
from unittest import TestCase

import pytest

from lexicon.tests.providers.integration_tests import IntegrationTestsV2

# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interface must
# pass, by inheritance from integration_tests.IntegrationTests
class LinodeProviderTests(TestCase, IntegrationTestsV2):
    """TestCase for Linode"""

    provider_name = "linode"
    domain = "lexicon-example.com"

    def _filter_post_data_parameters(self):
        return []

    def _filter_headers(self):
        return []

    def _filter_query_parameters(self):
        return ["api_key"]

    @pytest.mark.skip(reason="can not set ttl when creating/updating records")
    def test_provider_when_calling_list_records_after_setting_ttl(self):
        return


text:
package com.ynitq.utils.jmxInWeb.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpExchange;

/**
 *

 * 负责分析http请求参数的过滤器,
 * 将get或者post传过来的参数放到Map中,
 * Map的key是参数名,value是一个List<String>
 *
 * 最后将这个map,存在HttpExchange中
 *

 *
 * @authorAlex (梁韦江) 2015年9月10日
 */
public class ParameterFilter extends Filter {

	public static String ATTRIBUTE_NAME = "parameters";

	private static String CHARSET = "utf-8";

	@Override
	public String description() {
		return "Parses the requested URI for parameters";
	}

	public static List<String> getParameterNames(HttpExchange exchange) {
		Map<String, List<String>> parameters = getParameterMap(exchange);
		List<String> list = new LinkedList<String>();
		list.addAll(parameters.keySet());
		Collections.sort(list);
		return list;
	}

	public static String getParameter(HttpExchange exchange, String key) {
		if (key != null) {
			Map<String, List<String>> map = getParameterMap(exchange);
			List<String> list = map.get(key);
			if (list != null && list.size() > 0) {
				return list.get(0);
			}
		}
		return null;
	}

	public static List<String> getParameters(HttpExchange exchange, String key) {
		if (key != null) {
			Map<String, List<String>> map = getParameterMap(exchange);
			return map.get(key);
		}
		return null;
	}

	public static Map<String, List<String>> getParameterMap(HttpExchange exchange) {
		@SuppressWarnings("unchecked")
		Map<String, List<String>> map = (Map<String, List<String>>) exchange.getAttribute(ATTRIBUTE_NAME);
		if (map == null) {
			return new HashMap<String, List<String>>();
		} else {
			return map;
		}
	}

	@Override
	public void doFilter(HttpExchange exchange, Chain chain)
			throws IOException {

		// 先初始化一个map
		Map<String, List<String>> parameters = new HashMap<String, List<String>>();
		parseGetParameters(exchange, parameters);
		parsePostParameters(exchange, parameters);
		// 结束后将map放到attribute中
		exchange.setAttribute(ATTRIBUTE_NAME, parameters);

		chain.doFilter(exchange);

	}

	/**
	 * 解析get方式的参数
	 *
	 * @param exchange
	 * @param parameters2
	 * @throws UnsupportedEncodingException
	 */
	private void parseGetParameters(HttpExchange exchange, Map<String, List<String>> parameters)
			throws UnsupportedEncodingException {

		URI requestedUri = exchange.getRequestURI();
		String query = requestedUri.getRawQuery();
		parseQuery(query, parameters);
		exchange.setAttribute(ATTRIBUTE_NAME, parameters);
	}

	/**
	 * 解析post方式的参数
	 *
	 * @param exchange
	 * @param parameters2
	 * @throws IOException
	 */
	private void parsePostParameters(HttpExchange exchange, Map<String, List<String>> parameters)
			throws IOException {

		if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
			InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), CHARSET);
			BufferedReader br = new BufferedReader(isr);
			String query = br.readLine();
			parseQuery(query, parameters);
		}
	}

	private void parseQuery(String query, Map<String, List<String>> parameters)
			throws UnsupportedEncodingException {

		if (query != null) {
			String pairs[] = query.split("[&]");

			for (String pair : pairs) {
				String param[] = pair.split("[=]");

				String key = null;
				String value = null;
				if (param.length > 0) {
					key = URLDecoder.decode(param[0], CHARSET);
				}

				if (param.length > 1) {
					value = URLDecoder.decode(param[1], CHARSET);
				}

				List<String> values = parameters.get(key);
				if (values == null) {
					values = new ArrayList<String>();
					parameters.put(key, values);
				}
				values.add(value);
			}
		}
	}
}


text:
package net.kinetc.biryo.parser

import akka.actor.ActorRef
import org.typelevel.jawn.{AsyncParser, ast}
import net.kinetc.biryo.actor.MDictMaker.{FrameDoc, MDictDoc}

object JsonParser {
  final case class ParseOptions(
      printRaw: Boolean,
      useInlineCSS: Boolean,
      blocking: Boolean
  )
  final case class DoParse(fileName: String)
}

trait JsonParser {
  import JsonParser._

  val options: ParseOptions
  val mdictMakerRouter: ActorRef

  var docCount = 0
  val p = ast.JParser.async(mode = AsyncParser.UnwrapArray)

  protected def sendMDictData(
      title: String,
      text: String,
      prefix: String,
      isFrame: Boolean
  ): Unit = {
    if (!options.printRaw && !options.useInlineCSS && isFrame) {
      mdictMakerRouter ! FrameDoc(title, text)
    }

    mdictMakerRouter ! MDictDoc(prefix + title, text, options.printRaw)
    docCount += 1
    if (docCount % 10000 == 0) {
      println(s"parse count $docCount")
    }
  }

  protected def makeMDict(js: ast.JValue): Unit = {
    var isFrame = false

    val namespace = js.get("namespace")
    val prefix = namespace.getInt match {
      case Some(0) => ""
      case Some(1) => isFrame = true; "틀:"
      case Some(2) => "분류:"
      case Some(6) => "나무위키:"
      case _ => {
        // fall back to string
        namespace.getString match {
          case Some("0") => ""
          case Some("1") => isFrame = true; "틀:"
          case Some("2") => "분류:"
          case Some("6") => "나무위키:"
          case _ => {
            println(
              s"json namespace error: ${js.get("title").getString} / ${js.get("namespace")}"
            )
            return
          }
        }
      }
    }
    (js.get("title").getString, js.get("text").getString) match {
      case (Some(title), Some(text)) =>
        sendMDictData(title, text, prefix, isFrame)
      case _ => {
        println(s"json parse error: ${js.get("title")} / ${js.get("text")}")
      }
    }
  }

  protected final def absorb(chunk: String): Unit = {
    p.absorb(chunk) match {
      case Right(js) =>
        js.foreach(makeMDict)
      case Left(e) =>
        e.printStackTrace()
    }
  }

  protected final def finishParse(): Unit = {
    p.finish() match {
      case Right(js) =>
        js.foreach(makeMDict)
      case Left(e) =>
        e.printStackTrace()
    }
  }
}


text:
*condor_token_request*
======================

interactively request a token from a remote daemon for the IDTOKENS authentication method
:index:`condor_token_request<single: condor_token_request; HTCondor commands>`\ :index:`condor_token_request command`

Synopsis
--------

**condor_token_request** [**-identity** *user@domain*] [**-authz** *authz* ...]
[**-lifetime** *value*]
[**-pool** *pool_name*] [**-name** hostname] [**-type** *type*]
[**-token** *filename*]

**condor_token_request** [**-help** ]

Description
-----------

*condor_token_request* will request an authentication token from a remote
daemon. Token requests must be approved by the daemon's administrator using
*condor_token_request_approve*.  Unlike *condor_token_fetch*, the user doesn't
need an existing identity with the remote daemon when using
*condor_token_request* (an anonymous method, such as ``SSL`` without a client
certificate will suffice).

If the request is successfully enqueued, the request ID will be printed to ``stderr``;
the administrator will need to know the ID to approve the request.  *condor_token_request*
will wait until the request is approved, timing out after an hour.

The token request mechanism provides a powerful way to bootstrap authentication
in a HTCondor pool - a remote user can request an identity, verify the authenticity of
the request out-of-band with the remote daemon's administrator, and
then securely recieve their authentication token.

By default, *condor_token_request* will query the local *condor_collector*; by specifying
a combination of **-pool**, **-name**, or **-type**, the tool can request tokens
in other pools, on other hosts, or different daemon types.

If successful, the resulting token will be sent to ``stdout``; by specifying
the **-token** option, it will instead be written to the user's token directory.

Options
-------

 **-authz** *authz*
    Adds a restriction to the token so it is only valid to be used for
    a given authorization level (such as ``READ``, ``WRITE``, ``DAEMON``,
    ``ADVERTISE_STARTD``).  If multiple authorizations are needed, then
    **-authz** must be specified multiple times.  If **-authz** is not
    specified, no authorization restrictions are added and authorization
    will be solely based on the token's identity.
    **NOTE** that **-authz** cannot be used to give an identity additional
    permissions at the remote host.  If the server's admin only permits
    the user ``READ`` authorization, then specifying ``-authz WRITE`` in a
    token will not allow the user to perform writes.
 **-debug**
    Causes debugging information to be sent to ``stderr``, based on the
    value of the configuration variable ``TOOL_DEBUG``.
 **-help**
    Display brief usage information and exit.
 **-identity** *user@domain*
    Request a specific identity from the daemon; a client using the resulting token
    will authenticate as this identity with a remote server.  If not specified, the
    token will be issued for the ``condor`` identity.
 **-lifetime** *value*
    Specify the lifetime, in seconds, for the token to be valid (the
    token validity will start when the token is signed).  After the
    lifetime expires, the token cannot be used for authentication.  If
    not specified, the token will contain no lifetime restrictions.
 **-name** *hostname*
    Request a token from the daemon named *hostname* in the pool.  If not specified,
    the locally-running daemons will be used.
 **-pool** *pool_name*
    Request a token from a daemon in a non-default pool *pool_name*.
 **-token** *filename*
    Specifies a filename, relative to the directory in the *SEC_TOKEN_DIRECTORY*
    configuration variable (defaulting to ``~/.condor/tokens.d``), where
    the resulting token is stored.  If not specified, the token will be
    sent to ``stdout``.
 **-type** *type*
    Request a token from a specific daemon type *type*.  If not given, a
    *condor_collector* is used.

Examples
--------

To obtain a token with a lifetime of 10 minutes from the default *condor_collector*
(the token is not returned until the daemon's administrator takes action):

.. code-block:: console

    $ condor_token_request -lifetime 600
    Token request enqueued.  Ask an administrator to please approve request 6108900.
    eyJhbGciOiJIUzI1NiIsImtpZCI6IlBPT0wifQ.eyJpYX...ii7lAfCA

To request a token from ``bird.cs.wisc.edu`` which is limited to ``READ`` and
``WRITE``:

.. code-block:: console

    $ condor_token_request -name bird.cs.wisc.edu \
                           -identity bucky@cs.wisc.edu
                           -authz READ -authz WRITE
    Token request enqueued.  Ask an administrator to please approve request 2578154
    eyJhbGciOiJIUzI1NiIsImtpZCI6IlBPT0wifQ.eyJpYX...lJTj54

To create a token from the collector in the ``htcondor.cs.wisc.edu`` pool
and then to save it to ``~/.condor/tokens.d/friend``:

.. code-block:: console

    $ condor_token_request -pool htcondor.cs.wisc.edu \
                         -identity friend@cs.wisc.edu \
                         -lifetime 600 -token friend
    Token request enqueued.  Ask an administrator to please approve request 2720841.

Exit Status
-----------

*condor_token_request* will exit with a non-zero status value if it
fails to request or recieve the token.  Otherwise, it will exit 0.

See also
--------

:manpage:`condor_token_create(1)`, :manpage:`condor_token_fetch(1)`, :manpage:`condor_token_request_approve(1)`, :manpage:`condor_token_request_auto_approve(1)`, :manpage:`condor_token_list(1)`

Author
------

Center for High Throughput Computing, University of Wisconsin-Madison

Copyright
---------

Copyright © 1990-2019 Center for High Throughput Computing, Computer
Sciences Department, University of Wisconsin-Madison, Madison, WI. All
Rights Reserved. Licensed under the Apache License, Version 2.0.