text:
describe("API", function() {
    var actual = window;
    var expected = {Ext:{core:{Element: function(){} }}},
        Ext = expected.Ext,
        undefined;

    /* Touch out -- Element-more.js */ Ext.core.Element.prototype.clean = undefined;
    /* Touch out -- Element-more.js */ Ext.core.Element.prototype.createProxy = undefined;
    /* Touch out -- Element-more.js */ Ext.core.Element.prototype.getLoader = undefined;
    /* Touch out -- Element-more.js */ Ext.core.Element.prototype.monitorMouseLeave = undefined;
    /* Touch out -- Element-more.js */ Ext.core.Element.prototype.relayEvent = undefined;
    /* Touch out -- Element-more.js */ Ext.core.Element.prototype.swallowEvent = undefined;
    /* Touch out -- Element-more.js,Element.js */ Ext.core.Element.prototype.load = undefined;
    /* Touch out -- Element.alignment.js */ Ext.core.Element.prototype.getConstrainVector = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.fadeIn = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.fadeOut = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.frame = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.ghost = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.highlight = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.pause = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.puff = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.scale = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.shift = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.slideIn = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.slideOut = undefined;
    /* Touch out -- Element.anim.js */ Ext.core.Element.prototype.switchOff = undefined;
    /* Touch out -- Element.dd.js */ Ext.core.Element.prototype.initDD = undefined;
    /* Touch out -- Element.dd.js */ Ext.core.Element.prototype.initDDProxy = undefined;
    /* Touch out -- Element.dd.js */ Ext.core.Element.prototype.initDDTarget = undefined;
    /* Touch out -- Element.fx-more.js */ Ext.core.Element.prototype.createShim = undefined;
    /* Touch out -- Element.fx-more.js */ Ext.core.Element.prototype.enableDisplayMode = undefined;
    /* Touch out -- Element.fx-more.js */ Ext.core.Element.prototype.isDisplayed = undefined;
    /* Touch out -- Element.fx-more.js */ Ext.core.Element.prototype.isMasked = undefined;
    /* Touch out -- Element.fx.js */ Ext.core.Element.originalDisplay = undefined;
    /* Touch out -- Element.fx.js */ Ext.core.Element.prototype.animate = undefined;
    /* Touch out -- Element.fx.js */ Ext.core.Element.prototype.isVisible = undefined;
    /* Touch out -- Element.fx.js */ Ext.core.Element.prototype.setDisplayed = undefined;
    /* Touch out -- Element.fx.js */ Ext.core.Element.prototype.setVisibilityMode = undefined;
    /* Touch out -- Element.fx.js */ Ext.core.Element.prototype.toggle = undefined;
    /* Touch out -- Element.fx.js */ Ext.core.Element.visibilityCls = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.appendChild = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.appendTo = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.createChild = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.insertAfter = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.insertBefore = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.insertFirst = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.insertHtml = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.insertSibling = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.replace = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.replaceWith = undefined;
    /* Touch out -- Element.insertion.js */ Ext.core.Element.prototype.wrap = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.autoBoxAdjust = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.blur = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.clearListeners = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.destroy = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.focus = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.getAttributeNS = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.hover = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.isBorderBox = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.on = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.un = undefined;
    /* Touch out -- Element.js */ Ext.core.Element.prototype.update = undefined;
    /* Touch out -- Element.keys.js */ Ext.core.Element.prototype.addKeyListener = undefined;
    /* Touch out -- Element.keys.js */ Ext.core.Element.prototype.addKeyMap = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.clearPositioning = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.getPositioning = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.getRegion = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.getViewRegion = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.move = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.moveTo = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.position = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.setBounds = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.setLeftTop = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.setLocation = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.setPositioning = undefined;
    /* Touch out -- Element.position.js */ Ext.core.Element.prototype.setRegion = undefined;
    /* Touch out -- Element.scroll.js */ Ext.core.Element.prototype.getScroll = undefined;
    /* Touch out -- Element.scroll.js */ Ext.core.Element.prototype.isScrollable = undefined;
    /* Touch out -- Element.scroll.js */ Ext.core.Element.prototype.scroll = undefined;
    /* Touch out -- Element.scroll.js */ Ext.core.Element.prototype.scrollIntoView = undefined;
    /* Touch out -- Element.scroll.js */ Ext.core.Element.prototype.scrollTo = undefined;
    /* Touch out -- Element.static-more.js */ Ext.core.Element.prototype.getActiveElement = undefined;
    /* Touch out -- Element.static-more.js */ Ext.core.Element.prototype.serializeForm = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.fromPoint = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.getDocumentHeight = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.getDocumentWidth = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.getOrientation = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.getViewportHeight = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.getViewportWidth = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.normalize = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.parseBox = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.parseStyles = undefined;
    /* Touch out -- Element.static.js */ Ext.core.Element.prototype.unitizeBox = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.addClass = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.addClsOnClick = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.addClsOnFocus = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.addClsOnOver = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.boxWrap = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.clearOpacity = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.clip = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.getColor = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.getComputedHeight = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.getComputedWidth = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.getFrameWidth = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.getStyleSize = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.getStyles = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.hasClass = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.radioClass = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.removeClass = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.replaceClass = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.setOpacity = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.toggleClass = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.unclip = undefined;
    /* Touch out -- Element.style.js */ Ext.core.Element.prototype.unselectable = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.child = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.down = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.findParent = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.findParentNode = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.first = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.last = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.next = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.parent = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.prev = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.query = undefined;
    /* Touch out -- Element.traversal.js */ Ext.core.Element.prototype.up = undefined;

    APITest({Ext:expected.Ext}, {Ext:actual.Ext});
});


text:
package com.cc.jcg.examples.gen;

import com.cc.jcg.MGenerated;

@MGenerated
 interface SomeInterface<T> {
}

redpajama_set_name: RedPajamaGithub


text:
import type { FilterChoice } from '~/components/questions/filter/FilterSection';

import useCompanyOptions from '../shared/useCompanyOptions';

export default function useDefaultCompany(): FilterChoice | undefined {
  const { data: companyOptions } = useCompanyOptions('google');
  return companyOptions[0];
}


text:
type: post100
title:  Getting Started
categories: XAP100
parent: none
weight: 200
---

Here you will find a quick start guide that explains how to deploy and use a GigaSpace XAP Data Grid.
A full Java tutorial is also provided that will introduce you to the basic capabilities and features of the XAP platform.

<br>

{{%fpanel%}}

[XAP in 5 Minutes](./your-first-data-grid-application.html){{<wbr>}}
This tutorial explains how to deploy and use a XAP Data Grid from a Java client application.

[Full Tutorial](./java-home.html){{<wbr>}}
This Tutorial provides a high-level overview of the GigaSpaces XAP platform. Hands on examples are provided to demonstrate the core concepts and API's.

[Cook Books](./cook-books.html){{<wbr>}}
Here you will find example applications that demonstrate basic XAP features.
{{%/fpanel%}}


text:
"""Unit tests for pipelines expressed via dask.delayed

"""

import logging
import sys
import unittest

import numpy
from astropy import units as u
from astropy.coordinates import SkyCoord

from data_models.polarisation import PolarisationFrame
from workflows.serial.calibration.calibration_serial import calibrate_list_serial_workflow
from wrappers.serial.calibration.calibration_control import create_calibration_controls
from wrappers.serial.calibration.operations import create_gaintable_from_blockvisibility, apply_gaintable
from wrappers.serial.simulation.testing_support import ingest_unittest_visibility
from processing_components.simulation.configurations import create_named_configuration
from wrappers.serial.simulation.testing_support import simulate_gaintable
from wrappers.serial.visibility.base import copy_visibility

log = logging.getLogger(__name__)

log.setLevel(logging.DEBUG)
log.addHandler(logging.StreamHandler(sys.stdout))
log.addHandler(logging.StreamHandler(sys.stderr))

