text:
package tech.akpmakes.android.taskkeeper;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import tech.akpmakes.android.taskkeeper.models.WhenEvent;

public class TaskViewActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
    final Calendar whenTime = Calendar.getInstance();
    EditText taskName;
    TextView taskDate;
    TextView taskTime;
    CheckBox useCurrentTime;
    String whenKey;

    PreferenceManager pref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_view);
        taskName = findViewById(R.id.task_name_content);
        taskDate = findViewById(R.id.task_when_date);
        taskTime = findViewById(R.id.task_when_time);
        useCurrentTime = findViewById(R.id.useCurrentTime);
        pref = new PreferenceManager(this);

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(useCurrentTime.isChecked()) {
                    updateTime();
                }
                handler.postDelayed( this, delay() );
            }
        }, delay());

        Intent i = getIntent();
        if (i.hasExtra("whenName")) {
            taskName.setText(i.getStringExtra("whenName"));
        }

        if (i.hasExtra("whenTime")) {
            useCurrentTime.setChecked(false);
            whenTime.setTimeInMillis(i.getLongExtra("whenTime", 0));
        }

        if (i.hasExtra("whenKey")) {
            whenKey = i.getStringExtra("whenKey");
        }

        updateDateTimeUI();

        taskDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar now = whenTime;
                DatePickerDialog datePicker = new DatePickerDialog(
                        TaskViewActivity.this,
                        TaskViewActivity.this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && pref.getFirstDayOfWeek() > 0) {
                    datePicker.getDatePicker().setFirstDayOfWeek(pref.getFirstDayOfWeek());
                }
                datePicker.show();
            }
        });

        taskTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar now = whenTime;
                TimePickerDialog timePicker = new TimePickerDialog(
                        TaskViewActivity.this,
                        TaskViewActivity.this,
                        now.get(Calendar.HOUR_OF_DAY),
                        now.get(Calendar.MINUTE),
                        android.text.format.DateFormat.is24HourFormat(TaskViewActivity.this)
                );
                timePicker.show();
            }
        });

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }

    private long delay() {
        return 1000 - (SystemClock.uptimeMillis() % 1000);
    }

    private void saveTask() {
        if(useCurrentTime.isChecked()) {
            updateTime();
        }
        String name = taskName.getText().toString();
        long when = whenTime.getTimeInMillis();
        if (name.length() == 0) {
            taskName.setError("Task name is required!");
            return;
        }
        WhenEvent evt = new WhenEvent(name, when);
        Intent i = new Intent();
        i.putExtra("whenName", evt.getName());
        i.putExtra("whenTime", evt.getWhen());
        if(whenKey != null) {
            i.putExtra("whenKey", whenKey);
        }
        setResult(Activity.RESULT_OK, i);
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.add_task_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.save_task:
                saveTask();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
        whenTime.set(Calendar.YEAR, year);
        whenTime.set(Calendar.MONTH, monthOfYear);
        whenTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        useCurrentTime.setChecked(false);

        updateDateTimeUI();
    }

    @Override
    public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
        whenTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
        whenTime.set(Calendar.MINUTE, minute);
        whenTime.set(Calendar.SECOND, 0);

        useCurrentTime.setChecked(false);

        updateDateTimeUI();
    }

    private void updateTime() {
        whenTime.setTimeInMillis(System.currentTimeMillis());
        updateDateTimeUI();
    }

    private void updateDateTimeUI() {
        DateFormat dateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG);
        DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
        taskDate.setText(dateFormat.format(whenTime.getTime()));
        taskTime.setText(timeFormat.format(whenTime.getTime()));
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>targets.numerai_submission — numerflow v1.0.0 documentation</title>
    <link rel="stylesheet" href="../../_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />

  <link rel="stylesheet" href="../../_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Source code for targets.numerai_submission

import os
import sys
import luigi
from numerapi.numerapi import NumerAPI

[docs]class SubmissionTarget(luigi.target.Target):
    """
    Implements a submission target to "output" predictions from luigi tasks on
    the numer.ai servers.
    """

[docs]    def __init__(self, path, public_id, secret):
        """
        Creates a new SubmissionTarget.

        :param: path (str):
            local path to the predictions csv file
        :param: public_id (str):
            public_id as reported by the numer.ai website when creating API
            credentials
        :param: secret (str):
            secret as reported by the numer.ai website when creating API
            credentials
        """
        self.path = path
        self.fn = os.path.split(path)[1]

        self.apc = NumerAPI(public_id, secret)

[docs]    def exists(self):
        """
        Checks if a submission for the file named :py:attr:`path` was uploaded.

        NB: the filename as reported by the server is appended by a random
        string (before the file extension), and we can just access the file
        that was submitted last. This might result in double uploads for the
        same file.
        """
        qry = "query user { user { latestSubmission { filename } } }"
        res = self.apc.raw_query(qry, authorization=True)

        data = res['data']['user']['latestSubmission']

        for d in data:
            if d['filename'].startswith(self.fn.replace('.csv', '')):
                return True

        return False

[docs]    def submit(self):
        """
        Submits the predictions to the numer.ai servers and tries to report
        back the status.
        """
        ret = self.apc.upload_predictions(self.path)

        print(self.apc.submission_status())

numerflow

Navigation

Contents:

Tasks

Targets

Workflow

🚀 Github

💾 Download Releases

Related Topics

Documentation overview

Module code

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2018, Christian Schulze.

      |
      Powered by Sphinx 1.7.0
      & Alabaster 0.7.10

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import importlib

def can_import(name, package=None):
    """ Returns True if the given module can be imported.
        # Arguments
        name: str. The name of the module.
        package: str. The name of the package, if `name` is a relative import.
            This is ignored for Python versions < 3.4.
        # Return value
        If importing the specified module should succeed, returns True;
        otherwise, returns False.
    """
    try:
        importlib.util.find_spec
    except AttributeError:
        # Python < 3.4
        return importlib.find_loader(       # pylint: disable=deprecated-method
            name
        ) is not None
    else:
        # Python >= 3.4
        return importlib.util.find_spec(name, package=package) is not None

def import_name(import_name):
    """Import dotted module path and return attribute/class.

    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImportError if the import failed.
    """
    import_name = str(import_name).replace(':', '.')

    try:
        module_name, class_name = import_name.rsplit('.', 1)
    except ValueError:
        raise ImportError("%s isn't a module path" % import_name)

    module = importlib.import_module(module_name)

    try:
        return getattr(module, class_name)
    except AttributeError:
        raise ImportError(
            'Module "%s" does not define a "%s" attribute/class' %
            (module_name, class_name))

def module_dir(module):
    """Find the name of the directory that contains a module, if possible.

    Raise ValueError otherwise, e.g. for namespace packages that are split
    over several directories.

    """
    paths = list(getattr(module, '__path__', []))
    if len(paths) == 1:
        return paths[0]
    else:
        filename = getattr(module, '__file__', None)
        if filename is not None:
            return os.path.dirname(filename)
    raise ValueError('Cannot determine directory containing {}'.format(module))

def load_modules_from_path(path):
    """Import all modules from the given directory."""
    # Check and fix the path
    path += '/' if not path.endswith('/') else ''

    # Get a list of files in the directory, if the directory exists
    if not os.path.exists(path):
        raise OSError('Directory does not exist: {}'.format(path))

    # Add path to the system path and load all the files
    sys.path.append(path)
    for f in os.listdir(path):
        # Ignore anything that isn't a .py file
        if len(f) > 3 and f.endswith('.py'):
            module_name = f.rstrip('.py')
            importlib.import_module(module_name)


