text:
package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.hasMethod;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isStatic;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
import static com.google.errorprone.matchers.Matchers.methodHasVisibility;
import static com.google.errorprone.matchers.Matchers.methodIsNamed;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.variableType;
import static com.google.errorprone.suppliers.Suppliers.BOOLEAN_TYPE;
import static com.google.errorprone.suppliers.Suppliers.JAVA_LANG_BOOLEAN_TYPE;
import static com.google.errorprone.suppliers.Suppliers.OBJECT_TYPE;
import static com.sun.tools.javac.code.Flags.ENUM;

import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MethodVisibility.Visibility;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.Name;

/** Bug checker for equals methods that don't actually override equals. */
@BugPattern(
    summary = "equals method doesn't override Object.equals",
    severity = WARNING,
    tags = StandardTags.FRAGILE_CODE)
public class NonOverridingEquals extends BugChecker implements MethodTreeMatcher {

  private static final String MESSAGE_BASE = "equals method doesn't override Object.equals";

  /**
   * Matches any method definition that: 1) is named `equals` 2) takes a single argument of a type
   * other than Object 3) returns a boolean or Boolean
   */
  private static final Matcher<MethodTree> MATCHER =
      allOf(
          methodIsNamed("equals"),
          methodHasParameters(variableType(not(isSameType("java.lang.Object")))),
          anyOf(methodReturns(BOOLEAN_TYPE), methodReturns(JAVA_LANG_BOOLEAN_TYPE)));

  /** Matches if the enclosing class overrides Object#equals. */
  private static final Matcher<MethodTree> enclosingClassOverridesEquals =
      enclosingClass(
          hasMethod(
              allOf(
                  methodIsNamed("equals"),
                  methodReturns(BOOLEAN_TYPE),
                  methodHasParameters(variableType(isSameType(OBJECT_TYPE))),
                  not(isStatic()))));

  /**
   * Matches method declarations for which we cannot provide a fix. Our default fix rewrites the
   * equals method to override Object.equals. In these (uncommon) cases, our rewrite algorithm
   * doesn't work:
   *
   *

   *
the method is static
   *
the method is not public
   *
the method returns a boxed Boolean
   *

   */
  private static final Matcher<MethodTree> noFixMatcher =
      anyOf(
          isStatic(),
          not(methodHasVisibility(Visibility.PUBLIC)),
          methodReturns(JAVA_LANG_BOOLEAN_TYPE));

  @Override
  public Description matchMethod(MethodTree methodTree, VisitorState state) {
    if (!MATCHER.matches(methodTree, state)) {
      return Description.NO_MATCH;
    }

    // If an overriding equals method has already been defined in the enclosing class, assume
    // this is a type-specific helper method and give advice to either inline it or rename it.
    if (enclosingClassOverridesEquals.matches(methodTree, state)) {
      return buildDescription(methodTree)
          .setMessage(
              MESSAGE_BASE
                  + "; if this is a type-specific helper for a method that does"
                  + " override Object.equals, either inline it into the callers or rename it to"
                  + " avoid ambiguity")
          .build();
    }

    // Don't provide a fix if the method is static, non-public, or returns a boxed Boolean
    if (noFixMatcher.matches(methodTree, state)) {
      return describeMatch(methodTree);
    }

    JCClassDecl cls = (JCClassDecl) state.findEnclosing(ClassTree.class);

    if ((cls.getModifiers().flags & ENUM) != 0) {
      /* If the enclosing class is an enum, then just delete the equals method since enums
       * should always be compared for reference equality. Enum defines a final equals method for
       * just this reason. */
      return buildDescription(methodTree)
          .setMessage(
              MESSAGE_BASE
                  + "; enum instances can safely be compared by reference "
                  + "equality, so please delete this")
          .addFix(SuggestedFix.delete(methodTree))
          .build();
    } else {
      /* Otherwise, change the covariant equals method to override Object.equals. */

      SuggestedFix.Builder fix = SuggestedFix.builder();

      // Add @Override annotation if not present.
      if (ASTHelpers.getAnnotation(methodTree, Override.class) == null) {
        fix.prefixWith(methodTree, "@Override\n");
      }

      // Change method signature, substituting Object for parameter type.
      JCTree parameterType = (JCTree) methodTree.getParameters().get(0).getType();
      Name parameterName = ((JCVariableDecl) methodTree.getParameters().get(0)).getName();
      fix.replace(parameterType, "Object");

      // If there is a method body...
      if (methodTree.getBody() != null) {

        // Add type check at start
        String typeCheckStmt =
            "if (!("
                + parameterName
                + " instanceof "
                + state.getSourceForNode(parameterType)
                + ")) {\n"
                + "  return false;\n"
                + "}\n";
        fix.prefixWith(methodTree.getBody().getStatements().get(0), typeCheckStmt);

        // Cast all uses of the parameter name using a recursive TreeScanner.
        new CastScanner()
            .scan(
                methodTree.getBody(),
                new CastState(parameterName, state.getSourceForNode(parameterType), fix));
      }

      return describeMatch(methodTree, fix.build());
    }
  }

  private static class CastState {
    final Name name;
    final String castToType;
    final SuggestedFix.Builder fix;

    public CastState(Name name, String castToType, SuggestedFix.Builder fix) {
      this.name = name;
      this.castToType = castToType;
      this.fix = fix;
    }
  }

  /** A Scanner used to replace all references to a variable with a casted version. */
  private static class CastScanner extends TreeScanner<Void, CastState> {
    @Override
    public Void visitIdentifier(IdentifierTree node, CastState state) {
      if (state.name.equals(node.getName())) {
        state.fix.replace(node, "((" + state.castToType + ") " + state.name + ")");
      }

      return super.visitIdentifier(node, state);
    }
  }
}


text:
<?php

namespace Daken\ReleaseProfilerBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * DatabaseQueryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class DatabaseQueryRepository extends EntityRepository
{
}

redpajama_set_name: RedPajamaGithub


text:
from deuce.tests import V1Base
from deuce.model import File

class TestFilesModel(V1Base):

    def setUp(self):
        super(TestFilesModel, self).setUp()

        # Create a vault and a file for us to work with
        vault_name = 'files_vault_test'
        fileid = 'My_Testing_File_Id'
        self._file = File('test_projectd_id', vault_name, fileid)

    def tests(self):
        retval = self._file.file_id
        retval = self._file.vault_id
        retval = self._file.finalized


text:
package org.deidentifier.arx.gui.view.impl.menu;

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

import org.deidentifier.arx.gui.model.ModelCriterion;
import org.deidentifier.arx.gui.model.ModelDPresenceCriterion;
import org.deidentifier.arx.gui.resources.Resources;
import org.deidentifier.arx.gui.view.SWTUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import de.linearbits.swt.widgets.Knob;

/**
 * A view on a d-presence criterion.
 *
 * @author Fabian Prasser
 */
public class EditorCriterionDPresence extends EditorCriterion<ModelDPresenceCriterion>{

    /** View */
    private Knob<Double> knobDMin;

    /** View */
    private Knob<Double> knobDMax;

    /** View */
    private Text         labelDMin;

    /** View */
    private Text         labelDMax;

    /**
     * Creates a new instance.
     *
     * @param parent
     * @param model
     */
    public EditorCriterionDPresence(final Composite parent,
                                  final ModelDPresenceCriterion model) {
        super(parent, model);
    }

    /**
     * Build
     * @param parent
     * @return
     */
    protected Composite build(Composite parent) {

        // Create input group
        final Composite group = new Composite(parent, SWT.NONE);
        group.setLayoutData(SWTUtil.createFillHorizontallyGridData());
        final GridLayout groupInputGridLayout = new GridLayout();
        groupInputGridLayout.numColumns = 6;
        group.setLayout(groupInputGridLayout);

        // Create dmin slider
        final Label zLabel = new Label(group, SWT.NONE);
        zLabel.setText(Resources.getMessage("CriterionDefinitionView.50")); //$NON-NLS-1$

        labelDMin = createLabel(group);
        knobDMin = createKnobDouble(group, 0d, 1d);
        updateLabel(labelDMin, knobDMin.getValue());
        knobDMin.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(final SelectionEvent arg0) {
                model.setDmin(knobDMin.getValue());
                updateLabel(labelDMin, model.getDmin());

                if (model.getDmin() > model.getDmax()) {
                    model.setDmax(model.getDmin());
                    updateLabel(labelDMax, model.getDmin());
                    knobDMax.setValue(knobDMin.getValue());
                }
            }
        });

        // Create dax slider
        final Label z2Label = new Label(group, SWT.NONE);
        z2Label.setText(Resources.getMessage("CriterionDefinitionView.51")); //$NON-NLS-1$

        labelDMax = createLabel(group);
        knobDMax = createKnobDouble(group, 0d, 1d);
        updateLabel(labelDMax, knobDMax.getValue());
        knobDMax.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(final SelectionEvent arg0) {
                model.setDmax(knobDMax.getValue());
                updateLabel(labelDMax, model.getDmax());

                if (model.getDmax() < model.getDmin()) {
                    model.setDmin(model.getDmax());
                    updateLabel(labelDMin, model.getDmax());
                    knobDMin.setValue(knobDMax.getValue());
                }
            }
        });

        return group;
    }

    @Override
    protected List<ModelCriterion> getTypicalParameters() {

        List<ModelCriterion> result = new ArrayList<ModelCriterion>();
        result.add(new ModelDPresenceCriterion(0.00d, 0.05d));
        result.add(new ModelDPresenceCriterion(0.00d, 0.06d));
        result.add(new ModelDPresenceCriterion(0.00d, 0.07d));
        result.add(new ModelDPresenceCriterion(0.00d, 0.08d));
        result.add(new ModelDPresenceCriterion(0.00d, 0.09d));
        result.add(new ModelDPresenceCriterion(0.00d, 0.10d));
        result.add(new ModelDPresenceCriterion(0.00d, 0.20d));
        result.add(new ModelDPresenceCriterion(0.00d, 0.50d));
        result.add(new ModelDPresenceCriterion(0.00d, 0.70d));
        result.add(new ModelDPresenceCriterion(0.04d, 0.05d));
        result.add(new ModelDPresenceCriterion(0.01d, 0.05d));
        return result;
    }

    /**
     * Parses the input
     */
    protected void parse(ModelDPresenceCriterion model, boolean _default) {
        updateLabel(labelDMin, model.getDmin());
        knobDMin.setValue(model.getDmin());
        updateLabel(labelDMax, model.getDmax());
        knobDMax.setValue(model.getDmax());
    }
}


