text:
using System;
using System.Runtime.InteropServices;
using AudioUnit;
using ObjCRuntime;
using CoreFoundation;
using Foundation;
using System.Text;
namespace MusicPlayer
{
	public class AudioOutputHelper
	{
		const uint AudioDevicePropertyDataSourceNameForIDCFString = 1819501422;
		static uint kAudioHardwarePropertyDefaultOutputDevice = ConvertToUInt("dOut");
		const uint AudioDevicePropertyDataSource = 1936945763;
		const uint AudioDevicePropertyTransportType = 1953653102;
		public static  Action OutputChanged { get; set; }
		public static void Init()
		{
			try
			{
				var src = ConvertToUInt("dOut");
				uint theRunLoop = 0;
				var property  = new AudioObjectPropertyAddress(
					kAudioHardwarePropertyDefaultOutputDevice,
					(uint)AudioObjectPropertyScope.Global,
					(uint)AudioObjectPropertyElement.Master);

				AudioObjectAddPropertyListener(1, ref property, OutputDidChange, IntPtr.Zero);

				//var defaultDevice = GetCurrentOutputDevice();
				////	var name = GetDeviceName (defaultDevice);
				//var sourceId = GetDeviceSourceId(defaultDevice);
				////	var trasnport = ConvertToString (GetDeviceProperty (defaultDevice, AudioDevicePropertyTransportType));
				//var theAddress = new AudioObjectPropertyAddress(
				//	AudioDevicePropertyDataSource,
				//	(uint)AudioObjectPropertyScope.Output,
				//	(uint)AudioObjectPropertyElement.Master);
				//AudioObjectAddPropertyListener(1, ref theAddress, OutputDidChange, IntPtr.Zero);

			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
			}
		}

		[StructLayout(LayoutKind.Sequential)]
		struct AudioObjectPropertyAddress
		{
			public uint /* UInt32 */ Selector;
			public uint /* UInt32 */ Scope;
			public uint /* UInt32 */ Element;

			public AudioObjectPropertyAddress(uint selector, uint scope, uint element)
			{
				Selector = selector;
				Scope = scope;
				Element = element;
			}

			public AudioObjectPropertyAddress(AudioObjectPropertySelector selector, AudioObjectPropertyScope scope, AudioObjectPropertyElement element)
			{
				Selector = (uint)selector;
				Scope = (uint)scope;
				Element = (uint)element;
			}
		}

		public static uint GetCurrentOutputDevice()
		{
			uint outputDevice;
			uint size = (uint)Marshal.SizeOf(typeof(uint));

			var theAddress = new AudioObjectPropertyAddress(
				AudioObjectPropertySelector.DefaultSystemOutputDevice,
				AudioObjectPropertyScope.Global,
				AudioObjectPropertyElement.Master);

			uint inQualifierDataSize = 0;
			IntPtr inQualifierData = IntPtr.Zero;

			var err = AudioObjectGetPropertyData(1, ref theAddress, ref inQualifierDataSize, ref inQualifierData, ref size, out outputDevice);

			if (err != 0)
			{
				var status = (AudioUnitStatus)err;
				Console.WriteLine(status);
			}
			return outputDevice;
		}
		public static string GetDeviceName(uint deviceId)
		{
			var property = GetDeviceProperty(deviceId, AudioDevicePropertyDataSourceNameForIDCFString);
			return ConvertToString(property);
		}
		public static string GetDeviceSourceId(uint deviceId)
		{
			var property = GetDeviceProperty(deviceId, AudioDevicePropertyDataSource);
			return ConvertToString(property);
		}
		public static uint GetDeviceProperty(uint deviceId, uint property)
		{
			uint dataSourceId;
			uint size = (uint)Marshal.SizeOf(typeof(UInt64));
			var theAddress = new AudioObjectPropertyAddress(
				property,
				(uint)AudioObjectPropertyScope.Output,
				(uint)AudioObjectPropertyElement.Master);
			uint inQualifierDataSize = 0;
			IntPtr inQualifierData = IntPtr.Zero;

			var err = AudioObjectGetPropertyData(deviceId, ref theAddress, ref inQualifierDataSize, ref inQualifierData, ref size, out dataSourceId);

			if (err != 0)
			{
				var error = new NSError(NSError.OsStatusErrorDomain, err);
				Console.WriteLine(error);
			}

			return dataSourceId;
		}

		static bool SetDeviceProperty(AudioObjectPropertyAddress theAddress, uint deviceId, uint data)
		{
			uint dataSourceId = data;
			uint size = (uint)Marshal.SizeOf(typeof(UInt64));
			uint inQualifierDataSize = 0;
			IntPtr inQualifierData = IntPtr.Zero;

			var err = AudioObjectSetPropertyData(deviceId, ref theAddress, ref inQualifierDataSize, ref inQualifierData, ref size, ref dataSourceId);

			if (err != 0)
			{
				var error = new NSError(NSError.OsStatusErrorDomain, err);
				Console.WriteLine(error);
				return false;
			}

			return true;;
		}

		static string ConvertToString(uint input)
		{
			if (input == 0)
				return "";
			var hexString = input.ToString("x8");
			var sb = new StringBuilder();
			for (int i = 0; i < hexString.Length; i += 2)
			{
				string hs = hexString.Substring(i, 2);
				sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
			}
			return sb.ToString();
		}

		static uint ConvertToUInt(string input)
		{
			if (string.IsNullOrWhiteSpace(input))
				return 0;
			var hex = HexIt(input);
			return Convert.ToUInt32(hex, 16);
		}
		public static string HexIt(string yourString)
		{
			string hex = "";
			foreach (char c in yourString)
			{
				int tmp = c;
				hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
			}
			return hex;
		}

		[DllImport(Constants.SecurityLibrary)]
		static extern IntPtr SecCopyErrorMessageString(uint status, IntPtr reserved);

		[MonoPInvokeCallback(typeof(OutputChange))]
		static void OutputDidChange(uint inObjectID, uint inNumberAddresses, AudioObjectPropertyAddress inAddresses, IntPtr clientData)
		{
			Console.WriteLine("Output Changed");
			OutputChanged?.Invoke();
		}

		public static uint GetDeviceId(uint deviceId)
		{
			uint dataSourceId;
			uint size = (uint)Marshal.SizeOf(typeof(uint));
			var theAddress = new AudioObjectPropertyAddress(
				AudioDevicePropertyDataSource,
				(uint)AudioObjectPropertyScope.Output,
				(uint)AudioObjectPropertyElement.Master);
			uint inQualifierDataSize = 0;
			IntPtr inQualifierData = IntPtr.Zero;

			var err = AudioObjectGetPropertyData(deviceId, ref theAddress, ref inQualifierDataSize, ref inQualifierData, ref size, out dataSourceId);

			//if (err != 0)
			//throw new AudioUnitException((int)err);
			return dataSourceId;
		}

		[DllImport(Constants.AudioUnitLibrary)]
		static extern int AudioObjectGetPropertyData(
			uint inObjectID,
			ref AudioObjectPropertyAddress inAddress,
			ref uint inQualifierDataSize,
			ref IntPtr inQualifierData,
			ref uint ioDataSize,
			out uint outData
		);

		[DllImport(Constants.AudioUnitLibrary)]
		static extern int AudioObjectSetPropertyData(
			uint inObjectID,
			ref AudioObjectPropertyAddress inAddress,
			ref uint inQualifierDataSize,
			ref IntPtr inQualifierData,
			ref uint ioDataSize,
			ref uint inData
		);

		delegate void OutputChange(uint inObjectID, uint inNumberAddresses, AudioObjectPropertyAddress inAddresses, IntPtr clientData);

		[DllImport(Constants.AudioUnitLibrary)]
		static extern int AudioObjectAddPropertyListener(uint inObjectID,
															  ref AudioObjectPropertyAddress inAddress,
															  OutputChange callback, IntPtr clientData);

		[DllImport(Constants.libcLibrary)]
		// dispatch_queue_t dispatch_get_global_queue (long priority, unsigned long flags);
		extern static IntPtr dispatch_get_global_queue(nint priority, nuint flags);
	}
}


text:
FROM python:3

MAINTAINER brockp@umich.edu

ADD requirements.txt /tmp/requirements.txt
RUN pip install -r /tmp/requirements.txt

ADD . /code
WORKDIR /code

CMD ["python", "oauthtest.py"]

redpajama_set_name: RedPajamaGithub


text:
=======
Actions
=======

Horizon has two types of actions

* TableActions
* RowActions

some actions can by used for both categories.

Filter Action
-------------

Simple filter action which provide initial for our ``client-side`` filtering. Server-side is not implemented for now, but is not too many work and it's in the plan.

default search in all fields

.. code-block:: python

    from horizon_contrib.tables.actions import FilterAction

or specify one field

.. code-block:: python

    from horizon_contrib.tables.actions import FilterAction

    class MyFilter(FilterAction):

        fields = ['name', 'subject']

        lookups = ['project__name']

DeleteAction
------------

Simple action based on horizon's ``DeleteAction``. It's ``BatchAction`` for more detail see Horizon doc.

.. code-block:: python

    from horizon import tables
    from horizon_contrib.tables import DeleteAction

    class MyTable(tables.DataTable):

        class Meta:
            table_actions = (DeleteAction,)
            row_actions = (DeleteAction,)

.. warning::

    For this time is not implemented in transaction !

CreateAction
------------

There is nothing special it's only ``LinkAction`` with implemented ``get_link_url``

.. code-block:: python

    from horizon_contrib.tables.actions import CreateAction

UpdateAction
------------

There is nothing special it's only ``LinkAction`` with implemented ``get_link_url``

.. code-block:: python

    from horizon_contrib.tables.actions import UpdateAction

.. note::

    for more details and customization follow ``UpdateView``

Packs of Actions
----------------

For less code is there some action packs

* ``CD_ACTIONS`` - ``CREATE`` and ``DELETE`` can be used for table and row actions
* ``ROW_ACTIONS`` - same as CD_ACTIONS, but with UpdateAction
* ``TABLE_ACTIONS`` - same as CD_ACTIONS but with FilterAction

.. code-block:: python

    from horizon import tables
    from horizon_contrib.tables import ROW_ACTIONS, TABLE_ACTIONS

    class MyTable(tables.DataTable)

        class Meta:
            row_actions = ROW_ACTIONS
            tables_actions = TABLE_ACTIONS

.. warning::

    In default state these actions sets works only with our table classes !

UpdateColumnAction
------------------

This action is used for column as additional attribute and provide Ajax update power.

Optionaly can be provided form ``field`` with ``widget``.

.. code-block:: python

    from horizon import tables
    from horizon_contrib.tables.actions import UpdateAction

    my_column = tables.Columns('my_column', update_action=UpdateAction)


text:
import psycopg2
import numpy as np

def column_stats(table_name, column_name):
  # Establish the connection
  conn = psycopg2.connect(dbname='db', user='grok')
  cursor = conn.cursor()

  # Execute an SQL query and receive the output
  cursor.execute('SELECT ' + column_name + ' from ' + table_name)
  results = cursor.fetchall()

  mean = np.mean(results)
  median = np.median(results)

  return mean, median


text:
<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $em = $this
            ->getServiceLocator()
            ->get('Doctrine\ORM\EntityManager');

        die(var_dump($em->find('Application\Entity\Usertime', 1)));
    }
}


text:
.RenderJSON-headerCell {
    color: rgba(150, 150, 150, 1);
}

/* override bootstrap table style if used */
.table > tbody > tr > th.RenderJSON-headerCell {
    color: rgba(150, 150, 150, 1);
    text-align: left;
}


text:
namespace predictors {

// static
AutocompleteActionPredictor* AutocompleteActionPredictorFactory::GetForProfile(
    Profile* profile) {
  return static_cast<AutocompleteActionPredictor*>(
      GetInstance()->GetServiceForProfile(profile, true));
}

// static
AutocompleteActionPredictorFactory*
    AutocompleteActionPredictorFactory::GetInstance() {
  return Singleton<AutocompleteActionPredictorFactory>::get();
}

AutocompleteActionPredictorFactory::AutocompleteActionPredictorFactory()
    : ProfileKeyedServiceFactory("AutocompleteActionPredictor",
                                 ProfileDependencyManager::GetInstance()) {
  DependsOn(HistoryServiceFactory::GetInstance());
  DependsOn(PredictorDatabaseFactory::GetInstance());
}

AutocompleteActionPredictorFactory::~AutocompleteActionPredictorFactory() {}

content::BrowserContext*
AutocompleteActionPredictorFactory::GetBrowserContextToUse(
    content::BrowserContext* context) const {
  return chrome::GetBrowserContextOwnInstanceInIncognito(context);
}

ProfileKeyedService*
    AutocompleteActionPredictorFactory::BuildServiceInstanceFor(
        content::BrowserContext* profile) const {
  return new AutocompleteActionPredictor(static_cast<Profile*>(profile));
}

}  // namespace predictors