text:
<?php
/**
 * Theme wrapper
 *
 * @link http://roots.io/an-introduction-to-the-roots-theme-wrapper/
 * @link http://scribu.net/wordpress/theme-wrappers.html
 */
function roots_template_path() {
  return Roots_Wrapping::$main_template;
}

function roots_sidebar_path() {
  return new Roots_Wrapping('templates/sidebar.php');
}

function roots_sidebar2_path() {
  return new Roots_Wrapping('templates/sidebar-secondary.php');
}

class Roots_Wrapping {
  // Stores the full path to the main template file
  static $main_template;

  // Stores the base name of the template file; e.g. 'page' for 'page.php' etc.
  static $base;

  public function __construct($template = 'base.php') {
    $this->slug = basename($template, '.php');
    $this->templates = array($template);

    if (self::$base) {
      $str = substr($template, 0, -4);
      array_unshift($this->templates, sprintf($str . '-%s.php', self::$base));
    }
  }

  public function __toString() {
    $this->templates = apply_filters('roots_wrap_' . $this->slug, $this->templates);
    return locate_template($this->templates);
  }

  static function wrap($main) {
    self::$main_template = $main;
    self::$base = basename(self::$main_template, '.php');

    if (self::$base === 'index') {
      self::$base = false;
    }

    return new Roots_Wrapping();
  }
}
add_filter('template_include', array('Roots_Wrapping', 'wrap'), 99);


text:
jQuery.extend = jQuery.fn.extend = function() {

	// Rule: requireMultipleVarDecl: "onyvar"
	// Rule: requirePaddingNewLinesBeforeLineComments
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[ 0 ] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Rule: validateQuoteMarks: ""
	if ( typeof target === "boolean" ) {

		// Rule: requireSpacesInAnonymousFunctionExpression: before curly
		// Rule: disallowSpacesInAnonymousFunctionExpression: before opening round brace
		$( "#foo" ).click( function() {
	} );
	}

	// Rule: disallowMultipleLineBreaks
	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {

		// Modified for Rule: requireCurlyBraces
		try {

			// Rule: requireSpacesInsideObjectBrackets
			target = { foo: "bar" };
		} catch ( e ) {
			throw e;
		}
	}

	// Rule: requireParenthesesAroundIIFE
	( function() {

	} )();

	// Only deal with non-null/undefined values
	if ( ( options = arguments[ i ] ) != null ) {

		// Extend the base object
		for ( name in options ) {

			// Prevent never-ending loop
			if ( target === copy ) {

				// Rule: disallowSpaceAfterPrefixUnaryOperators
				++i;

				// Rule: disallowSpaceBeforePostfixUnaryOperators
				i++;
				continue;
			}

			// Rule: requireOperatorBeforeLineBreak
			if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
				( copyIsArray = jQuery.isArray( copy ) ) ) ) {

			// Don't bring in undefined values
			} else if ( copy !== undefined ) {

				// Rule: requireSpacesInsideArrayBrackets
				target[ name ] = copy;
			}
		}
	}

	// Return the modified object
	return target;
};

// Rule: maximumLineLength
// Long comment with a URL ................................................................. http://www.google.com
// Regex
var seventyeightchars = /............................................................................../;

// Rule: requireSpacesInFunctionExpression: before curly
var each = function( obj, callback, args ) {

	// Rule: commaBeforeLineBreak
	var value,
		i = 0,

		// Rule: requireDotNotation
		length = obj.length,

		// Rule: requireCamelCaseOrUpperCaseIdentifiers
		isArray = isArraylike( obj );

	if ( args ) {
		if ( isArray ) {
			for ( ; i < length; i++ ) {

				// Rule: requireSpaceBetweenArguments
				value = callback.apply( obj[ i ], args );

				// Rule: requireSpaceAfterBinaryOperators
				if ( value === false ) {
					break;
				}
			}

			// Rule: disallowKeywordsOnNewLine
		} else {
			for ( i in obj ) {
				value = callback.apply( obj[ i ], args );

				// Rule: requireSpacesInConditionalExpression
				if ( value === false ) {
					break;
				}
			}
		}
	}
};

// Rule: requireSpacesInNamedFunctionExpression: before curly
// Rule: disallowSpacesInNamedFunctionExpression: before opening round brace
function isArraylike( obj ) {
	var length = obj.length,
		type = jQuery.type( obj );

	// Rule: requireSpaceAfterKeywords
	if ( type === "function" || jQuery.isWindow( obj ) ) {
		return false;
	}

	if ( obj.nodeType === 1 && length ) {
		return true;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}


text:
.. _argus_pep_pip_request_validator:

Request Validator PIP
---------------------

.. warning::
   **This PIP is new in Argus 1.3 (EMI).**

The Request Validator PIP validates the incoming authorization request.
It checks that the incoming authorization request contains at least one
subject, one resource and one action, and that the attributes within
them have at least one value, which is not null or an empty string.

Configuration
^^^^^^^^^^^^^

#. Create a new INI section for you PIP (you may
   choose any valid INI section name. e.g. ``REQVALIDATOR_PIP``)
#. Into the PIP INI section add the ``parserClass`` property with the
   value
   ``org.glite.authz.pep.pip.provider.RequestValidatorPIPIniConfigurationParser``
#. Configure how the authorization request must be validated

PIP Configuration Properties
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

+----------------------------+---------------------------------------------------------------+-----------+---------------+
| Property                   | Description                                                   | Required? | Default Value |
+============================+===============================================================+===========+===============+
| validateRequestSubjects    | Require at least one subject with non-empty attribute values  | N         | ``true``      |
+----------------------------+---------------------------------------------------------------+-----------+---------------+
| validateRequestResources   | Require at least one resource with non-empty attribute values | N         | ``true``      |
+----------------------------+---------------------------------------------------------------+-----------+---------------+
| validateRequestAction      | Require one action with non-empty attribute values            | N         | ``true``      |
+----------------------------+---------------------------------------------------------------+-----------+---------------+
| validateRequestEnvironment | Require one environment with non-empty attribute values       | N         | ``false``     |
+----------------------------+---------------------------------------------------------------+-----------+---------------+

Example Configuration
^^^^^^^^^^^^^^^^^^^^^

The following example shows a PEP server configuration with the request
validator PIP enabled. The PIP validates the incoming authorization
request and checks that it contains at least one subject, at least one
resource and one action, all with non-empty or null attributes values.

::

    [SERVICE]
    entityId = https://example.org/pep
    hostname = example.org
    pips = REQVALIDATOR_PIP

    [PDP]
    pdps = http://localhost:8152/authz

    [SECURITY]
    trustInfoDir = /etc/grid-security/certificates

    [REQVALIDATOR_PIP]
    parserClass = org.glite.authz.pep.pip.provider.RequestValidatorPIPIniConfigurationParser
    validateRequestSubjects = true
    validateRequestResources = true
    validateRequestAction = true
    validateRequestEnvironment = false


text:
author: sourrabbit
date: '2009-04-12 14:03:51'
layout: post
slug: lovefree
status: publish
comments: true
title: love&free
wordpress_id: '511'
---

If you love something, set it free.

If it comes back to you, it is yours.

If it doesn't , it never was.


text:
<?php

namespace App\EventListener;

use App\DTO\Api1\ImsxCodeMinor;
use App\DTO\Api1\ImsxCodeMinorField;
use App\DTO\Api1\ImsxStatusInfo;
use App\Service\LoggerTrait;
use Ramsey\Uuid\Uuid;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Serializer\SerializerInterface;