text:
<BroadcastMonitor>
  <updated>2015-08-05T12:36:43</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-05T12:36:43</startTime>
    <itemId>1000080537:1241340</itemId>
    <titleId>216117150</titleId>
    <itemCode>08643</itemCode>
    <itemReference></itemReference>
    <titleName>Hands</titleName>
    <artistName>Macy Gray</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>228</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-05T12:40:17</startTime>
    <itemId>1000080537:1241341</itemId>
    <titleId>190149587</titleId>
    <itemCode>JFX1217-0009</itemCode>
    <itemReference>JFX1217-0009</itemReference>
    <titleName>Let's Get Lost</titleName>
    <artistName>Chet Baker</artistName>
    <albumName></albumName>
    <CategoryCode>737</CategoryCode>
    <CategoryName>JAZZ</CategoryName>
    <itemDuration>221</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
using System;
using System.Threading.Tasks;
using BKind.Web.Areas.Editor.Story.Models;
using BKind.Web.Core;
using BKind.Web.Features.Stories.Queries;
using BKind.Web.Infrastructure.Helpers;
using BKind.Web.Model;
using MediatR;

namespace BKind.Web.Areas.Editor.Story.Domain
{
    public class DeleteStoryHandler : IAsyncRequestHandler<DeleteStoryCommand, Response>
    {
        private readonly IMediator _mediator;
        private readonly IUnitOfWork _uow;

        public DeleteStoryHandler(IMediator mediator, IUnitOfWork uow)
        {
            _mediator = mediator;
            _uow = uow;
        }

        public async Task<Response> Handle(DeleteStoryCommand message)
        {
            var response = new Response();

            if (!message.UserWithRoles.Is<Administrator>())
                return response.AddError("user", "Only admin can delete story permanetly");

            var story = await _mediator.Send(new GetStoryQuery(message.Slug));

            if (story == null)
                return response.AddError("story", "Story not found");

            _uow.Delete(story);

            try
            {
                await _uow.CommitAsync();
            }
            catch (Exception e)
            {
                response.AddError("story", $"Error deleting the story: {e.Unwrap().Message}");
            }

            return response;
        }
    }
}


text:
require 'spec_helper'

describe Adm::BackersController do
  subject{ response }
  let(:admin) do
    u = Factory(:user)
    u.admin = true
    u.save!
    u
  end

  let(:unconfirmed_backer) do
    b = Factory(:backer)
    b.confirmed = false
    b.save!
    b
  end

  describe 'PUT confirm' do
    let(:backer) { Factory(:backer, confirmed: false) }
    subject { backer.confirmed }

    before {
      controller.stubs(:current_user).returns(admin)
      put :confirm, id: backer.id, locale: :pt
    }

    it {
      backer.reload
      should be_true
    }
  end

  describe 'PUT unconfirm' do
    let(:backer) { Factory(:backer, confirmed: true) }
    subject { backer.confirmed }

    before {
      controller.stubs(:current_user).returns(admin)
      put :unconfirm, id: backer.id, locale: :pt
    }

    it {
      backer.reload
      should be_false
    }
  end

  describe "GET index" do
    context "when I'm not logged in" do
      before do
        get :index, :locale => :pt
      end
      it{ should redirect_to login_path }
    end

    context "when I'm logged as admin" do
      before do
        controller.stubs(:current_user).returns(admin)
        get :index, :locale => :pt
      end
      its(:status){ should == 200 }
    end
  end

  describe ".menu" do
    it "should add a menu entry to the menu_items class variable when we pass a parameter and retrieve when we have no parameters" do
      Adm::BackersController.menu "Test Menu" => "/path"
      Adm::BaseController.menu.should include("Test Menu")
    end
  end
end


text:
namespace ZE {
	void GlobalRegistry::Register()
	{
		// Register all object classes
		Component::RegClass();
		Actor::RegClass();
		SceneComponent::RegClass();
		CameraComponent::RegClass();
		DebugCamera::RegClass();
		CameraManager::RegClass();
		EventDispatcher::RegClass();
		InputManager::RegClass();
		KeyboardMouseInput::RegClass();
		LightComponent::RegClass();

		// Register Resource Classes
		Material::RegClass();
		Mesh::RegClass();
		Texture::RegClass();

		ResourceManager::RegClass();
		MeshManager::RegClass();
		ShaderManager::RegClass();
		TextureManager::RegClass();

		// Register event classes
		Event::RegClass();
		Event_UPDATE::RegClass();
		Event_INPUT::RegClass();
			Event_KEY_UP::RegClass();
			Event_KEY_DOWN::RegClass();
			Event_MOUSE_DRAG::RegClass();
		Event_GATHER_LIGHT::RegClass();
		Event_GATHER_RENDER::RegClass();
		Event_RESOURCE_LOADED::RegClass();

		Event_Physics_BASE::RegClass();
		Event_Physics_ONCOLLIDE::RegClass();
		Event_Physics_PREUPDATE::RegClass();
		Event_Physics_UPDATE::RegClass();
		Event_Physics_POSTUPDATE::RegClass();
		Event_Physics_UPDATE_TRANSFORM::RegClass();
		Event_Physics_ON_TRIGGER::RegClass();
		Event_Physics_ON_BEGIN_TRIGGER::RegClass();
		Event_Physics_ON_END_TRIGGER::RegClass();
	}

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package thread.service;

import java.util.List;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;

/**
 *
 * @author Ruaridhi Bannatyne
 */
public class PcapTest {
    private static final int snaplen =  64 * 1024;
    private static final int timeout = 10000;
    private  static final int mode = Pcap.MODE_PROMISCUOUS;

    public static void main(String[] args)
    {
      StringBuilder sB = new StringBuilder();
      List<PcapIf> device = PcapIf.findAllDevs(sB);   //problem here
      for(PcapIf p: device)
      {
      System.out.println(p.toString());
      }
      //Pcap p = Pcap.openLive(device.getName(), snaplen, timeout, mode, sB);
    }
}


text:
"""Sensor platform for frigate."""
from __future__ import annotations

import logging
from typing import Any

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_URL, TEMP_CELSIUS
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import DeviceInfo, EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import (
    FrigateDataUpdateCoordinator,
    FrigateEntity,
    FrigateMQTTEntity,
    ReceiveMessage,
    get_cameras_zones_and_objects,
    get_friendly_name,
    get_frigate_device_identifier,
    get_frigate_entity_unique_id,
    get_zones,
)
from .const import ATTR_CONFIG, ATTR_COORDINATOR, DOMAIN, FPS, MS, NAME
from .icons import ICON_CORAL, ICON_SERVER, ICON_SPEEDOMETER, get_icon_from_type

_LOGGER: logging.Logger = logging.getLogger(__name__)

CAMERA_FPS_TYPES = ["camera", "detection", "process", "skipped"]

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
    """Sensor entry setup."""
    coordinator = hass.data[DOMAIN][entry.entry_id][ATTR_COORDINATOR]

    entities = []
    for key, value in coordinator.data.items():
        if key == "detection_fps":
            entities.append(FrigateFpsSensor(coordinator, entry))
        elif key == "detectors":
            for name in value.keys():
                entities.append(DetectorSpeedSensor(coordinator, entry, name))
        elif key == "service":
            # Temperature is only supported on PCIe Coral.
            for name in value.get("temperatures", {}):
                entities.append(DeviceTempSensor(coordinator, entry, name))
        else:
            entities.extend(
                [CameraFpsSensor(coordinator, entry, key, t) for t in CAMERA_FPS_TYPES]
            )

    frigate_config = hass.data[DOMAIN][entry.entry_id][ATTR_CONFIG]
    entities.extend(
        [
            FrigateObjectCountSensor(entry, frigate_config, cam_name, obj)
            for cam_name, obj in get_cameras_zones_and_objects(frigate_config)
        ]
    )
    entities.append(FrigateStatusSensor(coordinator, entry))
    async_add_entities(entities)

class FrigateFpsSensor(FrigateEntity, CoordinatorEntity):  # type: ignore[misc]
    """Frigate Sensor class."""

    _attr_entity_category = EntityCategory.DIAGNOSTIC
    _attr_name = "Detection fps"

    def __init__(
        self, coordinator: FrigateDataUpdateCoordinator, config_entry: ConfigEntry
    ) -> None:
        """Construct a FrigateFpsSensor."""
        FrigateEntity.__init__(self, config_entry)
        CoordinatorEntity.__init__(self, coordinator)
        self._attr_entity_registry_enabled_default = False

    @property
    def unique_id(self) -> str:
        """Return a unique ID to use for this entity."""
        return get_frigate_entity_unique_id(
            self._config_entry.entry_id, "sensor_fps", "detection"
        )

    @property
    def device_info(self) -> DeviceInfo:
        """Get device information."""
        return {
            "identifiers": {get_frigate_device_identifier(self._config_entry)},
            "name": NAME,
            "model": self._get_model(),
            "configuration_url": self._config_entry.data.get(CONF_URL),
            "manufacturer": NAME,
        }

    @property
    def state(self) -> int | None:
        """Return the state of the sensor."""
        if self.coordinator.data:
            data = self.coordinator.data.get("detection_fps")
            if data is not None:
                try:
                    return round(float(data))
                except ValueError:
                    pass
        return None

