text:
FootballRanking
===============

Algorithm to rank college football teams

This Algorithm is designed to walk through every game played by every team to determine a team's score. Games with fewer degrees of separation from a team will contribute more to that team's score. This is designed to reward team who play tough schedules. The Algorithm takes into account which team won the game and which lost and the margin of victory. There are special penalties for playing FCS teams.

This program is designed to read game data input from this source: http://prwolfe.bol.ucla.edu/cfootball/home.htm

Known Issues
============

- Parts of the user configuration are not very clean
- Game data and BCS team data come from different sources. There may still be differences that cause FBS teams to be counted as FCS teams
- Winner of the champ game might not win depending on user configuration.
- Algorithm favors teams who play fewer conference games

Top 30 (2012 Final):
====================
1. Alabama (13-1)
2. Notre Dame (12-1)
3. Oregon (12-1)
4. Stanford (12-2)
5. Florida (11-2)
6. Ohio State (12-0)
7. Georgia (12-2)
8. Texas A&M (11-2)
9. South Carolina (11-2)
10. Kansas St (11-2)
11. Florida St (12-2)
12. Clemson (11-2)
13. LSU (10-3)
14. Oklahoma (10-3)
15. Northern Illinois (12-2)
16. Boise St (11-2)
17. San José St (11-2)
18. Utah St (11-2)
19. Nebraska (10-4)
20. Louisville (11-2)
21. Oregon St (9-4)
22. Texas (9-4)
23. Northwestern (10-3)
24. Michigan (8-5)
25. Tulsa (11-3)
26. Central Florida (10-4)
27. Arkansas St (10-3)
28. UCLA (9-5)
29. Cincinnati (10-3)
30. Kent St (11-3)


text:
Tradução pt_BR para o plugin de Wordpress TotalPoll.

TotalPoll é um plugin de enquetes para worpress, simples, poderoso e customizavel.

Para mais informações sobre o plugin visite www.totalpoll.com.

# Notas

A tradução foi feita e testada com o **TotalPoll 3.3.3** e **Wordpress 4.9.7**.

# Como usar
Coloque os arquivos `totalpoll-pt_BR.mo` e `totalpoll-pt_BR.po` na pasta:
```
wp-content/plugins/totalpoll/languages
```

Quando acessar a página de administração do Wordpress verá que o item Poll do menu terá se transformado em Enquetes.

# Contribua

Caso encontre problemas ou tenha sugestões de melhorias, por favor, colabore.

redpajama_set_name: RedPajamaGithub


text:
using System;
using LamarCodeGeneration;
using LamarCodeGeneration.Frames;
using LamarCodeGeneration.Model;

namespace Marten.Events.CodeGeneration
{
    internal class DeclareAggregateFrame: SyncFrame
    {

        public DeclareAggregateFrame(Type aggregateType)
        {
            Variable = new Variable(aggregateType, this);
        }

        public Variable Variable { get; }

        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            writer.WriteLine($"{Variable.VariableType.FullNameInCode()} {Variable.Usage} = null;");
            Next?.GenerateCode(method, writer);
        }
    }
}


text:
using System.Text;

namespace Test.NDatabase.Odb.Test.VO.Arraycollectionmap
{
    public class PlayerWithArray
    {
        private readonly string[] games;
        private readonly string name;

        private int numberOfGames;

        public PlayerWithArray()
        {
        }

        public PlayerWithArray(string name)
        {
            this.name = name;
            games = new string[50];
            numberOfGames = 0;
        }

        public virtual void AddGame(string gameName)
        {
            games[numberOfGames] = gameName;
            numberOfGames++;
        }

        public virtual string GetGame(int index)
        {
            return games[index];
        }

        public override string ToString()
        {
            var buffer = new StringBuilder();
            buffer.Append("Name=").Append(name).Append("[");
            for (var i = 0; i < numberOfGames; i++)
                buffer.Append(games[i]).Append(" ");
            buffer.Append("]");
            return buffer.ToString();
        }
    }
}


text:
FROM python:3.6-alpine

LABEL maintainer="github.com/techgaun"
LABEL org.opencontainers.image.authors="kiddo3,techgaun"
LABEL org.opencontainers.image.title="DynamoDB Copy Table"
LABEL org.opencontainers.image.url="https://github.com/techgaun/dynamodb-copy-table"
LABEL org.opencontainers.image.documentation="https://github.com/techgaun/dynamodb-copy-table#readme"
LABEL org.opencontainers.image.source="https://github.com/techgaun/dynamodb-copy-table"

WORKDIR /project
COPY . /project
RUN pip install -r requirements.txt

ENTRYPOINT ["python", "dynamodb-copy-table.py"]


text:
<?php

namespace Aws\Tests\CloudFront\Waiter;

use Guzzle\Http\Message\Response;

class InvalidationCompletedTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException \Aws\Common\Exception\InvalidArgumentException
     */
    public function testValidatesInvalidationResource()
    {
        $client = $this->getServiceBuilder()->get('cloudfront');
        $client->waitUntil('InvalidationCompleted', array('Id' => 'foo'));
    }

    public function testReturnsTrueIfDeployed()
    {
        $client = $this->getServiceBuilder()->get('cloudfront');
        $this->setMockResponse($client, array(
            'cloudfront/GetInvalidation_InProgress',
            'cloudfront/GetInvalidation_Completed'
        ));
        $client->waitUntil(
            'InvalidationCompleted',
            array('DistributionId' => 'foo', 'Id' => 'bar', 'waiter.interval' => 0)
        );
        $requests = $this->getMockedRequests();
        $this->assertEquals(2, count($requests));
        $this->assertContains('/distribution/foo/invalidation/bar', $requests[0]->getUrl());
    }

    /**
     * @expectedException \Aws\Common\Exception\RuntimeException
     */
    public function testDoesNotBufferOtherExceptions()
    {
        $client = $this->getServiceBuilder()->get('cloudfront');
        $this->setMockResponse($client, array(new Response(404)));
        $client->waitUntil('invalidation_completed', array('DistributionId' => 'foo', 'Id' => 'bar'));
    }
}


text:
Global Event Dispatcher
=======================

The global event dispatcher is the core messaging system for your application.

This is a singleton so wherever you can inject you can get access to it here

```csharp
[Inject]
public IEventDispatcher dispatcher;
```

It used to designed to communicate primarily between the following:

* Mediators
* Commands
* Models / Services *(and other singletons)*

> *Note:* Mediators communicate with views with their own events / event dispatcher.

Events
------

The global event dispatcher uses IEvents to communicate with each other.

The IEvent interface is very simple and just requires you to have an Enum as a key for what you would like the event to do:

```csharp
using System;

namespace robotlegs.bender.extensions.eventDispatcher.api
{
	public interface IEvent
	{
		Enum type { get; }
	}
}
```

You may want to extend ```Event``` when making your own as it speeds up event creation. You'll need to add a key and any data with the event.

```csharp
public class ExampleEvent : Event
{
	public enum Type
	{
		ACTION_1,
		ACTION_2
		ACTION_3
	}

	public ExampleEvent(Type type) : base ( type )
	{

	}
}
```

Listening to events
-------------------

You can listen for messages on the global event dispatcher like so:

```csharp
dispatcher.AddEventListener(ExampleEvent.Type.ACTION_1, OnAction1);

void OnAction1()
{
	Console.WriteLine("Action 1 fired");
}
```

If you require the IEvent you can get the data like this:

```csharp
dispatcher.AddEventListener(ExampleEvent.Type.ACTION_1, OnAction1);

void OnAction1(IEvent evt)
{
	Console.WriteLine("Action 1 fired with data: " + evt);
}
```

And if you don't want to cast in your function, you can get your typed event like so:

```csharp
dispatcher.AddEventListener<ExampleEvent>(ExampleEvent.Type.ACTION_1, OnAction1);

void OnAction1(ExampleEvent evt)
{
	Console.WriteLine("Action 1 fired with data: " + evt);
}
```

> *Note:* You can add listener like this too without generics
	> ```dispatcher.AddEventListener(ExampleEvent.Type.ACTION_1, (Action<ExampleEvent>)OnAction1);```

It's best practice to only listen from an event from a Mediator (not a Service or Model). Communicating to Models/Services through the global event dispatcher should be done via [Commands](./Commands.md).

Dispatching events
------------------

If you want to send a message. You can send one by dispatching a new event.

```csharp
dispatcher.Dispatch(new ExampleEvent(ExampleEvent.ACTION_1));
```

When this is dispatched, any command mapped to this event or mediator listening for ExampleEvent.ACTION_1 will be called in the order they were listened to.

Why can't we use regular events?
--------------------------------

Unfortunately, events rely on the subscriber knowing the delegate type. This system allows you to not know the type and the data will be cast by the DynamicInvoke function.

This way, we can downcast the type to IEvent, get the message key. Send it to the appropriate people and upcast it back to how they expect it.

From here
---------

* [Readme](../../README.md)
	* [A Brief Overview](../ABriefOverview.md)
	* [Features](../Features.md)
		* [Context](./Context.md)
		* [Injector](./Injector.md)
		* [Global Event Dispatcher](./GlobalEventDispatcher.md)
		* [Mediators](./Mediators.md)
		* [Commands](./Commands.md)
		* [Guards](./Guards.md)
		* [Hooks](./Hooks.md)
		* [View Processor](./ViewProcessor.md)
		* [Logger](./Logger.md)
		* [Modularity](./Modularity.md)
	* [Platforms](../Platforms.md)
	* [Writing An Extension](../WritingAnExtension.md)
	* [Common Problems](../CommonProblems.md)
	* [The internals (how it all works)](../TheInternals.md)


text:
package org.openqa.selenium.server.browserlaunchers;

import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals;

import org.junit.Test;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.server.RemoteControlConfiguration;

/**
 * {@link org.openqa.selenium.server.browserlaunchers.AbstractBrowserLauncher} unit test class.
 */
public class AbstractBrowserLauncherUnitTest {

  @Test
  public void testGetConfigurationReturnsConfigurationProvidedInConstructor() {
    final RemoteControlConfiguration theConfiguration;
    final Capabilities browserOptions;

    theConfiguration = new RemoteControlConfiguration();
    browserOptions = BrowserOptions.newBrowserOptions();
    AbstractBrowserLauncher launcher =
        new AbstractBrowserLauncher(null, theConfiguration, browserOptions) {
          @Override
          protected void launch(String url) {
            throw new UnsupportedOperationException("Should never be called");
          }

          public void close() {
            throw new UnsupportedOperationException("Should never be called");
          }
        };
    assertEquals(theConfiguration, launcher.getConfiguration());
  }
}


text:
echo "INFO: waiting for SQL Server to come up"
(Get-Service MSSQLSERVER).WaitForStatus('Running')

echo "INFO: enabling TCP"
# https://docs.microsoft.com/en-us/sql/powershell/how-to-enable-tcp-sqlps?view=sql-server-ver15
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")
$wmi = New-Object 'Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer' localhost
$tcp = $wmi.ServerInstances['MSSQLSERVER'].ServerProtocols['Tcp']
$tcp.IsEnabled = $true
$tcp.Alter()

echo "INFO: setting LoginMode=Mixed"
### https://www.mode19.net/posts/changesqlauthmodewithps/
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')
$smo = New-Object 'Microsoft.SqlServer.Management.Smo.Server' localhost
$smo.Settings.LoginMode = "Mixed"
$smo.Alter()

echo "INFO: running setup.sql for integration tests"
sqlcmd -d master -i setup.sql -b -f 65001
if (-Not $?) {
    throw "ERROR: setup.sql failed"
}
echo "INFO: setup.sql completed"

echo "INFO: restarting MSSQLSERVER"
Restart-Service -Name MSSQLSERVER
(Get-Service MSSQLSERVER).WaitForStatus('Running')
echo "INFO: MSSQLSERVER running."

echo "INFO: Container initialization complete."
ping -t localhost | out-null


text:
require 'rspec'
require 'currency_spy'

shared_examples_for 'a valid scraper' do
  it "should contain a list of available currency codes" do
    scraper.available_codes.should_not be_nil
  end

  it "should have a data url defined" do
    scraper.url.should_not be_nil
  end

  it "should have an institution name" do
    scraper.institution.should_not be_nil
  end

  it "should return currency rates" do
    scraper.fetch_rates.should_not be_empty
  end
end