class ApiExceptionListener implements EventSubscriberInterface
{
    use LoggerTrait;

    public function __construct(
        private SerializerInterface $serializer,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::EXCEPTION => 'onKernelException'];
    }

    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getThrowable();
        if (!($exception instanceof NotFoundHttpException)) {
            return;
        }

        $request = $event->getRequest();
        if ('json' !== $request->getRequestFormat()) {
            return;
        }

        if (!str_starts_with($request->getPathInfo(), '/ims/case/v1p0/')) {
            return;
        }

        $event->setResponse($this->generate404($request->attributes->get('id'), $request->getRequestFormat('json')));
    }

    protected function generate404(string $identifier, string $_format): Response
    {
        // Object not found
        if ($this->isUuidValid($identifier)) {
            $errField = new ImsxCodeMinorField('sourcedId', ImsxCodeMinorField::CODE_MINOR_UNKNOWN_OBJECT);
            $errText = 'Not Found';
        } else {
            $errField = new ImsxCodeMinorField('sourcedId', ImsxCodeMinorField::CODE_MINOR_INVALID_UUID);
            $errText = 'Invalid UUID';
        }
        $errMinor = new ImsxCodeMinor([$errField]);
        $err = new ImsxStatusInfo(
            ImsxStatusInfo::CODE_MAJOR_FAILURE,
            ImsxStatusInfo::SEVERITY_ERROR,
            $errMinor
        );

        $this->info('CASE API: Not Found', ['identifier' => $identifier]);

        $response = new Response(
            $this->serializer->serialize($err, $_format),
            Response::HTTP_NOT_FOUND
        );
        $response->setStatusCode(Response::HTTP_NOT_FOUND, $errText); // Add error text for IMS Global Compliance Test Suite

        $response->setMaxAge(60);
        $response->setSharedMaxAge(60);
        $response->setPublic();

        return $response;
    }

    protected function isUuidValid(string $uuid): bool
    {
        if (!Uuid::isValid($uuid)) {
            return false;
        }

        if (!preg_match('/[a-f0-9]{8}-[a-f0-9]{4}-[12345][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}/', $uuid)) {
            // Only allow Variant 1 UUIDs for CASE Compliance test
            return false;
        }

        return true;
    }
}


text:
//---------------------------------------------------------------------------//

//---------------------------------------------------------------------------//
/*!
  * \file DTK_BoxGeometryImpl.cpp
  * \author Stuart R. Slattery
  * \brief BoxGeometry implementation.
  */
//---------------------------------------------------------------------------//

#include "DTK_BoxGeometryImpl.hpp"
#include "DTK_DBC.hpp"

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
 * \brief Default constructor.
 */
BoxGeometryImpl::BoxGeometryImpl()
    : d_global_id( dtk_invalid_entity_id )
    , d_owner_rank( -1 )
    , d_block_id( 0 )
    , d_x_min( 0.0 )
    , d_y_min( 0.0 )
    , d_z_min( 0.0 )
    , d_x_max( 0.0 )
    , d_y_max( 0.0 )
    , d_z_max( 0.0 )
{ /* ... */
}

//---------------------------------------------------------------------------//
/*!
 * \brief Constructor.
 *
 * \param global_id Unique global ID for this entity.
 *
 * \param owner_rank MPI rank that wons this entity.
 *
 * \param block_id Block ID this entity belongs to.
 *
 * \param x_min Minimum x coordinate value in the box.
 *
 * \param y_min Minimum y coordinate value in the box.
 *
 * \param z_min Minimum z coordinate value in the box.
 *
 * \param x_max Maximum x coordinate value in the box.
 *
 * \param y_max Maximum y coordinate value in the box.
 *
 * \param z_max Maximum z coordinate value in the box.
 */
BoxGeometryImpl::BoxGeometryImpl( const EntityId global_id,
                                  const int owner_rank, const int block_id,
                                  const double x_min, const double y_min,
                                  const double z_min, const double x_max,
                                  const double y_max, const double z_max )
    : d_global_id( global_id )
    , d_owner_rank( owner_rank )
    , d_block_id( block_id )
    , d_x_min( x_min )
    , d_y_min( y_min )
    , d_z_min( z_min )
    , d_x_max( x_max )
    , d_y_max( y_max )
    , d_z_max( z_max )
{
    DTK_REQUIRE( d_x_min <= d_x_max );
    DTK_REQUIRE( d_y_min <= d_y_max );
    DTK_REQUIRE( d_z_min <= d_z_max );
}

//---------------------------------------------------------------------------//
/*!
 * \brief Tuple constructor.
 *
 * \param global_id Unique global ID for this entity.
 * \param owner_rank MPI rank that wons this entity.
 * \param block_id Block ID this entity belongs to.
 * \param bounds Tuple containing {x_min, y_min, z_min, x_max, y_max, z_max}.
 */
BoxGeometryImpl::BoxGeometryImpl( const EntityId global_id,
                                  const int owner_rank, const int block_id,
                                  const Teuchos::Tuple<double, 6> &bounds )
    : d_global_id( global_id )
    , d_owner_rank( owner_rank )
    , d_block_id( block_id )
    , d_x_min( bounds[0] )
    , d_y_min( bounds[1] )
    , d_z_min( bounds[2] )
    , d_x_max( bounds[3] )
    , d_y_max( bounds[4] )
    , d_z_max( bounds[5] )
{
    DTK_REQUIRE( d_x_min <= d_x_max );
    DTK_REQUIRE( d_y_min <= d_y_max );
    DTK_REQUIRE( d_z_min <= d_z_max );
}

//---------------------------------------------------------------------------//
// Get the unique global identifier for the entity.
EntityId BoxGeometryImpl::id() const { return d_global_id; }

//---------------------------------------------------------------------------//
// Get the parallel rank that owns the entity.
int BoxGeometryImpl::ownerRank() const { return d_owner_rank; }

//---------------------------------------------------------------------------//
// Return the topological dimension of the entity.
int BoxGeometryImpl::topologicalDimension() const { return 3; }

//---------------------------------------------------------------------------//
// Return the physical dimension of the entity.
int BoxGeometryImpl::physicalDimension() const { return 3; }

//---------------------------------------------------------------------------//
/*!
 * \brief Compute the bounding box around the box.
 *
 * \return The bounding box bounds.
 */
void BoxGeometryImpl::boundingBox( Teuchos::Tuple<double, 6> &bounds ) const
{
    bounds =
        Teuchos::tuple( d_x_min, d_y_min, d_z_min, d_x_max, d_y_max, d_z_max );
}

//---------------------------------------------------------------------------//
// Determine if an entity is in the block with the given id.
bool BoxGeometryImpl::inBlock( const int block_id ) const
{
    return ( block_id == d_block_id );
}

//---------------------------------------------------------------------------//
// Determine if an entity is on the boundary with the given id.
bool BoxGeometryImpl::onBoundary( const int boundary_id ) const
{
    return false;
}

//---------------------------------------------------------------------------//
void BoxGeometryImpl::describe(
    Teuchos::FancyOStream &out,
    const Teuchos::EVerbosityLevel /*verb_level*/ ) const
{
    out << "---" << std::endl;
    out << description() << std::endl;
    out << "Id: " << id() << std::endl;
    out << "Owner rank: " << ownerRank() << std::endl;
    out << "Block id: " << d_block_id << std::endl;
    out << "(xmin,ymin,zmin,xmax,ymax,zmax): " << d_x_min << " " << d_y_min
        << " " << d_z_min << " " << d_x_max << " " << d_y_max << " " << d_z_max
        << std::endl;
}