class TestCalibrateGraphs(unittest.TestCase):

    def setUp(self):
        from data_models.parameters import arl_path
        self.dir = arl_path('test_results')

        self.persist = False

    def tearDown(self):
        pass

    def actualSetUp(self, nfreqwin=3, dospectral=True, dopol=False,
                    amp_errors=None, phase_errors=None, zerow=True):

        if amp_errors is None:
            amp_errors = {'T': 0.0, 'G': 0.1}
        if phase_errors is None:
            phase_errors = {'T': 1.0, 'G': 0.0}

        self.npixel = 512
        self.low = create_named_configuration('LOWBD2', rmax=750.0)
        self.freqwin = nfreqwin
        self.vis_list = list()
        self.ntimes = 1
        self.times = numpy.linspace(-3.0, +3.0, self.ntimes) * numpy.pi / 12.0
        self.frequency = numpy.linspace(0.8e8, 1.2e8, self.freqwin)

        if self.freqwin > 1:
            self.channelwidth = numpy.array(self.freqwin * [self.frequency[1] - self.frequency[0]])
        else:
            self.channelwidth = numpy.array([1e6])

        if dopol:
            self.vis_pol = PolarisationFrame('linear')
            self.image_pol = PolarisationFrame('stokesIQUV')
            f = numpy.array([100.0, 20.0, -10.0, 1.0])
        else:
            self.vis_pol = PolarisationFrame('stokesI')
            self.image_pol = PolarisationFrame('stokesI')
            f = numpy.array([100.0])

        if dospectral:
            flux = numpy.array([f * numpy.power(freq / 1e8, -0.7) for freq in self.frequency])
        else:
            flux = numpy.array([f])

        self.phasecentre = SkyCoord(ra=+180.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')
        self.blockvis_list = [ingest_unittest_visibility(self.low,
                                                         [self.frequency[i]],
                                                         [self.channelwidth[i]],
                                                         self.times,
                                                         self.vis_pol,
                                                         self.phasecentre, block=True,
                                                         zerow=zerow)
                              for i in range(nfreqwin)]

        for v in self.blockvis_list:
            v.data['vis'][...] = 1.0 + 0.0j

        self.error_blockvis_list = [copy_visibility(v) for v in self.blockvis_list]
        gt = create_gaintable_from_blockvisibility(self.blockvis_list[0])
        gt = simulate_gaintable(gt, phase_error=0.1, amplitude_error=0.0, smooth_channels=1, leakage=0.0)
        self.error_blockvis_list = [apply_gaintable(self.error_blockvis_list[i], gt)
                                    for i in range(self.freqwin)]

        assert numpy.max(numpy.abs(self.error_blockvis_list[0].vis - self.blockvis_list[0].vis)) > 0.0

    def test_time_setup(self):
        self.actualSetUp()

    def test_calibrate_serial(self):
        amp_errors = {'T': 0.0, 'G': 0.0}
        phase_errors = {'T': 1.0, 'G': 0.0}
        self.actualSetUp(amp_errors=amp_errors, phase_errors=phase_errors)

        controls = create_calibration_controls()
        controls['T']['first_selfcal'] = 0
        controls['T']['timeslice'] = 'auto'

        calibrate_list = \
            calibrate_list_serial_workflow(self.error_blockvis_list, self.blockvis_list,
                                           calibration_context='T', controls=controls, do_selfcal=True,
                                           global_solution=False)
        assert len(calibrate_list) == 2
        assert numpy.max(calibrate_list[1][0]['T'].residual) < 7e-6, numpy.max(calibrate_list[1][0]['T'].residual)
        assert numpy.max(numpy.abs(calibrate_list[0][0].vis - self.blockvis_list[0].vis)) < 2e-6

    def test_calibrate_serial_empty(self):
        amp_errors = {'T': 0.0, 'G': 0.0}
        phase_errors = {'T': 1.0, 'G': 0.0}
        self.actualSetUp(amp_errors=amp_errors, phase_errors=phase_errors)

        for v in self.blockvis_list:
            v.data['vis'][...] = 0.0 + 0.0j

        controls = create_calibration_controls()
        controls['T']['first_selfcal'] = 0
        controls['T']['timeslice'] = 'auto'

        calibrate_list = \
            calibrate_list_serial_workflow(self.error_blockvis_list, self.blockvis_list,
                                                calibration_context='T', controls=controls, do_selfcal=True,
                                                global_solution=False)
        assert len(calibrate_list[1][0]) == 1
        assert numpy.max(calibrate_list[1][0]['T'].residual) == 0.0, numpy.max(calibrate_list[1][0]['T'].residual)

    def test_calibrate_serial_global(self):
        amp_errors = {'T': 0.0, 'G': 0.0}
        phase_errors = {'T': 1.0, 'G': 0.0}
        self.actualSetUp(amp_errors=amp_errors, phase_errors=phase_errors)

        controls = create_calibration_controls()
        controls['T']['first_selfcal'] = 0
        controls['T']['timeslice'] = 'auto'

        calibrate_list = \
            calibrate_list_serial_workflow(self.error_blockvis_list, self.blockvis_list,
                                           calibration_context='T', controls=controls, do_selfcal=True,
                                           global_solution=True)

        assert len(calibrate_list) == 2
        assert numpy.max(calibrate_list[1][0]['T'].residual) < 7e-6, numpy.max(calibrate_list[1][0]['T'].residual)
        err = numpy.max(numpy.abs(calibrate_list[0][0].vis - self.blockvis_list[0].vis))
        assert err < 2e-6, err

    def test_calibrate_serial_global_empty(self):
        amp_errors = {'T': 0.0, 'G': 0.0}
        phase_errors = {'T': 1.0, 'G': 0.0}
        self.actualSetUp(amp_errors=amp_errors, phase_errors=phase_errors)

        for v in self.blockvis_list:
            v.data['vis'][...] = 0.0 + 0.0j

        controls = create_calibration_controls()
        controls['T']['first_selfcal'] = 0
        controls['T']['timeslice'] = 'auto'

        calibrate_list = \
            calibrate_list_serial_workflow(self.error_blockvis_list, self.blockvis_list,
                                                    calibration_context='T', controls=controls, do_selfcal=True,
                                                    global_solution=True)
        assert len(calibrate_list[1][0]) == 1
        assert numpy.max(calibrate_list[1][0]['T'].residual) == 0.0, numpy.max(calibrate_list[1][0]['T'].residual)

if __name__ == '__main__':
    unittest.main()


text:
import json
import os
import time

import grovepi
import iot

DHT_SENSOR_PORT = 7
DHT_SENSOR_TYPE = 0

def start(client_id):
    shadow_client = iot.create_shadow_client(
        os.environ.get('AWS_IOT_ENDPOINT'),
        os.environ.get('AWS_IOT_CA_CERT_PATH'),
        os.environ.get('AWS_IOT_KEY_PATH'),
        os.environ.get('AWS_IOT_COMBINE_CERT_PATH'),
        os.environ.get('RESIN_DEVICE_UUID')
    )

    shadow = shadow_client.connect_to_shadow(shadow_client, client_id)

    while True:
        try:
            # Get the temperature and Humidity from the DHT sensor
            [temp, hum] = grovepi.dht(DHT_SENSOR_PORT, DHT_SENSOR_TYPE)
            print("temp=", temp, "thumidity=", hum, "%")

            # Report data to AWS
            shadow_state = '{"state":{"desired":{"temperature":' + temp + ', "humidity":' + hum + '}}}'
            shadow.shadowUpdate(shadow_state, 5)

            # Sleep for 60 seconds
            time.sleep(60)
        except (IOError, TypeError) as err:
            print 'Error during measurement:', err

try:
    start('garden-aid')
except (IOError) as err:
    print 'Error during startup:', err


text:
package example.repo;

import example.model.Customer273;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface Customer273Repository extends CrudRepository<Customer273, Long> {

	List<Customer273> findByLastName(String lastName);
}


text:
namespace Stations.DataProcessor.Dto.Import
{
    using System.ComponentModel.DataAnnotations;

    public class TripDto
    {
        [Required]
        public string Train { get; set; }

        [Required]
        public string OriginStation { get; set; }

        [Required]
        public string DestinationStation { get; set; }

        [Required]
        public string DepartureTime { get; set; }

        [Required]
        public string ArrivalTime { get; set; }

        public string Status { get; set; } = "OnTime";

        public string TimeDifference { get; set; }
    }
}


text:
{% extends "mapentity/base.html" %}
{% load i18n static mapentity_tags leaflet_tags geojson_tags %}

{% block title %}{{ object }} | {{ block.super }}{% endblock title %}

{% block mainpanel %}

                {% block download %}
                    {% if mapentity_weasyprint %}
                         {% trans "PDF" %}
                    {% else %}
                         {% trans "ODT" %}
                         {% trans "DOC" %}
                         {% trans "PDF" %}
                    {% endif %}
                {% endblock download %}

                     {% trans "Properties" %}
                        {% smart_include "propertiestab" %}

                     {% trans "Attached files" %} ({{ object.attachments.count }})

                {% if ACTION_HISTORY_ENABLED %}

                         {% trans "History" %}

                {% endif %}
                {% if can_edit %}
                     {% trans "Update" %}
                {% else %}
                     {% trans "Update" %}
                {% endif %}

                    {% block detailspanel %}
                        {% include template_attributes %}
                    {% endblock detailspanel %}

                    {% block attachmentspanel %}
                        {% include 'paperclip/attachment_list.html' with attachment_form_next=object.get_detail_url|add:'?tab=attachments' %}
                    {% endblock attachmentspanel %}

                {% if ACTION_HISTORY_ENABLED %}

                                    {% trans "Date" %}
                                    {% trans "User" %}
                                    {% trans "Action" %}

                                {% for logentry in logentries %}

                                        {{ logentry.action_time }} ({{ logentry.action_time|timesince }})
                                        {{ logentry.user }}
                                        {{ logentry.action_flag_display }}{% if logentry.change_message %} - {{ logentry.change_message }}{% endif %}

                                {% empty %}

                                        {% trans "None" %}

                                {% endfor %}
                                {% if logentries_hellip %}

                                        …
                                        …
                                        …

                                {% endif %}

                        {% trans "Full history" %}

                {% endif %}

        {% block mappanel %}
        {% if object.get_geom %}
            {% include "mapentity/mapgeometry_fragment.html" with mapname="detailmap" %}
        {% else %}

{{ empty_map_message }}

        {% endif %}
        {% endblock mappanel %}

{% endblock mainpanel %}


text:
#include "DeleteNode.h"
#include<lang/log/LogLevel.h>

#include <commonlib/commonlib.h>

#include "../expr/xpath/XPathAccessNode.h"

namespace IAS {
namespace Lang {
namespace Model {
namespace Stmt {

/*************************************************************************/
DeleteNode::DeleteNode(Expr::XPath::XPathAccessNode  *pXPathAccessNode){
	IAS_TRACER;

	IAS_CHECK_IF_VALID(pXPathAccessNode);

	this->ptrXPathAccessNode=pXPathAccessNode;
}
/*************************************************************************/
DeleteNode::~DeleteNode() throw(){
	IAS_TRACER;
}
/*************************************************************************/
}
}
}
}


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

<TITLE>
org.codehaus.groovy.grails.web.servlet.mvc.exceptions (Grails 1.0.4)
</TITLE>

<META NAME="keywords" CONTENT="org.codehaus.groovy.grails.web.servlet.mvc.exceptions package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">

org.codehaus.groovy.grails.web.servlet.mvc.exceptions

Exceptions

ControllerExecutionException

GrailsMVCException

IncompatibleParameterCountException

InvalidUriException

NoClosurePropertyForURIException

NoViewNameDefinedException

UnknownControllerException

UnsupportedReturnValueException


text:
import math

# Импортируем один из пакетов Matplotlib
import pylab

# Импортируем пакет со вспомогательными функциями
from matplotlib import mlab

from matplotlib import pyplot as mpl
import matplotlib
#matplotlib.use('Agg')

def show_graph(xlist=None, ylist=None):
    pylab.ion()

    if xlist is None:
        xlist = mlab.frange (0, 1, 0.1)
    # Данные для очередного кадра
    if ylist is None:
        ylist = [math.sin (x) for x in xlist]

    # !!! Очистим график
    pylab.clf()

    # Выведем новые данные
    pylab.plot (xlist, ylist, ':')

    # !!! Нарисуем их
    # !!! Обратите внимание, что здесь используется функция draw(), а не show()
    pylab.draw()
    mpl.pause(0.001)


text:
class BooksController < ApplicationController

  before_action :set_book, only: [:show, :edit, :update, :destroy]

  def index
    @books = Book.all.page(params[:page])
  end

  def show
  end

  def new
    @book = Book.new
  end

  def create
    @book = Book.new(book_params)

    if @book.save
      redirect_to books_path, notice: 'Book was successfully created.'
    else
      render action: 'new'
    end
  end

  def update
    if @book.update(book_params)
      redirect_to books_path, notice: 'Book was successfully updated.'
    else
      render action: 'edit'
    end
  end

  def destroy
    @book.destroy
    redirect_to books_path
  end

  private

  def set_book
    @book = Book.find(params[:id])
  end

  def book_params
    params.require(:book).permit(:title, :description, :image)
  end
end


text:
<!DOCTYPE html>
<html>
<head>
    <title>pixiJS: Memory Game</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #ffffff;
        }
    </style>

    <script src="../js/pixi.js"></script>
    <script src="Main.js"></script>
    <script src="../js/stats.min.js"></script>
    <!--script src="tween.js"></script-->
    <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.10.1/TweenMax.min.js"></script>
    <!-- AS3 meme class for JS-->
    <script src="../js/Timer.js"></script>
    <!---->
    <style type="text/css" media="screen, print">
        @font-face {
          font-family: "Handycandy";
          src: url("../assets/font/Handycandy.ttf");
        }
    </style>