text:
package main.java.Intefaces;

public interface INameResolver {
    String getDAOTypeName(String nameDTO);
    String getDAOValueName(String typeDAO, String nameDTO);
}


text:
<?php

require ROOT . '/app/dbloader.php';

/*
|--------------------------------------------------------------------------
| Create Slim Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Slim application instance
| which serves as the "glue" for all the components of RedSlim.
|
*/

// Instantiate application
$app = new \Slim\Slim(require_once ROOT . '/app/config/app.php');
$app->setName('Hashgram');

// For native PHP session
session_cache_limiter(false);
session_start();

// For encrypted cookie session
/*
$app->add(new \Slim\Middleware\SessionCookie(array(
            'expires' => '20 minutes',
            'path' => '/',
            'domain' => null,
            'secure' => false,
            'httponly' => false,
            'name' => 'app_session_name',
            'secret' => md5('appsecretkey'),
            'cipher' => MCRYPT_RIJNDAEL_256,
            'cipher_mode' => MCRYPT_MODE_CBC
        )));
*/

/*
 * SET some globally available view data
 */
$resourceUri = $_SERVER['REQUEST_URI'];
$rootUri     = $app->request()->getRootUri();
$assetUri    = $rootUri;
$app->view()->appendData(
    array(
        'app' => $app,
        'rootUri' => $rootUri,
        'assetUri' => $assetUri,
        'resourceUri' => $resourceUri
    )
);

// Disable fluid mode in production environment
$app->configureMode(SLIM_MODE_PRO, function () use ($app) {
    // note, transactions will be auto-committed in fluid mode
    R::freeze(true);
});

/*
|--------------------------------------------------------------------------
| INCLUDING FRAMEWORK AND CONTROLLERS CLASSES
|--------------------------------------------------------------------------
|
| The application needs Framework Classes (e.g. RouteManager)
| and Controllers to works
|
*/

//INCLUDE FILES FRAMEWORK DEPENDENCIES
include_once ROOT . "/app/framework/util/YamlParser.php";

//INCLUDE FRAMEWORK CLASSES RECURSIVELY
$directory   = new RecursiveDirectoryIterator(ROOT . '/app/framework/');
$recIterator = new RecursiveIteratorIterator($directory);
$regex       = new RegexIterator($recIterator, '/\/*.php$/i');
foreach($regex as $item) {
	include_once $item->getPathname();
}

/*
|--------------------------------------------------------------------------
| INCLUDING SERVICES
|--------------------------------------------------------------------------
|
| The application needs Services (e.g. InstagramService) to be integrated
| with Social Networks
|
*/

//INCLUDE SERVICES CLASSES RECURSIVELY
$directory   = new RecursiveDirectoryIterator(ROOT . '/app/services/');
$recIterator = new RecursiveIteratorIterator($directory);
$regex       = new RegexIterator($recIterator, '/\/*.php$/i');
foreach($regex as $item) {
    include_once $item->getPathname();
}

/*
|--------------------------------------------------------------------------
| Configure Twig
|--------------------------------------------------------------------------
|
| The application uses Twig as its template engine. This script configures
| the template paths and adds some extensions.
|
*/

$view = $app->view();
$view->parserOptions = array(
    'debug' => true,
    'cache' => ROOT . '/app/storage/cache/twig',
    'auto_reload' => true,
    //'strict_variables' => true
);

$view->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
    new Twig_Extension_Debug()
);

/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/

return $app;


text:
<?php

class m120410_165114_fk_responses extends CDbMigration
{
	public function up()
	{
		$this->addForeignKey("FK_RESPONSES_USERS", "RESPONSES", "USER_ID", "USERS", "ID");
		$this->addForeignKey("FK_RESPONSES_QUESTIONS", "RESPONSES", "QUESTION_ID", "QUESTIONS", "ID");
	}

	public function down()
	{
		$this->dropForeignKey("FK_RESPONSES_USERS", "RESPONSES");
		$this->dropForeignKey("FK_RESPONSES_QUESTIONS", "RESPONSES");
	}

	/*
	// Use safeUp/safeDown to do migration with transaction
	public function safeUp()
	{
	}

	public function safeDown()
	{
	}
	*/
}


text:
<#@ template inherits="ETemplate" language="VB" #>
<?php
// No direct access
defined('_JEXEC') or die;

jimport('joomla.plugin.plugin');

/**
 * <#= StrConv(Value("Extension.name"), VbStrConv.ProperCase) #> <#= StrConv(Value("Extension.group"), VbStrConv.ProperCase) #> Plugin
 */
class plg<#= StrConv(Value("Extension.group"), VbStrConv.ProperCase) #><#= StrConv(Value("Extension.name"), VbStrConv.ProperCase) #> extends JPlugin
{
	//Joomla 1.6: Access plugin params by $this->params->get('REQUESTED_PARAM', 'DEFAULT_IF_NOT_SET')

    function __construct(&$subject, $params)
    {
        parent::__construct($subject, $params);
    	//Uncomment below if you are using the Joomla lang system
		//$this->loadLanguage();
    }

	/**
	 * Example after delete method.
	 *
	 * @param	string	The context for the content passed to the plugin.
	 * @param	object	The data relating to the content that was deleted.
	 * @return	boolean
	 * @since	1.6
	 */
	public function onContentAfterDelete($context, $data)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		return true;
	}

	/**
	 * Example after display content method
	 *
	 * Method is called by the view and the results are imploded and displayed in a placeholder
	 *
	 * @param	string		The context for the content passed to the plugin.
	 * @param	object		The content object.  Note $article->text is also available
	 * @param	object		The content params
	 * @param	int			The 'page' number
	 * @return	string
	 * @since	1.6
	 */
	public function onContentAfterDisplay($context, &$article, &$params, $limitstart)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		$app = JFactory::getApplication();

		return '';
	}

	/**
	 * Example after save content method
	 * Article is passed by reference, but after the save, so no changes will be saved.
	 * Method is called right after the content is saved
	 *
	 * @param	string		The context of the content passed to the plugin (added in 1.6)
	 * @param	object		A JTableContent object
	 * @param	bool		If the content is just about to be created
	 * @since	1.6
	 */
	public function onContentAfterSave($context, &$article, $isNew)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		$app = JFactory::getApplication();

		return true;
	}

	/**
	 * Example after display title method
	 *
	 * Method is called by the view and the results are imploded and displayed in a placeholder
	 *
	 * @param	string		The context for the content passed to the plugin.
	 * @param	object		The content object.  Note $article->text is also available
	 * @param	object		The content params
	 * @param	int			The 'page' number
	 * @return	string
	 * @since	1.6
	 */
	public function onContentAfterTitle($context, &$article, &$params, $limitstart)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		$app = JFactory::getApplication();

		return '';
	}

	/**
	 * Example before delete method.
	 *
	 * @param	string	The context for the content passed to the plugin.
	 * @param	object	The data relating to the content that is to be deleted.
	 * @return	boolean
	 * @since	1.6
	 */
	public function onContentBeforeDelete($context, $data)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		return true;
	}

	/**
	 * Example before display content method
	 *
	 * Method is called by the view and the results are imploded and displayed in a placeholder
	 *
	 * @param	string		The context for the content passed to the plugin.
	 * @param	object		The content object.  Note $article->text is also available
	 * @param	object		The content params
	 * @param	int			The 'page' number
	 * @return	string
	 * @since	1.6
	 */
	public function onContentBeforeDisplay($context, &$article, &$params, $limitstart)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		$app = JFactory::getApplication();

		return '';
	}

	/**
	 * Example before save content method
	 *
	 * Method is called right before content is saved into the database.
	 * Article object is passed by reference, so any changes will be saved!
	 * NOTE:  Returning false will abort the save with an error.
	 *You can set the error by calling $article->setError($message)
	 *
	 * @param	string		The context of the content passed to the plugin.
	 * @param	object		A JTableContent object
	 * @param	bool		If the content is just about to be created
	 * @return	bool		If false, abort the save
	 * @since	1.6
	 */
	public function onContentBeforeSave($context, &$article, $isNew)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		$app = JFactory::getApplication();

		return true;
	}

	/**
	 * Example after delete method.
	 *
	 * @param	string	The context for the content passed to the plugin.
	 * @param	array	A list of primary key ids of the content that has changed state.
	 * @param	int		The value of the state that the content has been changed to.
	 * @return	boolean
	 * @since	1.6
	 */
	public function onContentChangeState($context, $pks, $value)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		return true;
	}

	/**
	 * Example prepare content method
	 *
	 * Method is called by the view
	 *
	 * @param	string	The context of the content being passed to the plugin.
	 * @param	object	The content object.  Note $article->text is also available
	 * @param	object	The content params
	 * @param	int		The 'page' number
	 * @since	1.6
	 */
	public function onContentPrepare($context, &$article, &$params, $limitstart)
	{
		// Always make sure the plugin is operating in the correct context.
		if($context != 'com_content.article') {
			return true;
		}
		$app = JFactory::getApplication();
	}
}


text:
(function($) {
    "use strict"; // Start of use strict

    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 51
    });

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function(){
            $('.navbar-toggle:visible').click();
    });

    // Offset for Main Navigation
    $('#mainNav').affix({
        offset: {
            top: 100
        }
    })

    //Google map
    $('.map-container')
	.click(function(){$(this).find('iframe').addClass('clicked')})
	.mouseleave(function(){$(this).find('iframe').removeClass('clicked')});

    //Header background
    $('header').backstretch([
          "./img/fondo-prueba-1.jpg",
          "./img/fondo-prueba-2.jpg",
        ], {
            fade: 750,
            duration: 2500
        });

    //carousel-indicators bootstrap
    var myCarousels = $(".carousel");
	myCarousels.each(function( index, element  ) {
		var myCarousel = $("#"+$(element).attr('id'));
		myCarousel.append("

");
		var indicators = $("#"+$(element).attr('id') + " .carousel-indicators");
		$("#"+$(element).attr('id') +" .carousel-inner").children(".item").each(function(index) {
			console.log(index);
			(index === 0) ?
			indicators.append("

") :
			indicators.append("

");
		});
	});

})(jQuery); // End of use strict


text:
using UnityEngine;

public class Player : MonoBehaviour
{
    public Rigidbody2D Body;

    //Player's attributes
    public JumpingState JumpState;
    public PlayerStats PlayerStatistics;

    // Use this for initialization
    void Start()
    {
        //Start at default constructor with this instance of the class type Player
        JumpState = GetComponent<JumpingState>();

        //Init the player stats
        PlayerStatistics = new PlayerStats(3, 0, 10);

        //The player has not died.. yet
        PlayerStatistics.setPlayerHasDied(false);

        //Get the rigidbody of this game object.
        Body = gameObject.GetComponent<Rigidbody2D>();

        //By default the player is facing right
        PlayerStatistics.setIsFacingRight(true);

        //Player is not grounded
        PlayerStatistics.setIsGrounded(false);
    }

    // Update is called once per frame
    void Update()
    {
        JumpState.Jump();
        MoveBody();
    }

    //Move this Body.
    private void MoveBody()
    {
        Rotate();

        //Get the horizontal values of the axis. Will return -1, 0 or 1 on the X-axis
        float horizontalMove = Input.GetAxisRaw("Horizontal");

        if (horizontalMove >= .1f)
        {
            //The player is facing right
            PlayerStatistics.setIsFacingRight(true);
        }
        else if (horizontalMove <= -.1f)
        {
            //The player is not looking to the right anymore
            PlayerStatistics.setIsFacingRight(false);
        }

        //Apply Speed scalar to the player's Body.
        Body.velocity = new Vector2(horizontalMove * PlayerStatistics.getSpeed(), Body.velocity.y);
    }

    //Rotate
    private void Rotate()
    {
        Animator animator = GetComponent<Animator>();

        //Roate the player
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            //Rotate to the right
            transform.rotation *= Quaternion.FromToRotation(Vector2.left, Vector2.right);
            animator.SetBool("run", true);

        }
        else if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            //Rotate to the right
            transform.rotation *= Quaternion.FromToRotation(Vector2.right, Vector2.left);
            animator.SetBool("run", true);
        }

        else
        {
            animator.SetBool("run", false);
        }

    }
}