text:
<!--L
  Copyright Washington University at St. Louis

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/geneconnect/LICENSE.txt for details.
L-->

<CQLQuery xmlns="http://CQL.caBIG/1/gov.nih.nci.cagrid.CQLQuery">
	<Target name="edu.wustl.geneconnect.domain.GenomicIdentifierSet">
		<Group logicRelation="AND">
			<!--consensusIdentifierDataCollection-->
			<Association roleName="consensusIdentifierDataCollection"  name="edu.wustl.geneconnect.domain.ConsensusIdentifierData">
				<Attribute name="frequency" predicate="EQUAL_TO" value="0.2"/>
				<Association roleName="genomicIdentifier"  		name="edu.wustl.geneconnect.domain.GenomicIdentifier">
					<Attribute name="dataSource" predicate="EQUAL_TO" value="RefSeqProtein"/>
				</Association>
			</Association>

			<!--orderOfNodeTraversalCollection-->

			<Association roleName="orderOfNodeTraversalCollection"  name="edu.wustl.geneconnect.domain.OrderOfNodeTraversal">
					<Group logicRelation="AND">
						<Association roleName="sourceDataSource"  name="edu.wustl.geneconnect.domain.DataSource">
							<Attribute name="dataSourceName" predicate="EQUAL_TO" value="EnsemblGene"/>
						</Association>
						<Association roleName="linkType"  name="edu.wustl.geneconnect.domain.LinkType">
							<Attribute name="linkType" predicate="EQUAL_TO" value="DIRECT"/>
						</Association>
						<Association roleName="childOrderOfNodeTraversal"  name="edu.wustl.geneconnect.domain.OrderOfNodeTraversal">
							<Group logicRelation="AND">
								<Association roleName="sourceDataSource"  name="edu.wustl.geneconnect.domain.DataSource">
									<Attribute name="dataSourceName" predicate="EQUAL_TO" value="EnsemblTranscript"/>
								</Association>
								<Association roleName="linkType"  name="edu.wustl.geneconnect.domain.LinkType">
									<Attribute name="linkType" predicate="EQUAL_TO" value="DIRECT"/>
								</Association>
								<Association roleName="childOrderOfNodeTraversal"  name="edu.wustl.geneconnect.domain.OrderOfNodeTraversal">
									<Group logicRelation="AND">
										<Association roleName="sourceDataSource"  name="edu.wustl.geneconnect.domain.DataSource">
											<Attribute name="dataSourceName" predicate="EQUAL_TO" value="RefSeqmRNA"/>
										</Association>
										<Association roleName="linkType"  name="edu.wustl.geneconnect.domain.LinkType">
											<Attribute name="linkType" predicate="EQUAL_TO" value="DIRECT"/>
										</Association>
									</Group>
								</Association>
							</Group>
					</Association>
				</Group>
		</Association>
</Group>
</Target>
</CQLQuery>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Millettia buteoides Gagnep.

### Remarks
null


text:
IMPLEMENT_CONOBJECT(GuiButtonCtrl);

ConsoleDocClass( GuiButtonCtrl,
   "@brief The most widely used button class.\n\n"

   "GuiButtonCtrl renders seperately of, but utilizes all of the functionality of GuiBaseButtonCtrl.\n"
   "This grants GuiButtonCtrl the versatility to be either of the 3 button types.\n\n"

   "@tsexample\n"
   "// Create a PushButton GuiButtonCtrl that calls randomFunction when clicked\n"
   "%button = new GuiButtonCtrl()\n"
   "{\n"
   "   profile    = \"GuiButtonProfile\";\n"
   "   buttonType = \"PushButton\";\n"
   "   command    = \"randomFunction();\";\n"
   "};\n"
   "@endtsexample\n\n"

   "@ingroup GuiButtons"
);

//-----------------------------------------------------------------------------

GuiButtonCtrl::GuiButtonCtrl()
{
   setExtent(140, 30);
   mButtonText = StringTable->EmptyString();
   mHasTheme = false;
}

//-----------------------------------------------------------------------------

bool GuiButtonCtrl::onWake()
{
   if( !Parent::onWake() )
      return false;

   // Button Theme?
   if( mProfile->constructBitmapArray() >= 36 )
      mHasTheme = true;
   else
      mHasTheme = false;

   return true;

}

//-----------------------------------------------------------------------------

void GuiButtonCtrl::onRender(Point2I      offset,
                             const RectI& updateRect)
{
   bool highlight = mHighlighted;
   bool depressed = mDepressed;

   ColorI fontColor   = mActive ? ( highlight ? mProfile->mFontColorHL : mProfile->mFontColor ) : mProfile->mFontColorNA;
   ColorI fillColor   = mActive ? ( highlight ? mProfile->mFillColorHL : mProfile->mFillColor ) : mProfile->mFillColorNA;
   ColorI borderColor = mActive ? ( highlight ? mProfile->mBorderColorHL : mProfile->mBorderColor ) : mProfile->mBorderColorNA;

   RectI boundsRect(offset, getExtent());

   if( !mHasTheme )
   {
      if( mProfile->mBorder != 0 )
         renderFilledBorder( boundsRect, borderColor, fillColor, mProfile->mBorderThickness );
      else
         GFX->getDrawUtil()->drawRectFill( boundsRect, fillColor );
   }
   else
   {
      S32 indexMultiplier = 1;

      if( !mActive )
         indexMultiplier = 4;
      else if ( mDepressed || mStateOn )
         indexMultiplier = 2;
      else if ( mHighlighted )
         indexMultiplier = 3;

      renderSizableBitmapBordersFilled( boundsRect, indexMultiplier, mProfile );
   }

   Point2I textPos = offset;
   if( depressed )
      textPos += Point2I( 1, 1 );

   GFX->getDrawUtil()->setBitmapModulation( fontColor );
   renderJustifiedText( textPos, getExtent(), mButtonText );

   //render the children
   renderChildControls( offset, updateRect);
}


text:
// SDL defines
#include    "SDL.h"
#include    "SDL_joystick.h"
#include    "SDL_video.h"

// Matlab defines
#include    "mex.h"

#include    <stdio.h>
#include    <math.h>

// Output Arguments
#define	JOY_OUT	    plhs[0]
#define	BUTTON_OUT	plhs[1]

// Persistent data between calls
SDL_Joystick *joy;   // SDL joystick object pointer
double  *joydata;    // joystick data
int     njoy;        // number of joystick axes
double  *buttondata; // button data
int     nbutton;     // number of buttons

static void
cleanup(void)
{
    // free allocated arrays
    if (joydata)
        free(joydata);
    if (buttondata)
        free(buttondata);
}

void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

	// Check for proper number of arguments
    if (nrhs != 0) {
		mexErrMsgTxt("JOYSTICK requires zero input arguments.");
	}

    if (joy == NULL) {
        // init the joystick if none initialized

        // Gotch: must initialize video as well!
        //  see comments in sdl/test/testjoystick
        if ( SDL_Init( SDL_INIT_VIDEO| SDL_INIT_JOYSTICK  ) != 0 ) {
            mexErrMsgTxt("Couldnt initialize SDL");
        }

        // Check for a joystick
        if (SDL_NumJoysticks() > 0) {
          // Open joystick
          SDL_JoystickEventState(SDL_ENABLE);
          joy = SDL_JoystickOpen(0);

          if(joy) {
            printf("Opened Joystick 0\n");
            printf("Name: %s\n", SDL_JoystickName(0));
            printf("Number of Axes: %d\n", SDL_JoystickNumAxes(joy));
            printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(joy));
            printf("Number of Balls: %d\n", SDL_JoystickNumBalls(joy));
            printf("Number of Hats: %d\n", SDL_JoystickNumHats(joy));

            // record the number of axes and buttons
            njoy = SDL_JoystickNumAxes(joy);
            nbutton = SDL_JoystickNumButtons(joy);

            // allocate storage
            joydata = (double *)calloc(njoy, sizeof(double));
            buttondata = (double *)calloc(nbutton, sizeof(double));

            mexAtExit(cleanup);
          }
          else
            mexErrMsgTxt("Couldn't open Joystick 0\n");
        }
    }

    // process all events in the queue and update global data
    SDL_Event event;
    while (SDL_PollEvent(&event) ) {

        switch (event.type) {
        case SDL_JOYAXISMOTION:
            joydata[event.jaxis.axis] = event.jaxis.value / 32768.0;
            break;
        case SDL_JOYBUTTONDOWN:
            buttondata[event.jbutton.button] = 1;
            break;
        case SDL_JOYBUTTONUP:
            buttondata[event.jbutton.button] = 0;
            break;
        case SDL_QUIT:
            break;
        }
    }

    // create return values

    if (nlhs > 0) {
        int i;
        // copy out the joystick data
        JOY_OUT = mxCreateDoubleMatrix(1, njoy, mxREAL);
        double *p = mxGetPr(JOY_OUT);
        for (i=0; i<njoy; i++)
            *p++ = joydata[i];
    }
    if (nlhs > 1) {
        int i;
        // copy out the button data
        BUTTON_OUT = mxCreateDoubleMatrix(1, nbutton, mxREAL);
        double *p = mxGetPr(BUTTON_OUT);
        for (i=0; i<nbutton; i++)
            *p++ = buttondata[i];
    }
}


text:
package org.apache.sshd.common.keyprovider;

/**
 * @author Apache MINA SSHD Project
 */
public interface KeyPairProviderHolder {
    /**
     * Retrieve the KeyPairProvider that will be used to find
     * the host key to use on the server side or the user key on the client side.
     *
     * @return the KeyPairProvider, never {@code null}
     */
    KeyPairProvider getKeyPairProvider();

    void setKeyPairProvider(KeyPairProvider keyPairProvider);
}


text:
package models.daos;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.dao.DataAccessException;
import play.Logger;
import play.Play;
import utils.Urn;
import utils.JdbcUtil;
import wherehows.common.DatasetPath;
import wherehows.common.LineageCombiner;
import wherehows.common.schemas.ApplicationRecord;
import wherehows.common.schemas.JobExecutionRecord;
import wherehows.common.schemas.LineageDatasetRecord;
import wherehows.common.schemas.LineageRecord;
import wherehows.common.schemas.LineageRecordLite;
import wherehows.common.utils.PartitionPatternMatcher;
import wherehows.common.utils.PreparedStatementUtil;
import wherehows.common.writers.DatabaseWriter;

/**
 * Essentially only impliments insertLineage(), everything else returns empty objects and sticks an error in the log
 * created by norv on 07/06/16
 */
public class LineageDaoLite {

    public static List<Map<String, Object>> getJobsByDataset(String urn, String period, String cluster, String instance, String sourceTargetType)
            throws SQLException {
        Logger.error("getJobsByDataset is not implimented in diet mode");
        List<Map<String, Object>> empty = new ArrayList<>();
        return empty;
    }

    public static List<Map<String, Object>> getDatasetsByJob(String flowPath, String jobName, String instance, String sourceTargetType) {
        Logger.error("getDatasetsByJob is not implimented in diet mode");
        List<Map<String, Object>> empty = new ArrayList<>();
        return empty;
    }

    public static List<Map<String, Object>> getDatasetsByFlowExec(Long flowExecId, String jobName, String instance, String sourceTargetType) {
        Logger.error("getDatasetsByFlowExec is not implimented in diet mode");
        List<Map<String, Object>> empty = new ArrayList<>();
        return empty;
    }

    public static List<Map<String, Object>> getDatasetsByJobExec(Long jobExecId, String instance, String sourceTargetType) {
        Logger.error("getDatasetsByJobExec is not implimented in diet mode");
        List<Map<String, Object>> empty = new ArrayList<>();
        return empty;
    }

    // insert relationships between give nodes into family table
    // all parents in parents array are parents of every child in the children array
    public static void insertLineage(JsonNode lineage) throws Exception, IOException, SQLException {
        List<LineageRecordLite> records = new ArrayList<LineageRecordLite>();
        JsonNode parents = lineage.findPath("parent_urn");
        JsonNode children = lineage.findPath("child_urn");

        if (parents.isArray() && children.isArray()) {
            for (JsonNode parent : parents) {
                for (JsonNode child : children) {
                    LineageRecordLite record = new LineageRecordLite(parent.textValue(), child.textValue());
                    records.add(record);
                }
            }
        }

        DatabaseWriter dw = new DatabaseWriter(JdbcUtil.wherehowsJdbcTemplate, "family");
        for (LineageRecordLite record : records) {
            dw.append(record);
        }
        dw.insert("parent_urn, child_urn"); // overload to use slightly better version of insert function
        dw.close();
    }