//---------------------------------------------------------------------------//
/*!
 * \brief Compute the measure of the box.
 *
 * \return Return the measure of the box.
 */
double BoxGeometryImpl::measure() const
{
    return ( d_x_max - d_x_min ) * ( d_y_max - d_y_min ) *
           ( d_z_max - d_z_min );
}

//---------------------------------------------------------------------------//
/*!
 * \brief Get the centroid of the box.
 *
 * \return The centroid coordinates.
 */
void BoxGeometryImpl::centroid(
    const Teuchos::ArrayView<double> &centroid ) const
{
    centroid[0] = ( d_x_max + d_x_min ) / 2.0;
    centroid[1] = ( d_y_max + d_y_min ) / 2.0;
    centroid[2] = ( d_z_max + d_z_min ) / 2.0;
}

//---------------------------------------------------------------------------//
/*!
 * \brief Map a point to the reference space of an entity. Return the
 */
bool BoxGeometryImpl::mapToReferenceFrame(
    const Teuchos::ArrayView<const double> &point,
    const Teuchos::ArrayView<double> &reference_point ) const
{
    reference_point.assign( point );
    return true;
}

//---------------------------------------------------------------------------//
/*!
 * \brief Determine if a reference point is in the parameterized space of
 * an entity.
 */
bool BoxGeometryImpl::checkPointInclusion(
    const double tolerance,
    const Teuchos::ArrayView<const double> &reference_point ) const
{
    DTK_REQUIRE( 3 == reference_point.size() );

    double x_tol = ( d_x_max - d_x_min ) * tolerance;
    double y_tol = ( d_y_max - d_y_min ) * tolerance;
    double z_tol = ( d_z_max - d_z_min ) * tolerance;

    if ( reference_point[0] >= d_x_min - x_tol &&
         reference_point[1] >= d_y_min - y_tol &&
         reference_point[2] >= d_z_min - z_tol &&
         reference_point[0] <= d_x_max + x_tol &&
         reference_point[1] <= d_y_max + y_tol &&
         reference_point[2] <= d_z_max + z_tol )
    {
        return true;
    }

    return false;
}

//---------------------------------------------------------------------------//
/*!
 * \brief Map a reference point to the physical space of an entity.
 */
void BoxGeometryImpl::mapToPhysicalFrame(
    const Teuchos::ArrayView<const double> &reference_point,
    const Teuchos::ArrayView<double> &point ) const
{
    point.assign( reference_point );
}

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

} // end namespace DataTransferKit

//---------------------------------------------------------------------------//
// end DTK_BoxGeometryImpl.cpp
//---------------------------------------------------------------------------//


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kooboo.Globalization;

namespace Kooboo.CMS.Sites
{
    public class FieldError
    {
        public string FieldName { get; set; }
        public string ErrorMessage { get; set; }
    }
    public class JsonResultEntry
    {
        public JsonResultEntry()
        {
            this.Success = true;
            Messages = new string[0];
            FieldErrors = new FieldError[0];
        }

        public JsonResultEntry(ModelStateDictionary modelState)
            : this()
        {
            this.AddModelState(modelState);
        }

        public JsonResultEntry SetFailed()
        {
            this.Success = false;
            return this;
        }

        public JsonResultEntry SetSuccess()
        {
            //this.Messages = new string[1] { "Submit successfully!".Localize() };
            this.Success = true;
            return this;
        }

        public JsonResultEntry AddModelState(ModelStateDictionary modelState)
        {
            foreach (var ms in modelState)
            {
                foreach (var err in ms.Value.Errors)
                {
                    this.AddFieldError(ms.Key, err.ErrorMessage);
                }
            }

            return this;
        }

        public bool Success { get; set; }
        public string[] Messages { get; set; }
        public object Model { get; set; }
        public string RedirectUrl { get; set; }
        public bool ReloadPage { get; set; }
        private bool redirectToOpener = true;
        public bool RedirectToOpener { get { return redirectToOpener; } set { redirectToOpener = value; } }
        public FieldError[] FieldErrors { get; set; }
        public JsonResultEntry AddFieldError(string fieldName, string message)
        {
            Success = false;
            FieldErrors = FieldErrors.Concat(new[] { new FieldError() { FieldName = fieldName, ErrorMessage = message } }).ToArray();
            return this;
        }
        public JsonResultEntry AddMessage(string message)
        {
            Messages = Messages.Concat(new[] { message }).ToArray();
            return this;
        }
        public JsonResultEntry AddException(Exception e)
        {
            Kooboo.HealthMonitoring.Log.LogException(e);
            //the exception message can be wrapped.
            this.Success = false;
            return AddMessage(e.Message);
        }
    }
}


text:
import { Component, Input } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

// TODO: forward focus-, blur- and click-events if enabled

@Component({
  selector: 'adf-custom-checkbox',
  template: `
    <CheckBox
      [id]="id"
      [text]="text"
      [isEnabled]="isEnabled"
      [checked]="checked"
      (checkedChange)="checkedChange($event.value)"
      class="checkbox"
    ></CheckBox>
  `,
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: CustomCheckBoxComponent, multi: true }],
})
export class CustomCheckBoxComponent implements ControlValueAccessor {
  @Input()
  id?: string;

  @Input()
  text?: string;

  checked: boolean;
  isEnabled: boolean;

  constructor() {
    this.checked = false;
    this.isEnabled = true;
  }

  private onChange = (val: any): void => {};

  // tslint:disable no-unused-variable
  private onTouched = (): void => {};

  public checkedChange(checked: boolean): void {
    this.checked = !!checked;
    this.onChange(this.checked);
  }

  public registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  public registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
  writeValue(value: any): void {
    this.checked = !!value;
  }
  setDisabledState(isDisabled: boolean): void {
    this.isEnabled = !isDisabled;
  }
}


text:
#include "ntdll.h"
#include "PEB.h"

#ifdef _WIN64
#pragma comment(lib, "ntdll_x64.lib")
#else
#pragma comment(lib, "ntdll_x86.lib")
#endif

//Quote from The Ultimate Anti-Debugging Reference by Peter Ferrie
//Flags field exists at offset 0x0C in the heap on the 32-bit versions of Windows NT, Windows 2000, and Windows XP; and at offset 0x40 on the 32-bit versions of Windows Vista and later.
//Flags field exists at offset 0x14 in the heap on the 64-bit versions of Windows XP, and at offset 0x70 in the heap on the 64-bit versions of Windows Vista and later.
//ForceFlags field exists at offset 0x10 in the heap on the 32-bit versions of Windows NT, Windows 2000, and Windows XP; and at offset 0x44 on the 32-bit versions of Windows Vista and later.
//ForceFlags field exists at offset 0x18 in the heap on the 64-bit versions of Windows XP, and at offset 0x74 in the heap on the 64-bit versions of Windows Vista and later.

static bool
IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
{
    OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
    DWORDLONG        const dwlConditionMask = VerSetConditionMask(
                VerSetConditionMask(
                    VerSetConditionMask(
                        0, VER_MAJORVERSION, VER_GREATER_EQUAL),
                    VER_MINORVERSION, VER_GREATER_EQUAL),
                VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);

    osvi.dwMajorVersion = wMajorVersion;
    osvi.dwMinorVersion = wMinorVersion;
    osvi.wServicePackMajor = wServicePackMajor;

    return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE;
}