</head>
<body onLoad="init();"></body>

</html>


text:
alias cw="compass watch"
alias ci="compass init"


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

namespace Stamper.DataAccess
{
    public class Layer
    {
        public string Name { get; set; }
        public string File { get; set; }
        public string Mask { get; set; }
        public LayerType Type { get; set; }

        [JsonIgnore]
        public string JsonFileName { get; set; }

        public enum LayerType
        {
            Border, Overlay
        }
    }
}


text:
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
require('dotenv').config();

// Get our API routes
const api = require('./server/routes/api');

const app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

var port = process.env.PORT || 3000;

if(app.get('env') === 'development' ) {
/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(process.env.PORT || 3000, () => console.log(`API running on localhost:${port}`));
} else {
/**
 * Get port from environment and store in Express.
 */

app.listen(process.env.PORT || 3000, function(){
  console.log("Express server has been activated");
});

}


text:
from game import Agent
from game import Directions

class StationaryGhostAgent( Agent ):
    def __init__( self, index ):
        self.index = index

    def getAction( self, state ):
        return Directions.STOP


text:
{% load i18n %}

<title>BETS</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
{##}

 {% trans "Hello," %} {{ client.name }}

         {% trans "Back" %}

{% trans "Balance :" %}  {{ client.balance }}

{% trans "My Bet Page" %}

        USER IDIOT!

        {% trans "Ride ID" %}
        {% trans "HORSES" %}
        {% trans "1st CEFF" %}
        {% trans "2nd CEFF" %}
        {% trans "Bet" %}

    {% if latest_ride_list %}
        {% for ride in latest_ride_list %}

                     {{ ride.id }}

                    {{ ride.name }}

                     {{ ride.firstHorseChance }}

                     {{ ride.secondHorseChance }}

                        {% trans "Count:" %}
                        <input type="text" class="form-horizontal clearable" id="usr">

                    <button class="btn btn-primary btn-sm" id="bet-btn" onclick="makeBet()">{% trans "Bet" %}</button>

        {% endfor %}
    {% else %}

{% trans "No polls are available." %}

    {% endif %}


text:
package io.quarkus.vertx;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import io.vertx.core.eventbus.MessageCodec;
import io.vertx.mutiny.core.eventbus.Message;

/**
 * Marks a business method to be automatically registered as a Vertx message consumer.
 *

 * The method can accept the following parameters:
 *

 *
{@link io.vertx.core.eventbus.Message io.vertx.core.eventbus.Message} message

 *
{@link io.vertx.mutiny.core.eventbus.Message io.vertx.mutiny.core.eventbus.Message} message

 *
{@link Message#headers() MultiMap} headers, {@link Message#body() T} body

 *
{@link Message#body() T} body

 *

 *
 * If it accepts a {@link Message} then the return type must be void. For any other type the {@link Message#body()}
 * is passed as the parameter value and the method may return an object that is passed to {@link Message#reply(Object)},
 * either directly or via {@link java.util.concurrent.CompletionStage#thenAccept(java.util.function.Consumer)}
 * in case of the method returns a completion stage.
 *
 *

 * @ApplicationScoped
 * class MyService {
 *
 *     @ConsumeEvent("echo")
 *     String echo(String msg) {
 *         return msg.toUpperCase();
 *     }
 *
 *     @ConsumeEvent("echoHeaders")
 *     String echo(MultiMap headers, String msg) {
 *         return msg.toUpperCase();
 *     }
 *
 *     @ConsumeEvent("echoMessage")
 *     void echoMessage(Message<String> msg) {
 *         msg.reply(msg.body().toUpperCase());
 *     }
 *
 *     @ConsumeEvent(value = "echoMessageBlocking", blocking = true)
 *     void echoMessageBlocking(Message<String> msg) {
 *         msg.reply(msg.body().toUpperCase());
 *     }
 * }
 *

 *
 * If it accepts a {@link Message#headers()} then the first parameters must be the headers
 * and the second parameter must be the {@link Message#body()}.
 *
 *

 * @ConsumeEvent("echoHeaders")
 * String event(MultiMap headers, String msg) {
 *     String traceId = headers.get("traceId");
 *     return "Message is: " + msg + ", trace is: " + traceId;
 * }
 *

 *
 * The CDI request context is always active during notification of the registered message consumer.
 *

 * If a method annotated with {@link ConsumeEvent} throws an exception then:
 *

 *
if a reply handler is set the failure is propagated back to the sender via an
 * {@link io.vertx.core.eventbus.ReplyException} with code {@link #FAILURE_CODE} and the exception message,

 *
if no reply handler is set then the exception is rethrown (and wrapped in a {@link java.lang.RuntimeException} if
 * necessary) and can be handled by the default exception handler, i.e. {@link io.vertx.core.Vertx#exceptionHandler().}

 *

 *
 * @see io.vertx.core.eventbus.EventBus
 */
@Target(METHOD)
@Retention(RUNTIME)
public @interface ConsumeEvent {

    /**
     * Failure code used when a message consumer method throws an exception.
     */
    int FAILURE_CODE = 0x1FF9;

    /**
     * Failure code used when a message consumer explicitly fails an asynchronous processing.
     *
     * This status is used when the method annotated with {@link ConsumeEvent} returns a failed
     * {@link java.util.concurrent.CompletionStage} or {@link io.smallrye.mutiny.Uni}.
     */
    int EXPLICIT_FAILURE_CODE = 0x1FFF;

    /**
     * The address the consumer will be registered to. By default, the fully qualified name of the declaring bean class is
     * assumed.
     *
     * @return the address
     */
    String value() default "";

    /**
     *
     * @return {@code true} if the address should not be propagated across the cluster
     * @see io.vertx.core.eventbus.EventBus#localConsumer(String)
     */
    boolean local() default true;

    /**
     *
     * @return {@code true} if the consumer should be invoked as a blocking operation using a worker thread
     * @see io.vertx.core.Vertx#executeBlocking(io.vertx.core.Handler, boolean, io.vertx.core.Handler)
     */
    boolean blocking() default false;

    /**
     * @return {@code true} if the blocking consumption of the event must be ordered, meaning that the method
     *         won't be called concurrently. Instead, it serializes all the invocations based on the event order.
     *         {@code ordered} must be used in conjunction with {@code blocking=true} or {@code @Blocking}.
     * @see io.vertx.core.Vertx#executeBlocking(io.vertx.core.Handler, boolean, io.vertx.core.Handler)
     */
    boolean ordered() default false;

    /**
     *
     * @return {@code null} if it should use a default MessageCodec
     * @see io.quarkus.vertx.LocalEventBusCodec
     */
    Class<? extends MessageCodec> codec() default LocalEventBusCodec.class;

}


text:
from argparse import ArgumentParser
from ezdxf.acis import api as acis

def main():
    parser = ArgumentParser()
    parser.add_argument("file", nargs=1)
    args = parser.parse_args()
    if args.file:
        with open(args.file[0], "rb") as fp:
            data = fp.read()
    print("\n".join(acis.dump_sab_as_text(data)))

if __name__ == "__main__":
    main()


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\DocumentManagerBundle\Bridge\Serializer\Handler;

use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonSerializationVisitor;
use Sulu\Component\DocumentManager\Collection\ChildrenCollection;

/**
 * Handle serializeation and deserialization of children collections.
 */
class ChildrenCollectionHandler implements SubscribingHandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public static function getSubscribingMethods()
    {
        return [
            [
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'format' => 'json',
                'type' => ChildrenCollection::class,
                'method' => 'doSerialize',
            ],
        ];
    }

    /**
     * @param JsonSerializationVisitor $visitor
     * @param ChildrenCollection $childrenCollection
     * @param array $type
     * @param Context $context
     *
     * @return mixed
     */
    public function doSerialize(
        JsonSerializationVisitor $visitor,
        ChildrenCollection $childrenCollection,
        array $type,
        Context $context
    ) {
        $array = $childrenCollection->toArray();

        return $context->accept($array);
    }
}