    public static void updateJobExecutionLineage(JsonNode root)
            throws Exception {
        Logger.error("updateJobExecutionLineage is not implimented in diet mode");
    }

    // convert LineageDatasetRecord and JobExecutionRecord into LineageRecord
    private static LineageRecord convertLineageDataset(LineageDatasetRecord lineageDataset, JobExecutionRecord jobExec)
            throws Exception {
        Logger.error("convertLineageDataset is not implimented in diet mode");
        final LineageRecord record = new LineageRecord(jobExec.getAppId(), jobExec.getFlowExecutionId(), jobExec.getName(),
                jobExec.getExecutionId());
        return record;
    }
}


text:
<?php

require_once 'Dase/DBO.php';

/*
 * DO NOT EDIT THIS FILE
 * it is auto-generated by the
 * script 'bin/class_gen.php
 *
 */

class Dase_DBO_Autogen_Item extends Dase_DBO
{
	public function __construct($db,$assoc = false)
	{
		parent::__construct($db,'item', array('serial_number','title','type','body','url','file_url','thumbnail_url','view_url','file_path','thumbnail_path','view_path','filesize','file_ext','file_original_name','mime','width','height','lat','lng','created','created_by','updated','updated_by'));
		if ($assoc) {
			foreach ( $assoc as $key => $value) {
				$this->fields[$key] = $value;
			}
		}
	}
    public function getSerial_number() { return $this->fields["serial_number"]; }
    public function getTitle() { return $this->fields["title"]; }
    public function getType() { return $this->fields["type"]; }
    public function getBody() { return $this->fields["body"]; }
    public function getUrl() { return $this->fields["url"]; }
    public function getFile_url() { return $this->fields["file_url"]; }
    public function getThumbnail_url() { return $this->fields["thumbnail_url"]; }
    public function getView_url() { return $this->fields["view_url"]; }
    public function getFile_path() { return $this->fields["file_path"]; }
    public function getThumbnail_path() { return $this->fields["thumbnail_path"]; }
    public function getView_path() { return $this->fields["view_path"]; }
    public function getFilesize() { return $this->fields["filesize"]; }
    public function getFile_ext() { return $this->fields["file_ext"]; }
    public function getFile_original_name() { return $this->fields["file_original_name"]; }
    public function getMime() { return $this->fields["mime"]; }
    public function getWidth() { return $this->fields["width"]; }
    public function getHeight() { return $this->fields["height"]; }
    public function getLat() { return $this->fields["lat"]; }
    public function getLng() { return $this->fields["lng"]; }
    public function getCreated() { return $this->fields["created"]; }
    public function getCreated_by() { return $this->fields["created_by"]; }
    public function getUpdated() { return $this->fields["updated"]; }
    public function getUpdated_by() { return $this->fields["updated_by"]; }
}


text:
"use strict";
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderWithParse5 = exports.parseWithParse5 = void 0;
var domhandler_1 = require("domhandler");
var parse5_1 = require("parse5");
var parse5_htmlparser2_tree_adapter_1 = require("parse5-htmlparser2-tree-adapter");
/**
 * Parse the content with `parse5` in the context of the given `ParentNode`.
 *
 * @param content - The content to parse.
 * @param options - A set of options to use to parse.
 * @param isDocument - Whether to parse the content as a full HTML document.
 * @param context - The context in which to parse the content.
 * @returns The parsed content.
 */
function parseWithParse5(content, options, isDocument, context) {
    var opts = {
        scriptingEnabled: typeof options.scriptingEnabled === 'boolean'
            ? options.scriptingEnabled
            : true,
        treeAdapter: parse5_htmlparser2_tree_adapter_1.adapter,
        sourceCodeLocationInfo: options.sourceCodeLocationInfo,
    };
    return isDocument
        ? (0, parse5_1.parse)(content, opts)
        : (0, parse5_1.parseFragment)(context, content, opts);
}
exports.parseWithParse5 = parseWithParse5;
var renderOpts = { treeAdapter: parse5_htmlparser2_tree_adapter_1.adapter };
/**
 * Renders the given DOM tree with `parse5` and returns the result as a string.
 *
 * @param dom - The DOM tree to render.
 * @returns The rendered document.
 */
function renderWithParse5(dom) {
    var _a;
    /*
     * `dom-serializer` passes over the special "root" node and renders the
     * node's children in its place. To mimic this behavior with `parse5`, an
     * equivalent operation must be applied to the input array.
     */
    var nodes = 'length' in dom ? dom : [dom];
    for (var index = 0; index < nodes.length; index += 1) {
        var node = nodes[index];
        if ((0, domhandler_1.isDocument)(node)) {
            (_a = Array.prototype.splice).call.apply(_a, __spreadArray([nodes, index, 1], node.children, false));
        }
    }
    var result = '';
    for (var index = 0; index < nodes.length; index += 1) {
        var node = nodes[index];
        result += (0, parse5_1.serializeOuter)(node, renderOpts);
    }
    return result;
}
exports.renderWithParse5 = renderWithParse5;
//# sourceMappingURL=parse5-adapter.js.map


text:
import os
import subprocess
import sys
import unittest.mock as mk
from inspect import signature

import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_equal

import astropy
import astropy.modeling.core as core
import astropy.units as u
from astropy.convolution import convolve_models
from astropy.modeling import models
from astropy.modeling.bounding_box import CompoundBoundingBox, ModelBoundingBox
from astropy.modeling.core import (
    SPECIAL_OPERATORS,
    CompoundModel,
    Model,
    _add_special_operator,
    bind_bounding_box,
    bind_compound_bounding_box,
    custom_model,
    fix_inputs,
)
from astropy.modeling.parameters import Parameter
from astropy.modeling.separable import separability_matrix
from astropy.tests.helper import assert_quantity_allclose
from astropy.utils.compat.optional_deps import HAS_SCIPY

class NonFittableModel(Model):
    """An example class directly subclassing Model for testing."""

    a = Parameter()

    def __init__(self, a, model_set_axis=None):
        super().__init__(a, model_set_axis=model_set_axis)

    @staticmethod
    def evaluate():
        pass

def test_Model_instance_repr_and_str():
    m = NonFittableModel(42.5)
    assert repr(m) == "<NonFittableModel(a=42.5)>"
    assert (
        str(m) == "Model: NonFittableModel\n"
        "Inputs: ()\n"
        "Outputs: ()\n"
        "Model set size: 1\n"
        "Parameters:\n"
        "     a  \n"
        "    ----\n"
        "    42.5"
    )

    assert len(m) == 1

def test_Model_array_parameter():
    model = models.Gaussian1D(4, 2, 1)
    assert_allclose(model.param_sets, [[4], [2], [1]])

def test_inputless_model():
    """
    Regression test for
    https://github.com/astropy/astropy/pull/3772#issuecomment-101821641
    """

    class TestModel(Model):
        n_outputs = 1
        a = Parameter()

        @staticmethod
        def evaluate(a):
            return a

    m = TestModel(1)
    assert m.a == 1
    assert m() == 1

    # Test array-like output
    m = TestModel([1, 2, 3], model_set_axis=False)
    assert len(m) == 1
    assert np.all(m() == [1, 2, 3])

    # Test a model set
    m = TestModel(a=[1, 2, 3], model_set_axis=0)
    assert len(m) == 3
    assert np.all(m() == [1, 2, 3])

    # Test a model set
    m = TestModel(a=[[1, 2, 3], [4, 5, 6]], model_set_axis=0)
    assert len(m) == 2
    assert np.all(m() == [[1, 2, 3], [4, 5, 6]])

    # Test a model set
    m = TestModel(a=[[1, 2, 3], [4, 5, 6]], model_set_axis=np.int64(0))
    assert len(m) == 2
    assert np.all(m() == [[1, 2, 3], [4, 5, 6]])

def test_ParametericModel():
    MESSAGE = r"Gaussian1D.__init__.* got an unrecognized parameter 'wrong'"
    with pytest.raises(TypeError, match=MESSAGE):
        models.Gaussian1D(1, 2, 3, wrong=4)

def test_custom_model_signature():
    """
    Tests that the signatures for the __init__ and __call__
    methods of custom models are useful.
    """

    @custom_model
    def model_a(x):
        return x

    assert model_a.param_names == ()
    assert model_a.n_inputs == 1
    sig = signature(model_a.__init__)
    assert list(sig.parameters.keys()) == ["self", "args", "meta", "name", "kwargs"]
    sig = signature(model_a.__call__)
    assert list(sig.parameters.keys()) == [
        "self",
        "inputs",
        "model_set_axis",
        "with_bounding_box",
        "fill_value",
        "equivalencies",
        "inputs_map",
        "new_inputs",
    ]

    @custom_model
    def model_b(x, a=1, b=2):
        return x + a + b

    assert model_b.param_names == ("a", "b")
    assert model_b.n_inputs == 1
    sig = signature(model_b.__init__)
    assert list(sig.parameters.keys()) == ["self", "a", "b", "kwargs"]
    assert [x.default for x in sig.parameters.values()] == [sig.empty, 1, 2, sig.empty]
    sig = signature(model_b.__call__)
    assert list(sig.parameters.keys()) == [
        "self",
        "inputs",
        "model_set_axis",
        "with_bounding_box",
        "fill_value",
        "equivalencies",
        "inputs_map",
        "new_inputs",
    ]

    @custom_model
    def model_c(x, y, a=1, b=2):
        return x + y + a + b

    assert model_c.param_names == ("a", "b")
    assert model_c.n_inputs == 2
    sig = signature(model_c.__init__)
    assert list(sig.parameters.keys()) == ["self", "a", "b", "kwargs"]
    assert [x.default for x in sig.parameters.values()] == [sig.empty, 1, 2, sig.empty]
    sig = signature(model_c.__call__)
    assert list(sig.parameters.keys()) == [
        "self",
        "inputs",
        "model_set_axis",
        "with_bounding_box",
        "fill_value",
        "equivalencies",
        "inputs_map",
        "new_inputs",
    ]

def test_custom_model_subclass():
    """Test that custom models can be subclassed."""

    @custom_model
    def model_a(x, a=1):
        return x * a

    class model_b(model_a):
        # Override the evaluate from model_a
        @classmethod
        def evaluate(cls, x, a):
            return -super().evaluate(x, a)

    b = model_b()
    assert b.param_names == ("a",)
    assert b.a == 1
    assert b(1) == -1

    sig = signature(model_b.__init__)
    assert list(sig.parameters.keys()) == ["self", "a", "kwargs"]
    sig = signature(model_b.__call__)
    assert list(sig.parameters.keys()) == [
        "self",
        "inputs",
        "model_set_axis",
        "with_bounding_box",
        "fill_value",
        "equivalencies",
        "inputs_map",
        "new_inputs",
    ]

def test_custom_model_parametrized_decorator():
    """Tests using custom_model as a decorator with parameters."""

    def cosine(x, amplitude=1):
        return [amplitude * np.cos(x)]

    @custom_model(fit_deriv=cosine)
    def sine(x, amplitude=1):
        return amplitude * np.sin(x)

    assert issubclass(sine, Model)
    s = sine(2)
    assert_allclose(s(np.pi / 2), 2)
    assert_allclose(s.fit_deriv(0, 2), 2)

def test_custom_model_n_outputs():
    """
    Test creating a custom_model which has more than one output, which
    requires special handling.
        Demonstrates issue #11791's ``n_outputs`` error has been solved
    """

    @custom_model
    def model(x, y, n_outputs=2):
        return x + 1, y + 1

    m = model()
    assert not isinstance(m.n_outputs, Parameter)
    assert isinstance(m.n_outputs, int)
    assert m.n_outputs == 2
    assert m.outputs == ("x0", "x1")
    assert (
        separability_matrix(m)
        == [
            [True, True],
            [True, True],
        ]
    ).all()

    @custom_model
    def model(x, y, z, n_outputs=3):
        return x + 1, y + 1, z + 1

    m = model()
    assert not isinstance(m.n_outputs, Parameter)
    assert isinstance(m.n_outputs, int)
    assert m.n_outputs == 3
    assert m.outputs == ("x0", "x1", "x2")
    assert (
        separability_matrix(m)
        == [
            [True, True, True],
            [True, True, True],
            [True, True, True],
        ]
    ).all()