    @property
    def unit_of_measurement(self) -> str:
        """Return the unit of measurement of the sensor."""
        return FPS

    @property
    def icon(self) -> str:
        """Return the icon of the sensor."""
        return ICON_SPEEDOMETER

class FrigateStatusSensor(FrigateEntity, CoordinatorEntity):  # type: ignore[misc]
    """Frigate Status Sensor class."""

    _attr_entity_category = EntityCategory.DIAGNOSTIC
    _attr_name = "Status"

    def __init__(
        self, coordinator: FrigateDataUpdateCoordinator, config_entry: ConfigEntry
    ) -> None:
        """Construct a FrigateStatusSensor."""
        FrigateEntity.__init__(self, config_entry)
        CoordinatorEntity.__init__(self, coordinator)
        self._attr_entity_registry_enabled_default = False

    @property
    def unique_id(self) -> str:
        """Return a unique ID to use for this entity."""
        return get_frigate_entity_unique_id(
            self._config_entry.entry_id, "sensor_status", "frigate"
        )

    @property
    def device_info(self) -> DeviceInfo:
        """Get device information."""
        return {
            "identifiers": {get_frigate_device_identifier(self._config_entry)},
            "name": NAME,
            "model": self._get_model(),
            "configuration_url": self._config_entry.data.get(CONF_URL),
            "manufacturer": NAME,
        }

    @property
    def state(self) -> str:
        """Return the state of the sensor."""
        return str(self.coordinator.server_status)

    @property
    def icon(self) -> str:
        """Return the icon of the sensor."""
        return ICON_SERVER

class DetectorSpeedSensor(FrigateEntity, CoordinatorEntity):  # type: ignore[misc]
    """Frigate Detector Speed class."""

    _attr_entity_category = EntityCategory.DIAGNOSTIC

    def __init__(
        self,
        coordinator: FrigateDataUpdateCoordinator,
        config_entry: ConfigEntry,
        detector_name: str,
    ) -> None:
        """Construct a DetectorSpeedSensor."""
        FrigateEntity.__init__(self, config_entry)
        CoordinatorEntity.__init__(self, coordinator)
        self._detector_name = detector_name
        self._attr_entity_registry_enabled_default = False

    @property
    def unique_id(self) -> str:
        """Return a unique ID to use for this entity."""
        return get_frigate_entity_unique_id(
            self._config_entry.entry_id, "sensor_detector_speed", self._detector_name
        )

    @property
    def device_info(self) -> DeviceInfo:
        """Get device information."""
        return {
            "identifiers": {get_frigate_device_identifier(self._config_entry)},
            "name": NAME,
            "model": self._get_model(),
            "configuration_url": self._config_entry.data.get(CONF_URL),
            "manufacturer": NAME,
        }

    @property
    def name(self) -> str:
        """Return the name of the sensor."""
        return f"{get_friendly_name(self._detector_name)} inference speed"

    @property
    def state(self) -> int | None:
        """Return the state of the sensor."""
        if self.coordinator.data:
            data = (
                self.coordinator.data.get("detectors", {})
                .get(self._detector_name, {})
                .get("inference_speed")
            )
            if data is not None:
                try:
                    return round(float(data))
                except ValueError:
                    pass
        return None

    @property
    def unit_of_measurement(self) -> str:
        """Return the unit of measurement of the sensor."""
        return MS

    @property
    def icon(self) -> str:
        """Return the icon of the sensor."""
        return ICON_SPEEDOMETER

class CameraFpsSensor(FrigateEntity, CoordinatorEntity):  # type: ignore[misc]
    """Frigate Camera Fps class."""

    _attr_entity_category = EntityCategory.DIAGNOSTIC

    def __init__(
        self,
        coordinator: FrigateDataUpdateCoordinator,
        config_entry: ConfigEntry,
        cam_name: str,
        fps_type: str,
    ) -> None:
        """Construct a CameraFpsSensor."""
        FrigateEntity.__init__(self, config_entry)
        CoordinatorEntity.__init__(self, coordinator)
        self._cam_name = cam_name
        self._fps_type = fps_type
        self._attr_entity_registry_enabled_default = False

    @property
    def unique_id(self) -> str:
        """Return a unique ID to use for this entity."""
        return get_frigate_entity_unique_id(
            self._config_entry.entry_id,
            "sensor_fps",
            f"{self._cam_name}_{self._fps_type}",
        )

    @property
    def device_info(self) -> DeviceInfo:
        """Get device information."""
        return {
            "identifiers": {
                get_frigate_device_identifier(self._config_entry, self._cam_name)
            },
            "via_device": get_frigate_device_identifier(self._config_entry),
            "name": get_friendly_name(self._cam_name),
            "model": self._get_model(),
            "configuration_url": f"{self._config_entry.data.get(CONF_URL)}/cameras/{self._cam_name}",
            "manufacturer": NAME,
        }

    @property
    def name(self) -> str:
        """Return the name of the sensor."""
        return f"{self._fps_type} fps"

    @property
    def unit_of_measurement(self) -> str:
        """Return the unit of measurement of the sensor."""
        return FPS

    @property
    def state(self) -> int | None:
        """Return the state of the sensor."""

        if self.coordinator.data:
            data = self.coordinator.data.get(self._cam_name, {}).get(
                f"{self._fps_type}_fps"
            )
            if data is not None:
                try:
                    return round(float(data))
                except ValueError:
                    pass
        return None

    @property
    def icon(self) -> str:
        """Return the icon of the sensor."""
        return ICON_SPEEDOMETER

class FrigateObjectCountSensor(FrigateMQTTEntity):
    """Frigate Motion Sensor class."""

    def __init__(
        self,
        config_entry: ConfigEntry,
        frigate_config: dict[str, Any],
        cam_name: str,
        obj_name: str,
    ) -> None:
        """Construct a FrigateObjectCountSensor."""
        self._cam_name = cam_name
        self._obj_name = obj_name
        self._state = 0
        self._frigate_config = frigate_config
        self._icon = get_icon_from_type(self._obj_name)

        super().__init__(
            config_entry,
            frigate_config,
            {
                "state_topic": {
                    "msg_callback": self._state_message_received,
                    "qos": 0,
                    "topic": (
                        f"{self._frigate_config['mqtt']['topic_prefix']}"
                        f"/{self._cam_name}/{self._obj_name}"
                    ),
                    "encoding": None,
                },
            },
        )

    @callback  # type: ignore[misc]
    def _state_message_received(self, msg: ReceiveMessage) -> None:
        """Handle a new received MQTT state message."""
        try:
            self._state = int(msg.payload)
            self.async_write_ha_state()
        except ValueError:
            pass

    @property
    def unique_id(self) -> str:
        """Return a unique ID to use for this entity."""
        return get_frigate_entity_unique_id(
            self._config_entry.entry_id,
            "sensor_object_count",
            f"{self._cam_name}_{self._obj_name}",
        )

    @property
    def device_info(self) -> DeviceInfo:
        """Get device information."""
        return {
            "identifiers": {
                get_frigate_device_identifier(self._config_entry, self._cam_name)
            },
            "via_device": get_frigate_device_identifier(self._config_entry),
            "name": get_friendly_name(self._cam_name),
            "model": self._get_model(),
            "configuration_url": f"{self._config_entry.data.get(CONF_URL)}/cameras/{self._cam_name if self._cam_name not in get_zones(self._frigate_config) else ''}",
            "manufacturer": NAME,
        }

    @property
    def name(self) -> str:
        """Return the name of the sensor."""
        return f"{self._obj_name} count"

    @property
    def state(self) -> int:
        """Return true if the binary sensor is on."""
        return self._state

    @property
    def unit_of_measurement(self) -> str:
        """Return the unit of measurement of the sensor."""
        return "objects"

    @property
    def icon(self) -> str:
        """Return the icon of the sensor."""
        return self._icon

class DeviceTempSensor(FrigateEntity, CoordinatorEntity):  # type: ignore[misc]
    """Frigate Coral Temperature Sensor class."""

    _attr_entity_category = EntityCategory.DIAGNOSTIC

    def __init__(
        self,
        coordinator: FrigateDataUpdateCoordinator,
        config_entry: ConfigEntry,
        name: str,
    ) -> None:
        """Construct a CoralTempSensor."""
        self._name = name
        FrigateEntity.__init__(self, config_entry)
        CoordinatorEntity.__init__(self, coordinator)
        self._attr_entity_registry_enabled_default = False

    @property
    def unique_id(self) -> str:
        """Return a unique ID to use for this entity."""
        return get_frigate_entity_unique_id(
            self._config_entry.entry_id, "sensor_temp", self._name
        )

    @property
    def device_info(self) -> DeviceInfo:
        """Get device information."""
        return {
            "identifiers": {get_frigate_device_identifier(self._config_entry)},
            "name": NAME,
            "model": self._get_model(),
            "configuration_url": self._config_entry.data.get(CONF_URL),
            "manufacturer": NAME,
        }

    @property
    def name(self) -> str:
        """Return the name of the sensor."""
        return f"{get_friendly_name(self._name)} temperature"

    @property
    def state(self) -> float | None:
        """Return the state of the sensor."""
        if self.coordinator.data:
            data = (
                self.coordinator.data.get("service", {})
                .get("temperatures", {})
                .get(self._name, 0.0)
            )
            try:
                return float(data)
            except (TypeError, ValueError):
                pass
        return None

    @property
    def unit_of_measurement(self) -> Any:
        """Return the unit of measurement of the sensor."""
        return TEMP_CELSIUS

    @property
    def icon(self) -> str:
        """Return the icon of the sensor."""
        return ICON_CORAL


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data noupdate="0">