text:
import { Component, EventEmitter, OnInit, Output } from "@angular/core";
import { FormControl, FormGroup, Validators } from "@angular/forms";
import { Observable } from "rxjs/Rx";

import { AuthService, EMAIL_REGEX } from "./auth.service";
import { UserFormData } from "./user.model";

@Component({
    selector: "app-authentication",
    templateUrl: "./authentication.component.html",
})
/** @class Authentication component */
export class AuthenticationComponent implements OnInit {

    /** @event SignupForm#click signup form submitted */
    @Output() signupRequested: EventEmitter<any> = new EventEmitter();

    /** @property Authentication Component title */
    title: string = "";

    /** @property signin form */
    private signinForm: FormGroup;

    /** @property email control */
    private emailFormControl: FormControl;

    /** @property password control */
    private passwordFormControl: FormControl;

    /**
     * Construct Auth Service
     * @param authService Authentication service
     */
    constructor(public authService: AuthService) {

        /** Subscribe to Authentication Service's userData$ stream */
        authService.userData$.subscribe((user) => this.updateTitle(user ? user.username : null));
    }

    /**
     * Called after component initialization
     * Creates signin form
     */
    ngOnInit() {
        this.emailFormControl = new FormControl(null, [
                Validators.required,
                Validators.pattern(EMAIL_REGEX),
            ]);
        this.passwordFormControl = new FormControl(null, Validators.required);
        this.signinForm = new FormGroup({
            email: this.emailFormControl,
            password: this.passwordFormControl,
        });
    }

    /** Handles logout click */
    private onLogout() {
        this.authService.logout();
        this.signinForm.enable();
    }

    /** Handles Signin form submission */
    private onSubmit() {
        const formUser = new UserFormData(
            this.signinForm.value.email,
            this.signinForm.value.password,
        );

        /** Request signin from server with user submitted form data */
        this.authService.signin(formUser)
            .subscribe(
                (user) => this.signinForm.reset(),
                (errorDialog: Observable<any>) => errorDialog.subscribe(null, null, () => this.signinForm.enable())
            );

        /** Disable signin form until server response */
        this.signinForm.disable();
    }

    /**
     * Update the Authentication Component's title
     * @param {string|null} username Username to display in title
     */
    private updateTitle(username: string | null) {
        if (username) {
            this.title = "@" + username;
        } else {
            this.title = "Log in";
        }
    }
}


text:
package org.apache.jetspeed.portlets.wicket.component.editor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.jetspeed.portlets.wicket.component.JavascriptEventConfirmation;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.RefreshingView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;

/**
 *
 * @author Ruben Alexander de Gooijer
 *
 * @param <T>
 */
public abstract class EditorTemplate<T> extends Panel
{
    private static final long serialVersionUID = 1L;

    private List<SelectableModel<T>> rows;

    public static final String ITEMS_FRAGMENT_ID = "itemFragment";
    public static final String NEW_FRAGMENT_ID = "newFragment";

    public EditorTemplate(String id)
    {
        super(id);
    }

    public EditorTemplate initLayout()
    {
        rows = new ArrayList<SelectableModel<T>>();

        RefreshingView<T> data = new RefreshingView<T>("data")
        {
            private static final long serialVersionUID = 1L;

            @Override
            protected Iterator<IModel<T>> getItemModels()
            {
                return EditorTemplate.this.getItemModels();
            }

            @Override
            protected void populateItem(Item<T> item)
            {
                T object = item.getModelObject();

                final SelectableModel<T> model = rowModel(object);
                rows.add(model);

                Fragment fragment = new Fragment("items", ITEMS_FRAGMENT_ID, this);
                EditorTemplate.this.buildItems(fragment, model.getObject());

                //We cannot use the PropertyModel here. The SelectableObject might implement IModel
                //this causes the PropertyModel to resolve the getChecked method to the object contained inside the SelectableObject,
                //which should not happen.
                item.add(new CheckBox("select", new IModel<Boolean>() {
                    public Boolean getObject()
                    {
                        return model.getSelected();
                    }

                    public void setObject(Boolean object)
                    {
                        model.setSelected(object);
                    }

                    public void detach()
                    {

                    }
                }));
                item.add(fragment);
            }
        };

        Form form = new Form("form");

        form.add(data);

        Fragment newFragment = new Fragment("new", NEW_FRAGMENT_ID, this);
        buildNew(newFragment);
        form.add(newFragment);

        form.add(new Image("add", new ResourceReference(EditorTemplate.class, "add.png")));

        WebMarkupContainer footer = new WebMarkupContainer("footer");
        Button saveButton = saveButton("save");
        saveButton.setDefaultModel(new ResourceModel("pam.details.action.save"));
        footer.add(saveButton);
        Button deleteBtn = deleteButton("delete");
        deleteBtn.add(new JavascriptEventConfirmation("onclick", new ResourceModel("pam.details.action.delete.confirm")));
        footer.add(deleteBtn);
        footer.add(new AttributeModifier("colspan", true, new Model<Integer>(Integer.valueOf(getColumnCount()))));

        form.add(footer);
        add(form);

        return this;
    }