def test_custom_model_settable_parameters():
    """
    Test creating a custom_model which specifically sets adjustable model
    parameters.
        Demonstrates part of issue #11791's notes about what passed parameters
        should/shouldn't be allowed. In this case, settable parameters
        should be allowed to have defaults set.
    """

    @custom_model
    def model(x, y, n_outputs=2, bounding_box=((1, 2), (3, 4))):
        return x + 1, y + 1

    m = model()
    assert m.n_outputs == 2
    assert m.bounding_box == ((1, 2), (3, 4))
    m.bounding_box = ((9, 10), (11, 12))
    assert m.bounding_box == ((9, 10), (11, 12))
    m = model(bounding_box=((5, 6), (7, 8)))
    assert m.n_outputs == 2
    assert m.bounding_box == ((5, 6), (7, 8))
    m.bounding_box = ((9, 10), (11, 12))
    assert m.bounding_box == ((9, 10), (11, 12))

    @custom_model
    def model(x, y, n_outputs=2, outputs=("z0", "z1")):
        return x + 1, y + 1

    m = model()
    assert m.n_outputs == 2
    assert m.outputs == ("z0", "z1")
    m.outputs = ("a0", "a1")
    assert m.outputs == ("a0", "a1")
    m = model(outputs=("w0", "w1"))
    assert m.n_outputs == 2
    assert m.outputs == ("w0", "w1")
    m.outputs = ("a0", "a1")
    assert m.outputs == ("a0", "a1")

def test_custom_model_regected_parameters():
    """
    Test creating a custom_model which attempts to override non-overridable
    parameters.
        Demonstrates part of issue #11791's notes about what passed parameters
        should/shouldn't be allowed. In this case, non-settable parameters
        should raise an error (unexpected behavior may occur).
    """

    with pytest.raises(
        ValueError, match=r"Parameter 'n_inputs' cannot be a model property: *"
    ):

        @custom_model
        def model1(x, y, n_outputs=2, n_inputs=3):
            return x + 1, y + 1

    with pytest.raises(
        ValueError, match=r"Parameter 'uses_quantity' cannot be a model property: *"
    ):

        @custom_model
        def model2(x, y, n_outputs=2, uses_quantity=True):
            return x + 1, y + 1

def test_custom_inverse():
    """Test setting a custom inverse on a model."""

    p = models.Polynomial1D(1, c0=-2, c1=3)
    # A trivial inverse for a trivial polynomial
    inv = models.Polynomial1D(1, c0=(2.0 / 3.0), c1=(1.0 / 3.0))

    MESSAGE = (
        r"No analytical or user-supplied inverse transform has been implemented for"
        r" this model"
    )
    with pytest.raises(NotImplementedError, match=MESSAGE):
        p.inverse

    p.inverse = inv

    x = np.arange(100)

    assert_allclose(x, p(p.inverse(x)))
    assert_allclose(x, p.inverse(p(x)))

    p.inverse = None

    with pytest.raises(NotImplementedError, match=MESSAGE):
        p.inverse

def test_custom_inverse_reset():
    """Test resetting a custom inverse to the model's default inverse."""

    class TestModel(Model):
        n_inputs = 0
        outputs = ("y",)

        @property
        def inverse(self):
            return models.Shift()

        @staticmethod
        def evaluate():
            return 0

    # The above test model has no meaning, nor does its inverse--this just
    # tests that setting an inverse and resetting to the default inverse works

    m = TestModel()
    assert isinstance(m.inverse, models.Shift)

    m.inverse = models.Scale()
    assert isinstance(m.inverse, models.Scale)

    del m.inverse
    assert isinstance(m.inverse, models.Shift)

def test_render_model_2d():
    imshape = (71, 141)
    image = np.zeros(imshape)
    coords = y, x = np.indices(imshape)

    model = models.Gaussian2D(x_stddev=6.1, y_stddev=3.9, theta=np.pi / 3)

    # test points for edges
    ye, xe = [0, 35, 70], [0, 70, 140]
    # test points for floating point positions
    yf, xf = [35.1, 35.5, 35.9], [70.1, 70.5, 70.9]

    test_pts = [(a, b) for a in xe for b in ye]
    test_pts += [(a, b) for a in xf for b in yf]

    for x0, y0 in test_pts:
        model.x_mean = x0
        model.y_mean = y0
        expected = model(x, y)
        for xy in [coords, None]:
            for im in [image.copy(), None]:
                if (im is None) & (xy is None):
                    # this case is tested in Fittable2DModelTester
                    continue
                actual = model.render(out=im, coords=xy)
                if im is None:
                    assert_allclose(actual, model.render(coords=xy))
                # assert images match
                assert_allclose(expected, actual, atol=3e-7)
                # assert model fully captured
                if (x0, y0) == (70, 35):
                    boxed = model.render()
                    flux = np.sum(expected)
                    assert ((flux - np.sum(boxed)) / flux) < 1e-7
    # test an error is raised when the bounding box is larger than the input array
    try:
        actual = model.render(out=np.zeros((1, 1)))
    except ValueError:
        pass

def test_render_model_1d():
    npix = 101
    image = np.zeros(npix)
    coords = np.arange(npix)

    model = models.Gaussian1D()

    # test points
    test_pts = [0, 49.1, 49.5, 49.9, 100]

    # test widths
    test_stdv = np.arange(5.5, 6.7, 0.2)

    for x0, stdv in [(p, s) for p in test_pts for s in test_stdv]:
        model.mean = x0
        model.stddev = stdv
        expected = model(coords)
        for x in [coords, None]:
            for im in [image.copy(), None]:
                if (im is None) & (x is None):
                    # this case is tested in Fittable1DModelTester
                    continue
                actual = model.render(out=im, coords=x)
                # assert images match
                assert_allclose(expected, actual, atol=3e-7)
                # assert model fully captured
                if (x0, stdv) == (49.5, 5.5):
                    boxed = model.render()
                    flux = np.sum(expected)
                    assert ((flux - np.sum(boxed)) / flux) < 1e-7

@pytest.mark.filterwarnings("ignore:invalid value encountered in less")
def test_render_model_3d():
    imshape = (17, 21, 27)
    image = np.zeros(imshape)
    coords = np.indices(imshape)

    def ellipsoid(x, y, z, x0=13.0, y0=10.0, z0=8.0, a=4.0, b=3.0, c=2.0, amp=1.0):
        rsq = ((x - x0) / a) ** 2 + ((y - y0) / b) ** 2 + ((z - z0) / c) ** 2
        val = (rsq < 1) * amp
        return val

    class Ellipsoid3D(custom_model(ellipsoid)):
        @property
        def bounding_box(self):
            return (
                (self.z0 - self.c, self.z0 + self.c),
                (self.y0 - self.b, self.y0 + self.b),
                (self.x0 - self.a, self.x0 + self.a),
            )

    model = Ellipsoid3D()

    # test points for edges
    ze, ye, xe = [0, 8, 16], [0, 10, 20], [0, 13, 26]
    # test points for floating point positions
    zf, yf, xf = [8.1, 8.5, 8.9], [10.1, 10.5, 10.9], [13.1, 13.5, 13.9]

    test_pts = [(x, y, z) for x in xe for y in ye for z in ze]
    test_pts += [(x, y, z) for x in xf for y in yf for z in zf]

    for x0, y0, z0 in test_pts:
        model.x0 = x0
        model.y0 = y0
        model.z0 = z0
        expected = model(*coords[::-1])
        for c in [coords, None]:
            for im in [image.copy(), None]:
                if (im is None) & (c is None):
                    continue
                actual = model.render(out=im, coords=c)
                boxed = model.render()
                # assert images match
                assert_allclose(expected, actual)
                # assert model fully captured
                if (z0, y0, x0) == (8, 10, 13):
                    boxed = model.render()
                    assert (np.sum(expected) - np.sum(boxed)) == 0

def test_render_model_out_dtype():
    """Test different out.dtype for model.render."""
    MESSAGE = (
        r"Cannot cast ufunc 'add' output from .* to .* with casting rule 'same_kind"
    )
    for model in [models.Gaussian2D(), models.Gaussian2D() + models.Planar2D()]:
        for dtype in [np.float64, np.float32, np.complex64]:
            im = np.zeros((40, 40), dtype=dtype)
            imout = model.render(out=im)
            assert imout is im
            assert imout.sum() != 0

        with pytest.raises(TypeError, match=MESSAGE):
            im = np.zeros((40, 40), dtype=np.int32)
            imout = model.render(out=im)

def test_custom_bounding_box_1d():
    """
    Tests that the bounding_box setter works.
    """
    # 1D models
    g1 = models.Gaussian1D()
    bb = g1.bounding_box
    expected = g1.render()

    # assign the same bounding_box, now through the bounding_box setter
    g1.bounding_box = bb
    assert_allclose(g1.render(), expected)

    # 2D models
    g2 = models.Gaussian2D()
    bb = g2.bounding_box
    expected = g2.render()

    # assign the same bounding_box, now through the bounding_box setter
    g2.bounding_box = bb
    assert_allclose(g2.render(), expected)

def test_n_submodels_in_single_models():
    assert models.Gaussian1D().n_submodels == 1
    assert models.Gaussian2D().n_submodels == 1

def test_compound_deepcopy():
    model = (models.Gaussian1D(10, 2, 3) | models.Shift(2)) & models.Rotation2D(21.3)
    new_model = model.deepcopy()
    assert id(model) != id(new_model)
    assert id(model._leaflist) != id(new_model._leaflist)
    assert id(model[0]) != id(new_model[0])
    assert id(model[1]) != id(new_model[1])
    assert id(model[2]) != id(new_model[2])

@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
def test_units_with_bounding_box():
    points = np.arange(10, 20)
    table = np.arange(10) * u.Angstrom
    t = models.Tabular1D(points, lookup_table=table)

    assert isinstance(t(10), u.Quantity)
    assert isinstance(t(10, with_bounding_box=True), u.Quantity)

    assert_quantity_allclose(t(10), t(10, with_bounding_box=True))

RENAMED_MODEL = models.Gaussian1D.rename("CustomGaussian")

MODEL_RENAME_CODE = """
from astropy.modeling.models import Gaussian1D
print(repr(Gaussian1D))
print(repr(Gaussian1D.rename('CustomGaussian')))
""".strip()

MODEL_RENAME_EXPECTED = b"""
<class 'astropy.modeling.functional_models.Gaussian1D'>
Name: Gaussian1D
N_inputs: 1
N_outputs: 1
Fittable parameters: ('amplitude', 'mean', 'stddev')
<class '__main__.CustomGaussian'>
Name: CustomGaussian (Gaussian1D)
N_inputs: 1
N_outputs: 1
Fittable parameters: ('amplitude', 'mean', 'stddev')
""".strip()

def test_rename_path(tmp_path):
    # Regression test for a bug that caused the path to the class to be
    # incorrect in a renamed model's __repr__.

    assert (
        repr(RENAMED_MODEL).splitlines()[0]
        == "<class 'astropy.modeling.tests.test_core.CustomGaussian'>"
    )

    # Make sure that when called from a user script, the class name includes
    # __main__.

    env = os.environ.copy()
    paths = [os.path.dirname(astropy.__path__[0])] + sys.path
    env["PYTHONPATH"] = os.pathsep.join(paths)

    script = tmp_path / "rename.py"
    with open(script, "w") as f:
        f.write(MODEL_RENAME_CODE)

    output = subprocess.check_output([sys.executable, script], env=env)
    assert output.splitlines() == MODEL_RENAME_EXPECTED.splitlines()

@pytest.mark.parametrize(
    "model_class",
    [models.Gaussian1D, models.Polynomial1D, models.Shift, models.Tabular1D],
)
def test_rename_1d(model_class):
    new_model = model_class.rename(name="Test1D")
    assert new_model.name == "Test1D"

@pytest.mark.parametrize(
    "model_class", [models.Gaussian2D, models.Polynomial2D, models.Tabular2D]
)
def test_rename_2d(model_class):
    new_model = model_class.rename(name="Test2D")
    assert new_model.name == "Test2D"