static bool
IsWindowsVistaOrGreater()
{
    return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0);
}

static int getHeapFlagsOffset(bool x64)
{
    if(x64)   //x64 offsets
    {
        if(IsWindowsVistaOrGreater())
        {
            return 0x70;
        }
        else
        {
            return 0x14;
        }
    }
    else //x86 offsets
    {
        if(IsWindowsVistaOrGreater())
        {
            return 0x40;
        }
        else
        {
            return 0x0C;
        }
    }
}

static int getHeapForceFlagsOffset(bool x64)
{
    if(x64)   //x64 offsets
    {
        if(IsWindowsVistaOrGreater())
        {
            return 0x74;
        }
        else
        {
            return 0x18;
        }
    }
    else //x86 offsets
    {
        if(IsWindowsVistaOrGreater())
        {
            return 0x44;
        }
        else
        {
            return 0x10;
        }
    }
}

static void* GetPEBLocation_(HANDLE hProcess)
{
    ULONG RequiredLen = 0;
    void* PebAddress = 0;
    PROCESS_BASIC_INFORMATION myProcessBasicInformation[5] = { 0 };

    if(NtQueryInformationProcess(hProcess, ProcessBasicInformation, myProcessBasicInformation, sizeof(PROCESS_BASIC_INFORMATION), &RequiredLen) == 0)
    {
        PebAddress = (void*)myProcessBasicInformation->PebBaseAddress;
    }
    else
    {
        if(NtQueryInformationProcess(hProcess, ProcessBasicInformation, myProcessBasicInformation, RequiredLen, &RequiredLen) == 0)
        {
            PebAddress = (void*)myProcessBasicInformation->PebBaseAddress;
        }
    }

    return PebAddress;
}

static bool PebPatchHeapFlags(PEB_CURRENT* peb, HANDLE hProcess)
{
#ifdef _WIN64
    const auto is_x64 = true;
#else
    const auto is_x64 = false;
#endif

    std::vector<PVOID> heaps;
    heaps.resize(peb->NumberOfHeaps);

    if(ReadProcessMemory(hProcess, (PVOID)peb->ProcessHeaps, (PVOID)heaps.data(), heaps.size() * sizeof(PVOID), nullptr) == FALSE)
        return false;

    std::basic_string<uint8_t> heap;
    heap.resize(0x100); // hacky
    for(DWORD i = 0; i < peb->NumberOfHeaps; i++)
    {
        if(ReadProcessMemory(hProcess, heaps[i], (PVOID)heap.data(), heap.size(), nullptr) == FALSE)
            return false;

        auto flags = (DWORD*)(heap.data() + getHeapFlagsOffset(is_x64));
        auto force_flags = (DWORD*)(heap.data() + getHeapForceFlagsOffset(is_x64));

        if(i == 0)
        {
            // Default heap.
            *flags &= HEAP_GROWABLE;
        }
        else
        {
            // Flags from RtlCreateHeap/HeapCreate.
            *flags &= (HEAP_GROWABLE | HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_CREATE_ENABLE_EXECUTE);
        }

        *force_flags = 0;

        if(WriteProcessMemory(hProcess, heaps[i], (PVOID)heap.data(), heap.size(), nullptr) == FALSE)
            return false;
    }

    return true;
}

static bool FixPebInProcess(HANDLE hProcess)
{
    PEB_CURRENT myPEB = { 0 };
    SIZE_T ueNumberOfBytesRead = 0;
    void* heapFlagsAddress = 0;
    DWORD heapFlags = 0;
    void* heapForceFlagsAddress = 0;
    DWORD heapForceFlags = 0;

    void* AddressOfPEB = GetPEBLocation(hProcess);

    if(!AddressOfPEB)
        return false;

    if(ReadProcessMemory(hProcess, AddressOfPEB, (void*)&myPEB, sizeof(PEB_CURRENT), &ueNumberOfBytesRead))
    {
        myPEB.BeingDebugged = FALSE;
        myPEB.NtGlobalFlag &= ~0x70;

#ifdef _WIN64
        heapFlagsAddress = (void*)((LONG_PTR)myPEB.ProcessHeap + getHeapFlagsOffset(true));
        heapForceFlagsAddress = (void*)((LONG_PTR)myPEB.ProcessHeap + getHeapForceFlagsOffset(true));
#else
        heapFlagsAddress = (void*)((LONG_PTR)myPEB.ProcessHeap + getHeapFlagsOffset(false));
        heapForceFlagsAddress = (void*)((LONG_PTR)myPEB.ProcessHeap + getHeapForceFlagsOffset(false));
#endif //_WIN64

        ReadProcessMemory(hProcess, heapFlagsAddress, &heapFlags, sizeof(DWORD), 0);
        ReadProcessMemory(hProcess, heapForceFlagsAddress, &heapForceFlags, sizeof(DWORD), 0);

        heapFlags &= HEAP_GROWABLE;
        heapForceFlags = 0;

        WriteProcessMemory(hProcess, heapFlagsAddress, &heapFlags, sizeof(DWORD), 0);
        WriteProcessMemory(hProcess, heapForceFlagsAddress, &heapForceFlags, sizeof(DWORD), 0);

        PebPatchHeapFlags(&myPEB, hProcess);

        if(WriteProcessMemory(hProcess, AddressOfPEB, (void*)&myPEB, sizeof(PEB_CURRENT), &ueNumberOfBytesRead))
        {
            return true;
        }
    }
    return false;
}


text:
package armappplatform

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// ServicesClient contains the methods for the Services group.
// Don't use this type directly, use NewServicesClient() instead.
type ServicesClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewServicesClient creates a new instance of ServicesClient with the specified values.
// subscriptionID - Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ServicesClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &ServicesClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// CheckNameAvailability - Checks that the resource name is valid and is not already in use.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// location - the region
// availabilityParameters - Parameters supplied to the operation.
// options - ServicesClientCheckNameAvailabilityOptions contains the optional parameters for the ServicesClient.CheckNameAvailability
// method.
func (client *ServicesClient) CheckNameAvailability(ctx context.Context, location string, availabilityParameters NameAvailabilityParameters, options *ServicesClientCheckNameAvailabilityOptions) (ServicesClientCheckNameAvailabilityResponse, error) {
	req, err := client.checkNameAvailabilityCreateRequest(ctx, location, availabilityParameters, options)
	if err != nil {
		return ServicesClientCheckNameAvailabilityResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientCheckNameAvailabilityResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientCheckNameAvailabilityResponse{}, runtime.NewResponseError(resp)
	}
	return client.checkNameAvailabilityHandleResponse(resp)
}

// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request.
func (client *ServicesClient) checkNameAvailabilityCreateRequest(ctx context.Context, location string, availabilityParameters NameAvailabilityParameters, options *ServicesClientCheckNameAvailabilityOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AppPlatform/locations/{location}/checkNameAvailability"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if location == "" {
		return nil, errors.New("parameter location cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, availabilityParameters)
}

// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response.
func (client *ServicesClient) checkNameAvailabilityHandleResponse(resp *http.Response) (ServicesClientCheckNameAvailabilityResponse, error) {
	result := ServicesClientCheckNameAvailabilityResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.NameAvailability); err != nil {
		return ServicesClientCheckNameAvailabilityResponse{}, err
	}
	return result, nil
}