    protected Button deleteButton(String componentId)
    {
        return new Button(componentId, new ResourceModel("pam.details.action.delete")) {
            @Override
            public void onSubmit() {
                List<IModel<T>> removeList = new ArrayList<IModel<T>>();
                for(SelectableModel<T> field : rows) {
                    if(field.getSelected()) {
                        removeList.add(field);
                    }
                }

                delete(removeList.toArray(new IModel[removeList.size()]));
            }
        };
    }

    public final SelectableModel<T> rowModel(T object)
    {
        IModel<T> model = getNewRowModel(object);
        return new SelectableModel<T>(model);
    }

    public abstract int getColumnCount();

    public abstract IModel<T> getNewRowModel(T object);

    public abstract Iterator<IModel<T>> getItemModels();
    public abstract void delete(IModel<T>[] fields);
    protected abstract Button saveButton(String componentId);

    public abstract void buildItems(Fragment fragment, T model);
    public abstract void buildNew(Fragment fragment);
}


text:
{-# LANGUAGE OverloadedStrings #-}
module Day12 (day12, day12', run) where

import Data.Aeson
    ( Value
        ( Array
        , Number
        , Object
        , String
        )
    , decode'
    )
import Data.ByteString.Lazy.Char8 (pack)
import Data.Foldable (foldl)
import Data.Maybe (fromMaybe)
import Data.Scientific
import Data.Text (Text)

sumJson :: Value -> Scientific
sumJson (Object o) = foldl addNumbers 0 o
sumJson (Array a)  = foldl addNumbers 0 a
sumJson (Number n) = n
sumJson _          = 0

addNumbers :: Scientific -> Value -> Scientific
addNumbers x o@(Object _) = x + sumJson o
addNumbers x a@(Array _)  = x + sumJson a
addNumbers x (Number n)   = x + n
addNumbers x _            = x

sumJson' :: Value -> Scientific
sumJson' (Object o) = fromMaybe 0 $ foldl addNumbers' (Just 0) o
sumJson' (Array a)  = foldl addNumbers'' 0 a
sumJson' (Number n) = n
sumJson' _          = 0

addNumbers' :: Maybe Scientific ->  Value -> Maybe Scientific
addNumbers' Nothing _          = Nothing
addNumbers' x       (String s) = if s == "red" then Nothing else x
addNumbers' x       v          = fmap (`addNumbers''` v) x

addNumbers'' :: Scientific -> Value -> Scientific
addNumbers'' x o@(Object _) = x + sumJson' o
addNumbers'' x a@(Array _)  = x + sumJson' a
addNumbers'' x (Number n)   = x + n
addNumbers'' x _            = x

day12 :: String -> Scientific
day12 input = maybe (-1) sumJson (decode' . pack $ input)

day12' :: String -> Scientific
day12' input = maybe (-1) sumJson' (decode' . pack $ input)

-- Input
run :: IO ()
run = do
    putStrLn "Day 12 results: "
    input <- readFile "inputs/day12.txt"
    putStrLn $ "  " ++ show (day12 input)
    putStrLn $ "  " ++ show (day12' input)


text:
* Created By: Adam Wilson - Reservo.co
* Website: https://reservo.co
* Release Date: 11th November 2015
* Version: 1.0

#USAGE:

* Upload "migrate.php" to your Reservo installation in the root.
* Edit migrate.php at the top. Set your ImgShot database details.
* Save and open the script within your browser.

#SUPPORT:

* Feel free to contact us via https://reservo.co or https://mfscripts.com if you need any help.


text:
/* global define */
define(['underscore', 'oro/translator'],
function (_, __) {
    'use strict';

    var defaultParam = {
        minMessage: 'This value should be {{ limit }} or more.',
        maxMessage: 'This value should be {{ limit }} or less.',
        invalidMessage: 'This value should be a valid number.'
    };

    /**
     * @export oro/validator/range
     */
    return [
        'Range',
        function (value, element, param) {
            value = Number(value);
            return this.optional(element) ||
                !(isNaN(value) || value < Number(param.min) || value > Number(param.max));
        },
        function (param, element) {
            var message, placeholders = {},
                value = Number(this.elementValue(element));
            param = _.extend({}, defaultParam, param);
            if (isNaN(value)) {
                message = param.invalidMessage;
            } else if (value < Number(param.min)) {
                message = param.minMessage;
                placeholders.limit = param.min;
            } else if (value > Number(param.max)) {
                message = param.maxMessage;
                placeholders.limit = param.max;
            }
            return __(message, placeholders);
        }
    ];
});


text:
<?php

namespace RomaricDrigon\MetaYaml\XsdNodeGenerator;

class XsdPatternNodeGenerator extends XsdNodeGenerator
{
    public function build($name, $node, \XMLWriter &$writer, $under_root)
    {
        // always inside an xsd:element
        $writer->startElementNs('xsd', 'element', null);
        $writer->writeAttribute('name', $name);
        $this->addRequired($node, $writer, $under_root);

        // simpleType with restrictions
            $writer->startElementNs('xsd', 'simpleType', null);
                $writer->startElementNs('xsd', 'restriction', null);
                $writer->writeAttribute('base', 'xsd:string');
                    $writer->startElementNs('xsd', 'pattern', null);
                    $writer->writeAttribute('value', $node[$this->xsd_generator->getFullName('pattern')]);
                    $writer->endElement();
                $writer->endElement();
            $writer->endElement();

        $writer->endElement();
    }
}


text:
package io.airlift.dbpool;

import io.airlift.units.Duration;

import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Deque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * This class is not complete yet.
 */
abstract class PooledDataSource extends ManagedDataSource
{
    private final AtomicBoolean disposed = new AtomicBoolean();
    private final Deque<PooledConnection> pool = new LinkedBlockingDeque<PooledConnection>();

    PooledDataSource(ConnectionPoolDataSource dataSource, int maxConnections, Duration maxConnectionWait)
    {
        super(maxConnections, maxConnectionWait);
    }

    public void dispose()
    {
        disposed.set(true);

        // there is really no harm in running this loop every time dispose is called
        for (PooledConnection pooledConnection = pool.poll(); pooledConnection != null; pooledConnection = pool.poll()) {
            try {
                pooledConnection.close();
            }
            catch (SQLException ignored) {
            }
        }
    }

    @Override
    protected Connection createConnection()
            throws SQLException
    {
        assertNotDisposed();

        // check for a pooled connection
        PooledConnection pooledConnection = pool.pollLast();
        if (pooledConnection != null) {
            return prepareConnection(pooledConnection);
        }

        // otherwise create a new one
        return super.createConnection();
    }

    @Override
    protected void connectionReturned(PooledConnection pooledConnection, long checkoutTime)
    {
        // if this pool has been disposed, or if we have too many connections already
        if (disposed.get() || getConnectionsActive() + pool.size() > getMaxConnections()) {
            // close this connection
            super.connectionReturned(pooledConnection, checkoutTime);
        }
        else {
            // otherwise add it to the pool
            pool.addLast(pooledConnection);
        }
    }

    private void assertNotDisposed()
            throws SQLException
    {
        if (disposed.get()) {
            throw new SQLException(getClass().getSimpleName() + " has been disposed");
        }
    }
}


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

<title>_FAR_USE_WIN32_FIND_DATA</title>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../styles/styles.css">

_FAR_USE_WIN32_FIND_DATA

main |
types and definitions

The macro <dfn>_FAR_USE_WIN32_FIND_DATA</dfn> controls whether the
PluginPanelItem structure
uses the WIN32_FIND_DATA structure
defined in the Windows API headers or the the FAR_FIND_DATA
that has the same layout but is defined in plugin.hpp.
As some compilers (for instance, Borland C++ 5.5) force 8-byte alignment for structures defined in
the Windows API headers, it is not possible to achieve the correct 2-byte alignment for the entire
PluginPanelItem structure when the
WIN32_FIND_DATA structure is used.

If the <dfn>_FAR_USE_WIN32_FIND_DATA</dfn> macro is defined, the
PluginPanelItem structure
will be compatible with FAR 1.65 and FAR 1.70 headers.
But correct compilation will not be possible with Borland C++ 5.5 without modifying Windows API header files.

If the macro <dfn>_FAR_USE_WIN32_FIND_DATA</dfn> is not defined, the
FAR_FIND_DATA structure will be used. This way the code would compile correctly with any
compiler, but some plugins that depend on the usage of WIN32_FIND_DATA
would not compile.

 Attention!

In FAR 1.70 release WIN32_FIND_DATA is used by default
(<dfn>_FAR_USE_WIN32_FIND_DATA</dfn> is defined). In FAR 1.71 FAR_FIND_DATA will be used by default.

See also:

FAR_FIND_DATA |
WIN32_FIND_DATA


text:
package org.apache.geronimo.activation.handlers;

import java.awt.datatransfer.DataFlavor;
import javax.activation.ActivationDataFlavor;

/**
 * @version $Rev$ $Date$
 */
public class TextPlainHandler extends AbstractTextHandler {
    public TextPlainHandler() {
        super(new ActivationDataFlavor(String.class, "text/plain", "Plain Text"));
    }
}


text:
package org.mrgeo.hdfs.metadata;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.mrgeo.image.MrsImagePyramidMetadata;
import org.mrgeo.data.image.MrsImageDataProvider;
import org.mrgeo.data.image.MrsImagePyramidMetadataWriter;
import org.mrgeo.data.image.MrsImagePyramidMetadataWriterContext;
import org.mrgeo.hdfs.image.HdfsMrsImageDataProvider;
import org.mrgeo.hdfs.utils.HadoopFileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author tim.tisler
 * @version $Revision: 1.0 $
 */
public class HdfsMrsImagePyramidMetadataWriter implements MrsImagePyramidMetadataWriter
{
  private static final Logger log = LoggerFactory.getLogger(HdfsMrsImagePyramidMetadataWriter.class);

  private final MrsImageDataProvider provider;
  private Configuration conf;

  /**
   * Constructor for HdfsMrsImagePyramidMetadataWriter.
   * @param provider MrsImageDataProvider
   * @param context MrsImagePyramidMetadataWriterContext
   */
  public HdfsMrsImagePyramidMetadataWriter(MrsImageDataProvider provider,
      Configuration conf,
      MrsImagePyramidMetadataWriterContext context)
  {
    this.provider = provider;
    this.conf = conf;
  }

  /**
   * Write the (already loaded) metadata for the provider to HDFS
   * @throws IOException
   * @see org.mrgeo.data.image.MrsImagePyramidMetadataWriter#write()
   */
  @Override
  public void write() throws IOException
  {
    MrsImagePyramidMetadata metadata = provider.getMetadataReader(null).read();

    write(metadata);
  }
  /**
   * Write a provided metadata object to HDFS.
   * @param metadata MrsImagePyramidMetadata
   * @throws IOException
   * @see org.mrgeo.data.image.MrsImagePyramidMetadataWriter#write(MrsImagePyramidMetadata)
  */
  @Override
  public void write(MrsImagePyramidMetadata metadata) throws IOException
  {
    if (!(provider instanceof HdfsMrsImageDataProvider))
    {
      throw new IOException("Expected an instance of HdfsMrsImageDataprovider instead of " +
        provider.getClass().getCanonicalName());
    }
    final Path path = new Path(((HdfsMrsImageDataProvider)provider).getResolvedResourceName(true),
        HdfsMrsImageDataProvider.METADATA);

    final FileSystem fs = HadoopFileUtils.getFileSystem(conf, path);
    if (fs.exists(path))
    {
      fs.delete(path, false);
    }

    log.debug("Saving metadata to " + path.toString());
    FSDataOutputStream os = null;
    try
    {
      os = HadoopFileUtils.getFileSystem(conf, path).create(path);
      metadata.save(os);
    }
    catch (Exception e)
    {
      throw new IOException(e);
    }
    finally
    {
      if (os != null)
      {
        os.close();
      }
    }

    // reload the metadata after a save;
    provider.getMetadataReader(null).reload();
  }

}


text:
/*
 * (C) 2007-2013 Alibaba Group Holding Limited
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 *
 */
//
// Created by 文通 on 13-1-21 上午8:09.
//

#import "TBMBAutoNilDelegateView.h"
#import "TBMBBind.h"
#import "TBMBAutoNilDelegateViewDO.h"

@interface TBMBAutoNilDelegateView () <UITableViewDataSource, UITableViewDelegate>
@end

@implementation TBMBAutoNilDelegateView {
@private
    UITableView *_tableView;
}

- (void)loadView {
    [super loadView];

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.bounds];
    id testDelegate = [[NSObject alloc] init];
    TBMBAutoNilDelegate(UITableView *, tableView, delegate, testDelegate)
    testDelegate = nil;

    testDelegate = [[NSObject alloc] init];
    TBMBAutoNilDelegate(UITableView *, tableView, delegate, testDelegate)
    tableView = nil;

    tableView = [[UITableView alloc] initWithFrame:self.bounds];
    //用TBMBAutoNilDelegate设置delegate可以保证在delegate dealloc的时候 会被自动置为nil
    TBMBAutoNilDelegate(UITableView *, tableView, delegate, self)
    TBMBAutoNilDelegate(UITableView *, tableView, dataSource, self)
    [self addSubview:tableView];
    _tableView = tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewDO.tableData.count;
}

static NSString *const identifier = @"TBMBAutoNilDelegateViewCell";

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *value = nil;
    if (indexPath.row < self.viewDO.tableData.count && indexPath.row >= 0) {
        value = [self.viewDO.tableData objectAtIndex:(NSUInteger) indexPath.row];
    } else {
        return nil;
    }
    UITableViewCell *cell
            = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]
                                 initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:identifier];
    }
    cell.textLabel.text = value;
    return cell;
}