def test_fix_inputs_integer():
    """
    Tests that numpy integers can be passed as dictionary keys to fix_inputs
    Issue #11358
    """
    m = models.Identity(2)

    mf = models.fix_inputs(m, {1: 22})
    assert mf(1) == (1, 22)

    mf_int32 = models.fix_inputs(m, {np.int32(1): 33})
    assert mf_int32(1) == (1, 33)

    mf_int64 = models.fix_inputs(m, {np.int64(1): 44})
    assert mf_int64(1) == (1, 44)

def test_fix_inputs_empty_dict():
    """
    Tests that empty dictionary can be passed to fix_inputs
    Issue #11355
    """
    m = models.Identity(2)

    mf = models.fix_inputs(m, {})
    assert mf(1, 2) == (1, 2)

def test_rename_inputs_outputs():
    g2 = models.Gaussian2D(10, 2, 3, 1, 2)
    assert g2.inputs == ("x", "y")
    assert g2.outputs == ("z",)

    MESSAGE = r"Expected .* number of .*, got .*"
    with pytest.raises(ValueError, match=MESSAGE):
        g2.inputs = ("w",)

    with pytest.raises(ValueError, match=MESSAGE):
        g2.outputs = ("w", "e")

def test__prepare_output_single_model():
    model = models.Gaussian1D()

    # No broadcast
    assert (
        np.array([1, 2]) == model._prepare_output_single_model(np.array([1, 2]), None)
    ).all()

    # Broadcast to scalar
    assert 1 == model._prepare_output_single_model(np.array([1]), ())
    assert 2 == model._prepare_output_single_model(np.asanyarray(2), ())

    # Broadcast reshape
    output = np.array([[1, 2, 3], [4, 5, 6]])
    reshape = np.array([[1, 2], [3, 4], [5, 6]])
    assert (output == model._prepare_output_single_model(output, (2, 3))).all()
    assert (reshape == model._prepare_output_single_model(output, (3, 2))).all()

    # Broadcast reshape scalar
    assert 1 == model._prepare_output_single_model(np.array([1]), (1, 2))
    assert 2 == model._prepare_output_single_model(np.asanyarray(2), (3, 4))

    # Fail to broadcast
    assert (output == model._prepare_output_single_model(output, (1, 2))).all()
    assert (output == model._prepare_output_single_model(output, (3, 4))).all()

def test_prepare_outputs_mixed_broadcast():
    """
    Tests that _prepare_outputs_single_model does not fail when a smaller
    array is passed as first input, but output is broadcast to larger
    array.
    Issue #10170
    """

    model = models.Gaussian2D(1, 2, 3, 4, 5)

    output = model([1, 2], 3)
    assert output.shape == (2,)
    np.testing.assert_array_equal(output, [0.9692332344763441, 1.0])

    output = model(4, [5, 6])
    assert output.shape == (2,)
    np.testing.assert_array_equal(output, [0.8146473164114145, 0.7371233743916278])

def test_prepare_outputs_complex_reshape():
    x = np.array(
        [
            [1, 2, 3, 4, 5],
            [6, 7, 8, 9, 10],
            [11, 12, 13, 14, 15],
        ]
    )
    y = np.array(
        [
            [16, 17, 18, 19, 20],
            [21, 22, 23, 24, 25],
            [26, 27, 28, 29, 30],
        ]
    )

    m = models.Identity(3) | models.Mapping((2, 1, 0))
    m.bounding_box = ((0, 100), (0, 200), (0, 50))
    mf = models.fix_inputs(m, {2: 22})
    t = mf | models.Mapping((2, 1), n_inputs=3)

    output = mf(1, 2)
    assert output == (22, 2, 1)

    output = t(1, 2)
    assert output == (1, 2)

    output = t(x, y)
    assert len(output) == 2
    np.testing.assert_array_equal(output[0], x)
    np.testing.assert_array_equal(output[1], y)

    m = models.Identity(3) | models.Mapping((0, 1, 2))
    m.bounding_box = ((0, 100), (0, 200), (0, 50))
    mf = models.fix_inputs(m, {2: 22})
    t = mf | models.Mapping((0, 1), n_inputs=3)

    output = mf(1, 2)
    assert output == (1, 2, 22)

    output = t(1, 2)
    assert output == (1, 2)

    output = t(x, y)
    assert len(output) == 2
    np.testing.assert_array_equal(output[0], x)
    np.testing.assert_array_equal(output[1], y)

def test_prepare_outputs_single_entry_vector():
    """
    jwst and gwcs both require that single entry vectors produce single
    entry output vectors, not scalars. This tests for that behavior.
    """

    model = models.Gaussian2D(1, 2, 3, 4, 5)

    output = model(np.array([1]), np.array([2]))
    assert output.shape == (1,)
    np.testing.assert_allclose(output, [0.9500411305585278])

@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
@pytest.mark.filterwarnings("ignore: Using a non-tuple")
def test_prepare_outputs_sparse_grid():
    """
    Test to show that #11060 has been solved.
    """

    shape = (3, 3)
    data = np.arange(np.product(shape)).reshape(shape) * u.m / u.s

    points_unit = u.pix
    points = [np.arange(size) * points_unit for size in shape]

    kwargs = {
        "bounds_error": False,
        "fill_value": np.nan,
        "method": "nearest",
    }

    transform = models.Tabular2D(points, data, **kwargs)
    truth = (
        np.array(
            [
                [0.0, 1.0, 2.0],
                [3.0, 4.0, 5.0],
                [6.0, 7.0, 8.0],
            ]
        )
        * u.m
        / u.s
    )

    points = np.meshgrid(np.arange(3), np.arange(3), indexing="ij", sparse=True)
    x = points[0] * u.pix
    y = points[1] * u.pix
    value = transform(x, y)
    assert (value == truth).all()

    points = (
        np.meshgrid(np.arange(3), np.arange(3), indexing="ij", sparse=False) * u.pix
    )
    value = transform(*points)
    assert (value == truth).all()

def test_coerce_units():
    model = models.Polynomial1D(1, c0=1, c1=2)

    MESSAGE = r"Can only apply 'add' function to dimensionless quantities when other .*"
    with pytest.raises(u.UnitsError, match=MESSAGE):
        model(u.Quantity(10, u.m))

    with_input_units = model.coerce_units({"x": u.m})
    result = with_input_units(u.Quantity(10, u.m))
    assert np.isclose(result, 21.0)

    with_input_units_tuple = model.coerce_units((u.m,))
    result = with_input_units_tuple(u.Quantity(10, u.m))
    assert np.isclose(result, 21.0)

    with_return_units = model.coerce_units(return_units={"y": u.s})
    result = with_return_units(10)
    assert np.isclose(result.value, 21.0)
    assert result.unit == u.s

    with_return_units_tuple = model.coerce_units(return_units=(u.s,))
    result = with_return_units_tuple(10)
    assert np.isclose(result.value, 21.0)
    assert result.unit == u.s

    with_both = model.coerce_units({"x": u.m}, {"y": u.s})

    result = with_both(u.Quantity(10, u.m))
    assert np.isclose(result.value, 21.0)
    assert result.unit == u.s

    with pytest.raises(
        ValueError, match=r"input_units keys.*do not match model inputs"
    ):
        model.coerce_units({"q": u.m})

    with pytest.raises(ValueError, match=r"input_units length does not match n_inputs"):
        model.coerce_units((u.m, u.s))

    model_with_existing_input_units = models.BlackBody()
    with pytest.raises(
        ValueError,
        match=r"Cannot specify input_units for model with existing input units",
    ):
        model_with_existing_input_units.coerce_units({"x": u.m})

    with pytest.raises(
        ValueError, match=r"return_units keys.*do not match model outputs"
    ):
        model.coerce_units(return_units={"q": u.m})

    with pytest.raises(
        ValueError, match=r"return_units length does not match n_outputs"
    ):
        model.coerce_units(return_units=(u.m, u.s))

def test_bounding_box_general_inverse():
    model = NonFittableModel(42.5)

    MESSAGE = r"No bounding box is defined for this model"
    with pytest.raises(NotImplementedError, match=MESSAGE):
        model.bounding_box
    model.bounding_box = ()
    assert model.bounding_box.bounding_box() == ()

    model.inverse = NonFittableModel(3.14)
    inverse_model = model.inverse
    with pytest.raises(NotImplementedError, match=MESSAGE):
        inverse_model.bounding_box

def test__add_special_operator():
    sop_name = "name"
    sop = "value"

    key = _add_special_operator(sop_name, "value")
    assert key[0] == sop_name
    assert key[1] == SPECIAL_OPERATORS._unique_id

    assert key in SPECIAL_OPERATORS
    assert SPECIAL_OPERATORS[key] == sop

def test_print_special_operator_CompoundModel(capsys):
    """
    Test that issue #11310 has been fixed
    """

    model = convolve_models(models.Sersic2D(), models.Gaussian2D())
    with astropy.conf.set_temp("max_width", 80):
        # fmt: off
        assert str(model) == (
            "Model: CompoundModel\n"
            "Inputs: ('x', 'y')\n"
            "Outputs: ('z',)\n"
            "Model set size: 1\n"
            "Expression: convolve_fft (([0]), ([1]))\n"
            "Components: \n"
            "    [0]: <Sersic2D(amplitude=1., r_eff=1., n=4., "
            "x_0=0., y_0=0., ellip=0., theta=0.)>\n"
            "\n"
            "    [1]: <Gaussian2D(amplitude=1., x_mean=0., y_mean=0., "
            "x_stddev=1., y_stddev=1., theta=0.)>\n"
            "Parameters:\n"
            "    amplitude_0 r_eff_0 n_0 x_0_0 y_0_0 ... y_mean_1 x_stddev_1 y_stddev_1 theta_1\n"
            "    ----------- ------- --- ----- ----- ... -------- ---------- ---------- -------\n"
            "            1.0     1.0 4.0   0.0   0.0 ...      0.0        1.0        1.0     0.0"
        )
        # fmt: on

def test__validate_input_shape():
    model = models.Gaussian1D()
    model._n_models = 2

    _input = np.array(
        [
            [1, 2, 3],
            [4, 5, 6],
        ]
    )

    # Successful validation
    assert model._validate_input_shape(_input, 0, model.inputs, 1, False) == (2, 3)

    # Fail number of axes
    MESSAGE = r"For model_set_axis=2, all inputs must be at least 3-dimensional"
    with pytest.raises(ValueError, match=MESSAGE):
        model._validate_input_shape(_input, 0, model.inputs, 2, True)

    # Fail number of models (has argname)
    MESSAGE = r"Input argument '.*' does not have the correct dimensions in .*"
    with pytest.raises(ValueError, match=MESSAGE):
        model._validate_input_shape(_input, 0, model.inputs, 1, True)

    # Fail number of models  (no argname)
    with pytest.raises(ValueError, match=MESSAGE):
        model._validate_input_shape(_input, 0, [], 1, True)

def test__validate_input_shapes():
    model = models.Gaussian1D()
    model._n_models = 2
    inputs = [mk.MagicMock() for _ in range(3)]
    argnames = mk.MagicMock()
    model_set_axis = mk.MagicMock()
    all_shapes = [mk.MagicMock() for _ in inputs]

    # Successful validation
    with mk.patch.object(
        Model, "_validate_input_shape", autospec=True, side_effect=all_shapes
    ) as mkValidate:
        with mk.patch.object(core, "check_broadcast", autospec=True) as mkCheck:
            assert mkCheck.return_value == model._validate_input_shapes(
                inputs, argnames, model_set_axis
            )
            assert mkCheck.call_args_list == [mk.call(*all_shapes)]
            assert mkValidate.call_args_list == [
                mk.call(model, _input, idx, argnames, model_set_axis, True)
                for idx, _input in enumerate(inputs)
            ]

    # Fail check_broadcast
    MESSAGE = r"All inputs must have identical shapes or must be scalars"
    with mk.patch.object(
        Model, "_validate_input_shape", autospec=True, side_effect=all_shapes
    ) as mkValidate:
        with mk.patch.object(
            core, "check_broadcast", autospec=True, return_value=None
        ) as mkCheck:
            with pytest.raises(ValueError, match=MESSAGE):
                model._validate_input_shapes(inputs, argnames, model_set_axis)
            assert mkCheck.call_args_list == [mk.call(*all_shapes)]
            assert mkValidate.call_args_list == [
                mk.call(model, _input, idx, argnames, model_set_axis, True)
                for idx, _input in enumerate(inputs)
            ]