    <record model="ir.module.category" id="module_category_is_pg">
        <field name="name">Gestionnaire des tables</field>
        <field name="description">Gestionnaire des tables</field>
        <field name="sequence">2</field>
    </record>
    <record id="group_is_pg_manager" model="res.groups">
        <field name="name">Gestionnaire des tables</field>
        <field name="comment">les tables segment/Famille/sous famille sont accessibles par cet utilisateur.</field>
        <field name="category_id" ref="module_category_is_pg"/>
        <field name="users" eval="[(4, ref('base.user_root'))]"/>
    </record>

    <record model="ir.module.category" id="is_plastigray_module_category">
        <field name="name">Données techniques</field>
        <field name="description">Données techniques</field>
        <field name="sequence">2</field>
    </record>
    <record id="is_gestionnaire_donnees_techniques_group" model="res.groups">
        <field name="name">Gestionnaire des données techniques</field>
        <field name="comment">Groupe autorisé à modifier les articles, nomenclatures et gammes</field>
        <field name="category_id" ref="is_plastigray_module_category"/>
        <field name="users" eval="[(4, ref('base.user_root'))]"/>
    </record>

</data>
</openerp>


text:
from random import Random

from register.models import EmailVerifyRecord
from django.core.mail import send_mail
from nostray_prototype.settings import EMAIL_FROM

def random_str(randomlength=16):
	str = ''
	chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
	length = len(chars) - 1
	random = Random()
	for i in range(randomlength):
		str+=chars[random.randint(0, length)]
	return str

def emailVerify(email, send_type='registe'):
	email_record = EmailVerifyRecord()
	code = random_str(8)
	email_record.code = code
	email_record.email = email
	email_record.send_type = send_type
	email_record.save()

	email_title = ''
	email_body = ''

	if send_type == 'registe':
		email_title = '绑定邮箱链接'
		email_body = '请点击下面的链接激活你的账号:http://127.0.0.1:8000/active/{0}'.format(code)

		send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
		if send_status:
			pass
	elif send_type == 'forget':
		email_title = '找回密码链接'
		email_body = '请点击下面的链接重制你的密码:http://127.0.0.1:8000/reset/{0}'.format(code)

		send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
		if send_status:
			pass


text:
#ifndef LIB_TXT_SRC_LINE_METRICS_H_
#define LIB_TXT_SRC_LINE_METRICS_H_

#include <map>
#include <vector>

#include "run_metrics.h"

namespace txt {

class LineMetrics {
 public:
  // The following fields are used in the layout process itself.

  // The indexes in the text buffer the line begins and ends.
  size_t start_index = 0;
  size_t end_index = 0;
  size_t end_excluding_whitespace = 0;
  size_t end_including_newline = 0;
  bool hard_break = false;

  // The following fields are tracked after or during layout to provide to
  // the user as well as for computing bounding boxes.

  // The final computed ascent and descent for the line. This can be impacted by
  // the strut, height, scaling, as well as outlying runs that are very tall.
  //
  // The top edge is `baseline - ascent` and the bottom edge is `baseline +
  // descent`. Ascent and descent are provided as positive numbers. Raw numbers
  // for specific runs of text can be obtained in run_metrics_map. These values
  // are the cumulative metrics for the entire line.
  double ascent = 0.0;
  double descent = 0.0;
  double unscaled_ascent = 0.0;
  // Total height of the paragraph including the current line.
  //
  // The height of the current line is `round(ascent + descent)`.
  double height = 0.0;
  // Width of the line.
  double width = 0.0;
  // The left edge of the line. The right edge can be obtained with `left +
  // width`
  double left = 0.0;
  // The y position of the baseline for this line from the top of the paragraph.
  double baseline = 0.0;
  // Zero indexed line number.
  size_t line_number = 0;

  // Mapping between text index ranges and the FontMetrics associated with
  // them. The first run will be keyed under start_index. The metrics here
  // are before layout and are the base values we calculate from.
  std::map<size_t, RunMetrics> run_metrics;

  LineMetrics();

  LineMetrics(size_t start,
              size_t end,
              size_t end_excluding_whitespace,
              size_t end_including_newline,
              bool hard_break)
      : start_index(start),
        end_index(end),
        end_excluding_whitespace(end_excluding_whitespace),
        end_including_newline(end_including_newline),
        hard_break(hard_break) {}
};

}  // namespace txt

#endif  // LIB_TXT_SRC_LINE_METRICS_H_


text:
<?php

namespace PayPal\EnumType;

use \WsdlToPhp\PackageBase\AbstractStructEnumBase;

/**
 * This class stands for ShippingRegionCodeType EnumType
 * Meta information extracted from the WSDL
 * - documentation: ShippingRegion CodeType This code list module defines the enumerated types of regions for shipping items (i.e., a seller may support shipment of an item).
 * @subpackage Enumerations
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class ShippingRegionCodeType extends AbstractStructEnumBase
{
    /**
     * Constant for value 'Africa'
     * Meta information extracted from the WSDL
     * - documentation: Africa
     * @return string 'Africa'
     */
    const VALUE_AFRICA = 'Africa';
    /**
     * Constant for value 'Asia'
     * Meta information extracted from the WSDL
     * - documentation: Asia
     * @return string 'Asia'
     */
    const VALUE_ASIA = 'Asia';
    /**
     * Constant for value 'Caribbean'
     * Meta information extracted from the WSDL
     * - documentation: Carribbean
     * @return string 'Caribbean'
     */
    const VALUE_CARIBBEAN = 'Caribbean';
    /**
     * Constant for value 'Europe'
     * Meta information extracted from the WSDL
     * - documentation: Europe
     * @return string 'Europe'
     */
    const VALUE_EUROPE = 'Europe';
    /**
     * Constant for value 'LatinAmerica'
     * Meta information extracted from the WSDL
     * - documentation: LatinAmerica
     * @return string 'LatinAmerica'
     */
    const VALUE_LATIN_AMERICA = 'LatinAmerica';
    /**
     * Constant for value 'MiddleEast'
     * Meta information extracted from the WSDL
     * - documentation: MiddleEast
     * @return string 'MiddleEast'
     */
    const VALUE_MIDDLE_EAST = 'MiddleEast';
    /**
     * Constant for value 'NorthAmerica'
     * Meta information extracted from the WSDL
     * - documentation: NorthAmerica
     * @return string 'NorthAmerica'
     */
    const VALUE_NORTH_AMERICA = 'NorthAmerica';
    /**
     * Constant for value 'Oceania'
     * Meta information extracted from the WSDL
     * - documentation: Oceania (i.e., Pacific region other than Asia)
     * @return string 'Oceania'
     */
    const VALUE_OCEANIA = 'Oceania';
    /**
     * Constant for value 'SouthAmerica'
     * Meta information extracted from the WSDL
     * - documentation: SouthAmerica
     * @return string 'SouthAmerica'
     */
    const VALUE_SOUTH_AMERICA = 'SouthAmerica';
    /**
     * Constant for value 'CustomCode'
     * Meta information extracted from the WSDL
     * - documentation: Reserved for internal or future use.
     * @return string 'CustomCode'
     */
    const VALUE_CUSTOM_CODE = 'CustomCode';
    /**
     * Return allowed values
     * @uses self::VALUE_AFRICA
     * @uses self::VALUE_ASIA
     * @uses self::VALUE_CARIBBEAN
     * @uses self::VALUE_EUROPE
     * @uses self::VALUE_LATIN_AMERICA
     * @uses self::VALUE_MIDDLE_EAST
     * @uses self::VALUE_NORTH_AMERICA
     * @uses self::VALUE_OCEANIA
     * @uses self::VALUE_SOUTH_AMERICA
     * @uses self::VALUE_CUSTOM_CODE
     * @return string[]
     */
    public static function getValidValues()
    {
        return array(
            self::VALUE_AFRICA,
            self::VALUE_ASIA,
            self::VALUE_CARIBBEAN,
            self::VALUE_EUROPE,
            self::VALUE_LATIN_AMERICA,
            self::VALUE_MIDDLE_EAST,
            self::VALUE_NORTH_AMERICA,
            self::VALUE_OCEANIA,
            self::VALUE_SOUTH_AMERICA,
            self::VALUE_CUSTOM_CODE,
        );
    }
}


text:
<?php

/**
 * @since 1.5
 */
class HTMLTemplateInvoiceCore extends HTMLTemplate
{
    public $order;
    public $order_invoice;
    public $available_in_your_account = false;

    /**
     * @param OrderInvoice $order_invoice
     * @param $smarty
     * @throws PrestaShopException
     */
    public function __construct(OrderInvoice $order_invoice, $smarty, $bulk_mode = false)
    {
        $this->order_invoice = $order_invoice;
        $this->order = new Order((int)$this->order_invoice->id_order);
        $this->smarty = $smarty;

        // If shop_address is null, then update it with current one.
        // But no DB save required here to avoid massive updates for bulk PDF generation case.
        // (DB: bug fixed in 1.6.1.1 with upgrade SQL script to avoid null shop_address in old orderInvoices)
        if (!isset($this->order_invoice->shop_address) || !$this->order_invoice->shop_address) {
            $this->order_invoice->shop_address = OrderInvoice::getCurrentFormattedShopAddress((int)$this->order->id_shop);
            if (!$bulk_mode) {
                OrderInvoice::fixAllShopAddresses();
            }
        }

        // header informations
        $this->date = Tools::displayDate($order_invoice->date_add);

        $id_lang = Context::getContext()->language->id;
        $this->title = $order_invoice->getInvoiceNumberFormatted($id_lang,(int)$this->order->id_shop);

        $this->shop = new Shop((int)$this->order->id_shop);
    }

    /**
     * Returns the template's HTML header
     *
     * @return string HTML header
     */
    public function getHeader()
    {
        $this->assignCommonHeaderData();
        $this->smarty->assign(array('header' => HTMLTemplateInvoice::l('Invoice')));

        return $this->smarty->fetch($this->getTemplate('header'));
    }