text:
angular.module('ContactsApp')
  .config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider
      .when('/contacts', {
        controller: "ListController",
        controllerAs: 'list',
        templateUrl: "views/list.tmpl.html"
      });
    $locationProvider.html5Mode(true);
  }]);


text:
<?php

namespace AB4UGLog\Http\Controllers;

use Illuminate\Http\Request;

class CallsignController extends Controller
{
    //
}


text:
About Me

deleted

Contact

Email:{{ site.email }}

Website:{{ site.github_url }}

Skill Keywords

        {% if site.skill_software_keywords %}

Software Engineer Keywords

                {% for keyword in site.skill_software_keywords %}
                <button class="btn btn-default" type="button">{{ keyword }}</button>
                {% endfor %}

        {% endif %}

        {% if site.skill_hardware_chips %}

Hardware Chip Keywords

                {% for keyword in site.skill_hardware_chips %}
                <button class="btn btn-default" type="button">{{ keyword }}</button>
                {% endfor %}

        {% endif %}

        {% if site.skill_structure_keywords %}

Structure Analysis Keywords

                {% for keyword in site.skill_structure_keywords %}
                <button class="btn btn-default" type="button">{{ keyword }}</button>
                {% endfor %}

        {% endif %}

        {% include sidebar-search.html %}
        {% include sidebar-popular-repo-side.html %}


text:
#include <algorithm>
#include <iostream>
#include <vector>

/*
 * Solution: we use backtracking together with a running sum to generate all the possible combinations.
 * We also have two cases in which we prune:
 *
 * 1. when we skip duplicate elements
 * 2. when the current number plus our running sum is greater than the target sum, we can return from
 * our current level of recursion since any number after this one will also make our sum too large.
 *
 * Time complexity: O(2^n)
 * Space complexity: O(2^n)
 */

void backtracking(std::vector<int> & candidates, std::vector<std::vector<int>> & result, std::vector<int> combination, const int & target, const int & n, int sum, int start)
{
    if(sum==target)
    {
        result.push_back(combination);

        return;
    }

    for(int i=start;i<n;++i)
    {
        if(sum + candidates[i] > target)
        {
            return;
        }

        if(i > start && candidates[i]==candidates[i-1])
        {
            continue;
        }

        sum+=candidates[i];

        combination.push_back(candidates[i]);

        backtracking(candidates, result, combination, target, n, sum, i+1);

        sum-=candidates[i];

        combination.pop_back();
    }
}

std::vector<std::vector<int>> combinationSum2(std::vector<int> & candidates, int target)
{
    std::vector<std::vector<int>> result;

    if(candidates.empty())
    {
        return result;
    }

    std::sort(candidates.begin(), candidates.end());

    std::vector<int> combination;

    const int n=int(candidates.size());

    int start=0;

    int sum=0;

    backtracking(candidates, result, combination, target, n, sum, start);

    return result;
}