def test__remove_axes_from_shape():
    model = models.Gaussian1D()

    # len(shape) == 0
    assert model._remove_axes_from_shape((), mk.MagicMock()) == ()

    # axis < 0
    assert model._remove_axes_from_shape((1, 2, 3), -1) == (1, 2)
    assert model._remove_axes_from_shape((1, 2, 3), -2) == (1, 3)
    assert model._remove_axes_from_shape((1, 2, 3), -3) == (2, 3)

    # axis >= len(shape)
    assert model._remove_axes_from_shape((1, 2, 3), 3) == ()
    assert model._remove_axes_from_shape((1, 2, 3), 4) == ()

    # 0 <= axis < len(shape)
    assert model._remove_axes_from_shape((1, 2, 3), 0) == (2, 3)
    assert model._remove_axes_from_shape((1, 2, 3), 1) == (3,)
    assert model._remove_axes_from_shape((1, 2, 3), 2) == ()

def test_get_bounding_box():
    model = models.Const2D(2)

    # No with_bbox
    assert model.get_bounding_box(False) is None

    # No bounding_box
    MESSAGE = r"No bounding box is defined for this model"
    with pytest.raises(NotImplementedError, match=MESSAGE):
        model.bounding_box
    assert model.get_bounding_box(True) is None

    # Normal bounding_box
    model.bounding_box = ((0, 1), (0, 1))
    assert not isinstance(model.bounding_box, CompoundBoundingBox)
    assert model.get_bounding_box(True) == ((0, 1), (0, 1))

    # CompoundBoundingBox with no removal
    bbox = CompoundBoundingBox.validate(
        model,
        {(1,): ((-1, 0), (-1, 0)), (2,): ((0, 1), (0, 1))},
        selector_args=[("y", False)],
    )
    model.bounding_box = bbox
    assert isinstance(model.bounding_box, CompoundBoundingBox)
    # Get using argument not with_bbox
    assert model.get_bounding_box(True) == bbox
    # Get using with_bbox not argument
    assert model.get_bounding_box((1,)) == ((-1, 0), (-1, 0))
    assert model.get_bounding_box((2,)) == ((0, 1), (0, 1))

def test_compound_bounding_box():
    model = models.Gaussian1D()
    truth = models.Gaussian1D()
    bbox1 = CompoundBoundingBox.validate(
        model, {(1,): (-1, 0), (2,): (0, 1)}, selector_args=[("x", False)]
    )
    bbox2 = CompoundBoundingBox.validate(
        model, {(-0.5,): (-1, 0), (0.5,): (0, 1)}, selector_args=[("x", False)]
    )

    # Using with_bounding_box to pass a selector
    model.bounding_box = bbox1
    assert model(-0.5) == truth(-0.5)
    assert model(-0.5, with_bounding_box=(1,)) == truth(-0.5)
    assert np.isnan(model(-0.5, with_bounding_box=(2,)))
    assert model(0.5) == truth(0.5)
    assert model(0.5, with_bounding_box=(2,)) == truth(0.5)
    assert np.isnan(model(0.5, with_bounding_box=(1,)))

    # Using argument value to pass bounding_box
    model.bounding_box = bbox2
    assert model(-0.5) == truth(-0.5)
    assert model(-0.5, with_bounding_box=True) == truth(-0.5)
    assert model(0.5) == truth(0.5)
    assert model(0.5, with_bounding_box=True) == truth(0.5)

    MESSAGE = r"No bounding box is defined for selector: .*"
    with pytest.raises(RuntimeError, match=MESSAGE):
        model(0, with_bounding_box=True)

    model1 = models.Gaussian1D()
    truth1 = models.Gaussian1D()
    model2 = models.Const1D(2)
    truth2 = models.Const1D(2)
    model = model1 + model2
    truth = truth1 + truth2
    assert isinstance(model, CompoundModel)

    model.bounding_box = bbox1
    assert model(-0.5) == truth(-0.5)
    assert model(-0.5, with_bounding_box=1) == truth(-0.5)
    assert np.isnan(model(-0.5, with_bounding_box=(2,)))
    assert model(0.5) == truth(0.5)
    assert model(0.5, with_bounding_box=2) == truth(0.5)
    assert np.isnan(model(0.5, with_bounding_box=(1,)))

    model.bounding_box = bbox2
    assert model(-0.5) == truth(-0.5)
    assert model(-0.5, with_bounding_box=True) == truth(-0.5)
    assert model(0.5) == truth(0.5)
    assert model(0.5, with_bounding_box=True) == truth(0.5)
    with pytest.raises(RuntimeError, match=MESSAGE):
        model(0, with_bounding_box=True)

def test_bind_bounding_box():
    model = models.Polynomial2D(3)
    bbox = ((-1, 1), (-2, 2))

    bind_bounding_box(model, bbox)
    assert model.get_bounding_box() is not None
    assert model.bounding_box == bbox
    assert model.bounding_box["x"] == (-2, 2)
    assert model.bounding_box["y"] == (-1, 1)

    bind_bounding_box(model, bbox, order="F")
    assert model.get_bounding_box() is not None
    assert model.bounding_box == bbox
    assert model.bounding_box["x"] == (-1, 1)
    assert model.bounding_box["y"] == (-2, 2)

def test_bind_compound_bounding_box_using_with_bounding_box_select():
    """
    This demonstrates how to bind multiple bounding_boxes which are
    selectable using the `with_bounding_box`, note there must be a
    fall-back to implicit.
    """
    model = models.Gaussian1D()
    truth = models.Gaussian1D()

    bbox = (0, 1)
    MESSAGE = r"'tuple' object has no attribute 'items"
    with pytest.raises(AttributeError, match=MESSAGE):
        bind_compound_bounding_box(model, bbox, "x")

    bbox = {0: (-1, 0), 1: (0, 1)}
    bind_compound_bounding_box(model, bbox, [("x", False)])

    # No bounding box
    assert model(-0.5) == truth(-0.5)
    assert model(0.5) == truth(0.5)
    assert model(0) == truth(0)
    assert model(1) == truth(1)

    # `with_bounding_box` selects as `-0.5` will not be a key
    assert model(-0.5, with_bounding_box=0) == truth(-0.5)
    assert np.isnan(model(-0.5, with_bounding_box=1))

    # `with_bounding_box` selects as `0.5` will not be a key
    assert model(0.5, with_bounding_box=1) == truth(0.5)
    assert np.isnan(model(0.5, with_bounding_box=(0,)))

    # Fall back onto implicit selector
    assert model(0, with_bounding_box=True) == truth(0)
    assert model(1, with_bounding_box=True) == truth(1)

    # Attempt to fall-back on implicit selector, but no bounding_box
    MESSAGE = r"No bounding box is defined for selector: .*"
    with pytest.raises(RuntimeError, match=MESSAGE):
        model(0.5, with_bounding_box=True)

    # Override implicit selector
    assert np.isnan(model(1, with_bounding_box=0))

def test_fix_inputs_compound_bounding_box():
    base_model = models.Gaussian2D(1, 2, 3, 4, 5)
    bbox = {2.5: (-1, 1), 3.14: (-7, 3)}

    model = fix_inputs(base_model, {"y": 2.5}, bounding_boxes=bbox)
    assert model.bounding_box == (-1, 1)
    model = fix_inputs(base_model, {"x": 2.5}, bounding_boxes=bbox)
    assert model.bounding_box == (-1, 1)

    model = fix_inputs(
        base_model, {"y": 2.5}, bounding_boxes=bbox, selector_args=(("y", True),)
    )
    assert model.bounding_box == (-1, 1)
    model = fix_inputs(
        base_model, {"x": 2.5}, bounding_boxes=bbox, selector_args=(("x", True),)
    )
    assert model.bounding_box == (-1, 1)
    model = fix_inputs(
        base_model, {"x": 2.5}, bounding_boxes=bbox, selector_args=((0, True),)
    )
    assert model.bounding_box == (-1, 1)

    base_model = models.Identity(4)
    bbox = {(2.5, 1.3): ((-1, 1), (-3, 3)), (2.5, 2.71): ((-3, 3), (-1, 1))}

    model = fix_inputs(base_model, {"x0": 2.5, "x1": 1.3}, bounding_boxes=bbox)
    assert model.bounding_box == ((-1, 1), (-3, 3))

    model = fix_inputs(
        base_model,
        {"x0": 2.5, "x1": 1.3},
        bounding_boxes=bbox,
        selector_args=(("x0", True), ("x1", True)),
    )
    assert model.bounding_box == ((-1, 1), (-3, 3))
    model = fix_inputs(
        base_model,
        {"x0": 2.5, "x1": 1.3},
        bounding_boxes=bbox,
        selector_args=((0, True), (1, True)),
    )
    assert model.bounding_box == ((-1, 1), (-3, 3))

def test_model_copy_with_bounding_box():
    model = models.Polynomial2D(2)
    bbox = ModelBoundingBox.validate(model, ((-0.5, 1047.5), (-0.5, 2047.5)), order="F")

    # No bbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert model_copy.get_bounding_box() is None
    assert model.get_bounding_box() is None

    # with bbox
    model.bounding_box = bbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert id(model_copy.bounding_box) != id(model.bounding_box)
    for index, interval in model.bounding_box.intervals.items():
        interval_copy = model_copy.bounding_box.intervals[index]
        assert interval == interval_copy
        assert id(interval) != interval_copy

    # add model to compound model
    model1 = model | models.Identity(1)
    model_copy = model1.copy()
    assert id(model_copy) != id(model1)
    assert model_copy.get_bounding_box() is None
    assert model1.get_bounding_box() is None

def test_compound_model_copy_with_bounding_box():
    model = models.Shift(1) & models.Shift(2) & models.Identity(1)
    model.inputs = ("x", "y", "slit_id")
    bbox = ModelBoundingBox.validate(
        model, ((-0.5, 1047.5), (-0.5, 2047.5), (-np.inf, np.inf)), order="F"
    )

    # No bbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert model_copy.get_bounding_box() is None
    assert model.get_bounding_box() is None

    # with bbox
    model.bounding_box = bbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert id(model_copy.bounding_box) != id(model.bounding_box)
    for index, interval in model.bounding_box.intervals.items():
        interval_copy = model_copy.bounding_box.intervals[index]
        assert interval == interval_copy
        assert id(interval) != interval_copy

    # add model to compound model
    model1 = model | models.Identity(3)
    model_copy = model1.copy()
    assert id(model_copy) != id(model1)
    assert model_copy.get_bounding_box() is None
    assert model1.get_bounding_box() is None

def test_model_copy_with_compound_bounding_box():
    model = models.Polynomial2D(2)
    bbox = {(0,): (-0.5, 1047.5), (1,): (-0.5, 3047.5)}
    cbbox = CompoundBoundingBox.validate(
        model, bbox, selector_args=[("x", True)], order="F"
    )

    # No cbbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert model_copy.get_bounding_box() is None
    assert model.get_bounding_box() is None

    # with cbbox
    model.bounding_box = cbbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert id(model_copy.bounding_box) != id(model.bounding_box)
    assert model_copy.bounding_box.selector_args == model.bounding_box.selector_args
    assert id(model_copy.bounding_box.selector_args) != id(
        model.bounding_box.selector_args
    )
    for selector, bbox in model.bounding_box.bounding_boxes.items():
        for index, interval in bbox.intervals.items():
            interval_copy = model_copy.bounding_box.bounding_boxes[selector].intervals[
                index
            ]
            assert interval == interval_copy
            assert id(interval) != interval_copy

    # add model to compound model
    model1 = model | models.Identity(1)
    model_copy = model1.copy()
    assert id(model_copy) != id(model1)
    assert model_copy.get_bounding_box() is None
    assert model1.get_bounding_box() is None