    /**
     * Compute layout elements size
     *
     * @param $params Array Layout elements
     *
     * @return Array Layout elements columns size
     */
    protected function computeLayout($params)
    {
        $layout = array(
            'reference' => array(
                'width' => 15,
            ),
            'product' => array(
                'width' => 40,
            ),
            'quantity' => array(
                'width' => 8,
            ),
            'tax_code' => array(
                'width' => 8,
            ),
            'unit_price_tax_excl' => array(
                'width' => 0,
            ),
            'total_tax_excl' => array(
                'width' => 0,
            )
        );

        if (isset($params['has_discount']) && $params['has_discount']) {
            $layout['before_discount'] = array('width' => 0);
            $layout['product']['width'] -= 7;
            $layout['reference']['width'] -= 3;
        }

        $total_width = 0;
        $free_columns_count = 0;
        foreach ($layout as $data) {
            if ($data['width'] === 0) {
                ++$free_columns_count;
            }

            $total_width += $data['width'];
        }

        $delta = 100 - $total_width;

        foreach ($layout as $row => $data) {
            if ($data['width'] === 0) {
                $layout[$row]['width'] = $delta / $free_columns_count;
            }
        }

        $layout['_colCount'] = count($layout);

        return $layout;
    }

    /**
     * Returns the template's HTML content
     *
     * @return string HTML content
     */
    public function getContent()
    {
        $invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
        $deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);

        $invoice_address = new Address((int)$this->order->id_address_invoice);
        $country = new Country((int)$invoice_address->id_country);
        $formatted_invoice_address = AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '
', ' ');

        $delivery_address = null;
        $formatted_delivery_address = '';
        if (isset($this->order->id_address_delivery) && $this->order->id_address_delivery) {
            $delivery_address = new Address((int)$this->order->id_address_delivery);
            $formatted_delivery_address = AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '
', ' ');
        }

        $customer = new Customer((int)$this->order->id_customer);
        $carrier = new Carrier((int)$this->order->id_carrier);

        $order_details = $this->order_invoice->getProducts();

        $has_discount = false;
        foreach ($order_details as $id => &$order_detail) {
            // Find out if column 'price before discount' is required
            if ($order_detail['reduction_amount_tax_excl'] > 0) {
                $has_discount = true;
                $order_detail['unit_price_tax_excl_before_specific_price'] = $order_detail['unit_price_tax_excl_including_ecotax'] + $order_detail['reduction_amount_tax_excl'];
            } elseif ($order_detail['reduction_percent'] > 0) {
                $has_discount = true;
                $order_detail['unit_price_tax_excl_before_specific_price'] = (100 * $order_detail['unit_price_tax_excl_including_ecotax']) / (100 - $order_detail['reduction_percent']);
            }

            // Set tax_code
            $taxes = OrderDetail::getTaxListStatic($id);
            $tax_temp = array();
            foreach ($taxes as $tax) {
                $obj = new Tax($tax['id_tax']);
                $tax_temp[] = sprintf($this->l('%1$s%2$s%%'), ($obj->rate + 0), ' ');
            }

            $order_detail['order_detail_tax'] = $taxes;
            $order_detail['order_detail_tax_label'] = implode(', ', $tax_temp);
        }
        unset($tax_temp);
        unset($order_detail);

        if (Configuration::get('PS_PDF_IMG_INVOICE')) {
            foreach ($order_details as &$order_detail) {
                if ($order_detail['image'] != null) {
                    $name = 'product_mini_'.(int)$order_detail['product_id'].(isset($order_detail['product_attribute_id']) ? '_'.(int)$order_detail['product_attribute_id'] : '').'.jpg';
                    $path = _PS_PROD_IMG_DIR_.$order_detail['image']->getExistingImgPath().'.jpg';

                    $order_detail['image_tag'] = preg_replace(
                        '/\.*'.preg_quote(__PS_BASE_URI__, '/').'/',
                        _PS_ROOT_DIR_.DIRECTORY_SEPARATOR,
                        ImageManager::thumbnail($path, $name, 45, 'jpg', false),
                        1
                    );

                    if (file_exists(_PS_TMP_IMG_DIR_.$name)) {
                        $order_detail['image_size'] = getimagesize(_PS_TMP_IMG_DIR_.$name);
                    } else {
                        $order_detail['image_size'] = false;
                    }
                }
            }
            unset($order_detail); // don't overwrite the last order_detail later
        }

        $cart_rules = $this->order->getCartRules($this->order_invoice->id);
        $free_shipping = false;
        foreach ($cart_rules as $key => $cart_rule) {
            if ($cart_rule['free_shipping']) {
                $free_shipping = true;
                /**
                 * Adjust cart rule value to remove the amount of the shipping.
                 * We're not interested in displaying the shipping discount as it is already shown as "Free Shipping".
                 */
                $cart_rules[$key]['value_tax_excl'] -= $this->order_invoice->total_shipping_tax_excl;
                $cart_rules[$key]['value'] -= $this->order_invoice->total_shipping_tax_incl;

                /**
                 * Don't display cart rules that are only about free shipping and don't create
                 * a discount on products.
                 */
                if ($cart_rules[$key]['value'] == 0) {
                    unset($cart_rules[$key]);
                }
            }
        }

        $product_taxes = 0;
        foreach ($this->order_invoice->getProductTaxesBreakdown($this->order) as $details) {
            $product_taxes += $details['total_amount'];
        }

        $product_discounts_tax_excl = $this->order_invoice->total_discount_tax_excl;
        $product_discounts_tax_incl = $this->order_invoice->total_discount_tax_incl;
        if ($free_shipping) {
            $product_discounts_tax_excl -= $this->order_invoice->total_shipping_tax_excl;
            $product_discounts_tax_incl -= $this->order_invoice->total_shipping_tax_incl;
        }

        $products_after_discounts_tax_excl = $this->order_invoice->total_products - $product_discounts_tax_excl;
        $products_after_discounts_tax_incl = $this->order_invoice->total_products_wt - $product_discounts_tax_incl;

        $shipping_tax_excl = $free_shipping ? 0 : $this->order_invoice->total_shipping_tax_excl;
        $shipping_tax_incl = $free_shipping ? 0 : $this->order_invoice->total_shipping_tax_incl;
        $shipping_taxes = $shipping_tax_incl - $shipping_tax_excl;

        $wrapping_taxes = $this->order_invoice->total_wrapping_tax_incl - $this->order_invoice->total_wrapping_tax_excl;

        $total_taxes = $this->order_invoice->total_paid_tax_incl - $this->order_invoice->total_paid_tax_excl;

        $footer = array(
            'products_before_discounts_tax_excl' => $this->order_invoice->total_products,
            'product_discounts_tax_excl' => $product_discounts_tax_excl,
            'products_after_discounts_tax_excl' => $products_after_discounts_tax_excl,
            'products_before_discounts_tax_incl' => $this->order_invoice->total_products_wt,
            'product_discounts_tax_incl' => $product_discounts_tax_incl,
            'products_after_discounts_tax_incl' => $products_after_discounts_tax_incl,
            'product_taxes' => $product_taxes,
            'shipping_tax_excl' => $shipping_tax_excl,
            'shipping_taxes' => $shipping_taxes,
            'shipping_tax_incl' => $shipping_tax_incl,
            'wrapping_tax_excl' => $this->order_invoice->total_wrapping_tax_excl,
            'wrapping_taxes' => $wrapping_taxes,
            'wrapping_tax_incl' => $this->order_invoice->total_wrapping_tax_incl,
            'ecotax_taxes' => $total_taxes - $product_taxes - $wrapping_taxes - $shipping_taxes,
            'total_taxes' => $total_taxes,
            'total_paid_tax_excl' => $this->order_invoice->total_paid_tax_excl,
            'total_paid_tax_incl' => $this->order_invoice->total_paid_tax_incl
        );

        foreach ($footer as $key => $value) {
            $footer[$key] = Tools::ps_round($value, _PS_PRICE_COMPUTE_PRECISION_, $this->order->round_mode);
        }

        /**
         * Need the $round_mode for the tests.
         */
        $round_type = null;
        switch ($this->order->round_type) {
        case Order::ROUND_TOTAL:
                $round_type = 'total';
            break;
        case Order::ROUND_LINE:
                $round_type = 'line';
            break;
        case Order::ROUND_ITEM:
                $round_type = 'item';
            break;
        default:
                $round_type = 'line';
            break;
        }

        $display_product_images = Configuration::get('PS_PDF_IMG_INVOICE');
        $tax_excluded_display = Group::getPriceDisplayMethod($customer->id_default_group);

        $layout = $this->computeLayout(array('has_discount' => $has_discount));

        $legal_free_text = Hook::exec('displayInvoiceLegalFreeText', array('order' => $this->order));
        if (!$legal_free_text) {
            $legal_free_text = Configuration::get('PS_INVOICE_LEGAL_FREE_TEXT', (int)Context::getContext()->language->id, null, (int)$this->order->id_shop);
        }

        $data = array(
            'order' => $this->order,
            'order_invoice' => $this->order_invoice,
            'order_details' => $order_details,
            'carrier' => $carrier,
            'cart_rules' => $cart_rules,
            'delivery_address' => $formatted_delivery_address,
            'invoice_address' => $formatted_invoice_address,
            'addresses' => array('invoice' => $invoice_address, 'delivery' => $delivery_address),
            'tax_excluded_display' => $tax_excluded_display,
            'display_product_images' => $display_product_images,
            'layout' => $layout,
            'tax_tab' => $this->getTaxTabContent(),
            'customer' => $customer,
            'footer' => $footer,
            'ps_price_compute_precision' => _PS_PRICE_COMPUTE_PRECISION_,
            'round_type' => $round_type,
            'legal_free_text' => $legal_free_text,
        );

        if (Tools::getValue('debug')) {
            die(json_encode($data));
        }

        $this->smarty->assign($data);