// BeginCreateOrUpdate - Create a new Service or update an exiting Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// resource - Parameters for the create or update operation
// options - ServicesClientBeginCreateOrUpdateOptions contains the optional parameters for the ServicesClient.BeginCreateOrUpdate
// method.
func (client *ServicesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource, options *ServicesClientBeginCreateOrUpdateOptions) (*runtime.Poller[ServicesClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, serviceName, resource, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[ServicesClientCreateOrUpdateResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[ServicesClientCreateOrUpdateResponse](options.ResumeToken, client.pl, nil)
	}
}

// CreateOrUpdate - Create a new Service or update an exiting Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
func (client *ServicesClient) createOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource, options *ServicesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, resource, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *ServicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource, options *ServicesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, resource)
}

// BeginDelete - Operation to delete a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// options - ServicesClientBeginDeleteOptions contains the optional parameters for the ServicesClient.BeginDelete method.
func (client *ServicesClient) BeginDelete(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginDeleteOptions) (*runtime.Poller[ServicesClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, serviceName, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[ServicesClientDeleteResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[ServicesClientDeleteResponse](options.ResumeToken, client.pl, nil)
	}
}

// Delete - Operation to delete a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
func (client *ServicesClient) deleteOperation(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginDeleteOptions) (*http.Response, error) {
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *ServicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// DisableTestEndpoint - Disable test endpoint functionality for a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// options - ServicesClientDisableTestEndpointOptions contains the optional parameters for the ServicesClient.DisableTestEndpoint
// method.
func (client *ServicesClient) DisableTestEndpoint(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientDisableTestEndpointOptions) (ServicesClientDisableTestEndpointResponse, error) {
	req, err := client.disableTestEndpointCreateRequest(ctx, resourceGroupName, serviceName, options)
	if err != nil {
		return ServicesClientDisableTestEndpointResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientDisableTestEndpointResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientDisableTestEndpointResponse{}, runtime.NewResponseError(resp)
	}
	return ServicesClientDisableTestEndpointResponse{}, nil
}

// disableTestEndpointCreateRequest creates the DisableTestEndpoint request.
func (client *ServicesClient) disableTestEndpointCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientDisableTestEndpointOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/disableTestEndpoint"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// EnableTestEndpoint - Enable test endpoint functionality for a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// options - ServicesClientEnableTestEndpointOptions contains the optional parameters for the ServicesClient.EnableTestEndpoint
// method.
func (client *ServicesClient) EnableTestEndpoint(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientEnableTestEndpointOptions) (ServicesClientEnableTestEndpointResponse, error) {
	req, err := client.enableTestEndpointCreateRequest(ctx, resourceGroupName, serviceName, options)
	if err != nil {
		return ServicesClientEnableTestEndpointResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientEnableTestEndpointResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientEnableTestEndpointResponse{}, runtime.NewResponseError(resp)
	}
	return client.enableTestEndpointHandleResponse(resp)
}

// enableTestEndpointCreateRequest creates the EnableTestEndpoint request.
func (client *ServicesClient) enableTestEndpointCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientEnableTestEndpointOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/enableTestEndpoint"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// enableTestEndpointHandleResponse handles the EnableTestEndpoint response.
func (client *ServicesClient) enableTestEndpointHandleResponse(resp *http.Response) (ServicesClientEnableTestEndpointResponse, error) {
	result := ServicesClientEnableTestEndpointResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.TestKeys); err != nil {
		return ServicesClientEnableTestEndpointResponse{}, err
	}
	return result, nil
}

// Get - Get a Service and its properties.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// options - ServicesClientGetOptions contains the optional parameters for the ServicesClient.Get method.
func (client *ServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientGetOptions) (ServicesClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, options)
	if err != nil {
		return ServicesClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *ServicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *ServicesClient) getHandleResponse(resp *http.Response) (ServicesClientGetResponse, error) {
	result := ServicesClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ServiceResource); err != nil {
		return ServicesClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - Handles requests to list all resources in a resource group.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// options - ServicesClientListOptions contains the optional parameters for the ServicesClient.List method.
func (client *ServicesClient) NewListPager(resourceGroupName string, options *ServicesClientListOptions) *runtime.Pager[ServicesClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[ServicesClientListResponse]{
		More: func(page ServicesClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ServicesClientListResponse) (ServicesClientListResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listCreateRequest(ctx, resourceGroupName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return ServicesClientListResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return ServicesClientListResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return ServicesClientListResponse{}, runtime.NewResponseError(resp)
			}
			return client.listHandleResponse(resp)
		},
	})
}

// listCreateRequest creates the List request.
func (client *ServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *ServicesClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *ServicesClient) listHandleResponse(resp *http.Response) (ServicesClientListResponse, error) {
	result := ServicesClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ServiceResourceList); err != nil {
		return ServicesClientListResponse{}, err
	}
	return result, nil
}

// NewListBySubscriptionPager - Handles requests to list all resources in a subscription.
// Generated from API version 2022-11-01-preview
// options - ServicesClientListBySubscriptionOptions contains the optional parameters for the ServicesClient.ListBySubscription
// method.
func (client *ServicesClient) NewListBySubscriptionPager(options *ServicesClientListBySubscriptionOptions) *runtime.Pager[ServicesClientListBySubscriptionResponse] {
	return runtime.NewPager(runtime.PagingHandler[ServicesClientListBySubscriptionResponse]{
		More: func(page ServicesClientListBySubscriptionResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ServicesClientListBySubscriptionResponse) (ServicesClientListBySubscriptionResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listBySubscriptionCreateRequest(ctx, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return ServicesClientListBySubscriptionResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return ServicesClientListBySubscriptionResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return ServicesClientListBySubscriptionResponse{}, runtime.NewResponseError(resp)
			}
			return client.listBySubscriptionHandleResponse(resp)
		},
	})
}

// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *ServicesClient) listBySubscriptionCreateRequest(ctx context.Context, options *ServicesClientListBySubscriptionOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AppPlatform/Spring"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *ServicesClient) listBySubscriptionHandleResponse(resp *http.Response) (ServicesClientListBySubscriptionResponse, error) {
	result := ServicesClientListBySubscriptionResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ServiceResourceList); err != nil {
		return ServicesClientListBySubscriptionResponse{}, err
	}
	return result, nil
}

// ListTestKeys - List test keys for a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// options - ServicesClientListTestKeysOptions contains the optional parameters for the ServicesClient.ListTestKeys method.
func (client *ServicesClient) ListTestKeys(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientListTestKeysOptions) (ServicesClientListTestKeysResponse, error) {
	req, err := client.listTestKeysCreateRequest(ctx, resourceGroupName, serviceName, options)
	if err != nil {
		return ServicesClientListTestKeysResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientListTestKeysResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientListTestKeysResponse{}, runtime.NewResponseError(resp)
	}
	return client.listTestKeysHandleResponse(resp)
}

// listTestKeysCreateRequest creates the ListTestKeys request.
func (client *ServicesClient) listTestKeysCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientListTestKeysOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/listTestKeys"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listTestKeysHandleResponse handles the ListTestKeys response.
func (client *ServicesClient) listTestKeysHandleResponse(resp *http.Response) (ServicesClientListTestKeysResponse, error) {
	result := ServicesClientListTestKeysResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.TestKeys); err != nil {
		return ServicesClientListTestKeysResponse{}, err
	}
	return result, nil
}