def test_compound_model_copy_with_compound_bounding_box():
    model = models.Shift(1) & models.Shift(2) & models.Identity(1)
    model.inputs = ("x", "y", "slit_id")
    bbox = {
        (0,): ((-0.5, 1047.5), (-0.5, 2047.5)),
        (1,): ((-0.5, 3047.5), (-0.5, 4047.5)),
    }
    cbbox = CompoundBoundingBox.validate(
        model, bbox, selector_args=[("slit_id", True)], order="F"
    )

    # No cbbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert model_copy.get_bounding_box() is None
    assert model.get_bounding_box() is None

    # with cbbox
    model.bounding_box = cbbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert id(model_copy.bounding_box) != id(model.bounding_box)
    assert model_copy.bounding_box.selector_args == model.bounding_box.selector_args
    assert id(model_copy.bounding_box.selector_args) != id(
        model.bounding_box.selector_args
    )
    for selector, bbox in model.bounding_box.bounding_boxes.items():
        for index, interval in bbox.intervals.items():
            interval_copy = model_copy.bounding_box.bounding_boxes[selector].intervals[
                index
            ]
            assert interval == interval_copy
            assert id(interval) != interval_copy

    # add model to compound model
    model1 = model | models.Identity(3)
    model_copy = model1.copy()
    assert id(model_copy) != id(model1)
    assert model_copy.get_bounding_box() is None
    assert model1.get_bounding_box() is None

def test_compound_model_copy_user_attribute():
    """Regression test for issue #12370"""

    model = models.Gaussian2D(100, 25, 25, 5, 5) | models.Identity(1)
    model.xname = "x_mean"  # user-defined attribute
    assert hasattr(model, "xname")
    assert model.xname == "x_mean"

    model_copy = model.copy()
    model_copy.xname
    assert hasattr(model_copy, "xname")
    assert model_copy.xname == "x_mean"

def test_model_mixed_array_scalar_bounding_box():
    """Regression test for issue #12319"""

    model = models.Gaussian2D()
    bbox = ModelBoundingBox.validate(model, ((-1, 1), (-np.inf, np.inf)), order="F")
    model.bounding_box = bbox

    x = np.array([-0.5, 0.5])
    y = 0

    # Everything works when its all in the bounding box
    assert (model(x, y) == (model(x, y, with_bounding_box=True))).all()

def test_compound_model_mixed_array_scalar_bounding_box():
    """Regression test for issue #12319"""

    model = models.Shift(1) & models.Shift(2) & models.Identity(1)
    model.inputs = ("x", "y", "slit_id")
    bbox = ModelBoundingBox.validate(
        model, ((-0.5, 1047.5), (-0.5, 2047.5), (-np.inf, np.inf)), order="F"
    )
    model.bounding_box = bbox
    x = np.array([1000, 1001])
    y = np.array([2000, 2001])
    slit_id = 0

    # Everything works when its all in the bounding box
    value0 = model(x, y, slit_id)
    value1 = model(x, y, slit_id, with_bounding_box=True)
    assert_equal(value0, value1)

def test_model_with_bounding_box_true_and_single_output():
    """Regression test for issue #12373"""

    model = models.Mapping((1,))
    x = [1, 2]
    y = [3, 4]

    # Check baseline
    assert_equal(model(x, y), [3, 4])
    # Check with_bounding_box=True should be the same
    assert_equal(model(x, y, with_bounding_box=True), [3, 4])

    model.bounding_box = ((-np.inf, np.inf), (-np.inf, np.inf))
    # Check baseline
    assert_equal(model(x, y), [3, 4])
    # Check with_bounding_box=True should be the same
    assert_equal(model(x, y, with_bounding_box=True), [3, 4])

def test_compound_model_with_bounding_box_true_and_single_output():
    """Regression test for issue #12373"""

    model = models.Mapping((1,)) | models.Shift(1)
    x = [1, 2]
    y = [3, 4]

    # Check baseline
    assert_equal(model(x, y), [4, 5])
    # Check with_bounding_box=True should be the same
    assert_equal(model(x, y, with_bounding_box=True), [4, 5])

    model.bounding_box = ((-np.inf, np.inf), (-np.inf, np.inf))
    # Check baseline
    assert_equal(model(x, y), [4, 5])
    # Check with_bounding_box=True should be the same
    assert_equal(model(x, y, with_bounding_box=True), [4, 5])

def test_bounding_box_pass_with_ignored():
    """Test the possiblity of setting ignored variables in bounding box"""

    model = models.Polynomial2D(2)
    bbox = ModelBoundingBox.validate(model, (-1, 1), ignored=["y"])
    model.bounding_box = bbox
    assert model.bounding_box.bounding_box() == (-1, 1)
    assert model.bounding_box == bbox

    model = models.Polynomial2D(2)
    bind_bounding_box(model, (-1, 1), ignored=["y"])
    assert model.bounding_box.bounding_box() == (-1, 1)
    assert model.bounding_box == bbox

def test_compound_bounding_box_pass_with_ignored():
    model = models.Shift(1) & models.Shift(2) & models.Identity(1)
    model.inputs = ("x", "y", "slit_id")
    bbox = {
        (0,): (-0.5, 1047.5),
        (1,): (-0.5, 2047.5),
    }
    cbbox = CompoundBoundingBox.validate(
        model, bbox, selector_args=[("slit_id", True)], ignored=["y"], order="F"
    )
    model.bounding_box = cbbox

    model = models.Shift(1) & models.Shift(2) & models.Identity(1)
    model.inputs = ("x", "y", "slit_id")
    bind_compound_bounding_box(
        model, bbox, selector_args=[("slit_id", True)], ignored=["y"], order="F"
    )
    assert model.bounding_box == cbbox

@pytest.mark.parametrize("int_type", [int, np.int32, np.int64, np.uint32, np.uint64])
def test_model_integer_indexing(int_type):
    """Regression for PR 12561; verify that compound model components
    can be accessed by integer index"""
    gauss = models.Gaussian2D()
    airy = models.AiryDisk2D()
    compound = gauss + airy

    assert compound[int_type(0)] == gauss
    assert compound[int_type(1)] == airy

def test_model_string_indexing():
    """Regression for PR 12561; verify that compound model components
    can be accessed by indexing with model name"""
    gauss = models.Gaussian2D()
    gauss.name = "Model1"
    airy = models.AiryDisk2D()
    airy.name = "Model2"
    compound = gauss + airy

    assert compound["Model1"] == gauss
    assert compound["Model2"] == airy


text:
layout: postag
title: 'VERB'
shortdef: 'verb'
udver: '2'
---

### Definition

A verb is a member of the syntactic class of words that typically
signal events and actions, can constitute a minimal predicate in a
clause, and govern the number and types of other constituents which
may occur in the clause. Verbs are often associated with grammatical
categories like tense, mood, aspect and voice, which can either be
expressed inflectionally or using auxilliary verbs or particles.

Note that the `VERB` tag covers main verbs _(content verbs)_
but it does not cover _auxiliary verbs_ and verbal _copulas_
(in the narrow sense), for which there is
the [AUX]() tag. _Modal verbs_ may be considered `VERB` or `AUX`,
depending on their behavior in the given language. Language-specific
documentation should specify which verbs are tagged `AUX` in which
contexts.

Note that _participles_ are word forms that may share properties and
usage of adjectives and verbs. Depending on language and context, they
may be classified as either `VERB` or [ADJ]().

Note that some verb forms such as _gerunds_ and _infinitives_ may
share properties and usage of nouns and verbs. Depending on language
and context, they may be classified as either `VERB` or [NOUN]().

Note that there are verb forms such as _converbs (transgressives)_ or _adverbial
participles_ that share properties and usage of adverbs and
verbs. Depending on language and context, they may be classified as
either `VERB` or [ADV]().

### Examples

- _run, eat_
- _runs, ate_
- _running, eating_

### References