        $tpls = array(
            'style_tab' => $this->smarty->fetch($this->getTemplate('invoice.style-tab')),
            'addresses_tab' => $this->smarty->fetch($this->getTemplate('invoice.addresses-tab')),
            'summary_tab' => $this->smarty->fetch($this->getTemplate('invoice.summary-tab')),
            'product_tab' => $this->smarty->fetch($this->getTemplate('invoice.product-tab')),
            'tax_tab' => $this->getTaxTabContent(),
            'payment_tab' => $this->smarty->fetch($this->getTemplate('invoice.payment-tab')),
			'note_tab' => $this->smarty->fetch($this->getTemplate('invoice.note-tab')),
            'total_tab' => $this->smarty->fetch($this->getTemplate('invoice.total-tab')),
            'shipping_tab' => $this->smarty->fetch($this->getTemplate('invoice.shipping-tab')),
        );
        $this->smarty->assign($tpls);

        return $this->smarty->fetch($this->getTemplateByCountry($country->iso_code));
    }

    /**
     * Returns the tax tab content
     *
     * @return String Tax tab html content
     */
    public function getTaxTabContent()
    {
        $debug = Tools::getValue('debug');

        $address = new Address((int)$this->order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
        $tax_exempt = Configuration::get('VATNUMBER_MANAGEMENT')
                            && !empty($address->vat_number)
                            && $address->id_country != Configuration::get('VATNUMBER_COUNTRY');
        $carrier = new Carrier($this->order->id_carrier);

        $tax_breakdowns = $this->getTaxBreakdown();

        $data = array(
            'tax_exempt' => $tax_exempt,
            'use_one_after_another_method' => $this->order_invoice->useOneAfterAnotherTaxComputationMethod(),
            'display_tax_bases_in_breakdowns' => $this->order_invoice->displayTaxBasesInProductTaxesBreakdown(),
            'product_tax_breakdown' => $this->order_invoice->getProductTaxesBreakdown($this->order),
            'shipping_tax_breakdown' => $this->order_invoice->getShippingTaxesBreakdown($this->order),
            'ecotax_tax_breakdown' => $this->order_invoice->getEcoTaxTaxesBreakdown(),
            'wrapping_tax_breakdown' => $this->order_invoice->getWrappingTaxesBreakdown(),
            'tax_breakdowns' => $tax_breakdowns,
            'order' => $debug ? null : $this->order,
            'order_invoice' => $debug ? null : $this->order_invoice,
            'carrier' => $debug ? null : $carrier
        );

        if ($debug) {
            return $data;
        }

        $this->smarty->assign($data);

        return $this->smarty->fetch($this->getTemplate('invoice.tax-tab'));
    }

    /**
     * Returns different tax breakdown elements
     *
     * @return Array Different tax breakdown elements
     */
    protected function getTaxBreakdown()
    {
        $breakdowns = array(
            'product_tax' => $this->order_invoice->getProductTaxesBreakdown($this->order),
            'shipping_tax' => $this->order_invoice->getShippingTaxesBreakdown($this->order),
            'ecotax_tax' => $this->order_invoice->getEcoTaxTaxesBreakdown(),
            'wrapping_tax' => $this->order_invoice->getWrappingTaxesBreakdown(),
        );

        foreach ($breakdowns as $type => $bd) {
            if (empty($bd)) {
                unset($breakdowns[$type]);
            }
        }

        if (empty($breakdowns)) {
            $breakdowns = false;
        }

        if (isset($breakdowns['product_tax'])) {
            foreach ($breakdowns['product_tax'] as &$bd) {
                $bd['total_tax_excl'] = $bd['total_price_tax_excl'];
            }
        }

        if (isset($breakdowns['ecotax_tax'])) {
            foreach ($breakdowns['ecotax_tax'] as &$bd) {
                $bd['total_tax_excl'] = $bd['ecotax_tax_excl'];
                $bd['total_amount'] = $bd['ecotax_tax_incl'] - $bd['ecotax_tax_excl'];
            }
        }

        return $breakdowns;
    }

    /*
    protected function getTaxLabel($tax_breakdowns)
    {
        $tax_label = '';
        $all_taxes = array();

        foreach ($tax_breakdowns as $type => $bd)
            foreach ($bd as $line)
                if(isset($line['id_tax']))
                    $all_taxes[] = $line['id_tax'];

        $taxes = array_unique($all_taxes);

        foreach ($taxes as $id_tax) {
            $tax = new Tax($id_tax);
            $tax_label .= $tax->id.': '.$tax->name[$this->order->id_lang].' ('.$tax->rate.'%) ';
        }

        return $tax_label;
    }
    */

    /**
     * Returns the invoice template associated to the country iso_code
     *
     * @param string $iso_country
     */
    protected function getTemplateByCountry($iso_country)
    {
        $file = Configuration::get('PS_INVOICE_MODEL');

        // try to fetch the iso template
        $template = $this->getTemplate($file.'.'.$iso_country);

        // else use the default one
        if (!$template) {
            $template = $this->getTemplate($file);
        }

        return $template;
    }

    /**
     * Returns the template filename when using bulk rendering
     *
     * @return string filename
     */
    public function getBulkFilename()
    {
        return 'invoices.pdf';
    }

    /**
     * Returns the template filename
     *
     * @return string filename
     */
    public function getFilename()
    {
        $id_lang = Context::getContext()->language->id;
        $id_shop = (int)$this->order->id_shop;
        $format = '%1$s%2$06d';

        if (Configuration::get('PS_INVOICE_USE_YEAR')) {
            $format = Configuration::get('PS_INVOICE_YEAR_POS') ? '%1$s%3$s-%2$06d' : '%1$s%2$06d-%3$s';
        }

        return sprintf(
            $format,
            Configuration::get('PS_INVOICE_PREFIX', $id_lang, null, $id_shop),
            $this->order_invoice->number,
            date('Y', strtotime($this->order_invoice->date_add))
        ).'.pdf';
    }

    /**
     * Returns the template's HTML pagination block
     *
     * @return string HTML pagination block
     */
    public function getPagination()
    {
        return $this->smarty->fetch($this->getTemplate('pagination'));
    }
}


text:
package queries

import (
	"bytes"
	"context"
	"database/sql"
	"database/sql/driver"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"time"
	"unicode"

	"github.com/friendsofgo/errors"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/strmangle"
)

// Identifies what kind of object we're binding to
type bindKind int

const (
	kindStruct bindKind = iota
	kindSliceStruct
	kindPtrSliceStruct
)

const (
	loadMethodPrefix       = "Load"
	relationshipStructName = "R"
	loaderStructName       = "L"
	sentinel               = uint64(255)
)

// BindP executes the query and inserts the
// result into the passed in object pointer.
// It panics on error.
// Also see documentation for Bind() and Query.Bind()
func (q *Query) BindP(ctx context.Context, exec boil.Executor, obj interface{}) {
	if err := q.Bind(ctx, exec, obj); err != nil {
		panic(boil.WrapErr(err))
	}
}

// BindG executes the query and inserts
// the result into the passed in object pointer.
// It uses the global executor.
// Also see documentation for Bind() and Query.Bind()
func (q *Query) BindG(ctx context.Context, obj interface{}) error {
	return q.Bind(ctx, boil.GetDB(), obj)
}

// Bind inserts the rows into the passed in object pointer, because the caller
// owns the rows it is imperative to note that the caller MUST both close the
// rows and check for errors on the rows.
//
// If you neglect closing the rows your application may have a memory leak
// if the rows are not implicitly closed by iteration alone.
// If you neglect checking the rows.Err silent failures may occur in your
// application.
//
// Valid types to bind to are: *Struct, []*Struct, and []Struct. Keep in mind
// if you use []Struct that Bind will be doing copy-by-value as a method
// of keeping heap memory usage low which means if your Struct contains
// reference types/pointers you will see incorrect results, do not use
// []Struct with a Struct with reference types.
//
// Bind rules:
//   - Struct tags control bind, in the form of: `boil:"name,bind"`
//   - If "name" is omitted the sql column names that come back are TitleCased
//     and matched against the field name.
//   - If the "name" part of the struct tag is specified, the given name will
//     be used instead of the struct field name for binding.
//   - If the "name" of the struct tag is "-", this field will not be bound to.
//   - If the ",bind" option is specified on a struct field and that field
//     is a struct itself, it will be recursed into to look for fields for
//     binding.
//   - If one or more boil struct tags are duplicated and there are multiple
//     matching columns for those tags the behaviour of Bind will be undefined
//     for those fields with duplicated struct tags.
//
// Example usage:
//
//   type JoinStruct struct {
//     // User1 can have it's struct fields bound to since it specifies
//     // ,bind in the struct tag, it will look specifically for
//     // fields that are prefixed with "user." returning from the query.
//     // For example "user.id" column name will bind to User1.ID
//     User1      *models.User `boil:"user,bind"`
//     // User2 will follow the same rules as noted above except it will use
//     // "friend." as the prefix it's looking for.
//     User2      *models.User `boil:"friend,bind"`
//     // RandomData will not be recursed into to look for fields to
//     // bind and will not be bound to because of the - for the name.
//     RandomData myStruct     `boil:"-"`
//     // Date will not be recursed into to look for fields to bind because
//     // it does not specify ,bind in the struct tag. But it can be bound to
//     // as it does not specify a - for the name.
//     Date       time.Time
//   }
//
//   models.Users(
//     qm.InnerJoin("users as friend on users.friend_id = friend.id")
//   ).Bind(&joinStruct)
//
// For custom objects that want to use eager loading, please see the
// loadRelationships function.
func Bind(rows *sql.Rows, obj interface{}) error {
	structType, sliceType, singular, err := bindChecks(obj)
	if err != nil {
		return err
	}

	return bind(rows, obj, structType, sliceType, singular)
}