- (void)dealloc {
    NSLog(@"%@ dealloc", self);
}

@end


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

<TITLE>
GlobPatternMapper (Apache Ant API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.tools.ant.util.GlobPatternMapper class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.tools.ant.util

Class GlobPatternMapper

java.lang.Object
  org.apache.tools.ant.util.GlobPatternMapper

All Implemented Interfaces:
FileNameMapper

Direct Known Subclasses:
PackageNameMapper, UnPackageNameMapper

public class GlobPatternMapper
extends java.lang.Object
implements FileNameMapper

Implementation of FileNameMapper that does simple wildcard pattern
 replacements.

This does simple translations like *.foo -> *.bar where the
 prefix to .foo will be left unchanged. It only handles a single *
 character, use regular expressions for more complicated
 situations.

This is one of the more useful Mappers, it is used by javac for
 example.

Field Summary

protected  java.lang.String
fromPostfix

          Part of "from" pattern after the *.

protected  java.lang.String
fromPrefix

          Part of "from" pattern before the *.

protected  int
postfixLength

          Length of the postfix ("from" pattern).

protected  int
prefixLength

          Length of the prefix ("from" pattern).

protected  java.lang.String
toPostfix

          Part of "to" pattern after the *.

protected  java.lang.String
toPrefix

          Part of "to" pattern before the *.

Constructor Summary

GlobPatternMapper()

Method Summary

protected  java.lang.String
extractVariablePart(java.lang.String name)

          Returns the part of the given string that matches the * in the
 "from" pattern.

 java.lang.String[]
mapFileName(java.lang.String sourceFileName)

          Returns null if the source file name doesn't match the
 "from" pattern, an one-element array containing the
 translated file otherwise.

 void
setCaseSensitive(boolean caseSensitive)

          Attribute specifing whether to ignore the case difference
 in the names.

 void
setFrom(java.lang.String from)

          Sets the "from" pattern.

 void
setHandleDirSep(boolean handleDirSep)

          Attribute specifing whether to ignore the difference
 between / and \ (the two common directory characters).

 void
setTo(java.lang.String to)

          Sets the "to" pattern.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

fromPrefix

protected java.lang.String fromPrefix

Part of "from" pattern before the *.

fromPostfix

protected java.lang.String fromPostfix

Part of "from" pattern after the *.

prefixLength

protected int prefixLength

Length of the prefix ("from" pattern).

postfixLength

protected int postfixLength

Length of the postfix ("from" pattern).

toPrefix

protected java.lang.String toPrefix

Part of "to" pattern before the *.

toPostfix

protected java.lang.String toPostfix

Part of "to" pattern after the *.

Constructor Detail

GlobPatternMapper

public GlobPatternMapper()

Method Detail

setHandleDirSep

public void setHandleDirSep(boolean handleDirSep)

Attribute specifing whether to ignore the difference
 between / and \ (the two common directory characters).

Parameters:
handleDirSep - a boolean, default is false.
Since:

Ant 1.6.3

setCaseSensitive

public void setCaseSensitive(boolean caseSensitive)

Attribute specifing whether to ignore the case difference
 in the names.

Parameters:
caseSensitive - a boolean, default is false.
Since:

Ant 1.6.3

setFrom

public void setFrom(java.lang.String from)

Sets the "from" pattern. Required.

Specified by:
setFrom in interface FileNameMapper

Parameters:
from - a string

setTo

public void setTo(java.lang.String to)

Sets the "to" pattern. Required.

Specified by:
setTo in interface FileNameMapper

Parameters:
to - a string

mapFileName

public java.lang.String[] mapFileName(java.lang.String sourceFileName)

Returns null if the source file name doesn't match the
 "from" pattern, an one-element array containing the
 translated file otherwise.

Specified by:
mapFileName in interface FileNameMapper

Parameters:
sourceFileName - the filename to map

Returns:
a list of converted filenames

extractVariablePart

protected java.lang.String extractVariablePart(java.lang.String name)

Returns the part of the given string that matches the * in the
 "from" pattern.

Parameters:
name - the source file name

Returns:
the variable part of the name

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
#NamePicker_Layout_Cell13        { text-align: left; }
#NamePicker_Layout_Cell21 select { width: 334px; margin: 8px 0px; }

#NamePicker_Layout_Cell22        { text-align: center; }
#NamePicker_Layout_Cell22 button { margin: 4px 0px; }

#NamePicker_Layout_Cell23 select { width: 334px; margin: 8px 0px; }

#NamePicker_Layout_Cell31        { text-align: center; }
#NamePicker_Layout_Cell31 button { margin: 0px 4px; }

#NamePicker_Layout_Cell33        { text-align: center; }

#NamePicker .small-help	{ font-weight: normal; font-style: italic; font-size: 0.8em; color: #CC3535; }


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

namespace FluentBoilerplate.Runtime.Extensions
{
    internal static class IEnumerableExtensions
    {
        public static IImmutableSet<Type> AggregateProvidableTypes(this IEnumerable<ITypeProvider> providers)
        {
            IImmutableSet<Type> currentTypes = new HashSet<Type>().ToImmutableHashSet();

            if (providers == null)
                return currentTypes;

            foreach (var provider in providers)
            {
                currentTypes = currentTypes.Merge(provider.ProvidableTypes);
            }

            return currentTypes;
        }
    }
}


text:
package org.lp20.aikuma.ui;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.lp20.aikuma.model.Language;
import org.lp20.aikuma.model.Recording;
import org.lp20.aikuma.model.Speaker;
import org.lp20.aikuma.R;
import org.lp20.aikuma.util.ImageUtils;

/**
 * Takes a list of recordings and provides views as appropriate.
 *
 * @author	Oliver Adams	<oliver.adams@gmail.com>
 * @author	Florian Hanke	<florian.hanke@gmail.com>
 */
public class RecordingArrayAdapter extends ArrayAdapter<Recording> {

	/**
	 * Constructor.
	 *
	 * @param	context	the current context
	 * @param	recordings	The list of recordings.
	 */
	public RecordingArrayAdapter(Context context, List<Recording> recordings) {
		super(context, LIST_ITEM_LAYOUT, recordings);
		this.context = context;
		this.recordings = new ArrayList<Recording>(recordings);
		inflater = (LayoutInflater)
				context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		// Sort so that the recordings with the most stars are displayed first.
		this.sort(new Comparator<Recording>() {
			@Override
			public int compare(Recording lhs, Recording rhs) {
				if (lhs.numStars() - 2*lhs.numFlags() < rhs.numStars() -
						2*rhs.numFlags()) {
					return +1;
				} else if (lhs.numStars() - 2*lhs.numFlags() > rhs.numStars() -
						2*rhs.numFlags()) {
					return -1;
				} else {
					return 0;
				}
			}
		});
	}

	/**
	 * Constructor when Quick-menu is attached to each list_item
	 *
	 * @param	context	the current context
	 * @param	recordings	The list of recordings.
	 * @param	quickMenu	QuickActionMenu for each liste item
	 */
	public RecordingArrayAdapter(Context context, List<Recording> recordings,
			QuickActionMenu quickMenu) {
		this(context, recordings);
		this.quickMenu = quickMenu;
	}

	@Override
	public View getView(int position, View _, ViewGroup parent) {
		LinearLayout recordingView =
				(LinearLayout) inflater.inflate(LIST_ITEM_LAYOUT, parent, false);
		Recording recording = getItem(position);

		// Set the view to have recording name, date, duration, speakerImage
		TextView recordingNameView =
				(TextView) recordingView.findViewById(R.id.recordingName);
		TextView recordingDateDurationView =
				(TextView) recordingView.findViewById(R.id.recordingDateDuration);
		LinearLayout speakerImagesView = (LinearLayout)
				recordingView.findViewById(R.id.speakerImages);
		for (String id : recording.getSpeakersIds()) {
			speakerImagesView.addView(makeSpeakerImageView(id));
		}
		recordingNameView.setText(recording.getNameAndLang());

		Integer duration = recording.getDurationMsec() / 1000;
		if (recording.getDurationMsec() == -1) {
			recordingDateDurationView.setText(
					simpleDateFormat.format(recording.getDate()));
		} else {
			recordingDateDurationView.setText(
				simpleDateFormat.format(recording.getDate()) + " (" +
				duration.toString() + "s)");
		}

		// Set the speakers' names
		List<String> speakers = recording.getSpeakersIds();
		StringBuilder sb = new StringBuilder();
		for(String speakerId : speakers) {
			try {
				sb.append(Speaker.read(speakerId).getName()+", ");
			} catch (IOException e) {
				// If the reader can't be read for whatever reason
				// (perhaps JSON file wasn't formatted correctly),
				// Empty the speakersName
				e.printStackTrace();
			}
		}

		TextView speakerNameView = (TextView)
				recordingView.findViewById(R.id.speakerNames);
		speakerNameView.setText(sb.substring(0, sb.length()-2));

		// Add the comment(two way arrow icon) or movie icon
		LinearLayout icons = (LinearLayout)
				recordingView.findViewById(R.id.recordingIcons);

		List<Recording> respeakings = recording.getRespeakings();
		int numComments = respeakings.size();
		if(numComments > 0) {
			icons.addView(makeRecordingInfoIcon(R.drawable.commentary_32));
		}
		if(recording.isMovie()) {
			icons.addView(makeRecordingInfoIcon(R.drawable.movie_32));
		}

		// Add the number of views information
		TextView viewCountsView = (TextView)
				recordingView.findViewById(R.id.viewCounts);
		viewCountsView.setText(""+recording.numViews());

		// Add the number of stars information
		TextView numStarsView = (TextView)
				recordingView.findViewById(R.id.numStars);
		numStarsView.setText(String.valueOf(recording.numStars()));

		// Add the number of flags information
		TextView numFlagsView = (TextView)
				recordingView.findViewById(R.id.numFlags);
		numFlagsView.setText(String.valueOf(recording.numFlags()));

		// When list is used to show only one item, quickMenu is not null
		// and only long-click is enabled for the item
		if(quickMenu != null) {
			recordingView.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					quickMenu.show(v);
					return false;
				}

			});
		}

		return recordingView;
	}

	/**
	 * Create the view for a icon with resourceId
	 *
	 * @param resourceId	The id of a drawalbe image
	 * @return
	 */
	private ImageView makeRecordingInfoIcon(int resourceId) {
		ImageView iconImage = new ImageView(context);
		iconImage.setImageResource(resourceId);
		iconImage.setAdjustViewBounds(true);
		iconImage.setLayoutParams(new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));

		return iconImage;
	}

	/**
	 * Creates the view for a given speaker.
	 *
	 * @param	speakerId	The ID of the speaker.
	 * @return	The image view for the speaker.
	 */
	private ImageView makeSpeakerImageView(String speakerId) {
		ImageView speakerImage = new ImageView(context);
		speakerImage.setAdjustViewBounds(true);
//		speakerImage.setScaleType(ImageView.ScaleType.FIT_END);
		speakerImage.setMaxHeight(60);//40
		speakerImage.setMaxWidth(60);//40
		try {
			speakerImage.setImageBitmap(Speaker.getSmallImage(speakerId));
		} catch (IOException e) {
			// Not much can be done if the image can't be loaded.
		}
		return speakerImage;
	}

	@Override
	public Filter getFilter() {
		return new Filter() {

			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				// TODO Auto-generated method stub
				constraint = constraint.toString().toLowerCase();
				Filter.FilterResults results = new Filter.FilterResults();

				if(constraint == null || constraint.length() == 0) {
					results.values = recordings;
				} else {
					List<Recording> filteredRecordings =
							new ArrayList<Recording>();
					for(int i=0; i<recordings.size(); i++) {
						Recording item = recordings.get(i);
						List<Language> languages = item.getLanguages();
						for(Language lang : languages) {
							if(lang.getCode().contains(constraint)) {
								filteredRecordings.add(item);
								break;
							}
						}
					}
					results.values = filteredRecordings;
				}
				return results;
			}

			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {
				// TODO Auto-generated method stub
				List<Recording> filteredRecordings =
						(List<Recording>) results.values;
				RecordingArrayAdapter.this.clear();
				RecordingArrayAdapter.this.addAll(filteredRecordings);
				RecordingArrayAdapter.this.notifyDataSetChanged();
			}

		};
	}

	private static final int LIST_ITEM_LAYOUT = R.layout.recording_list_item;
	private LayoutInflater inflater;
	private Context context;
	private List<Recording> recordings;
	private SimpleDateFormat simpleDateFormat;
	private QuickActionMenu quickMenu = null;

}