text:
"""
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

# x = np.arange(0, 2*np.pi, 0.01)        # x-array
x = np.linspace(0, 1023, 1024)        # x-array
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x+i/10.0))  # update the data
    return line,

#Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
    interval=25, blit=True)
plt.show()


text:
<?php

namespace OpenCloud\Autoscale\Resource;

use OpenCloud\Common\Exceptions;
use OpenCloud\Common\Http\Message\Formatter;

/**
 * An autoscaling group is monitored by Rackspace CloudMonitoring. When
 * Monitoring triggers an alarm for high utilization within the autoscaling
 * group, a webhook is triggered. The webhook stimulates the autoscale service
 * which consults a policy in accordance with the webhook. The policy determines
 * how many additional cloud servers should be added or removed in accordance
 * with the alarm.
 *
 * There are three components to Autoscale:
 *
 * - The Scaling Group Configuration ($this->groupConfiguration)
 * - The Scaling Group's Launch Configuration ($this->launchConfiguration)
 * - The Scaling Group's Policies ($this->scalingPolicies)
 *
 * @link https://github.com/rackerlabs/otter/blob/master/doc/getting_started.rst
 * @link http://docs.autoscale.apiary.io/
 */
class Group extends AbstractResource
{
    private $id;
    private $links;
    private $groupConfiguration;
    private $launchConfiguration;
    private $scalingPolicies;
    private $name;
    protected $metadata;

    private $active;
    private $activeCapacity;
    private $pendingCapacity;
    private $desiredCapacity;
    private $paused;

    protected static $json_name = 'group';
    protected static $url_resource = 'groups';
    protected static $json_collection_name = 'groups';

    /**
     * {@inheritDoc}
     */
    public $createKeys = array(
        'groupConfiguration',
        'launchConfiguration',
        'scalingPolicies'
    );

    /**
     * {@inheritDoc}
     */
    public $associatedResources = array(
        'groupConfiguration'  => 'GroupConfiguration',
        'launchConfiguration' => 'LaunchConfiguration',

    );

    /**
     * {@inheritDoc}
     */
    public $associatedCollections = array(
        'scalingPolicies' => 'ScalingPolicy'
    );

    /**
     * {@inheritDoc}
     */
    public function update($params = array())
    {
        return $this->noUpdate();
    }

    /**
     * Get the current state of the scaling group, including the current set of
     * active entities, the number of pending entities, and the desired number
     * of entities.
     *
     * @return object|boolean
     * @throws Exceptions\HttpError
     * @throws Exceptions\ServerActionError
     */
    public function getState()
    {
        $response = $this->getService()
            ->getClient()
            ->get($this->url('state'))
            ->send();

        $body = Formatter::decode($response);

        return (!empty($body->group)) ? $body->group : false;
    }

    /**
     * Get the group configuration for this autoscale group.
     *
     * @return GroupConfiguration
     */
    public function getGroupConfig()
    {
        if (($config = $this->getProperty('groupConfiguration')) instanceof GroupConfiguration) {
            return $config;
        }

        $config = $this->getService()->resource('GroupConfiguration');
        $config->setParent($this);
        if ($this->getId()) {
            $config->refresh(null, $config->url());
        }
        return $config;
    }

    /**
     * Get the launch configuration for this autoscale group.
     *
     * @return LaunchConfiguration
     */
    public function getLaunchConfig()
    {
        if (($config = $this->getProperty('launchConfiguration')) instanceof LaunchConfiguration) {
            return $config;
        }

        $config = $this->getService()->resource('LaunchConfiguration');
        $config->setParent($this);
        if ($this->getId()) {
            $config->refresh(null, $config->url());
        }
        return $config;
    }

    /**
     * NB: NOT SUPPORTED YET.
     *
     * @codeCoverageIgnore
     */
    public function pause()
    {
        return $this->getService()->getClient()->post($this->url('pause'))->send();
    }

    /**
     * NB: NOT SUPPORTED YET.
     *
     * @codeCoverageIgnore
     */
    public function resume()
    {
        return $this->getService()->getClient()->post($this->url('resume'))->send();
    }

    /**
     * Get the scaling policies associated with this autoscale group.
     *
     * @return Collection
     */
    public function getScalingPolicies($override = false)
    {
        if (null === $this->scalingPolicies || $override === true) {
            $this->scalingPolicies = $this->getService()->resourceList('ScalingPolicy', null, $this);
        }
        return $this->scalingPolicies;
    }

    /**
     * Get a particular scaling policy for this autoscale group.
     *
     * @param  object|int $id
     * @return ScalingPolicy
     */
    public function getScalingPolicy($id = null)
    {
        $config = $this->getService()->resource('ScalingPolicy');
        $config->setParent($this);
        if ($id) {
            $config->populate($id);
        }
        return $config;
    }

}


text:
TM1638-GEM for Raspberry Pi
===========================

This is a ruby wrapper for driving the TM1638 module - a cheap board with 8 7-segment displays, 8 buttons and 8 Red/Green LEDs - on a Raspberry Pi. It's based on the excellent driver by Martin Oldfield.

Installation on your Pi:

- Compile and install the bcm2835 lib from http://www.airspayce.com/mikem/bcm2835/index.html
- Compile and install the pi-tm1638 lib from https://github.com/mjoldfield/pi-tm1638
- Download the gem from https://github.com/RickP/tm1638_gem/releases and install with `gem install tm1638-0.1.0.gem`

Ruby example:

    require 'tm1638'              # Include the gem

    Tm1638.init(17, 21, 22)       # Initialize the tm1638 on GPIO pins 17 (data), 21 (clock) and 22 (strobe)

    Tm1638.set_leds([1,1,1,0,0,0,0,0], [0,0,0,1,1,1,0,0])  # Set LEDs 1-3 to red and 4-6 to green

    Tm1638.set_intensity(5)       # Set display intensity to 5 (Valid values: 0-7)

    Tm1638.write("hello123", [0,0,0,0,0,1,1,1])   # Puts 'hello1.2.3.' on display (the array defines displayed decimal points)

    button_array = Tm1638.get_buttons()  # Read current value of the 8 buttons - returns an array with 8 ints (1 = pressed, 0 = not pressed)

You should use something like event-engine to poll the buttons.


text:
package org.apache.skywalking.apm.agent.test.helper;

import java.lang.reflect.Field;

/**
 * Created by xin on 2017/7/9.
 */
public class FieldSetter {

    public static <T> void setValue(Object instance,
        String fieldName, T value) throws IllegalAccessException, NoSuchFieldException {
        Field field = instance.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(instance, value);
    }

    public static <T> void setStaticValue(Class instance,
        String fieldName, T value) throws IllegalAccessException, NoSuchFieldException {
        Field field = instance.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(instance, value);
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceská Mykol. 30(1): 4 (1976)

#### Original name
Oidium vesiculosum Linder

### Remarks
null


text:
namespace features {

#if defined(OS_WIN)
// If enabled, calculate native window occlusion - Windows-only.
const base::Feature kCalculateNativeWinOcclusion{
    "CalculateNativeWinOcclusion", base::FEATURE_DISABLED_BY_DEFAULT};
#endif  // OW_WIN

// Whether or not to delegate color queries to the color provider.
const base::Feature kColorProviderRedirection = {
    "ColorProviderRedirection", base::FEATURE_DISABLED_BY_DEFAULT};

#if defined(OS_CHROMEOS)
// Integrate input method specific settings to Chrome OS settings page.
// https://crbug.com/895886.
const base::Feature kSettingsShowsPerKeyboardSettings = {
    "InputMethodIntegratedSettings", base::FEATURE_DISABLED_BY_DEFAULT};

// Experimental shortcut handling and mapping to address i18n issues.
// https://crbug.com/1067269
const base::Feature kNewShortcutMapping = {"NewShortcutMapping",
                                           base::FEATURE_DISABLED_BY_DEFAULT};

bool IsNewShortcutMappingEnabled() {
  return base::FeatureList::IsEnabled(kNewShortcutMapping);
}
#endif  // defined(OS_CHROMEOS)

// Update of the virtual keyboard settings UI as described in
// https://crbug.com/876901.
const base::Feature kInputMethodSettingsUiUpdate = {
    "InputMethodSettingsUiUpdate", base::FEATURE_DISABLED_BY_DEFAULT};

// Enables percent-based scrolling for mousewheel and keyboard initiated
// scrolls.
const base::Feature kPercentBasedScrolling = {
    "PercentBasedScrolling", base::FEATURE_DISABLED_BY_DEFAULT};

// Allows requesting unadjusted movement when entering pointerlock.
const base::Feature kPointerLockOptions = {"PointerLockOptions",
                                           base::FEATURE_DISABLED_BY_DEFAULT};

// Allows system caption style for WebVTT Captions.
const base::Feature kSystemCaptionStyle{"SystemCaptionStyle",
                                        base::FEATURE_ENABLED_BY_DEFAULT};

// Allows system keyboard event capture via the keyboard lock API.
const base::Feature kSystemKeyboardLock{"SystemKeyboardLock",
                                        base::FEATURE_ENABLED_BY_DEFAULT};

const base::Feature kNotificationIndicator = {
    "EnableNotificationIndicator", base::FEATURE_DISABLED_BY_DEFAULT};

bool IsNotificationIndicatorEnabled() {
  return base::FeatureList::IsEnabled(kNotificationIndicator);
}

// Enables GPU rasterization for all UI drawing (where not blacklisted).
const base::Feature kUiGpuRasterization = {"UiGpuRasterization",
#if defined(OS_MACOSX) || defined(OS_CHROMEOS) || defined(OS_FUCHSIA)
                                           base::FEATURE_ENABLED_BY_DEFAULT
#else
                                           base::FEATURE_DISABLED_BY_DEFAULT
#endif
};

bool IsUiGpuRasterizationEnabled() {
  return base::FeatureList::IsEnabled(kUiGpuRasterization);
}

// Enables scrolling with layers under ui using the ui::Compositor.
const base::Feature kUiCompositorScrollWithLayers = {
    "UiCompositorScrollWithLayers",
// TODO(https://crbug.com/615948): Use composited scrolling on all platforms.
#if defined(OS_MACOSX)
    base::FEATURE_ENABLED_BY_DEFAULT
#else
    base::FEATURE_DISABLED_BY_DEFAULT
#endif
};

// Enables compositor threaded scrollbar scrolling by mapping pointer events to
// gesture events.
const base::Feature kCompositorThreadedScrollbarScrolling = {
    "CompositorThreadedScrollbarScrolling", base::FEATURE_ENABLED_BY_DEFAULT};

// Enables the use of a touch fling curve that is based on the behavior of
// native apps on Windows.
const base::Feature kExperimentalFlingAnimation {
  "ExperimentalFlingAnimation",
#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
      base::FEATURE_ENABLED_BY_DEFAULT
#else
      base::FEATURE_DISABLED_BY_DEFAULT
#endif
};

#if defined(OS_WIN)
const base::Feature kElasticOverscrollWin = {"ElasticOverscrollWin",
                                             base::FEATURE_DISABLED_BY_DEFAULT};

// Enables InputPane API for controlling on screen keyboard.
const base::Feature kInputPaneOnScreenKeyboard = {
    "InputPaneOnScreenKeyboard", base::FEATURE_ENABLED_BY_DEFAULT};

// Enables using WM_POINTER instead of WM_TOUCH for touch events.
const base::Feature kPointerEventsForTouch = {"PointerEventsForTouch",
                                              base::FEATURE_ENABLED_BY_DEFAULT};
// Enables using TSF (over IMM32) for IME.
const base::Feature kTSFImeSupport = {"TSFImeSupport",
                                      base::FEATURE_ENABLED_BY_DEFAULT};

bool IsUsingWMPointerForTouch() {
  return base::win::GetVersion() >= base::win::Version::WIN8 &&
         base::FeatureList::IsEnabled(kPointerEventsForTouch);
}

// Enables Logging for DirectManipulation.
const base::Feature kPrecisionTouchpadLogging{
    "PrecisionTouchpadLogging", base::FEATURE_DISABLED_BY_DEFAULT};
#endif  // defined(OS_WIN)

#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
// Enables stylus appearing as touch when in contact with digitizer.
const base::Feature kDirectManipulationStylus = {
    "DirectManipulationStylus",
#if defined(OS_WIN)
    base::FEATURE_ENABLED_BY_DEFAULT
#else
    base::FEATURE_DISABLED_BY_DEFAULT
#endif
};
#endif  // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)

// Enables forced colors mode for web content.
const base::Feature kForcedColors{"ForcedColors",
                                  base::FEATURE_DISABLED_BY_DEFAULT};

bool IsForcedColorsEnabled() {
  static const bool forced_colors_enabled =
      base::FeatureList::IsEnabled(features::kForcedColors);
  return forced_colors_enabled;
}

// Enables the eye-dropper in the refresh color-picker.
const base::Feature kEyeDropper{"EyeDropper",
                                base::FEATURE_DISABLED_BY_DEFAULT};

bool IsEyeDropperEnabled() {
  return IsFormControlsRefreshEnabled() &&
         base::FeatureList::IsEnabled(features::kEyeDropper);
}

// Enable the FormControlsRefresh feature for Windows, ChromeOS, Linux, and Mac.
// This feature will be released for Android in later milestones. See
// crbug.com/1012106 for the Windows launch bug, and crbug.com/1012108 for the
// Mac launch bug.
const base::Feature kFormControlsRefresh = {"FormControlsRefresh",
#if defined(OS_WIN) || defined(OS_CHROMEOS) || defined(OS_LINUX) || \
    defined(OS_MACOSX)
                                            base::FEATURE_ENABLED_BY_DEFAULT
#else
                                            base::FEATURE_DISABLED_BY_DEFAULT
#endif
};

bool IsFormControlsRefreshEnabled() {
  static const bool form_controls_refresh_enabled =
      base::FeatureList::IsEnabled(features::kFormControlsRefresh);
  return form_controls_refresh_enabled;
}

// Enable the common select popup.
const base::Feature kUseCommonSelectPopup = {"UseCommonSelectPopup",
                                             base::FEATURE_DISABLED_BY_DEFAULT};

bool IsUseCommonSelectPopupEnabled() {
  return base::FeatureList::IsEnabled(features::kUseCommonSelectPopup);
}

// Enable WebUI accessibility enhancements for review and testing.
const base::Feature kWebUIA11yEnhancements{"WebUIA11yEnhancements",
                                           base::FEATURE_DISABLED_BY_DEFAULT};

#if defined(OS_CHROMEOS)
const base::Feature kHandwritingGesture = {"HandwritingGesture",
                                           base::FEATURE_DISABLED_BY_DEFAULT};
#endif

const base::Feature kSynchronousPageFlipTesting{
    "SynchronousPageFlipTesting", base::FEATURE_DISABLED_BY_DEFAULT};

bool IsSynchronousPageFlipTestingEnabled() {
  return base::FeatureList::IsEnabled(kSynchronousPageFlipTesting);
}

}  // namespace features


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/kmod.h>
#include <linux/if_arp.h>
#include <linux/wireless.h>
#include <linux/sockios.h>
#include <linux/etherdevice.h>
#include <linux/if_ether.h>
#include <linux/byteorder/generic.h>
#include <linux/bitops.h>
#include <linux/uaccess.h>
#include <asm/byteorder.h>

#ifdef SIOCETHTOOL
#include <linux/ethtool.h>
#endif

#include <net/iw_handler.h>
#include <net/net_namespace.h>
#include <net/cfg80211.h>

#include "p80211types.h"
#include "p80211hdr.h"
#include "p80211conv.h"
#include "p80211mgmt.h"
#include "p80211msg.h"
#include "p80211netdev.h"
#include "p80211ioctl.h"
#include "p80211req.h"
#include "p80211metastruct.h"
#include "p80211metadef.h"

#include "cfg80211.c"

/* netdevice method functions */
static int p80211knetdev_init(netdevice_t *netdev);
static int p80211knetdev_open(netdevice_t *netdev);
static int p80211knetdev_stop(netdevice_t *netdev);
static int p80211knetdev_hard_start_xmit(struct sk_buff *skb,
					 netdevice_t *netdev);
static void p80211knetdev_set_multicast_list(netdevice_t *dev);
static int p80211knetdev_do_ioctl(netdevice_t *dev, struct ifreq *ifr,
				  int cmd);
static int p80211knetdev_set_mac_address(netdevice_t *dev, void *addr);
static void p80211knetdev_tx_timeout(netdevice_t *netdev);
static int p80211_rx_typedrop(wlandevice_t *wlandev, u16 fc);

int wlan_watchdog = 5000;
module_param(wlan_watchdog, int, 0644);
MODULE_PARM_DESC(wlan_watchdog, "transmit timeout in milliseconds");

int wlan_wext_write = 1;
module_param(wlan_wext_write, int, 0644);
MODULE_PARM_DESC(wlan_wext_write, "enable write wireless extensions");

/*----------------------------------------------------------------
* p80211knetdev_init
*
* Init method for a Linux netdevice.  Called in response to
* register_netdev.
*
* Arguments:
*	none
*
* Returns:
*	nothing
----------------------------------------------------------------*/
static int p80211knetdev_init(netdevice_t *netdev)
{
	/* Called in response to register_netdev */
	/* This is usually the probe function, but the probe has */
	/* already been done by the MSD and the create_kdev */
	/* function.  All we do here is return success */
	return 0;
}

/*----------------------------------------------------------------
* p80211knetdev_open
*
* Linux netdevice open method.  Following a successful call here,
* the device is supposed to be ready for tx and rx.  In our
* situation that may not be entirely true due to the state of the
* MAC below.
*
* Arguments:
*	netdev		Linux network device structure
*
* Returns:
*	zero on success, non-zero otherwise
----------------------------------------------------------------*/
static int p80211knetdev_open(netdevice_t *netdev)
{
	int result = 0;		/* success */
	wlandevice_t *wlandev = netdev->ml_priv;

	/* Check to make sure the MSD is running */
	if (wlandev->msdstate != WLAN_MSD_RUNNING)
		return -ENODEV;

	/* Tell the MSD to open */
	if (wlandev->open) {
		result = wlandev->open(wlandev);
		if (result == 0) {
			netif_start_queue(wlandev->netdev);
			wlandev->state = WLAN_DEVICE_OPEN;
		}
	} else {
		result = -EAGAIN;
	}

	return result;
}

/*----------------------------------------------------------------
* p80211knetdev_stop
*
* Linux netdevice stop (close) method.  Following this call,
* no frames should go up or down through this interface.
*
* Arguments:
*	netdev		Linux network device structure
*
* Returns:
*	zero on success, non-zero otherwise
----------------------------------------------------------------*/
static int p80211knetdev_stop(netdevice_t *netdev)
{
	int result = 0;
	wlandevice_t *wlandev = netdev->ml_priv;

	if (wlandev->close)
		result = wlandev->close(wlandev);

	netif_stop_queue(wlandev->netdev);
	wlandev->state = WLAN_DEVICE_CLOSED;

	return result;
}

/*----------------------------------------------------------------
* p80211netdev_rx
*
* Frame receive function called by the mac specific driver.
*
* Arguments:
*	wlandev		WLAN network device structure
*	skb		skbuff containing a full 802.11 frame.
* Returns:
*	nothing
* Side effects:
*
----------------------------------------------------------------*/
void p80211netdev_rx(wlandevice_t *wlandev, struct sk_buff *skb)
{
	/* Enqueue for post-irq processing */
	skb_queue_tail(&wlandev->nsd_rxq, skb);
	tasklet_schedule(&wlandev->rx_bh);
}

#define CONV_TO_ETHER_SKIPPED	0x01
#define CONV_TO_ETHER_FAILED	0x02

/**
 * p80211_convert_to_ether - conversion from 802.11 frame to ethernet frame
 * @wlandev: pointer to WLAN device
 * @skb: pointer to socket buffer
 *
 * Returns: 0 if conversion succeeded
 *	    CONV_TO_ETHER_FAILED if conversion failed
 *	    CONV_TO_ETHER_SKIPPED if frame is ignored
 */
static int p80211_convert_to_ether(wlandevice_t *wlandev, struct sk_buff *skb)
{
	struct p80211_hdr_a3 *hdr;

	hdr = (struct p80211_hdr_a3 *) skb->data;
	if (p80211_rx_typedrop(wlandev, hdr->fc))
		return CONV_TO_ETHER_SKIPPED;

	/* perform mcast filtering: allow my local address through but reject
	 * anything else that isn't multicast
	 */
	if (wlandev->netdev->flags & IFF_ALLMULTI) {
		if (!ether_addr_equal_unaligned(wlandev->netdev->dev_addr,
						hdr->a1)) {
			if (!is_multicast_ether_addr(hdr->a1))
				return CONV_TO_ETHER_SKIPPED;
		}
	}

	if (skb_p80211_to_ether(wlandev, wlandev->ethconv, skb) == 0) {
		skb->dev->last_rx = jiffies;
		wlandev->netdev->stats.rx_packets++;
		wlandev->netdev->stats.rx_bytes += skb->len;
		netif_rx_ni(skb);
		return 0;
	}

	netdev_dbg(wlandev->netdev, "p80211_convert_to_ether failed.\n");
	return CONV_TO_ETHER_FAILED;
}

/**
 * p80211netdev_rx_bh - deferred processing of all received frames
 *
 * @arg: pointer to WLAN network device structure (cast to unsigned long)
 */
static void p80211netdev_rx_bh(unsigned long arg)
{
	wlandevice_t *wlandev = (wlandevice_t *) arg;
	struct sk_buff *skb = NULL;
	netdevice_t *dev = wlandev->netdev;

	/* Let's empty our our queue */
	while ((skb = skb_dequeue(&wlandev->nsd_rxq))) {
		if (wlandev->state == WLAN_DEVICE_OPEN) {

			if (dev->type != ARPHRD_ETHER) {
				/* RAW frame; we shouldn't convert it */
				/* XXX Append the Prism Header here instead. */

				/* set up various data fields */
				skb->dev = dev;
				skb_reset_mac_header(skb);
				skb->ip_summed = CHECKSUM_NONE;
				skb->pkt_type = PACKET_OTHERHOST;
				skb->protocol = htons(ETH_P_80211_RAW);
				dev->last_rx = jiffies;

				dev->stats.rx_packets++;
				dev->stats.rx_bytes += skb->len;
				netif_rx_ni(skb);
				continue;
			} else {
				if (!p80211_convert_to_ether(wlandev, skb))
					continue;
			}
		}
		dev_kfree_skb(skb);
	}
}

/*----------------------------------------------------------------
* p80211knetdev_hard_start_xmit
*
* Linux netdevice method for transmitting a frame.
*
* Arguments:
*	skb	Linux sk_buff containing the frame.
*	netdev	Linux netdevice.
*
* Side effects:
*	If the lower layers report that buffers are full. netdev->tbusy
*	will be set to prevent higher layers from sending more traffic.
*
*	Note: If this function returns non-zero, higher layers retain
*	      ownership of the skb.
*
* Returns:
*	zero on success, non-zero on failure.
----------------------------------------------------------------*/
static int p80211knetdev_hard_start_xmit(struct sk_buff *skb,
					 netdevice_t *netdev)
{
	int result = 0;
	int txresult = -1;
	wlandevice_t *wlandev = netdev->ml_priv;
	union p80211_hdr p80211_hdr;
	struct p80211_metawep p80211_wep;

	p80211_wep.data = NULL;

	if (!skb)
		return NETDEV_TX_OK;

	if (wlandev->state != WLAN_DEVICE_OPEN) {
		result = 1;
		goto failed;
	}

	memset(&p80211_hdr, 0, sizeof(union p80211_hdr));
	memset(&p80211_wep, 0, sizeof(struct p80211_metawep));

	if (netif_queue_stopped(netdev)) {
		netdev_dbg(netdev, "called when queue stopped.\n");
		result = 1;
		goto failed;
	}

	netif_stop_queue(netdev);

	/* Check to see that a valid mode is set */
	switch (wlandev->macmode) {
	case WLAN_MACMODE_IBSS_STA:
	case WLAN_MACMODE_ESS_STA:
	case WLAN_MACMODE_ESS_AP:
		break;
	default:
		/* Mode isn't set yet, just drop the frame
		 * and return success .
		 * TODO: we need a saner way to handle this
		 */
		if (be16_to_cpu(skb->protocol) != ETH_P_80211_RAW) {
			netif_start_queue(wlandev->netdev);
			netdev_notice(netdev, "Tx attempt prior to association, frame dropped.\n");
			netdev->stats.tx_dropped++;
			result = 0;
			goto failed;
		}
		break;
	}

	/* Check for raw transmits */
	if (be16_to_cpu(skb->protocol) == ETH_P_80211_RAW) {
		if (!capable(CAP_NET_ADMIN)) {
			result = 1;
			goto failed;
		}
		/* move the header over */
		memcpy(&p80211_hdr, skb->data, sizeof(union p80211_hdr));
		skb_pull(skb, sizeof(union p80211_hdr));
	} else {
		if (skb_ether_to_p80211
		    (wlandev, wlandev->ethconv, skb, &p80211_hdr,
		     &p80211_wep) != 0) {
			/* convert failed */
			netdev_dbg(netdev, "ether_to_80211(%d) failed.\n",
				   wlandev->ethconv);
			result = 1;
			goto failed;
		}
	}
	if (!wlandev->txframe) {
		result = 1;
		goto failed;
	}

	netif_trans_update(netdev);

	netdev->stats.tx_packets++;
	/* count only the packet payload */
	netdev->stats.tx_bytes += skb->len;

	txresult = wlandev->txframe(wlandev, skb, &p80211_hdr, &p80211_wep);

	if (txresult == 0) {
		/* success and more buf */
		/* avail, re: hw_txdata */
		netif_wake_queue(wlandev->netdev);
		result = NETDEV_TX_OK;
	} else if (txresult == 1) {
		/* success, no more avail */
		netdev_dbg(netdev, "txframe success, no more bufs\n");
		/* netdev->tbusy = 1;  don't set here, irqhdlr */
		/*   may have already cleared it */
		result = NETDEV_TX_OK;
	} else if (txresult == 2) {
		/* alloc failure, drop frame */
		netdev_dbg(netdev, "txframe returned alloc_fail\n");
		result = NETDEV_TX_BUSY;
	} else {
		/* buffer full or queue busy, drop frame. */
		netdev_dbg(netdev, "txframe returned full or busy\n");
		result = NETDEV_TX_BUSY;
	}

failed:
	/* Free up the WEP buffer if it's not the same as the skb */
	if ((p80211_wep.data) && (p80211_wep.data != skb->data))
		kzfree(p80211_wep.data);

	/* we always free the skb here, never in a lower level. */
	if (!result)
		dev_kfree_skb(skb);

	return result;
}

/*----------------------------------------------------------------
* p80211knetdev_set_multicast_list
*
* Called from higher layers whenever there's a need to set/clear
* promiscuous mode or rewrite the multicast list.
*
* Arguments:
*	none
*
* Returns:
*	nothing
----------------------------------------------------------------*/
static void p80211knetdev_set_multicast_list(netdevice_t *dev)
{
	wlandevice_t *wlandev = dev->ml_priv;

	/* TODO:  real multicast support as well */

	if (wlandev->set_multicast_list)
		wlandev->set_multicast_list(wlandev, dev);

}

#ifdef SIOCETHTOOL

static int p80211netdev_ethtool(wlandevice_t *wlandev, void __user *useraddr)
{
	u32 ethcmd;
	struct ethtool_drvinfo info;
	struct ethtool_value edata;

	memset(&info, 0, sizeof(info));
	memset(&edata, 0, sizeof(edata));

	if (copy_from_user(&ethcmd, useraddr, sizeof(ethcmd)))
		return -EFAULT;

	switch (ethcmd) {
	case ETHTOOL_GDRVINFO:
		info.cmd = ethcmd;
		snprintf(info.driver, sizeof(info.driver), "p80211_%s",
			 wlandev->nsdname);
		snprintf(info.version, sizeof(info.version), "%s",
			 WLAN_RELEASE);

		if (copy_to_user(useraddr, &info, sizeof(info)))
			return -EFAULT;
		return 0;
#ifdef ETHTOOL_GLINK
	case ETHTOOL_GLINK:
		edata.cmd = ethcmd;

		if (wlandev->linkstatus &&
		    (wlandev->macmode != WLAN_MACMODE_NONE)) {
			edata.data = 1;
		} else {
			edata.data = 0;
		}

		if (copy_to_user(useraddr, &edata, sizeof(edata)))
			return -EFAULT;
		return 0;
#endif
	}

	return -EOPNOTSUPP;
}

#endif

/*----------------------------------------------------------------
* p80211knetdev_do_ioctl
*
* Handle an ioctl call on one of our devices.  Everything Linux
* ioctl specific is done here.  Then we pass the contents of the
* ifr->data to the request message handler.
*
* Arguments:
*	dev	Linux kernel netdevice
*	ifr	Our private ioctl request structure, typed for the
*		generic struct ifreq so we can use ptr to func
*		w/o cast.
*
* Returns:
*	zero on success, a negative errno on failure.  Possible values:
*		-ENETDOWN Device isn't up.
*		-EBUSY	cmd already in progress
*		-ETIME	p80211 cmd timed out (MSD may have its own timers)
*		-EFAULT memory fault copying msg from user buffer
*		-ENOMEM unable to allocate kernel msg buffer
*		-ENOSYS	bad magic, it the cmd really for us?
*		-EintR	sleeping on cmd, awakened by signal, cmd cancelled.
*
* Call Context:
*	Process thread (ioctl caller).  TODO: SMP support may require
*	locks.
----------------------------------------------------------------*/
static int p80211knetdev_do_ioctl(netdevice_t *dev, struct ifreq *ifr, int cmd)
{
	int result = 0;
	struct p80211ioctl_req *req = (struct p80211ioctl_req *) ifr;
	wlandevice_t *wlandev = dev->ml_priv;
	u8 *msgbuf;

	netdev_dbg(dev, "rx'd ioctl, cmd=%d, len=%d\n", cmd, req->len);

#ifdef SIOCETHTOOL
	if (cmd == SIOCETHTOOL) {
		result =
		    p80211netdev_ethtool(wlandev, (void __user *)ifr->ifr_data);
		goto bail;
	}
#endif

	/* Test the magic, assume ifr is good if it's there */
	if (req->magic != P80211_IOCTL_MAGIC) {
		result = -ENOSYS;
		goto bail;
	}

	if (cmd == P80211_IFTEST) {
		result = 0;
		goto bail;
	} else if (cmd != P80211_IFREQ) {
		result = -ENOSYS;
		goto bail;
	}

	/* Allocate a buf of size req->len */
	msgbuf = kmalloc(req->len, GFP_KERNEL);
	if (msgbuf) {
		if (copy_from_user(msgbuf, (void __user *)req->data, req->len))
			result = -EFAULT;
		else
			result = p80211req_dorequest(wlandev, msgbuf);

		if (result == 0) {
			if (copy_to_user
			    ((void __user *)req->data, msgbuf, req->len)) {
				result = -EFAULT;
			}
		}
		kfree(msgbuf);
	} else {
		result = -ENOMEM;
	}
bail:
	/* If allocate,copyfrom or copyto fails, return errno */
	return result;
}

/*----------------------------------------------------------------
* p80211knetdev_set_mac_address
*
* Handles the ioctl for changing the MACAddress of a netdevice
*
* references: linux/netdevice.h and drivers/net/net_init.c
*
* NOTE: [MSM] We only prevent address changes when the netdev is
* up.  We don't control anything based on dot11 state.  If the
* address is changed on a STA that's currently associated, you
* will probably lose the ability to send and receive data frames.
* Just be aware.  Therefore, this should usually only be done
* prior to scan/join/auth/assoc.
*
* Arguments:
*	dev	netdevice struct
*	addr	the new MACAddress (a struct)
*
* Returns:
*	zero on success, a negative errno on failure.  Possible values:
*		-EBUSY	device is bussy (cmd not possible)
*		-and errors returned by: p80211req_dorequest(..)
*
* by: Collin R. Mulliner <collin@mulliner.org>
----------------------------------------------------------------*/
static int p80211knetdev_set_mac_address(netdevice_t *dev, void *addr)
{
	struct sockaddr *new_addr = addr;
	struct p80211msg_dot11req_mibset dot11req;
	p80211item_unk392_t *mibattr;
	p80211item_pstr6_t *macaddr;
	p80211item_uint32_t *resultcode;
	int result;

	/* If we're running, we don't allow MAC address changes */
	if (netif_running(dev))
		return -EBUSY;

	/* Set up some convenience pointers. */
	mibattr = &dot11req.mibattribute;
	macaddr = (p80211item_pstr6_t *) &mibattr->data;
	resultcode = &dot11req.resultcode;

	/* Set up a dot11req_mibset */
	memset(&dot11req, 0, sizeof(struct p80211msg_dot11req_mibset));
	dot11req.msgcode = DIDmsg_dot11req_mibset;
	dot11req.msglen = sizeof(struct p80211msg_dot11req_mibset);
	memcpy(dot11req.devname,
	       ((wlandevice_t *) dev->ml_priv)->name, WLAN_DEVNAMELEN_MAX - 1);

	/* Set up the mibattribute argument */
	mibattr->did = DIDmsg_dot11req_mibset_mibattribute;
	mibattr->status = P80211ENUM_msgitem_status_data_ok;
	mibattr->len = sizeof(mibattr->data);

	macaddr->did = DIDmib_dot11mac_dot11OperationTable_dot11MACAddress;
	macaddr->status = P80211ENUM_msgitem_status_data_ok;
	macaddr->len = sizeof(macaddr->data);
	macaddr->data.len = ETH_ALEN;
	memcpy(&macaddr->data.data, new_addr->sa_data, ETH_ALEN);

	/* Set up the resultcode argument */
	resultcode->did = DIDmsg_dot11req_mibset_resultcode;
	resultcode->status = P80211ENUM_msgitem_status_no_value;
	resultcode->len = sizeof(resultcode->data);
	resultcode->data = 0;

	/* now fire the request */
	result = p80211req_dorequest(dev->ml_priv, (u8 *) &dot11req);

	/* If the request wasn't successful, report an error and don't
	 * change the netdev address
	 */
	if (result != 0 || resultcode->data != P80211ENUM_resultcode_success) {
		netdev_err(dev, "Low-level driver failed dot11req_mibset(dot11MACAddress).\n");
		result = -EADDRNOTAVAIL;
	} else {
		/* everything's ok, change the addr in netdev */
		memcpy(dev->dev_addr, new_addr->sa_data, dev->addr_len);
	}

	return result;
}

static int wlan_change_mtu(netdevice_t *dev, int new_mtu)
{
	/* 2312 is max 802.11 payload, 20 is overhead, (ether + llc +snap)
	   and another 8 for wep. */
	if ((new_mtu < 68) || (new_mtu > (2312 - 20 - 8)))
		return -EINVAL;

	dev->mtu = new_mtu;

	return 0;
}

static const struct net_device_ops p80211_netdev_ops = {
	.ndo_init = p80211knetdev_init,
	.ndo_open = p80211knetdev_open,
	.ndo_stop = p80211knetdev_stop,
	.ndo_start_xmit = p80211knetdev_hard_start_xmit,
	.ndo_set_rx_mode = p80211knetdev_set_multicast_list,
	.ndo_do_ioctl = p80211knetdev_do_ioctl,
	.ndo_set_mac_address = p80211knetdev_set_mac_address,
	.ndo_tx_timeout = p80211knetdev_tx_timeout,
	.ndo_change_mtu = wlan_change_mtu,
	.ndo_validate_addr = eth_validate_addr,
};

/*----------------------------------------------------------------
* wlan_setup
*
* Roughly matches the functionality of ether_setup.  Here
* we set up any members of the wlandevice structure that are common
* to all devices.  Additionally, we allocate a linux 'struct device'
* and perform the same setup as ether_setup.
*
* Note: It's important that the caller have setup the wlandev->name
*	ptr prior to calling this function.
*
* Arguments:
*	wlandev		ptr to the wlandev structure for the
*			interface.
*	physdev		ptr to usb device
* Returns:
*	zero on success, non-zero otherwise.
* Call Context:
*	Should be process thread.  We'll assume it might be
*	interrupt though.  When we add support for statically
*	compiled drivers, this function will be called in the
*	context of the kernel startup code.
----------------------------------------------------------------*/
int wlan_setup(wlandevice_t *wlandev, struct device *physdev)
{
	int result = 0;
	netdevice_t *netdev;
	struct wiphy *wiphy;
	struct wireless_dev *wdev;

	/* Set up the wlandev */
	wlandev->state = WLAN_DEVICE_CLOSED;
	wlandev->ethconv = WLAN_ETHCONV_8021h;
	wlandev->macmode = WLAN_MACMODE_NONE;

	/* Set up the rx queue */
	skb_queue_head_init(&wlandev->nsd_rxq);
	tasklet_init(&wlandev->rx_bh,
		     p80211netdev_rx_bh, (unsigned long)wlandev);

	/* Allocate and initialize the wiphy struct */
	wiphy = wlan_create_wiphy(physdev, wlandev);
	if (!wiphy) {
		dev_err(physdev, "Failed to alloc wiphy.\n");
		return 1;
	}

	/* Allocate and initialize the struct device */
	netdev = alloc_netdev(sizeof(struct wireless_dev), "wlan%d",
			      NET_NAME_UNKNOWN, ether_setup);
	if (!netdev) {
		dev_err(physdev, "Failed to alloc netdev.\n");
		wlan_free_wiphy(wiphy);
		result = 1;
	} else {
		wlandev->netdev = netdev;
		netdev->ml_priv = wlandev;
		netdev->netdev_ops = &p80211_netdev_ops;
		wdev = netdev_priv(netdev);
		wdev->wiphy = wiphy;
		wdev->iftype = NL80211_IFTYPE_STATION;
		netdev->ieee80211_ptr = wdev;

		netif_stop_queue(netdev);
		netif_carrier_off(netdev);
	}

	return result;
}

/*----------------------------------------------------------------
* wlan_unsetup
*
* This function is paired with the wlan_setup routine.  It should
* be called after unregister_wlandev.  Basically, all it does is
* free the 'struct device' that's associated with the wlandev.
* We do it here because the 'struct device' isn't allocated
* explicitly in the driver code, it's done in wlan_setup.  To
* do the free in the driver might seem like 'magic'.
*
* Arguments:
*	wlandev		ptr to the wlandev structure for the
*			interface.
* Call Context:
*	Should be process thread.  We'll assume it might be
*	interrupt though.  When we add support for statically
*	compiled drivers, this function will be called in the
*	context of the kernel startup code.
----------------------------------------------------------------*/
void wlan_unsetup(wlandevice_t *wlandev)
{
	struct wireless_dev *wdev;

	tasklet_kill(&wlandev->rx_bh);

	if (wlandev->netdev) {
		wdev = netdev_priv(wlandev->netdev);
		if (wdev->wiphy)
			wlan_free_wiphy(wdev->wiphy);
		free_netdev(wlandev->netdev);
		wlandev->netdev = NULL;
	}
}

/*----------------------------------------------------------------
* register_wlandev
*
* Roughly matches the functionality of register_netdev.  This function
* is called after the driver has successfully probed and set up the
* resources for the device.  It's now ready to become a named device
* in the Linux system.
*
* First we allocate a name for the device (if not already set), then
* we call the Linux function register_netdevice.
*
* Arguments:
*	wlandev		ptr to the wlandev structure for the
*			interface.
* Returns:
*	zero on success, non-zero otherwise.
* Call Context:
*	Can be either interrupt or not.
----------------------------------------------------------------*/
int register_wlandev(wlandevice_t *wlandev)
{
	return register_netdev(wlandev->netdev);
}

/*----------------------------------------------------------------
* unregister_wlandev
*
* Roughly matches the functionality of unregister_netdev.  This
* function is called to remove a named device from the system.
*
* First we tell linux that the device should no longer exist.
* Then we remove it from the list of known wlan devices.
*
* Arguments:
*	wlandev		ptr to the wlandev structure for the
*			interface.
* Returns:
*	zero on success, non-zero otherwise.
* Call Context:
*	Can be either interrupt or not.
----------------------------------------------------------------*/
int unregister_wlandev(wlandevice_t *wlandev)
{
	struct sk_buff *skb;

	unregister_netdev(wlandev->netdev);

	/* Now to clean out the rx queue */
	while ((skb = skb_dequeue(&wlandev->nsd_rxq)))
		dev_kfree_skb(skb);

	return 0;
}

/*----------------------------------------------------------------
* p80211netdev_hwremoved
*
* Hardware removed notification. This function should be called
* immediately after an MSD has detected that the underlying hardware
* has been yanked out from under us.  The primary things we need
* to do are:
*   - Mark the wlandev
*   - Prevent any further traffic from the knetdev i/f
*   - Prevent any further requests from mgmt i/f
*   - If there are any waitq'd mgmt requests or mgmt-frame exchanges,
*     shut them down.
*   - Call the MSD hwremoved function.
*
* The remainder of the cleanup will be handled by unregister().
* Our primary goal here is to prevent as much tickling of the MSD
* as possible since the MSD is already in a 'wounded' state.
*
* TODO: As new features are added, this function should be
*       updated.
*
* Arguments:
*	wlandev		WLAN network device structure
* Returns:
*	nothing
* Side effects:
*
* Call context:
*	Usually interrupt.
----------------------------------------------------------------*/
void p80211netdev_hwremoved(wlandevice_t *wlandev)
{
	wlandev->hwremoved = 1;
	if (wlandev->state == WLAN_DEVICE_OPEN)
		netif_stop_queue(wlandev->netdev);

	netif_device_detach(wlandev->netdev);
}

/*----------------------------------------------------------------
* p80211_rx_typedrop
*
* Classifies the frame, increments the appropriate counter, and
* returns 0|1|2 indicating whether the driver should handle, ignore, or
* drop the frame
*
* Arguments:
*	wlandev		wlan device structure
*	fc		frame control field
*
* Returns:
*	zero if the frame should be handled by the driver,
*       one if the frame should be ignored
*       anything else means we drop it.
*
* Side effects:
*
* Call context:
*	interrupt
----------------------------------------------------------------*/
static int p80211_rx_typedrop(wlandevice_t *wlandev, u16 fc)
{
	u16 ftype;
	u16 fstype;
	int drop = 0;
	/* Classify frame, increment counter */
	ftype = WLAN_GET_FC_FTYPE(fc);
	fstype = WLAN_GET_FC_FSTYPE(fc);
#if 0
	netdev_dbg(wlandev->netdev, "rx_typedrop : ftype=%d fstype=%d.\n",
		   ftype, fstype);
#endif
	switch (ftype) {
	case WLAN_FTYPE_MGMT:
		if ((wlandev->netdev->flags & IFF_PROMISC) ||
		    (wlandev->netdev->flags & IFF_ALLMULTI)) {
			drop = 1;
			break;
		}
		netdev_dbg(wlandev->netdev, "rx'd mgmt:\n");
		wlandev->rx.mgmt++;
		switch (fstype) {
		case WLAN_FSTYPE_ASSOCREQ:
			/* printk("assocreq"); */
			wlandev->rx.assocreq++;
			break;
		case WLAN_FSTYPE_ASSOCRESP:
			/* printk("assocresp"); */
			wlandev->rx.assocresp++;
			break;
		case WLAN_FSTYPE_REASSOCREQ:
			/* printk("reassocreq"); */
			wlandev->rx.reassocreq++;
			break;
		case WLAN_FSTYPE_REASSOCRESP:
			/* printk("reassocresp"); */
			wlandev->rx.reassocresp++;
			break;
		case WLAN_FSTYPE_PROBEREQ:
			/* printk("probereq"); */
			wlandev->rx.probereq++;
			break;
		case WLAN_FSTYPE_PROBERESP:
			/* printk("proberesp"); */
			wlandev->rx.proberesp++;
			break;
		case WLAN_FSTYPE_BEACON:
			/* printk("beacon"); */
			wlandev->rx.beacon++;
			break;
		case WLAN_FSTYPE_ATIM:
			/* printk("atim"); */
			wlandev->rx.atim++;
			break;
		case WLAN_FSTYPE_DISASSOC:
			/* printk("disassoc"); */
			wlandev->rx.disassoc++;
			break;
		case WLAN_FSTYPE_AUTHEN:
			/* printk("authen"); */
			wlandev->rx.authen++;
			break;
		case WLAN_FSTYPE_DEAUTHEN:
			/* printk("deauthen"); */
			wlandev->rx.deauthen++;
			break;
		default:
			/* printk("unknown"); */
			wlandev->rx.mgmt_unknown++;
			break;
		}
		/* printk("\n"); */
		drop = 2;
		break;

	case WLAN_FTYPE_CTL:
		if ((wlandev->netdev->flags & IFF_PROMISC) ||
		    (wlandev->netdev->flags & IFF_ALLMULTI)) {
			drop = 1;
			break;
		}
		netdev_dbg(wlandev->netdev, "rx'd ctl:\n");
		wlandev->rx.ctl++;
		switch (fstype) {
		case WLAN_FSTYPE_PSPOLL:
			/* printk("pspoll"); */
			wlandev->rx.pspoll++;
			break;
		case WLAN_FSTYPE_RTS:
			/* printk("rts"); */
			wlandev->rx.rts++;
			break;
		case WLAN_FSTYPE_CTS:
			/* printk("cts"); */
			wlandev->rx.cts++;
			break;
		case WLAN_FSTYPE_ACK:
			/* printk("ack"); */
			wlandev->rx.ack++;
			break;
		case WLAN_FSTYPE_CFEND:
			/* printk("cfend"); */
			wlandev->rx.cfend++;
			break;
		case WLAN_FSTYPE_CFENDCFACK:
			/* printk("cfendcfack"); */
			wlandev->rx.cfendcfack++;
			break;
		default:
			/* printk("unknown"); */
			wlandev->rx.ctl_unknown++;
			break;
		}
		/* printk("\n"); */
		drop = 2;
		break;

	case WLAN_FTYPE_DATA:
		wlandev->rx.data++;
		switch (fstype) {
		case WLAN_FSTYPE_DATAONLY:
			wlandev->rx.dataonly++;
			break;
		case WLAN_FSTYPE_DATA_CFACK:
			wlandev->rx.data_cfack++;
			break;
		case WLAN_FSTYPE_DATA_CFPOLL:
			wlandev->rx.data_cfpoll++;
			break;
		case WLAN_FSTYPE_DATA_CFACK_CFPOLL:
			wlandev->rx.data__cfack_cfpoll++;
			break;
		case WLAN_FSTYPE_NULL:
			netdev_dbg(wlandev->netdev, "rx'd data:null\n");
			wlandev->rx.null++;
			break;
		case WLAN_FSTYPE_CFACK:
			netdev_dbg(wlandev->netdev, "rx'd data:cfack\n");
			wlandev->rx.cfack++;
			break;
		case WLAN_FSTYPE_CFPOLL:
			netdev_dbg(wlandev->netdev, "rx'd data:cfpoll\n");
			wlandev->rx.cfpoll++;
			break;
		case WLAN_FSTYPE_CFACK_CFPOLL:
			netdev_dbg(wlandev->netdev, "rx'd data:cfack_cfpoll\n");
			wlandev->rx.cfack_cfpoll++;
			break;
		default:
			/* printk("unknown"); */
			wlandev->rx.data_unknown++;
			break;
		}

		break;
	}
	return drop;
}

static void p80211knetdev_tx_timeout(netdevice_t *netdev)
{
	wlandevice_t *wlandev = netdev->ml_priv;

	if (wlandev->tx_timeout) {
		wlandev->tx_timeout(wlandev);
	} else {
		netdev_warn(netdev, "Implement tx_timeout for %s\n",
			    wlandev->nsdname);
		netif_wake_queue(wlandev->netdev);
	}
}


text:
package ru.job4j.calculator;
/**
 * Calculate.
 *
 * @author Valery Labunets (vavilonw@gmail.ru)
 * @version $Id$
 * @since 0.1
 */
public class Calculator {
    /**
     * Calculator.
     * @param args - args.
     */
    private double result;
    /**
     * Method add.
     * @param first .
     * @param second .
     */
    public void add(double first, double second) {
        this.result = first + second;
    }
    /**
     * Method subtrackt.
     * @param first .
     * @param second .
     */
    public void subtrackt(double first, double second) {
        this.result = first - second;
    }
    /**
     * Method div.
     * @param first .
     * @param second .
     */
    public void div(double first, double second) {
        this.result = first / second;
    }
    /**
     * Method multiple.
     * @param first .
     * @param second .
     */
    public void multiple(double first, double second) {
        this.result = first * second;
    }
    /**
     * Method getResult.
     * @param
     * @return result.
     */
    public double getResult() {
        return this.result;
    }

}


text:
<?php namespace Orchestra\Foundation\Tests\Validation;

use Mockery as m;
use Orchestra\Foundation\Validation\Extension;

class ExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test Orchestra\Foundation\Validation\Extension.
     *
     * @test
     */
    public function testInstance()
    {
        $events = m::mock('\Illuminate\Contracts\Events\Dispatcher');
        $factory = m::mock('\Illuminate\Contracts\Validation\Factory');

        $stub = new Extension($factory, $events);

        $this->assertInstanceOf('\Orchestra\Foundation\Validation\Extension', $stub);
        $this->assertInstanceOf('\Orchestra\Support\Validator', $stub);
    }
}


text:
<?php

namespace modules\directory\models\query;
use modules\translations\models\Lang;

/**
 * This is the ActiveQuery class for [[\modules\directory\models\Placement]].
 *
 * @see \modules\directory\models\Placement
 */
class PlacementQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        $this->andWhere('[[status]]=1');
        return $this;
    }*/

    /**
     * @inheritdoc
     * @return \modules\directory\models\Placement[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return \modules\directory\models\Placement|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }

    /*
     * Привязываем переводы с указанным языком
     * */
    public function lang($langId = null){
        if(!$langId){
            $lang = Lang::getCurrent();
            $langId = $lang->id;
        }
        $this->innerJoinWith([
            'placementLangs' => function($query) use($langId){
                $query->where([
                    'lang_id' => $langId,
                ]);
            }
        ]);
        return $this;
    }
}


text:
<?php

use Phalcon\Mvc\Controller;

use business\website\BDianping as BDianping;

class IndexController extends Controller{

    public function initialize(){

    }

    public function index(){

        $dp = new BDianping();
        $dp->getLanguageBarJson("password");
        return ["2"];
    }

    public function testXhprof(){
    	$arr = ["1","3","2","1"];
    	sort($arr);
    }

}


text:
_THIS PROJECT IS DEPRECATED!_
=============================

Use [Dagger‡](https://google.github.com/dagger/) instead.

Sheath: Dagger† Inside
=====================

A proof-of-concept adapter for using [Dagger†][1] with [GWT][2].

Currently, the code generated by Dagger† itself is leveraged as much as possible.
This leads to suboptimal GWT code: many things done at runtime that could have been done
at compile time, probably doesn't play well with code splitting, etc.

[1]: http://square.github.com/dagger
[2]: https://developers.google.com/webtoolkit/


text:
define([
  'backbone',
  'marionette',
  'router'
], function(Backbone, Marionette, AppRouter) {

  var app = new Marionette.Application();

  app.addRegions({
    listRegion: '#listRegion',
    contentRegion: '#contentRegion'
  });

  app.on('initialize:after', function() {
    var modules = ['repository'].map(function(module) {
      return 'modules/' + module + '/module';
    });

    require(modules, function() {
      app.Router = new AppRouter();
      if (!Backbone.History.started) {
        Backbone.history.start({ pushState: true });
      }
    });
  });

  return app;

});


text:
import os

from numpy.testing import (
    assert_, run_module_suite, assert_allclose, assert_equal)
import numpy as np

from qutip.qip.device.processor import Processor
from qutip.states import basis
from qutip.operators import sigmaz, sigmax, sigmay, identity, destroy
from qutip.qip.operations.gates import hadamard_transform
from qutip.tensor import tensor
from qutip.solver import Options
from qutip.random_objects import rand_ket, rand_dm
from qutip.qip.noise import (
    DecoherenceNoise, RandomNoise, ControlAmpNoise)
from qutip.qip.qubits import qubit_states
from qutip.metrics import fidelity
from qutip.qip.pulse import Pulse

class TestCircuitProcessor:
    def test_modify_ctrls(self):
        """
        Test for modifying Hamiltonian, add_control, remove_pulse
        """
        N = 2
        proc = Processor(N=N)
        proc.ctrls
        proc.add_control(sigmaz())
        assert_(tensor([sigmaz(), identity(2)]), proc.ctrls[0])
        proc.add_control(sigmax(), cyclic_permutation=True)
        assert_allclose(len(proc.ctrls), 3)
        assert_allclose(tensor([sigmax(), identity(2)]), proc.ctrls[1])
        assert_allclose(tensor([identity(2), sigmax()]), proc.ctrls[2])
        proc.add_control(sigmay(), targets=1)
        assert_allclose(tensor([identity(2), sigmay()]), proc.ctrls[3])
        proc.remove_pulse([0, 1, 2])
        assert_allclose(tensor([identity(2), sigmay()]), proc.ctrls[0])
        proc.remove_pulse(0)
        assert_allclose(len(proc.ctrls), 0)

    def test_save_read(self):
        """
        Test for saving and reading a pulse matrix
        """
        proc = Processor(N=2)
        proc.add_control(sigmaz(), cyclic_permutation=True)
        proc1 = Processor(N=2)
        proc1.add_control(sigmaz(), cyclic_permutation=True)
        proc2 = Processor(N=2)
        proc2.add_control(sigmaz(), cyclic_permutation=True)
        # TODO generalize to different tlist
        tlist = [0., 0.1, 0.2, 0.3, 0.4, 0.5]
        amp1 = np.arange(0, 5, 1)
        amp2 = np.arange(5, 0, -1)

        proc.pulses[0].tlist = tlist
        proc.pulses[0].coeff = amp1
        proc.pulses[1].tlist = tlist
        proc.pulses[1].coeff = amp2
        proc.save_coeff("qutip_test_CircuitProcessor.txt")
        proc1.read_coeff("qutip_test_CircuitProcessor.txt")
        os.remove("qutip_test_CircuitProcessor.txt")
        assert_allclose(proc1.get_full_coeffs(), proc.get_full_coeffs())
        assert_allclose(proc1.get_full_tlist(), proc.get_full_tlist())
        proc.save_coeff("qutip_test_CircuitProcessor.txt", inctime=False)
        proc2.read_coeff("qutip_test_CircuitProcessor.txt", inctime=False)
        proc2.set_all_tlist(tlist)
        os.remove("qutip_test_CircuitProcessor.txt")
        assert_allclose(proc2.get_full_coeffs(), proc.get_full_coeffs())

    def test_id_evolution(self):
        """
        Test for identity evolution
        """
        N = 1
        proc = Processor(N=N)
        init_state = rand_ket(2)
        tlist = [0., 1., 2.]
        proc.add_pulse(Pulse(identity(2), 0, tlist, False))
        result = proc.run_state(
            init_state, options=Options(store_final_state=True))
        global_phase = init_state.data[0, 0]/result.final_state.data[0, 0]
        assert_allclose(global_phase*result.final_state, init_state)

    def test_id_with_T1_T2(self):
        """
        Test for identity evolution with relaxation t1 and t2
        """
        # setup
        a = destroy(2)
        Hadamard = hadamard_transform(1)
        ex_state = basis(2, 1)
        mines_state = (basis(2, 1)-basis(2, 0)).unit()
        end_time = 2.
        tlist = np.arange(0, end_time + 0.02, 0.02)
        t1 = 1.
        t2 = 0.5

        # test t1
        test = Processor(1, t1=t1)
        # zero ham evolution
        test.add_pulse(Pulse(identity(2), 0, tlist, False))
        result = test.run_state(ex_state, e_ops=[a.dag()*a])
        assert_allclose(
            result.expect[0][-1], np.exp(-1./t1*end_time),
            rtol=1e-5, err_msg="Error in t1 time simulation")

        # test t2
        test = Processor(1, t2=t2)
        test.add_pulse(Pulse(identity(2), 0, tlist, False))
        result = test.run_state(
            init_state=mines_state, e_ops=[Hadamard*a.dag()*a*Hadamard])
        assert_allclose(
            result.expect[0][-1], np.exp(-1./t2*end_time)*0.5+0.5,
            rtol=1e-5, err_msg="Error in t2 time simulation")

        # test t1 and t2
        t1 = np.random.rand(1) + 0.5
        t2 = np.random.rand(1) * 0.5 + 0.5
        test = Processor(1, t1=t1, t2=t2)
        test.add_pulse(Pulse(identity(2), 0, tlist, False))
        result = test.run_state(
            init_state=mines_state, e_ops=[Hadamard*a.dag()*a*Hadamard])
        assert_allclose(
            result.expect[0][-1], np.exp(-1./t2*end_time)*0.5+0.5,
            rtol=1e-5,
            err_msg="Error in t1 & t2 simulation, "
                    "with t1={} and t2={}".format(t1, t2))

    def testPlot(self):
        """
        Test for plotting functions
        """
        try:
            import matplotlib.pyplot as plt
        except Exception:
            return True
        # step_func
        tlist = np.linspace(0., 2*np.pi, 20)
        processor = Processor(N=1, spline_kind="step_func")
        processor.add_control(sigmaz())
        processor.pulses[0].tlist = tlist
        processor.pulses[0].coeff = np.array([np.sin(t) for t in tlist])
        fig, _ = processor.plot_pulses()
        # testing under Xvfb with pytest-xvfb complains if figure windows are
        # left open, so we politely close it:
        plt.close(fig)

        # cubic spline
        tlist = np.linspace(0., 2*np.pi, 20)
        processor = Processor(N=1, spline_kind="cubic")
        processor.add_control(sigmaz())
        processor.pulses[0].tlist = tlist
        processor.pulses[0].coeff = np.array([np.sin(t) for t in tlist])
        fig, _ = processor.plot_pulses()
        # testing under Xvfb with pytest-xvfb complains if figure windows are
        # left open, so we politely close it:
        plt.close(fig)

    def testSpline(self):
        """
        Test if the spline kind is correctly transfered into
        the arguments in QobjEvo
        """
        tlist = np.array([1, 2, 3, 4, 5, 6], dtype=float)
        coeff = np.array([1, 1, 1, 1, 1, 1], dtype=float)
        processor = Processor(N=1, spline_kind="step_func")
        processor.add_control(sigmaz())
        processor.pulses[0].tlist = tlist
        processor.pulses[0].coeff = coeff

        ideal_qobjevo, _ = processor.get_qobjevo(noisy=False)
        assert_(ideal_qobjevo.args["_step_func_coeff"])
        noisy_qobjevo, c_ops = processor.get_qobjevo(noisy=True)
        assert_(noisy_qobjevo.args["_step_func_coeff"])
        processor.T1 = 100.
        processor.add_noise(ControlAmpNoise(coeff=coeff, tlist=tlist))
        noisy_qobjevo, c_ops = processor.get_qobjevo(noisy=True)
        assert_(noisy_qobjevo.args["_step_func_coeff"])

        tlist = np.array([1, 2, 3, 4, 5, 6], dtype=float)
        coeff = np.array([1, 1, 1, 1, 1, 1], dtype=float)
        processor = Processor(N=1, spline_kind="cubic")
        processor.add_control(sigmaz())
        processor.pulses[0].tlist = tlist
        processor.pulses[0].coeff = coeff

        ideal_qobjevo, _ = processor.get_qobjevo(noisy=False)
        assert_(not ideal_qobjevo.args["_step_func_coeff"])
        noisy_qobjevo, c_ops = processor.get_qobjevo(noisy=True)
        assert_(not noisy_qobjevo.args["_step_func_coeff"])
        processor.T1 = 100.
        processor.add_noise(ControlAmpNoise(coeff=coeff, tlist=tlist))
        noisy_qobjevo, c_ops = processor.get_qobjevo(noisy=True)
        assert_(not noisy_qobjevo.args["_step_func_coeff"])

    def testGetObjevo(self):
        tlist = np.array([1, 2, 3, 4, 5, 6], dtype=float)
        coeff = np.array([1, 1, 1, 1, 1, 1], dtype=float)
        processor = Processor(N=1)
        processor.add_control(sigmaz())
        processor.pulses[0].tlist = tlist
        processor.pulses[0].coeff = coeff

        # without noise
        unitary_qobjevo, _ = processor.get_qobjevo(
            args={"test": True}, noisy=False)
        assert_allclose(unitary_qobjevo.ops[0].qobj, sigmaz())
        assert_allclose(unitary_qobjevo.tlist, tlist)
        assert_allclose(unitary_qobjevo.ops[0].coeff, coeff[0])
        assert_(unitary_qobjevo.args["test"],
                msg="Arguments not correctly passed on")

        # with decoherence noise
        dec_noise = DecoherenceNoise(
            c_ops=sigmax(), coeff=coeff, tlist=tlist)
        processor.add_noise(dec_noise)
        assert_equal(unitary_qobjevo.to_list(),
                     processor.get_qobjevo(noisy=False)[0].to_list())

        noisy_qobjevo, c_ops = processor.get_qobjevo(
            args={"test": True}, noisy=True)
        assert_(noisy_qobjevo.args["_step_func_coeff"],
                msg="Spline type not correctly passed on")
        assert_(noisy_qobjevo.args["test"],
                msg="Arguments not correctly passed on")
        assert_(sigmaz() in [pair[0] for pair in noisy_qobjevo.to_list()])
        assert_equal(c_ops[0].ops[0].qobj, sigmax())
        assert_equal(c_ops[0].tlist, tlist)

        # with amplitude noise
        processor = Processor(N=1, spline_kind="cubic")
        processor.add_control(sigmaz())
        tlist = np.linspace(1, 6, int(5/0.2))
        coeff = np.random.rand(len(tlist))
        processor.pulses[0].tlist = tlist
        processor.pulses[0].coeff = coeff

        amp_noise = ControlAmpNoise(coeff=coeff, tlist=tlist)
        processor.add_noise(amp_noise)
        noisy_qobjevo, c_ops = processor.get_qobjevo(
            args={"test": True}, noisy=True)
        assert_(not noisy_qobjevo.args["_step_func_coeff"],
                msg="Spline type not correctly passed on")
        assert_(noisy_qobjevo.args["test"],
                msg="Arguments not correctly passed on")
        assert_equal(len(noisy_qobjevo.ops), 2)
        assert_equal(sigmaz(), noisy_qobjevo.ops[0].qobj)
        assert_allclose(coeff, noisy_qobjevo.ops[0].coeff, rtol=1.e-10)

    def testNoise(self):
        """
        Test for Processor with noise
        """
        # setup and fidelity without noise
        init_state = qubit_states(2, [0, 0, 0, 0])
        tlist = np.array([0., np.pi/2.])
        a = destroy(2)
        proc = Processor(N=2)
        proc.add_control(sigmax(), targets=1)
        proc.pulses[0].tlist = tlist
        proc.pulses[0].coeff = np.array([1])
        result = proc.run_state(init_state=init_state)
        assert_allclose(
            fidelity(result.states[-1], qubit_states(2, [0, 1, 0, 0])),
            1, rtol=1.e-7)

        # decoherence noise
        dec_noise = DecoherenceNoise([0.25*a], targets=1)
        proc.add_noise(dec_noise)
        result = proc.run_state(init_state=init_state)
        assert_allclose(
            fidelity(result.states[-1], qubit_states(2, [0, 1, 0, 0])),
            0.981852, rtol=1.e-3)

        # white random noise
        proc.noise = []
        white_noise = RandomNoise(0.2, np.random.normal, loc=0.1, scale=0.1)
        proc.add_noise(white_noise)
        result = proc.run_state(init_state=init_state)

    def testMultiLevelSystem(self):
        """
        Test for processor with multi-level system
        """
        N = 2
        proc = Processor(N=N, dims=[2, 3])
        proc.add_control(tensor(sigmaz(), rand_dm(3, density=1.)))
        proc.pulses[0].coeff = np.array([1, 2])
        proc.pulses[0].tlist = np.array([0., 1., 2])
        proc.run_state(init_state=tensor([basis(2, 0), basis(3, 1)]))

    def testDrift(self):
        """
        Test for the drift Hamiltonian
        """
        processor = Processor(N=1)
        processor.add_drift(sigmax() / 2, 0)
        tlist = np.array([0., np.pi, 2*np.pi, 3*np.pi])
        processor.add_pulse(Pulse(None, None, tlist, False))
        ideal_qobjevo, _ = processor.get_qobjevo(noisy=True)
        assert_equal(ideal_qobjevo.cte, sigmax() / 2)

        init_state = basis(2)
        propagators = processor.run_analytically()
        analytical_result = init_state
        for unitary in propagators:
            analytical_result = unitary * analytical_result
        fid = fidelity(sigmax() * init_state, analytical_result)
        assert((1 - fid) < 1.0e-6)

    def testChooseSolver(self):
        # setup and fidelity without noise
        init_state = qubit_states(2, [0, 0, 0, 0])
        tlist = np.array([0., np.pi/2.])
        a = destroy(2)
        proc = Processor(N=2)
        proc.add_control(sigmax(), targets=1)
        proc.pulses[0].tlist = tlist
        proc.pulses[0].coeff = np.array([1])
        result = proc.run_state(init_state=init_state, solver="mcsolve")
        assert_allclose(
            fidelity(result.states[-1], qubit_states(2, [0, 1, 0, 0])),
            1, rtol=1.e-7)

if __name__ == "__main__":
    run_module_suite()


text:
module WHMCS
  # WHMCS::Order is the class for managing orders
  class Order < Base

    # Create a new order
    #
    # Parameters:
    #
    # * <tt>:clientid</tt> - client id for order
    # * <tt>:pid</tt> - product id
    # * <tt>:domain</tt> - domain name
    # * <tt>:billingcycle</tt> - onetime, monthly, quarterly, semiannually, etc..
    # * <tt>:addons</tt> - comma seperated list of addon ids
    # * <tt>:customfields</tt> - a base64 encoded serialized array of custom field values
    # * <tt>:configoptions</tt> - a base64 encoded serialized array of configurable product options
    # * <tt>:domaintype</tt> - set for domain registration - register or transfer
    # * <tt>:regperiod</tt> - 1,2,3,etc...
    # * <tt>:dnsmanagement</tt> - true to enable
    # * <tt>:emailforwarding</tt> - true to enable
    # * <tt>:idprotection</tt> - true to enable
    # * <tt>:eppcode</tt> - if transfer
    # * <tt>:nameserver1</tt> - first nameserver (req for domain reg only)
    # * <tt>:nameserver2</tt> - second nameserver
    # * <tt>:nameserver3</tt> - third nameserver
    # * <tt>:nameserver4</tt> - fourth nameserver
    # * <tt>:paymentmethod</tt> - paypal, authorize, etc...
    # * <tt>:promocode</tt> - pass coupon code to apply to the order (optional)
    # * <tt>:affid</tt> - affiliate ID if you want to assign the order to an affiliate (optional)
    # * <tt>:noinvoice</tt> - set true to not generate an invoice for this order
    # * <tt>:noemail</tt> - set true to surpress the order confirmation email
    # * <tt>:clientip</tt> - can be used to pass the customers IP (optional)
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Add_Order
    def self.add_order(params = {})
      params.merge!(:action => 'addorder')
      send_request(params)
    end

    # Get orders
    #
    # Parameters:
    #
    # * <tt>:limitstart</tt> - The record number to start at (default = 0)
    # * <tt>:limitnum</tt> - The number of order records to return (default = 25)
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Get_Orders
    def self.get_orders(params = {})
      params.merge!(:action => 'getorders')
      send_request(params)
    end

    # Get products
    #
    # Parameters:
    #
    # * <tt>:pid</tt> - can be used to just retrieve the details of a specific product ID
    # * <tt>:gid</tt> - can be passed to just retrieve products in a specific group
    # * <tt>:module</tt> - can be passed to just retrieve products assigned to a specific module
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Get_Products
    def self.get_products(params = {})
      params.merge!(:action => 'getproducts')
      send_request(params)
    end

    # Get promotions
    #
    # Parameters:
    #
    # * <tt>:code</tt> - the specific promotion code to return information for (optional)
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Get_Promotions
    def self.get_promotions(params = {})
      params.merge!(:action => 'getpromotions')
      send_request(params)
    end

    # Get order statuses
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Get_Order_Statuses
    def self.get_order_statuses
      params.merge!(:action => 'getorderstatuses')
      send_request(params)
    end

    # Accept an order
    #
    # Parameters:
    #
    # * <tt>:orderid</tt> - the Order ID
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Accept_Order
    def self.accept_order(params = {})
      params.merge!(:action => 'acceptorder')
      send_request(params)
    end

    # Place an order in pending
    #
    # Parameters:
    #
    # * <tt>:orderid</tt> - the Order ID
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Pending_Order
    def self.pending_order(params = {})
      params.merge!(:action => 'pendingorder')
      send_request(params)
    end

    # Cancel an order
    #
    # Parameters:
    #
    # * <tt>:orderid</tt> - the Order ID
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Cancel_Order
    def self.cancel_order(params = {})
      params.merge!(:action => 'cancelorder')
      send_request(params)
    end

    # Mark an order as fraud
    #
    # Parameters:
    #
    # * <tt>:orderid</tt> - the Order ID
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Fraud_Order
    def self.fraud_order(params = {})
      params.merge!(:action => 'fraudorder')
      send_request(params)
    end

    # Delete an order
    #
    # Parameters:
    #
    # * <tt>:orderid</tt> - the Order ID
    #
    # See:
    #
    # http://wiki.whmcs.com/API:Delete_Order
    def self.delete_order(params = {})
      params.merge!(:action => 'deleteorder')
      send_request(params)
    end
  end
end


text:
"""
The exceptions module contains all kleeanalysis exceptions
"""

class Error(Exception):
    """
    Base class for exceptions in this module.
    """
    pass

class InputError(Error):
    """
    Exception raised for errors in the input.
    """

    def __init__(self, message):
        Error.__init__(self, message)


text:
<?php
namespace Mtg\RulesImporter;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class Factory implements FactoryInterface
{
    /**
     * @param ServiceLocatorInterface $serviceLocator
     * @return RulesImporter
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $objectManager = $serviceLocator->get('doctrine.entitymanager.orm_default');
        $service = new RulesImporter($objectManager);

        $config = $serviceLocator->get('config');
        if (!empty($config['rulesections'])) {
            $service->setSections($config['rulesections']);
        }
        return $service;
    }

}


text:
module Azure::ServiceFabric::V6_2_0_9
  module Models
    #
    # Defines values for PartitionAccessStatus
    #
    module PartitionAccessStatus
      Invalid = "Invalid"
      Granted = "Granted"
      ReconfigurationPending = "ReconfigurationPending"
      NotPrimary = "NotPrimary"
      NoWriteQuorum = "NoWriteQuorum"
    end
  end
end


text:
- - -

#### `tf.contrib.bayesflow.stochastic_graph.MeanValue.__init__(stop_gradient=False)` {#MeanValue.__init__}

- - -

#### `tf.contrib.bayesflow.stochastic_graph.MeanValue.popped_above(unused_value_type)` {#MeanValue.popped_above}

- - -

#### `tf.contrib.bayesflow.stochastic_graph.MeanValue.pushed_above(unused_value_type)` {#MeanValue.pushed_above}

- - -

#### `tf.contrib.bayesflow.stochastic_graph.MeanValue.stop_gradient` {#MeanValue.stop_gradient}