// RegenerateTestKey - Regenerate a test key for a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// regenerateTestKeyRequest - Parameters for the operation
// options - ServicesClientRegenerateTestKeyOptions contains the optional parameters for the ServicesClient.RegenerateTestKey
// method.
func (client *ServicesClient) RegenerateTestKey(ctx context.Context, resourceGroupName string, serviceName string, regenerateTestKeyRequest RegenerateTestKeyRequestPayload, options *ServicesClientRegenerateTestKeyOptions) (ServicesClientRegenerateTestKeyResponse, error) {
	req, err := client.regenerateTestKeyCreateRequest(ctx, resourceGroupName, serviceName, regenerateTestKeyRequest, options)
	if err != nil {
		return ServicesClientRegenerateTestKeyResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ServicesClientRegenerateTestKeyResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ServicesClientRegenerateTestKeyResponse{}, runtime.NewResponseError(resp)
	}
	return client.regenerateTestKeyHandleResponse(resp)
}

// regenerateTestKeyCreateRequest creates the RegenerateTestKey request.
func (client *ServicesClient) regenerateTestKeyCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, regenerateTestKeyRequest RegenerateTestKeyRequestPayload, options *ServicesClientRegenerateTestKeyOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/regenerateTestKey"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, regenerateTestKeyRequest)
}

// regenerateTestKeyHandleResponse handles the RegenerateTestKey response.
func (client *ServicesClient) regenerateTestKeyHandleResponse(resp *http.Response) (ServicesClientRegenerateTestKeyResponse, error) {
	result := ServicesClientRegenerateTestKeyResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.TestKeys); err != nil {
		return ServicesClientRegenerateTestKeyResponse{}, err
	}
	return result, nil
}