text:
package com.tagmycode.sdk.model;

import com.tagmycode.sdk.FileNameToLanguage;
import com.tagmycode.sdk.exception.TagMyCodeJsonException;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.List;

public class LanguagesCollection extends ModelCollection<Language> {
    public LanguagesCollection(String json) throws TagMyCodeJsonException {
        JSONArray ja;
        try {
            ja = new JSONArray(json);
            for (int i = 0; i < ja.length(); i++) {
                Language language = new Language(ja.getJSONObject(i));
                add(language);
            }
        } catch (JSONException e) {
            throw new TagMyCodeJsonException(e);
        }
    }

    public LanguagesCollection() {
    }

    public LanguagesCollection(Language... languages) {
        super(languages);
    }

    public LanguagesCollection(List<Language> languageList) {
        super(languageList);
    }

    public Language findByCode(String code) {
        for (Language language : this) {
            if (language.getCode().equals(code)) {
                return language;
            }
        }
        return null;
    }

    public Language findByFileName(String fileName) {
        return findByCode(FileNameToLanguage.getCode(fileName));
    }
}


text:
#ifndef ZESPOLONE_HH
#define ZESPOLONE_HH

#include <iostream>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>

using namespace std;

/*!
 * \file
 * \brief Klasa publiczna zawierająca definicję struktury Liczba Zespolona. Jej elementami są pola typu float przeznaczone dla wartości
 *	rzeczywistej i urojonej, umożliwające przedstawienie liczby w postaci (Re+Im*i), gdzie nawiasy są konieczne. Zawarta w niej jest
 *	również zmienna boolowska, która przechowuję informację czy przez podaną liczbę można dzielić.
*/
class Zespolona{
	public:
	float Re, Im;
	bool OK;
};