// Bind executes the query and inserts the
// result into the passed in object pointer.
//
// If Context is non-nil it will upgrade the
// Executor to a ContextExecutor and query with the passed context.
// If Context is non-nil, any eager loading that's done must also
// be using load* methods that support context as the first parameter.
//
// Also see documentation for Bind()
func (q *Query) Bind(ctx context.Context, exec boil.Executor, obj interface{}) error {
	structType, sliceType, bkind, err := bindChecks(obj)
	if err != nil {
		return err
	}

	var rows *sql.Rows
	if ctx != nil {
		rows, err = q.QueryContext(ctx, exec.(boil.ContextExecutor))
	} else {
		rows, err = q.Query(exec)
	}
	if err != nil {
		return errors.Wrap(err, "bind failed to execute query")
	}
	if err = bind(rows, obj, structType, sliceType, bkind); err != nil {
		if innerErr := rows.Close(); innerErr != nil {
			return errors.Wrapf(err, "error on rows.Close after bind error: %+v", innerErr)
		}

		return err
	}
	if err = rows.Close(); err != nil {
		return errors.Wrap(err, "failed to clean up rows in bind")
	}
	if err = rows.Err(); err != nil {
		return errors.Wrap(err, "error from rows in bind")
	}

	if len(q.load) != 0 {
		return eagerLoad(ctx, exec, q.load, q.loadMods, obj, bkind)
	}

	return nil
}

// bindChecks resolves information about the bind target, and errors if it's not an object
// we can bind to.
func bindChecks(obj interface{}) (structType reflect.Type, sliceType reflect.Type, bkind bindKind, err error) {
	typ := reflect.TypeOf(obj)
	kind := typ.Kind()

	setErr := func() {
		err = errors.Errorf("obj type should be *Type, *[]Type, or *[]*Type but was %q", reflect.TypeOf(obj).String())
	}

	for i := 0; ; i++ {
		switch i {
		case 0:
			if kind != reflect.Ptr {
				setErr()
				return
			}
		case 1:
			switch kind {
			case reflect.Struct:
				structType = typ
				bkind = kindStruct
				return
			case reflect.Slice:
				sliceType = typ
			default:
				setErr()
				return
			}
		case 2:
			switch kind {
			case reflect.Struct:
				structType = typ
				bkind = kindSliceStruct
				return
			case reflect.Ptr:
			default:
				setErr()
				return
			}
		case 3:
			if kind != reflect.Struct {
				setErr()
				return
			}
			structType = typ
			bkind = kindPtrSliceStruct
			return
		}

		typ = typ.Elem()
		kind = typ.Kind()
	}
}

func bind(rows *sql.Rows, obj interface{}, structType, sliceType reflect.Type, bkind bindKind) error {
	cols, err := rows.Columns()
	if err != nil {
		return errors.Wrap(err, "bind failed to get column names")
	}

	var ptrSlice reflect.Value
	switch bkind {
	case kindSliceStruct, kindPtrSliceStruct:
		ptrSlice = reflect.Indirect(reflect.ValueOf(obj))
	}

	mapping, err := getMappingCache(structType).mapping(cols)
	if err != nil {
		return err
	}

	var oneStruct reflect.Value
	if bkind == kindSliceStruct {
		oneStruct = reflect.Indirect(reflect.New(structType))
	}

	foundOne := false
Rows:
	for rows.Next() {
		foundOne = true
		var newStruct reflect.Value
		var pointers []interface{}

		switch bkind {
		case kindStruct:
			pointers = PtrsFromMapping(reflect.Indirect(reflect.ValueOf(obj)), mapping)
		case kindSliceStruct:
			pointers = PtrsFromMapping(oneStruct, mapping)
		case kindPtrSliceStruct:
			newStruct = reflect.New(structType)
			pointers = PtrsFromMapping(reflect.Indirect(newStruct), mapping)
		}
		if err != nil {
			return err
		}

		if err := rows.Scan(pointers...); err != nil {
			return errors.Wrap(err, "failed to bind pointers to obj")
		}

		switch bkind {
		case kindStruct:
			break Rows
		case kindSliceStruct:
			ptrSlice.Set(reflect.Append(ptrSlice, oneStruct))
		case kindPtrSliceStruct:
			ptrSlice.Set(reflect.Append(ptrSlice, newStruct))
		}
	}

	if bkind == kindStruct && !foundOne {
		return sql.ErrNoRows
	}

	return nil
}

// BindMapping creates a mapping that helps look up the pointer for the
// column given.
func BindMapping(typ reflect.Type, mapping map[string]uint64, cols []string) ([]uint64, error) {
	ptrs := make([]uint64, len(cols))

ColLoop:
	for i, c := range cols {
		ptrMap, ok := mapping[c]
		if ok {
			ptrs[i] = ptrMap
			continue
		}

		suffix := "." + c
		for maybeMatch, mapping := range mapping {
			if strings.HasSuffix(maybeMatch, suffix) {
				ptrs[i] = mapping
				continue ColLoop
			}
		}
		// if c doesn't exist in the model, the pointer will be the zero value in the ptrs array and it's value will be thrown away
		continue
	}

	return ptrs, nil
}

// PtrsFromMapping expects to be passed an addressable struct and a mapping
// of where to find things. It pulls the pointers out referred to by the mapping.
func PtrsFromMapping(val reflect.Value, mapping []uint64) []interface{} {
	ptrs := make([]interface{}, len(mapping))
	for i, m := range mapping {
		ptrs[i] = ptrFromMapping(val, m, true).Interface()
	}
	return ptrs
}

// ValuesFromMapping expects to be passed an addressable struct and a mapping
// of where to find things. It pulls the pointers out referred to by the mapping.
func ValuesFromMapping(val reflect.Value, mapping []uint64) []interface{} {
	ptrs := make([]interface{}, len(mapping))
	for i, m := range mapping {
		ptrs[i] = ptrFromMapping(val, m, false).Interface()
	}
	return ptrs
}

// ptrFromMapping expects to be passed an addressable struct that it's looking
// for things on.
func ptrFromMapping(val reflect.Value, mapping uint64, addressOf bool) reflect.Value {
	if mapping == 0 {
		var ignored interface{}
		return reflect.ValueOf(&ignored)
	}
	for i := 0; i < 8; i++ {
		v := (mapping >> uint(i*8)) & sentinel

		if v == sentinel {
			if addressOf && val.Kind() != reflect.Ptr {
				return val.Addr()
			} else if !addressOf && val.Kind() == reflect.Ptr {
				return reflect.Indirect(val)
			}
			return val
		}

		val = val.Field(int(v))
		if val.Kind() == reflect.Ptr {
			val = reflect.Indirect(val)
		}
	}

	panic("could not find pointer from mapping")
}

// MakeStructMapping creates a map of the struct to be able to quickly look
// up its pointers and values by name.
func MakeStructMapping(typ reflect.Type) map[string]uint64 {
	fieldMaps := make(map[string]uint64)
	makeStructMappingHelper(typ, "", 0, 0, fieldMaps)
	return fieldMaps
}

func makeStructMappingHelper(typ reflect.Type, prefix string, current uint64, depth uint, fieldMaps map[string]uint64) {
	if typ.Kind() == reflect.Ptr {
		typ = typ.Elem()
	}

	n := typ.NumField()
	for i := 0; i < n; i++ {
		f := typ.Field(i)

		tag, recurse := getBoilTag(f)
		if len(tag) == 0 {
			tag = unTitleCase(f.Name)
		} else if tag[0] == '-' {
			continue
		}

		if len(prefix) != 0 {
			tag = fmt.Sprintf("%s.%s", prefix, tag)
		}

		if recurse {
			makeStructMappingHelper(f.Type, tag, current|uint64(i)<<depth, depth+8, fieldMaps)
			continue
		}

		fieldMaps[tag] = current | (sentinel << (depth + 8)) | (uint64(i) << depth)
	}
}

func getBoilTag(field reflect.StructField) (name string, recurse bool) {
	tag := field.Tag.Get("boil")

	if len(tag) == 0 {
		return "", false
	}

	ind := strings.IndexByte(tag, ',')
	if ind == -1 {
		return tag, false
	} else if ind == 0 {
		return "", true
	}

	nameFragment := tag[:ind]
	return nameFragment, true
}

var (
	mappingCachesMu sync.Mutex
	mappingCaches   = make(map[reflect.Type]*mappingCache)
)

func getMappingCache(typ reflect.Type) *mappingCache {
	mappingCachesMu.Lock()
	defer mappingCachesMu.Unlock()

	cache := mappingCaches[typ]
	if cache != nil {
		return cache
	}

	cache = newMappingCache(typ)
	mappingCaches[typ] = cache

	return cache
}

type mappingCache struct {
	typ reflect.Type

	mu          sync.Mutex
	structMap   map[string]uint64
	colMappings map[string][]uint64
}

func newMappingCache(typ reflect.Type) *mappingCache {
	return &mappingCache{
		typ:         typ,
		structMap:   MakeStructMapping(typ),
		colMappings: make(map[string][]uint64),
	}
}

func (b *mappingCache) mapping(cols []string) ([]uint64, error) {
	buf := strmangle.GetBuffer()
	defer strmangle.PutBuffer(buf)

	for _, s := range cols {
		buf.WriteString(s)
		buf.WriteByte(0)
	}

	key := buf.Bytes()

	b.mu.Lock()
	defer b.mu.Unlock()

	mapping := b.colMappings[string(key)]
	if mapping != nil {
		return mapping, nil
	}

	mapping, err := BindMapping(b.typ, b.structMap, cols)
	if err != nil {
		return nil, err
	}

	b.colMappings[string(key)] = mapping

	return mapping, nil
}