// BeginStart - Start a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// options - ServicesClientBeginStartOptions contains the optional parameters for the ServicesClient.BeginStart method.
func (client *ServicesClient) BeginStart(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginStartOptions) (*runtime.Poller[ServicesClientStartResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.start(ctx, resourceGroupName, serviceName, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[ServicesClientStartResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[ServicesClientStartResponse](options.ResumeToken, client.pl, nil)
	}
}

// Start - Start a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
func (client *ServicesClient) start(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginStartOptions) (*http.Response, error) {
	req, err := client.startCreateRequest(ctx, resourceGroupName, serviceName, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusAccepted) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// startCreateRequest creates the Start request.
func (client *ServicesClient) startCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginStartOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/start"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// BeginStop - Stop a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// options - ServicesClientBeginStopOptions contains the optional parameters for the ServicesClient.BeginStop method.
func (client *ServicesClient) BeginStop(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginStopOptions) (*runtime.Poller[ServicesClientStopResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.stop(ctx, resourceGroupName, serviceName, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[ServicesClientStopResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[ServicesClientStopResponse](options.ResumeToken, client.pl, nil)
	}
}

// Stop - Stop a Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
func (client *ServicesClient) stop(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginStopOptions) (*http.Response, error) {
	req, err := client.stopCreateRequest(ctx, resourceGroupName, serviceName, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusAccepted) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// stopCreateRequest creates the Stop request.
func (client *ServicesClient) stopCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientBeginStopOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/stop"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// BeginUpdate - Operation to update an exiting Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
// resourceGroupName - The name of the resource group that contains the resource. You can obtain this value from the Azure
// Resource Manager API or the portal.
// serviceName - The name of the Service resource.
// resource - Parameters for the update operation
// options - ServicesClientBeginUpdateOptions contains the optional parameters for the ServicesClient.BeginUpdate method.
func (client *ServicesClient) BeginUpdate(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource, options *ServicesClientBeginUpdateOptions) (*runtime.Poller[ServicesClientUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.update(ctx, resourceGroupName, serviceName, resource, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[ServicesClientUpdateResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[ServicesClientUpdateResponse](options.ResumeToken, client.pl, nil)
	}
}

// Update - Operation to update an exiting Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-11-01-preview
func (client *ServicesClient) update(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource, options *ServicesClientBeginUpdateOptions) (*http.Response, error) {
	req, err := client.updateCreateRequest(ctx, resourceGroupName, serviceName, resource, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// updateCreateRequest creates the Update request.
func (client *ServicesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource, options *ServicesClientBeginUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if serviceName == "" {
		return nil, errors.New("parameter serviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, resource)
}


text:
title: Firmin, a JavaScript animation library using CSS transforms and transitions
---

**Firmin** is a JavaScript animation library that uses CSS transforms and
transitions to create smooth, hardware-accelerated animations.

The project [resides on GitHub]. You can report bugs and request features on
[the issue tracker]. To see the project development history, take a look at
[the changelog].

[resides on GitHub]: https://github.com/beastaugh/firmin
[the issue tracker]: https://github.com/beastaugh/firmin/issues
[the changelog]:     /changelog.html

Downloads
---------

The latest release of Firmin is version **1.0.0**.

* [Development version](/downloads/firmin-1.0.0.js)
* [Production version](/downloads/firmin-1.0.0-min.js)
  <small>8.3kb packed, 2.4kb gzipped</small>

Older versions are available from [the release archive].

[the release archive]: /downloads.html

Using Firmin
------------

Firmin's API is not large, and mainly consists of convenience methods which
make performing particular transforms easier. All of these methods are based on
two core operations: the `animate` function and the `animate` method.

The `animate` function takes three arguments: the element to be animated; a
description of the animation to be run; and the duration of the animation.
Durations can be given as a string ending in `s` (meaning a time in seconds) or
`ms` (meaning milliseconds). They can also be given as plain numbers, in which
case they are assumed to denote a time in seconds.

~~~{.JavaScript}
var box = document.getElementById("box");

Firmin.animate(box, {
    skew: {
        x: "45deg",
        y: "30deg"
    }
}, "2.1s");
~~~

It's worth mentioning that any Firmin animation without a specified duration
will be executed instantaneously---that is, the element will transition
from its initial state to its final state with no visible intermediate states.

The `animate` function returns an object with a complementary `animate` method.
This method takes two arguments, an animation description and a duration, and
will be applied to the same element (in other words, the method's interface is
the same as the function's, just without the element parameter). This allows
animations to be chained, applying transformations sequentially.

~~~{.JavaScript}
Firmin.animate(box, {translateX: "200px"}, "1.6s")
      .animate({translateY: "100px"}, "0.8s");
~~~

There are a number of shortcut methods with the same names as the CSS transform
functions. These provide a convenient way to perform single transformations
without passing a verbose description to `animate`. Detailed documentation can
be found in the [reference](/api.html). All of Firmin's objects and methods
fall under the `Firmin` namespace.

### Transform origins

Aside from the transforms themselves, there is a further transform-related
property which can be given in an animation description: the `origin` from
which the transform will be performed. This should be supplied as an object
with `x` and `y` properties (both CSS lengths).

~~~{.JavaScript}
Firmin.animate(box, {
    rotate: "1.5rad",
    origin: {x: "10%", y: 0}
}, "400ms");
~~~

CSS transitions will also animate other properties, not merely transforms. For
example, one could animate the opacity, background colour or height of an
element. CSS property names are given in camelCase as is usual when modifying
them with JavaScript.

~~~{.JavaScript}
Firmin.animate(box, {
    opacity:         0.8,
    height:          "200px",
    backgroundColor: "#000"
}, 0.5);
~~~

Relative transforms
-------------------

Every animation function in Firmin has a complementary _relative_ version;
these can be used simply by appending an uppercase `R` to the function name,
e.g. `Firmin.animateR` or `Firmin.translateXR`.

When using a relative animation, any transform functions called will use the
element's current transformation matrix as a basis for the new transformation
being generated, rather than the identity or origin matrix.

For example, if one wanted to move an element 100 pixels to the right, and then
move it 200 pixels up, then using Firmin's normal, absolute animation functions
one would write this:

~~~{.JavaScript}
Firmin.translateX(el, 100).translate(el, {x: 100, y: -200});
~~~

In many contexts, this can be expressed more naturally using a relative
transformation: move the element 100 pixels to the right, and then move it 200
pixels up.

~~~{.JavaScript}
Firmin.translateX(el, 100).translateYR(el, -200);
~~~

Relative animations can be used at any time; Firmin maintains an internal list
of previous animations which can be referred to when necessary, so one can call
a series of absolute transforms and then a relative transform, or vice versa.

This internal state is encapsulated in the `Animated` objects returned by all
transform functions and methods. This is similar to the way other libraries
which offer chaining APIs (like jQuery) work. To make what's going on here
clearer, let's replace the chains of method calls used above with a more
obviously stateful assignment and sequence of method calls.

~~~{.JavaScript}
// Store a reference to the Animated object encapsulating
// the element's transformation state.
var animated = Firmin.rotate(el, 90);

// Call an animation method on that object.
animated.skewX(30);

// Call a relative transform on that object; the final transformation
// state will include a rotation through 120 degrees, not 30.
animated.rotateR(30);
~~~

Transform states are stored in these `Animated` instances, rather than read
from the DOM. Because of this, to perform relative transforms on an element a
reference to the relevant object must be kept, whether through a variable or a
sequence of method calls.

Operation order
---------------

[Matrix multiplication] for non-[diagonal] square matrices is not in general
[commutative], so the order in which transforms are applied will affect the
final state of the transform. Consider this CSS declaration:

[Matrix multiplication]: http://en.wikipedia.org/wiki/Matrix_multiplication
[diagonal]:              http://en.wikipedia.org/wiki/Diagonal_matrix
[commutative]:           http://en.wikipedia.org/wiki/Commutativity

~~~{.CSS}
#an-element {
    transform: skew(15deg, 30deg) rotate(45deg);
}
~~~

This is _not_ equivalent to the following declaration:

~~~{.CSS}
#an-element {
    transform: rotate(45deg) skew(15deg, 30deg);
}
~~~

Firmin will respect the order of operations specified in an animation
description, so one can write Firmin code that will produce the same outcome as
the first CSS declaration above.

~~~{.JavaScript}
Firmin.animate(document.getElementById("an-element"), {
    skew:   {x: "15deg", y: "30deg"},
    rotate: "45deg"
});
~~~

One could also use the relative transform functions to generate the same final
transformation as the second example CSS declaration.

~~~{.JavaScript}
Firmin.rotate(document.getElementById("an-element"), "45deg")
      .skewR({x: "15deg", y: "30deg"});
~~~

One caveat is necessary. Firmin is able to respect the order of operations
specified in an animation description only because most widely-used JavaScript
interpreters iterate over object properties (using a `for...in` loop) in the
order that they those properties are declared, despite the fact that the
JavaScript specification states that "The mechanics and order of
enumerating the properties is not specified."

Supported platforms
-------------------

Currently, the only supported platforms are those that use a recent version of
the WebKit engine: _Safari 4_ and _5_, _Mobile Safari_ (i.e. iPhone and iPad)
and _Google Chrome_. While CSS transforms and transitions are available for
other browsers such as Opera 11 and Firefox 4, their implementations are less
than complete. The CSS transforms and transitions API is experimental, and
support for it varies between browsers. In the future, I hope to make Firmin
compatible with more browsers.

### Hardware acceleration

One advantage of combining CSS transforms and transitions is that together they
provide hardware-accelerated animation on WebKit-based browsers such as Safari
on the Mac and Mobile Safari on the iPhone. Transitions which change the
`opacity` property are also hardware accelerated on these platforms.

Transition properties
---------------------

The description object passed to the `animate` function allows for the
customisation of the transition. The properties that can be used to do this
are:

* `properties`
* `timingFunction`
* `duration`
* `delay`

Here's an example using all of them.

~~~{.JavaScript}
Firmin.animate(document.getElementById("an-element"), {
    backgroundColor: "#C4DDDA"
    color:           "#142367",
    opacity:         0.75,

    properties:      ["opacity", "color"],
    timingFunction:  "ease-out",
    duration:        "2s",
    delay:           "1s"
});
~~~

### `properties`

This allows for the filtering of properties which the transition will be
applied to. It defaults to `"all"` and can be set to the string `"none"` or an
array of CSS property names. It's described in detail in the CSS Transitions
Module specification [section 2.1].

### `timingFunction`

This allows for control over how intermediate values used during a transition
will be calculated. It accepts the name of a timing function as a string, or an
array of numbers to be passed to the `cubic-bezier` function. There are five
timing functions defined in the spec: `ease`, `linear`, `ease-in`, `ease-out`
and `ease-in-out`. The default is `ease`. See [section 2.3] of the CSS
Transitions Module specification for details.

### `duration`

The time taken by the transition. It can be specified in either seconds
(`"1.5s"`) or milliseconds (`"300ms"`). If a number is given, rather than a
string, it will be interpreted as a value in seconds. Negative values are
interpreted as `0`, i.e. executing immediately.

### `delay`

This accepts a time in the same way as `duration`, and specifies an interval to
delay the execution of the transition by. Negative values will result in the
transition executing immediately, but will begin part-way through the play
cycle. This is explained further in [section 2.4] of the specification.

[section 2.1]: http://www.w3.org/TR/css3-transitions/#the-transition-property-property-
[section 2.3]: http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag
[section 2.4]: http://www.w3.org/TR/css3-transitions/#the-transition-delay-property-

Units
-----

Most CSS properties, including transform functions and transition durations,
have a magnitude and a unit. Angles are given in degrees, or radians; lengths
in pixels or ems; times in seconds or milliseconds. In order to be as flexible
as possible, Firmin accepts (with a couple of restrictions) the same CSS
datatype values as a stylesheet. Keywords are not currently accepted as
arguments to transform functions.

### Angles

Angles can be given as strings in _radians_ (e.g. `"2rad"`), _grads_ (e.g.
`"1grad"`), _turns_ (e.g. `"0.5turn"`) and _degrees_ (e.g. `"45deg"`).
These correspond exactly to the [CSS angle type]. The default is degrees, so if
you provide a number as an angle argument, it is assumed to be in degrees.

### Lengths

Because lengths in CSS are generally relative to the current browser and
operating system environment, Firmin only accepts _pixel_ lengths, e.g.
`"340px"` or `340`.

### Times

Times can be given as strings in _seconds_ (e.g. `"2s"`) or _milliseconds_
(e.g. `"300ms"`). The default is seconds, so if you provide a numeric argument,
Firmin will assume it is in seconds.

[CSS angle type]: http://www.w3.org/TR/css3-values/#angles

Axes
----

A number of transform functions modify the state of an element relative to
a particular axis. For example, `translateX` will move the
element along the horizontal (_X_) axis, while `scaleY`
scales the element vertically (along the _Y_ axis). The _Z_
axis can be thought of as going into or coming out of the screen.

As well as the `translate` function, `scale` and
`rotate` both have _X_, _Y_ and _Z_
versions, while `skew` only has _X_ and _Y_
variants (`matrix` always operates on all three axes, and so has
no axis-specific functions).