/*!
 * \brief Operator wyjścia dla typu Zespolona.
 * \param[in] Jako argumenty przyjmuje strumień wyjściowy oraz zmienną typu Zespolona.
 * \return Zwraca podany jako argument strumień wyjściowy.
*/
ostream & operator << (ostream & wy, Zespolona x);

/*!
 * \brief Operator wejścia dla typu Zespolona.
 * \param[in] Jako argumenty przyjmuje strumień wejściowy oraz zmienną w której zostanie zapamiętana (w przyadku poprawnego wczytania) wartość
 * 	typu Zespolona. Konieczne jest podanie liczby w formacie (Re+Im*i), gdzie nawiasów nie można pominąć.
 * \return Zwracany jest wejściowy strumień podany jako argument (w przypadku błędu we wczytywaniu ze stanem ustawionym na 'fail').
*/
istream & operator >> (istream & we, Zespolona & x);

/*!
 * \brief Operator dwuargumentowy '+'.
 * \param[in] Jako argumenty przyjmuje dwie zmienne typu Zespolona.
 * \return Zwraca ich sumę.
*/
Zespolona operator + (Zespolona x, Zespolona y);

/*!
 * \brief Operator dwuargumentowy '*'.
 * \param[in] Jako argumenty przyjmuje dwie zmienne typu Zespolona.
 * \return Zwraca iloczyn argumentów.
*/
Zespolona operator * (Zespolona x, Zespolona y);

/*!
 * \brief Operator dwuargumentowy '=='.
 * \param[in] Jako argumenty przyjmuje dwie zmienne typu Zespolona.
 * \return Zwraca 'true', jeśli są one równe, oraz 'false' w przypadku przeciwnym.
*/
bool operator == (Zespolona x, Zespolona y);

/*!
 * \brief Funkcja zerująca zmienną typu Zespolona.
 * \param[in] Ustawia wartości Re oraz Im zmiennej podanej jako argument na 0.
 * \return Zwraca wyzerowną zmienną.
*/
Zespolona Zeruj(Zespolona x);

#endif


text:
class Solution {
public:
    string simplifyPath(string path) {
        string token, result;
        istringstream iss;
        vector<string> tokens;
        iss.str(path);
        while ( getline(iss, token, '/') ) {
            if ( token.empty() || token == "." ) continue;
            if ( token == ".." ) {
                if ( tokens.size() ) tokens.pop_back();
                continue;
            }
            tokens.push_back(token);
        }
        for ( auto &t : tokens ) result = result + "/" + t;
        return result.empty() ? "/" : result;
    }
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NSpec.Domain.Extensions;

namespace NSpec.Domain
{
    [Serializable]
    public class ContextBuilder
    {
        public ContextCollection Contexts()
        {
            contexts.Clear();

            conventions.Initialize();

            var specClasses = finder.SpecClasses().OrderBy(type => type.Name);

            var container = new ClassContext(typeof(nspec), conventions, tagsFilter);

            Build(container, specClasses);

            contexts.AddRange(container.Contexts);

            return contexts;
        }

        public ClassContext CreateClassContext(Type type)
        {
            var tagAttributes = ((TagAttribute[])type.GetTypeInfo().GetCustomAttributes(typeof(TagAttribute), false)).ToList();

            tagAttributes.Add(new TagAttribute(type.Name));

            type.GetAbstractBaseClassChainWithClass()
                .Where(s => s != type)
                .Each(s => tagAttributes.Add(new TagAttribute(s.Name)));

            var tags = TagStringFor(tagAttributes);

            var context = new ClassContext(type, conventions, tagsFilter, tags);

            return context;
        }

        public void BuildMethodContexts(Context classContext, Type specClass)
        {
            specClass
                .Methods()
                .Where(s => conventions.IsMethodLevelContext(s.Name))
                .Do(contextMethod =>
                {
                    var methodContext = new MethodContext(contextMethod, TagStringFor(contextMethod));

                    classContext.AddContext(methodContext);
                });
        }

        public void BuildMethodLevelExamples(Context classContext, Type specClass)
        {
            Func<MethodInfo, MethodExampleBase> buildMethodLevel = method =>
                new MethodExample(method, TagStringFor(method));

            Func<MethodInfo, MethodExampleBase> buildAsyncMethodLevel = method =>
                new AsyncMethodExample(method, TagStringFor(method));

            specClass
                .Methods()
                .Union(specClass
                    .AsyncMethods())
                .Where(method => conventions.IsMethodLevelExample(method.Name))
                .Select(method =>
                {
                    return method.IsAsync()
                        ? buildAsyncMethodLevel(method)
                        : buildMethodLevel(method);
                })
                .Do(methodExample =>
                {
                    classContext.AddExample(methodExample);
                });
        }

        void Build(Context parent, IEnumerable<Type> allSpecClasses)
        {
            var derivedTypes = allSpecClasses.Where(s => parent.IsSub(s.GetTypeInfo().BaseType));

            foreach (var derived in derivedTypes)
            {
                var classContext = CreateClassContext(derived);

                parent.AddContext(classContext);

                BuildMethodContexts(classContext, derived);

                BuildMethodLevelExamples(classContext, derived);

                Build(classContext, allSpecClasses);
            }
        }

        string TagStringFor(MethodInfo method)
        {
            return TagStringFor(TagAttributesFor(method));
        }

        string TagStringFor(IEnumerable<TagAttribute> tagAttributes)
        {
            return tagAttributes.Aggregate("", (current, tagAttribute) => current + (", " + tagAttribute.Tags));
        }

        IEnumerable<TagAttribute> TagAttributesFor(MethodInfo method)
        {
            return (TagAttribute[])method.GetCustomAttributes(typeof(TagAttribute), false);
        }

        public ContextBuilder(ISpecFinder finder, Tags tagsFilter)
            : this(finder, tagsFilter, new DefaultConventions()) { }

        public ContextBuilder(ISpecFinder finder, Conventions conventions)
            : this(finder, new Tags(), conventions) { }

        public ContextBuilder(ISpecFinder finder, Tags tagsFilter, Conventions conventions)
        {
            contexts = new ContextCollection();

            this.finder = finder;

            this.conventions = conventions;

            this.tagsFilter = tagsFilter;
        }

        Tags tagsFilter;

        Conventions conventions;

        ISpecFinder finder;

        ContextCollection contexts;
    }
}