// Equal is different to reflect.DeepEqual in that it's both less efficient
// less magical, and dosen't concern itself with a wide variety of types that could
// be present but it does use the driver.Valuer interface since many types that will
// go through database things will use these.
//
// We're focused on basic types + []byte. Since we're really only interested in things
// that are typically used for primary keys in a database.
//
// Choosing not to use the DefaultParameterConverter here because sqlboiler doesn't generate
// pointer columns.
func Equal(a, b interface{}) bool {
	if (a == nil && b != nil) || (a != nil && b == nil) {
		return false
	}

	// Here we make a fast-path for bytes, because it's the most likely thing
	// this method will be called with.
	if ab, ok := a.([]byte); ok {
		if bb, ok := b.([]byte); ok {
			return bytes.Equal(ab, bb)
		}
	}

	var err error
	// If either is a sql.Scanner, pull the primitive value out before we get into type checking
	// since we can't compare complex types anyway.
	if v, ok := a.(driver.Valuer); ok {
		a, err = v.Value()
		if err != nil {
			panic(fmt.Sprintf("while comparing values, although 'a' implemented driver.Valuer, an error occured when calling it: %+v", err))
		}
	}
	if v, ok := b.(driver.Valuer); ok {
		b, err = v.Value()
		if err != nil {
			panic(fmt.Sprintf("while comparing values, although 'b' implemented driver.Valuer, an error occured when calling it: %+v", err))
		}
	}

	// Do nil checks again, since a Null type could have returned nil
	if (a == nil && b != nil) || (a != nil && b == nil) {
		return false
	}

	// If either is string and another is numeric, try to parse string as numeric
	if as, ok := a.(string); ok && isNumeric(b) {
		a = parseNumeric(as, reflect.TypeOf(b))
	}
	if bs, ok := b.(string); ok && isNumeric(a) {
		b = parseNumeric(bs, reflect.TypeOf(a))
	}

	a = upgradeNumericTypes(a)
	b = upgradeNumericTypes(b)

	if at, bt := reflect.TypeOf(a), reflect.TypeOf(b); at != bt {
		panic(fmt.Sprintf("primitive type of a (%s) was not the same primitive type as b (%s)", at.String(), bt.String()))
	}

	switch t := a.(type) {
	case int64, float64, bool, string:
		return a == b
	case []byte:
		return bytes.Equal(t, b.([]byte))
	case time.Time:
		return t.Equal(b.(time.Time))
	}

	return false
}

// isNumeric tests if i is a numeric value.
func isNumeric(i interface{}) bool {
	switch i.(type) {
	case int,
		int8,
		int16,
		int32,
		int64,
		uint,
		uint8,
		uint16,
		uint32,
		uint64,
		float32,
		float64:
		return true
	}
	return false
}

// parseNumeric tries to parse s as t.
// t must be a numeric type.
func parseNumeric(s string, t reflect.Type) interface{} {
	var (
		res interface{}
		err error
	)
	switch t.Kind() {
	case reflect.Int,
		reflect.Int8,
		reflect.Int16,
		reflect.Int32,
		reflect.Int64:
		res, err = strconv.ParseInt(s, 0, t.Bits())
	case reflect.Uint,
		reflect.Uint8,
		reflect.Uint16,
		reflect.Uint32,
		reflect.Uint64:
		res, err = strconv.ParseUint(s, 0, t.Bits())
	case reflect.Float32,
		reflect.Float64:
		res, err = strconv.ParseFloat(s, t.Bits())
	}
	if err != nil {
		panic(fmt.Sprintf("tries to parse %q as %s but got error: %+v", s, t.String(), err))
	}
	return res
}

// Assign assigns a value to another using reflection.
// Dst must be a pointer.
func Assign(dst, src interface{}) {
	// Fast path for []byte since it's one of the
	// most frequent other "ids" we'll be assigning.
	if db, ok := dst.(*[]byte); ok {
		if sb, ok := src.([]byte); ok {
			*db = make([]byte, len(sb))
			copy(*db, sb)
			return
		}
	}

	scan, isDstScanner := dst.(sql.Scanner)
	val, isSrcValuer := src.(driver.Valuer)

	switch {
	case isDstScanner && isSrcValuer:
		val, err := val.Value()
		if err != nil {
			panic(fmt.Sprintf("tried to call value on %T but got err: %+v", src, err))
		}

		err = scan.Scan(val)
		if err != nil {
			panic(fmt.Sprintf("tried to call Scan on %T with %#v but got err: %+v", dst, val, err))
		}

	case isDstScanner && !isSrcValuer:
		// Compress any lower width integer types
		src = upgradeNumericTypes(src)

		if err := scan.Scan(src); err != nil {
			panic(fmt.Sprintf("tried to call Scan on %T with %#v but got err: %+v", dst, src, err))
		}

	case !isDstScanner && isSrcValuer:
		val, err := val.Value()
		if err != nil {
			panic(fmt.Sprintf("tried to call value on %T but got err: %+v", src, err))
		}

		assignValue(dst, val)

	default:
		// We should always be comparing primitives with each other with == in templates
		// so this method should never be called for say: string, string, or int, int
		panic("this case should have been handled by something other than this method")
	}
}

func upgradeNumericTypes(i interface{}) interface{} {
	switch t := i.(type) {
	case int:
		return int64(t)
	case int8:
		return int64(t)
	case int16:
		return int64(t)
	case int32:
		return int64(t)
	case uint:
		return int64(t)
	case uint8:
		return int64(t)
	case uint16:
		return int64(t)
	case uint32:
		return int64(t)
	case uint64:
		return int64(t)
	case float32:
		return float64(t)
	default:
		return i
	}
}

// This whole function makes assumptions that whatever type
// dst is, will be compatible with whatever came out of the Valuer.
// We handle the types that driver.Value could possibly be.
func assignValue(dst interface{}, val driver.Value) {
	dstType := reflect.TypeOf(dst).Elem()
	dstVal := reflect.ValueOf(dst).Elem()

	if val == nil {
		dstVal.Set(reflect.Zero(dstType))
		return
	}

	v := reflect.ValueOf(val)

	switch dstType.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		dstVal.SetInt(v.Int())
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		dstVal.SetInt(int64(v.Uint()))
	case reflect.Bool:
		dstVal.SetBool(v.Bool())
	case reflect.String:
		dstVal.SetString(v.String())
	case reflect.Float32, reflect.Float64:
		dstVal.SetFloat(v.Float())
	case reflect.Slice:
		// Assume []byte
		db, sb := dst.(*[]byte), val.([]byte)
		*db = make([]byte, len(sb))
		copy(*db, sb)
	case reflect.Struct:
		// Assume time.Time
		dstVal.Set(v)
	}
}

// MustTime retrieves a time value from a valuer.
func MustTime(val driver.Valuer) time.Time {
	v, err := val.Value()
	if err != nil {
		panic(fmt.Sprintf("attempted to call value on %T to get time but got an error: %+v", val, err))
	}

	if v == nil {
		return time.Time{}
	}

	return v.(time.Time)
}

// IsValuerNil returns true if the valuer's value is null.
func IsValuerNil(val driver.Valuer) bool {
	v, err := val.Value()
	if err != nil {
		panic(fmt.Sprintf("attempted to call value on %T but got an error: %+v", val, err))
	}

	return v == nil
}

// IsNil is a more generic version of IsValuerNil, will check to make sure it's
// not a valuer first.
func IsNil(val interface{}) bool {
	if val == nil {
		return true
	}

	valuer, ok := val.(driver.Valuer)
	if ok {
		return IsValuerNil(valuer)
	}

	return reflect.ValueOf(val).IsNil()
}

// SetScanner attempts to set a scannable value on a scanner.
func SetScanner(scanner sql.Scanner, val driver.Value) {
	if err := scanner.Scan(val); err != nil {
		panic(fmt.Sprintf("attempted to call Scan on %T with %#v but got an error: %+v", scanner, val, err))
	}
}

// These are sorted by size so that the biggest thing
// gets replaced first (think guid/id). This list is copied
// from strmangle.uppercaseWords and should hopefully be kept
// in sync.
var specialWordReplacer = strings.NewReplacer(
	"ASCII", "Ascii",
	"GUID", "Guid",
	"JSON", "Json",
	"UUID", "Uuid",
	"UTF8", "Utf8",
	"ACL", "Acl",
	"API", "Api",
	"CPU", "Cpu",
	"EOF", "Eof",
	"RAM", "Ram",
	"SLA", "Sla",
	"UDP", "Udp",
	"UID", "Uid",
	"URI", "Uri",
	"URL", "Url",
	"ID", "Id",
	"IP", "Ip",
	"UI", "Ui",
)

// unTitleCase attempts to undo a title-cased string.
//
// DO NOT USE THIS METHOD IF YOU CAN AVOID IT
//
// Normally this would be easy but we have to deal with uppercased words
// of varying lengths. We almost never use this function so it
// can be as badly performing as we want. If people don't want to incur
// it's cost they should be able to use the `boil` struct tag to avoid it.
//
// We did not put this in strmangle because we don't want it being part
// of any public API as it's loaded with corner cases and sad performance.
func unTitleCase(n string) string {
	if len(n) == 0 {
		return ""
	}

	// Make our words no longer special case
	n = specialWordReplacer.Replace(n)

	buf := strmangle.GetBuffer()

	first := true

	writeIt := func(s string) {
		if first {
			first = false
		} else {
			buf.WriteByte('_')
		}
		buf.WriteString(strings.ToLower(s))
	}

	lastUp := true
	start := 0
	for i, r := range n {
		currentUp := unicode.IsUpper(r)
		isDigit := unicode.IsDigit(r)

		if !isDigit && !lastUp && currentUp {
			fragment := n[start:i]
			writeIt(fragment)
			start = i
		}

		if !isDigit && lastUp && !currentUp && i-1-start > 1 {
			fragment := n[start : i-1]
			writeIt(fragment)
			start = i - 1
		}

		lastUp = currentUp
	}

	remaining := n[start:]
	if len(remaining) > 0 {
		writeIt(remaining)
	}

	ret := buf.String()
	strmangle.PutBuffer(buf)
	return ret
}