- [Loos, Eugene E., et al. 2003. Glossary of linguistic terms: What is a verb?](http://www-01.sil.org/linguistics/GlossaryOfLinguisticTerms/WhatIsAVerbLinguistics.htm)
- [Wikipedia](http://en.wikipedia.org/wiki/Verb)


text:
using Abp.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;

namespace Abp.AspNetCore.App.Controllers
{
    public class ResponseCacheTestController : AbpController
    {
        [HttpGet]
        [Route("ResponseCacheTest/Get")]
        public int Get()
        {
            return 42;
        }

        [HttpGet]
        [Route("ResponseCacheTest/GetWithCache")]
        [ResponseCache(Duration = 60)]
        public int GetWithCache()
        {
            return 42;
        }

        [HttpGet]
        [Route("ResponseCacheTest/GetWithoutCache")]
        [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
        public int GetWithoutCache()
        {
            return 42;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/sgml/loosedtd.html">

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Registering Hextrapolate</title>
<meta name="author" content="Wincent Colaiuta">
<meta name="author-email" content="win@wincent.com">
<meta name="copyright" content="Copyright 2007-2010 Wincent Coliauta">
<meta name="description" content="">
<link href="../css/base.css" rel="stylesheet" media="all" type="text/css">

Hextrapolate Help

Index

Registering Hextrapolate

Once you have purchased a Hextrapolate license you will receive a license code via email. To complete the registration you will copy your license code from the email into Hextrapolate.

To register your copy of Hextrapolate:

From the Hextrapolate menu select Register…

When the registration preference pane appears, click the "Enter license code" button

When the confirmation sheet drops down, enter your email address exactly as it appears in your license notice (if you enter a different address your license will not work) into the text field labelled "Email address"

In the field labelled "License code", enter your license code exactly as it appears in your license notice; license codes are quite long so the best way to do this is to use copy and paste (you can copy the entire code at once as a single slab of text)

Click the Verify button to activate your license

Screenshots

See also

Activation

Unregistering Hextrapolate

Transferring your license to another machine


text:
                                 Add Vendor

                                 <input type="text" name="add_vendor_name" id="add_vendor_name" placeholder="Vendor Name"/>

                                 <input type="text" name="add_owner_name" id="add_owner_name" placeholder="Owner Name"/>

                                 <input type="text" name="add_address" id="add_address" placeholder="Address"/>

                                 <input type="text" name="add_contact" id="add_contact" placeholder="Contact"/>

                                    Submit

                              Print

                              <button type="button" class="close" data-dismiss="modal">×Close</button>

Edit Vendor Detail


text:
EventDrops
==========

A time based / event series interactive visualization using d3.js. Use drag and zoom to navigate in time.

![EventDrops example](http://static.marmelab.com/EventDrops.gif)

## Installation

You can use npm to install event-drops
```
npm install event-drops --save
```

Additionally you can also use bower
```
bower install event-drops --save
```

## Usage

Include the `src/eventDrops.js` script in your page after d3:

```html
<script src="path/to/d3.js"></script>
<script src="src/eventDrops.js"></script>
```

**Tip**: You can also use RequireJs, see [example/amd](https://github.com/marmelab/EventDrops/tree/master/example/amd) for an implementation.

In the HTML source, create a new EventDrops chart, bind data to a DOM element, then call the chart on the element.

```js
var eventDropsChart = d3.chart.eventDrops();
d3.select('#chart_placeholder')
  .datum(data)
  .call(eventDropsChart);
```

The data must be an array of named time series. For instance:

```js
var data = [
  { name: "http requests", dates: [new Date('2014/09/15 13:24:54'), new Date('2014/09/15 13:25:03'), new Date('2014/09/15 13:25:05'), ...] },
  { name: "SQL queries", dates: [new Date('2014/09/15 13:24:57'), new Date('2014/09/15 13:25:04'), new Date('2014/09/15 13:25:04'), ...] },
  { name: "cache invalidations", dates: [new Date('2014/09/15 13:25:12'), ...] }
];
```

## Configuration

EventDrops follows the [d3.js reusable charts pattern](http://bost.ocks.org/mike/chart/) to let you customize the chart at will:

```js
var eventDropsChart = d3.chart.eventDrops()
  .width(1200)
  .hasTopAxis(false);
```

Configurable values:

  - `start`: start date of the scale. Defaults to `new Date(0)`.
  - `end`: end date of the scale. Defaults to `new Date()`
  - `width`: width of the chart in pixels. Default to 1000px.
  - `margin`: margins of the graph in pixels. Defaults to `{ top: 60, left: 200, bottom: 40, right: 50 }`
  - `locale`: locale used for the X axis labels. See [d3.locale](https://github.com/mbostock/d3/wiki/Localization#locale) for the expected format. Defaults to null (i.e. d3 default locale).
  - `axisFormat`: function receiving the d3 axis object, to customize tick number and size.
  - `tickFormat`: tickFormat for the X axis. See [d3.timeFormat.multi()](https://github.com/mbostock/d3/wiki/Time-Formatting#format_multi) for expected format.
  - `eventHover`: function to be called when hovering an event in the chart. Receives the DOM element hovered (uses event delegation).
  - `eventZoom`: function to be called when done zooming on the chart. Receives the d3 scale at the end of the zoom.
  - `hasDelimiter`: whether to draw time boundaries on top of the chart. Defaults to true.
  - `hasTopAxis`: whether the chart has a top X axis. Accepts both a boolean or a function receiving the data of the graph that returns a boolean.
  - `hasBottomAxis`: same as topAxis but for the bottom X axis
  - `eventLineColor`: The color of the event line. Accepts a color (color name or `#ffffff` notation), or a function receiving the eventData and returning a color. Defaults to 'black'.
  - `eventColor`: The color of the event. Accepts a color (color name or `#ffffff` notation), or a function receiving the eventData and returning a color. Defaults to null. EventLineColor will be ignored if this is used.
  - `minScale`: The minimum scaling (zoom out), default to 0.
  - `maxScale`: The maximum scaling (zoom in), default to Infinity.

## Styling

You can style all elements of the chart in CSS. Check the source to see the available selectors.

## Extending / Hacking

First, install the dependencies:

```sh
$ npm install
```

Source files are located under the `lib/` folder, and use [browserify](http://browserify.org/) for dependency management.
Once your changes are finished, regenerate the combined and minified source under `src/` by calling the following command:

```sh
$ gulp browserify
```

To update your change dynamically and have sourcemap that allow the console to map to the original file type:
```
$ gulp watch
```

To run the test :
```
$ gulp test // all test
$ gulp karma-test
$ gulp mocha-test
```
You can test the result by launching a server at the project root, and navigating to the `examples/` directory.

## License

EventDrops is released under the MIT License, courtesy of [marmelab](http://marmelab.com) and [Canal Plus](https://github.com/canalplus).


text:
package validator

import (
	"fmt"
	"math/big"

	"github.com/hyperledger/burrow/crypto"
)

// Ring stores the validator power history in buckets as a ring buffer. The primary storage is a the difference between
// each rotation (commit - i.e. block) in 'delta' and the cumulative result of each delta in cum, where the result of
// the delta at i is stored in the cum at i+1. For example suppose we have 4 buckets then graphically:
//
// delta [d1| d2  |   d3    |    d4      ]
// cum   [v0|v0+d1|v0+d1+d2 |v0+d1+d2+d3 ]
//
// After the fourth rotation we loop back to the 0th bucket (with [pwer
//
// delta [d5            | d6| d7   | d8  ]
// cum   [v0+d1+d2+d3+d4|...|      |     ]
type Ring struct {
	buckets []*Bucket
	// Power tracks the sliding sum of all powers for each validator added by each delta bucket - power is added for the newest delta and subtracted from the oldest delta each rotation
	power *Set
	// Index of current head bucket
	head int
	// Number of buckets
	size int
	// Number of buckets that have so far had any increments made to them - equivalently the number of rotations made up to a maximum of the number of buckets available
	populated int
}

var _ History = &Ring{}

// NewRing provides a sliding window over the last size buckets of validator power changes
func NewRing(initialSet Iterable, windowSize int) *Ring {
	if windowSize < 1 {
		windowSize = 1
	}
	vc := &Ring{
		buckets: make([]*Bucket, windowSize),
		power:   NewTrimSet(),
		size:    windowSize,
	}
	for i := 0; i < windowSize; i++ {
		vc.buckets[i] = NewBucket()
	}
	if initialSet != nil {
		vc.populated = 1
		vc.buckets[0] = NewBucket(initialSet)
	}
	return vc
}

// Implement Reader

// Power gets the balance at index from the delta bucket then falling through to the cumulative
func (vc *Ring) Power(id crypto.Address) (*big.Int, error) {
	return vc.GetPower(id), nil
}

func (vc *Ring) GetPower(id crypto.Address) *big.Int {
	return vc.Head().Previous.GetPower(id)
}

func (vc *Ring) SetPower(id *crypto.PublicKey, power *big.Int) (*big.Int, error) {
	return vc.Head().SetPower(id, power)
}

// CumulativePower gets the sum of all powers added in any bucket
func (vc *Ring) CumulativePower() *Set {
	return vc.power
}

// Rotate the current head bucket to the next bucket and returns the change in total power between the previous bucket
// and the current head, and the total flow which is the sum of absolute values of all changes each validator's power
// after rotation the next head is a copy of the current head
func (vc *Ring) Rotate() (totalPowerChange *big.Int, totalFlow *big.Int, err error) {
	// Subtract the tail bucket (if any) from the total
	err = Subtract(vc.power, vc.Next().Delta)
	if err != nil {
		return
	}
	// Capture current head as previous before advancing buffer
	prevHead := vc.Head()
	// Add head delta to total power
	err = Add(vc.power, prevHead.Delta)
	if err != nil {
		return
	}
	// Advance the ring buffer
	vc.head = vc.index(1)
	// Overwrite new head bucket (previous tail) with a fresh bucket with Previous_i+1 = Next_i = Previous_i + Delta_i
	vc.buckets[vc.head] = NewBucket(prevHead.Next)
	// Capture flow before we wipe it
	totalFlow = prevHead.Flow.totalPower
	// Subtract the previous bucket total power so we can add on the current buckets power after this
	totalPowerChange = new(big.Int).Sub(vc.Head().Previous.TotalPower(), prevHead.Previous.TotalPower())
	// Record how many of our buckets we have cycled over
	if vc.populated < vc.size {
		vc.populated++
	}
	return
}

func (vc *Ring) ReIndex(newHead int) {
	buckets := make([]*Bucket, len(vc.buckets))
	for i := 0; i < len(buckets); i++ {
		buckets[(i+newHead)%len(buckets)] = vc.buckets[vc.index(i)]
	}
	vc.head = newHead
	vc.buckets = buckets
}

func (vc *Ring) CurrentSet() *Set {
	return vc.Head().Previous
}

// Get the current accumulator bucket
func (vc *Ring) Head() *Bucket {
	return vc.buckets[vc.head]
}

func (vc *Ring) ValidatorChanges(blocksAgo int) IterableReader {
	return vc.PreviousDelta(blocksAgo)
}

func (vc *Ring) Validators(blocksAgo int) IterableReader {
	return vc.PreviousSet(blocksAgo)
}

func (vc *Ring) PreviousSet(delay int) *Set {
	// report the oldest cumulative set (i.e. genesis) if given a longer delay than populated
	if delay >= vc.populated {
		delay = vc.populated - 1
	}
	return vc.buckets[vc.index(-delay)].Previous
}

func (vc *Ring) PreviousDelta(delay int) *Set {
	if delay >= vc.populated {
		return NewSet()
	}
	return vc.buckets[vc.index(-delay)].Delta
}

func (vc *Ring) Next() *Bucket {
	return vc.buckets[vc.index(1)]
}

func (vc *Ring) index(i int) int {
	return (vc.size + vc.head + i) % vc.size
}

// Get the number of buckets in the ring (use Current().Count() to get the current number of validators)
func (vc *Ring) Size() int {
	return vc.size
}

// Returns buckets in order head, previous, ...
func (vc *Ring) OrderedBuckets() []*Bucket {
	buckets := make([]*Bucket, len(vc.buckets))
	for i := int(0); i < vc.size; i++ {
		index := vc.index(-i)
		buckets[i] = vc.buckets[index]
	}
	return buckets
}

func (vc *Ring) String() string {
	buckets := vc.OrderedBuckets()
	return fmt.Sprintf("ValidatorsRing{Total: %v; Buckets: %v}", vc.power, buckets)
}

func (vc *Ring) Equal(vcOther *Ring) error {
	if vc.size != vcOther.size {
		return fmt.Errorf("ring size %d != other ring size %d", vc.size, vcOther.size)
	}
	if vc.head != vcOther.head {
		return fmt.Errorf("ring head index %d != other head index %d", vc.head, vcOther.head)
	}
	err := vc.power.Equal(vcOther.power)
	if err != nil {
		return fmt.Errorf("ring power != other ring power: %v", err)
	}
	for i := 0; i < len(vc.buckets); i++ {
		err = vc.buckets[i].Equal(vcOther.buckets[i])
		if err != nil {
			return fmt.Errorf("ring buckets do not match at index %d: %v", i, err)
		}
	}
	return nil
}


text:
using namespace Core;

namespace SDLut
{
namespace font
{
FontImpl::FontImpl()  throw (std::logic_error)
try:
    pvm_fontsurf(0)
{
    system::RWOps res(resources::_defaultFont,sizeof(resources::_defaultFont));
    pvm_fontsurf.reset(new video::internal::RGBSurface(res));
    //checking initialized font
    if ( ( pvm_fontsurf.get() == 0 ) || ( ! pvm_fontsurf->initialized() ) )
    {
        throw std::logic_error("Error initializing default Font !");
    }
}
catch (std::exception& e)
{
    Log << nl << "Exception caught in internal FontImpl constructor : " << e.what();
}

std::map<char, video::Rect> FontImpl::InitAlphaLookup()
{
    std::map<char, video::Rect> result;
#define ASSOCIATE( key, x, y ) result[key] = video::Rect( 14 * x, 16 * y, 14, 16 );
#include "SDLFontLookup.inl"
#undef ASSOCIATE

    return result;
}

std::map<char, video::Rect> FontImpl::alphalookup = FontImpl::InitAlphaLookup();

video::Rect FontImpl::getSize(const std::string & text) const
{
    //number of lines in text -> todo
    //number of character max per line
    video::Rect r(0,0,text.size() * 14,16);
    return r;
}

int FontImpl::height()
{
    return 16;
}

FontImpl::FontImpl(const FontImpl & font) throw (std::logic_error)
try :
    pvm_fontsurf(0)
{
    //deep copy of the RGB Surface
    pvm_fontsurf.reset( new video::internal::RGBSurface(*(font.pvm_fontsurf)) );
    if ( pvm_fontsurf.get() == 0 )
        throw std::logic_error("RGBSurface for fontsurf is NULL");
}
catch (std::exception& e)
{
    Log << nl << "Exception caught in internal FontImpl copy constructor : " << e.what();
}

FontImpl & FontImpl::operator=(const FontImpl & font) throw (std::logic_error)
{
    //deep copy of the RGB Surface
    pvm_fontsurf.reset( new video::internal::RGBSurface(*(font.pvm_fontsurf)) );
    if ( pvm_fontsurf.get() == 0 )
        throw std::logic_error("RGBSurface for fontsurf is NULL");

    return * this;
}

FontImpl::~FontImpl()
{

    //statically initialized, so we shouldnt clear here
    //alphalookup.clear();
}

std::auto_ptr<video::internal::RGBSurface> FontImpl::render(const std::string & text,video::Color c, video::Color bgc, Font::RenderMode mode) const
{

    std::auto_ptr<video::internal::RGBSurface> result( new video::internal::OGL::GLSurface( getSize(text).getw(), getSize(text).geth(), 16) );
    //std::auto_ptr<SDL_Surface> result(SDL_CreateRGBSurface(SDL_SWSURFACE, getSize(text).getw(), getSize(text).geth(), 16, BaseSurface::r_default_mask, BaseSurface::g_default_mask, BaseSurface::b_default_mask, BaseSurface::a_default_mask));
    //Log << getSize(text);
    for (unsigned int i= 0; i< text.size(); i++)
    {
        video::Rect src(i*14,0,14,16);
        result->blit(*pvm_fontsurf, src,alphalookup[text[i]]);
        //
        //TODO : better if we code that directly in SDL, as we wont be affected by other code parts changes...
        //
        //Rect txtrect = alphalookup[text[i]];
        //Log << nl << "Txtrect X : "<< txtrect.getx() << " Y : "<< txtrect.gety() << " W : " << txtrect.getw() << " H : " << txtrect.geth() ;
        //Log.flush();

        //Rect charrect(0,i*14,14,16);
        //Log << nl << "Charrect X : "<< charrect.getx() << " Y : "<< charrect.gety() << " W : " << charrect.getw() << " H : " << charrect.geth() ;
        //Log.flush();

        //BUG here : only first letter is blitted.. why ???
        //SDL_BlitSurface(const_cast<SDL_Surface*>(_fontsurf->get_pSDL()),
        //                const_cast<SDL_Rect*>(txtrect.get_pSDL()),
        //                const_cast<SDL_Surface*>(result->get_pSDL()),
        //                const_cast<SDL_Rect*>(charrect.get_pSDL()));

        //result->saveBMP( text + "_fimpl.bmp");

    }

    //beware : ownership transferred for auto_ptr
    return result;
}

}
}