text:
using System;
namespace CSJ2K.j2k.util
{

	///  This class implements a thread pool. The thread pool contains a set of
	/// threads which can be given work to do.
	///
	///
If the Java Virtual Machine (JVM) uses native threads, then the
	/// different threads will be able to execute in different processors in
	/// parallel on multiprocessors machines. However, under some JVMs and
	/// operating systems using native threads is not sufficient to allow the JVM
	/// access to multiple processors. This is the case when native threads are
	/// implemented using POSIX threads on lightweight processes
	/// (i.e. PTHREAD_SCOPE_PROCESS sopce scheduling), which is the case on most
	/// UNIX operating systems. In order to do provide access to multiple
	/// processors it is necessary to set the concurrency level to the number of
	/// processors or slightly higher. This can be achieved by setting the Java
	/// system property with the name defined by CONCURRENCY_PROP_NAME to some
	/// non-negative number. This will make use of the 'NativeServices' class and
	/// supporting native libraries. See 'NativeServices' for details. See
	/// 'CONCURRENCY_PROP_NAME' for the name of the property.
	///
	///
Initially the thread pool contains a user specified number of idle
	/// threads. Idle threads can be given a target which is run. While running the
	/// target the thread temporarily leaves the idle list. When the target
	/// finishes, it joins the idle list again, waiting for a new target. When a
	/// target is finished a thread can be notified on a particular object that is
	/// given as a lock.
	///
	///
Jobs can be submitted using Runnable interfaces, using the 'runTarget()'
	/// methods. When the job is submitted, an idle thread will be obtained, the
	/// 'run()' method of the 'Runnable' interface will be executed and when it
	/// completes the thread will be returned to the idle list. In general the
	/// 'run()' method should complete in a rather short time, so that the threds
	/// of the pool are not starved.
	///
	///
If using the non-asynchronous calls to 'runTarget()', it is important
	/// that any target's 'run()' method, or any method called from it, does not
	/// use non-asynchronous calls to 'runTarget()' on the same thread pool where
	/// it was started. Otherwise this could create a dead-lock when there are not
	/// enough idle threads.
	///
	///
The pool also has a global error and runtime exception condition (one
	/// for 'Error' and one for 'RuntimeException'). If a target's 'run()' method
	/// throws an 'Error' or 'RuntimeException' the corresponding exception
	/// condition is set and the exception object saved. In any subsequent call to
	/// 'checkTargetErrors()' the saved exception object is thrown. Likewise, if a
	/// target's 'run()' method throws any other subclass of 'Throwable' a new
	/// 'RuntimeException' is created and saved. It will be thrown on a subsequent
	/// call to 'checkTargetErrors()'. If more than one exception occurs between
	/// calls to 'checkTargetErrors()' only the last one is saved. Any 'Error'
	/// condition has precedence on all 'RuntimeException' conditions. The threads
	/// in the pool are unaffected by any exceptions thrown by targets.
	///
	///
The only exception to the above is the 'ThreadDeath' exception. If a
	/// target's 'run()' method throws the 'ThreadDeath' exception a warning
	/// message is printed and the exception is propagated, which will terminate
	/// the thread in which it occurs. This could lead to instabilities of the
	/// pool. The 'ThreadDeath' exception should never be thrown by the program. It
	/// is thrown by the Java(TM) Virtual Machine when Thread.stop() is
	/// called. This method is deprecated and should never be called.
	///
	///
All the threads in the pool are "daemon" threads and will automatically
	/// terminate when no daemon threads are running.
	///
	///
	/// <seealso cref="NativeServices">
	///
	/// </seealso>
	/// <seealso cref="CONCURRENCY_PROP_NAME">
	///
	/// </seealso>
	/// <seealso cref="Runnable">
	///
	/// </seealso>
	/// <seealso cref="Thread">
	///
	/// </seealso>
	/// <seealso cref="Error">
	///
	/// </seealso>
	/// <seealso cref="RuntimeException">
	///
	///
	/// </seealso>
	public class ThreadPool
	{
		///  Returns the size of the pool. That is the number of threads in this
		/// pool (idle + busy).
		///
		///
		/// <returns> The pool's size.
		///
		///
		/// </returns>
		virtual public int Size
		{
			get
			{
				return idle.Length;
			}

		}

		/// The name of the property that sets the concurrency level:
		/// jj2000.j2k.util.ThreadPool.concurrency
		///
		public const System.String CONCURRENCY_PROP_NAME = "jj2000.j2k.util.ThreadPool.concurrency";

		/// The array of idle threads and the lock for the manipulation of the
		/// idle thread list.
		///
		private ThreadPoolThread[] idle;

		/// The number of idle threads
		private int nidle;

		/// The name of the pool
		private System.String poolName;

		/// The priority for the pool
		private int poolPriority;

		/// The last error thrown by a target. Null if none
		// NOTE: needs to be volatile, so that only one copy exits in memory
		private volatile System.ApplicationException targetE;

		/// The last runtime exception thrown by a target. Null if none
		// NOTE: needs to be volatile, so that only one copy exits in memory
		private volatile System.SystemException targetRE;

		//UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'ThreadPoolThread' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'"
		///  The threads that are managed by the pool.
		///
		///
		internal class ThreadPoolThread:SupportClass.ThreadClass
		{
			private void  InitBlock(ThreadPool enclosingInstance)
			{
				this.enclosingInstance = enclosingInstance;
			}
			private ThreadPool enclosingInstance;
			public ThreadPool Enclosing_Instance
			{
				get
				{
					return enclosingInstance;
				}

			}
			private IThreadRunnable target;
			private System.Object lock_Renamed;
			private bool doNotifyAll;

			///  Creates a ThreadPoolThread object, setting its name according to
			/// the given 'idx', daemon type and the priority to the one of the
			/// pool.
			///
			///
			/// <param name="idx">The index of this thread in the pool
			///
			/// </param>
			/// <param name="name">The name of the thread
			///
			/// </param>
			public ThreadPoolThread(ThreadPool enclosingInstance, int idx, System.String name):base(name)
			{
				InitBlock(enclosingInstance);
				IsBackground = true;
				//UPGRADE_TODO: The differences in the type  of parameters for method 'java.lang.Thread.setPriority'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
				Priority = (System.Threading.ThreadPriority) Enclosing_Instance.poolPriority;
			}

			///  The method that is run by the thread. This method first joins the
			/// idle state in the pool and then enters an infinite loop. In this
			/// loop it waits until a target to run exists and runs it. Once the
			/// target's run() method is done it re-joins the idle state and
			/// notifies the waiting lock object, if one exists.
			///
			///
An interrupt on this thread has no effect other than forcing a
			/// check on the target. Normally the target is checked every time the
			/// thread is woken up by notify, no interrupts should be done.
			///
			///
Any exception thrown by the target's 'run()' method is catched
			/// and this thread is not affected, except for 'ThreadDeath'. If a
			/// 'ThreadDeath' exception is catched a warning message is printed by
			/// the 'FacilityManager' and the exception is propagated up. For
			/// exceptions which are subclasses of 'Error' or 'RuntimeException'
			/// the corresponding error condition is set and this thread is not
			/// affected. For any other exceptions a new 'RuntimeException' is
			/// created and the error condition is set, this thread is not affected.
			///
			///
			override public void  Run()
			{
				// Join the idle threads list
				Enclosing_Instance.putInIdleList(this);
				// Permanently lock the object while running so that target can
				// not be changed until we are waiting again. While waiting for a
				// target the lock is released.
				lock (this)
				{
					while (true)
					{
						// Wait until we get a target
						while (target == null)
						{
							try
							{
								System.Threading.Monitor.Wait(this);
							}
							catch (System.Threading.ThreadInterruptedException)
							{
							}
						}
						// Run the target and catch all possible errors
						try
						{
							target.Run();
						}
						//UPGRADE_NOTE: Exception 'java.lang.ThreadDeath' was converted to 'System.ApplicationException' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
						catch (System.Threading.ThreadAbortException td)
						{
							// We have been instructed to abruptly terminate
							// the thread, which should never be done. This can
							// cause another thread, or the system, to lock.
							FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Thread.stop() called on a ThreadPool " + "thread or ThreadDeath thrown. This is " + "deprecated. Lock-up might occur.");
							throw td;
						}
						catch (System.ApplicationException e)
						{
							Enclosing_Instance.targetE = e;
						}
						catch (System.SystemException re)
						{
							Enclosing_Instance.targetRE = re;
						}
						//UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
						catch (System.Exception)
						{
							// A totally unexpected error has occurred
							// (Thread.stop(Throwable) has been used, which should
							// never be.
							Enclosing_Instance.targetRE = new System.SystemException("Unchecked exception " + "thrown by target's " + "run() method in pool " + Enclosing_Instance.poolName + ".");
						}
						// Join idle threads
						Enclosing_Instance.putInIdleList(this);
						// Release the target and notify lock (i.e. wakeup)
						target = null;
						if (lock_Renamed != null)
						{
							lock (lock_Renamed)
							{
								if (doNotifyAll)
								{
									System.Threading.Monitor.PulseAll(lock_Renamed);
								}
								else
								{
									System.Threading.Monitor.Pulse(lock_Renamed);
								}
							}
						}
					}
				}
			}

			///  Assigns a target to this thread, with an optional notify lock and a
			/// notify mode. The another target is currently running the method
			/// will block until it terminates. After setting the new target the
			/// runner thread will be wakenup and execytion will start.
			///
			///
			/// <param name="target">The runnable object containing the 'run()' method to
			/// run.
			///
			/// </param>
			/// <param name="lock">An object on which notify will be called once the
			/// target's run method has finished. A thread to be notified should be
			/// waiting on that object. If null no thread is notified.
			///
			/// </param>
			/// <param name="notifyAll">If true 'notifyAll()', instead of 'notify()', will
			/// be called on tghe lock.
			///
			/// </param>
			//UPGRADE_NOTE: Synchronized keyword was removed from method 'setTarget'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'"
			internal virtual void  setTarget(IThreadRunnable target, System.Object lock_Renamed, bool notifyAll)
			{
				lock (this)
				{
					// Set the target
					this.target = target;
					this.lock_Renamed = lock_Renamed;
					doNotifyAll = notifyAll;
					// Wakeup the thread
					System.Threading.Monitor.Pulse(this);
				}
			}
		}

		///  Creates a new thread pool of the given size, thread priority and pool
		/// name.
		///
		///
If the Java system property of the name defined by
		/// 'CONCURRENCY_PROP_NAME' is set, then an attempt will be made to load
		/// the library that supports concurrency setting (see
		/// 'NativeServices'). If that succeds the concurrency level will be set to
		/// the specified value. Otherwise a warning is printed.
		///
		///
		/// <param name="size">The size of the pool (number of threads to create in the
		/// pool).
		///
		/// </param>
		/// <param name="priority">The priority to give to the threads in the pool. If
		/// less than 'Thread.MIN_PRIORITY' it will be the same as the priority of
		/// the calling thread.
		///
		/// </param>
		/// <param name="name">The name of the pool. If null a default generic name is
		/// chosen.
		///
		/// </param>
		/// <seealso cref="NativeServices">
		///
		/// </seealso>
		/// <seealso cref="CONCURRENCY_PROP_NAME">
		///
		/// </seealso>
		public ThreadPool(int size, int priority, System.String name)
		{
			int i;
			ThreadPoolThread t;
			//System.String prop;
			//int clevel;

			// Initialize variables checking for special cases
			if (size <= 0)
			{
				throw new System.ArgumentException("Pool must be of positive size");
			}
			if (priority < (int) System.Threading.ThreadPriority.Lowest)
			{
				poolPriority = (System.Int32) SupportClass.ThreadClass.Current().Priority;
			}
			else
			{
				poolPriority = (priority < (int) System.Threading.ThreadPriority.Highest)?priority:(int) System.Threading.ThreadPriority.Highest;
			}
			if (name == null)
			{
				poolName = "Anonymous ThreadPool";
			}
			else
			{
				poolName = name;
			}

			// Allocate internal variables
			idle = new ThreadPoolThread[size];
			nidle = 0;

			// Create and start the threads
			for (i = 0; i < size; i++)
			{
				t = new ThreadPoolThread(this, i, poolName + "-" + i);
				t.Start();
			}
		}

		///  Runs the run method of the specified target in an idle thread of this
		/// pool. When the target's run method completes, the thread waiting on the
		/// lock object is notified, if any. If there is currently no idle thread
		/// the method will block until a thread of the pool becomes idle or the
		/// calling thread is interrupted.
		///
		///
This method is the same as <tt>runTarget(t,l,true,false)</tt>.
		///
		///
		/// <param name="t">The target. The 'run()' method of this object will be run in
		/// an idle thread of the pool.
		///
		/// </param>
		/// <param name="l">The lock object. A thread waiting on the lock of the 'l'
		/// object will be notified, through the 'notify()' call, when the target's
		/// run method completes. If null no thread is notified.
		///
		/// </param>
		/// <returns> True if the target was submitted to some thread. False if no
		/// idle thread could be found and the target was not submitted for
		/// execution.
		///
		///
		/// </returns>
		public virtual bool runTarget(IThreadRunnable t, System.Object l)
		{
			return runTarget(t, l, false, false);
		}

		///  Runs the run method of the specified target in an idle thread of this
		/// pool. When the target's run method completes, the thread waiting on the
		/// lock object is notified, if any. If there is currently no idle thread
		/// and the asynchronous mode is not used the method will block until a
		/// thread of the pool becomes idle or the calling thread is
		/// interrupted. If the asynchronous mode is used then the method will not
		/// block and will return false.
		///
		///
This method is the same as <tt>runTarget(t,l,async,false)</tt>.
		///
		///
		/// <param name="t">The target. The 'run()' method of this object will be run in
		/// an idle thread of the pool.
		///
		/// </param>
		/// <param name="l">The lock object. A thread waiting on the lock of the 'l'
		/// object will be notified, through the 'notify()' call, when the target's
		/// run method completes. If null no thread is notified.
		///
		/// </param>
		/// <param name="async">If true the asynchronous mode will be used.
		///
		/// </param>
		/// <returns> True if the target was submitted to some thread. False if no
		/// idle thread could be found and the target was not submitted for
		/// execution.
		///
		///
		/// </returns>
		public virtual bool runTarget(IThreadRunnable t, System.Object l, bool async)
		{
			return runTarget(t, l, async, false);
		}

		///  Runs the run method of the specified target in an idle thread of this
		/// pool. When the target's run method completes, the thread waiting on the
		/// lock object is notified, if any. If there is currently no idle thread
		/// and the asynchronous mode is not used the method will block until a
		/// thread of the pool becomes idle or the calling thread is
		/// interrupted. If the asynchronous mode is used then the method will not
		/// block and will return false.
		///
		///
		/// <param name="t">The target. The 'run()' method of this object will be run in
		/// an idle thread of the pool.
		///
		/// </param>
		/// <param name="l">The lock object. A thread waiting on the lock of the 'l'
		/// object will be notified, through the 'notify()' call, when the target's
		/// run method completes. If null no thread is notified.
		///
		/// </param>
		/// <param name="async">If true the asynchronous mode will be used.
		///
		/// </param>
		/// <param name="notifyAll">If true, threads waiting on the lock of the 'l' object
		/// will be notified trough the 'notifyAll()' instead of the normal
		/// 'notify()' call. This is not normally needed.
		///
		/// </param>
		/// <returns> True if the target was submitted to some thread. False if no
		/// idle thread could be found and the target was not submitted for
		/// execution.
		///
		///
		/// </returns>
		public virtual bool runTarget(IThreadRunnable t, System.Object l, bool async, bool notifyAll)
		{
			ThreadPoolThread runner; // The thread to run the target

			// Get a thread to run
			runner = getIdle(async);
			// If no runner return failure
			if (runner == null)
				return false;
			// Set the runner
			runner.setTarget(t, l, notifyAll);
			return true;
		}

		///  Checks that no error or runtime exception in any target have occurred
		/// so far. If an error or runtime exception has occurred in a target's run
		/// method they are thrown by this method.
		///
		///
		/// <exception cref="Error">If an error condition has been thrown by a target
		/// 'run()' method.
		///
		/// </exception>
		/// <exception cref="RuntimeException">If a runtime exception has been thrown by a
		/// target 'run()' method.
		///
		/// </exception>
		public virtual void  checkTargetErrors()
		{
			// Check for Error
			if (targetE != null)
				throw targetE;
			// Check for RuntimeException
			if (targetRE != null)
				throw targetRE;
		}

		///  Clears the current target error conditions, if any. Note that a thread
		/// in the pool might have set the error conditions since the last check
		/// and that those error conditions will be lost. Likewise, before
		/// returning from this method another thread might set the error
		/// conditions. There is no guarantee that no error conditions exist when
		/// returning from this method.
		///
		///
In order to ensure that no error conditions exist when returning
		/// from this method cooperation from the targets and the thread using this
		/// pool is necessary (i.e. currently no targets running or waiting to
		/// run).
		///
		///
		public virtual void  clearTargetErrors()
		{
			// Clear the error and runtime exception conditions
			targetE = null;
			targetRE = null;
		}

		///  Puts the thread 't' in the idle list. The thread 't' should be in fact
		/// idle and ready to accept a new target when it joins the idle list.
		///
		///
 An idle thread that is already in the list should never add itself
		/// to the list before it is removed. For efficiency reasons there is no
		/// check to see if the thread is already in the list of idle threads.
		///
		///
 If the idle list was empty 'notify()' will be called on the 'idle'
		/// array, to wake up a thread that might be waiting (within the
		/// 'getIdle()' method) on an idle thread to become available.
		///
		///
		/// <param name="t">The thread to put in the idle list.
		///
		/// </param>
		private void  putInIdleList(ThreadPoolThread t)
		{
			// NOTE: if already in idle => catastrophe! (should be OK since //
			// this is private method)
			// Lock the idle array to avoid races with 'getIdle()'
			lock (idle)
			{
				idle[nidle] = t;
				nidle++;
				// If idle array was empty wakeup any waiting threads.
				if (nidle == 1)
					System.Threading.Monitor.Pulse(idle);
			}
		}

		///  Returns and idle thread and removes it from the list of idle
		/// threads. In asynchronous mode it will immediately return an idle
		/// thread, or null if none is available. In non-asynchronous mode it will
		/// block until a thread of the pool becomes idle or the calling thread is
		/// interrupted.
		///
		///
If in non-asynchronous mode and there are currently no idle threads
		/// available the calling thread will wait on the 'idle' array lock, until
		/// notified by 'putInIdleList()' that an idle thread might have become
		/// available.
		///
		///
		/// <param name="async">If true asynchronous mode is used.
		///
		/// </param>
		/// <returns> An idle thread of the pool, that has been removed from the idle
		/// list, or null if none is available.
		///
		/// </returns>
		private ThreadPoolThread getIdle(bool async)
		{
			// Lock the idle array to avoid races with 'putInIdleList()'
			lock (idle)
			{
				if (async)
				{
					// In asynchronous mode just return null if no idle thread
					if (nidle == 0)
						return null;
				}
				else
				{
					// In synchronous mode wait until a thread becomes idle
					while (nidle == 0)
					{
						try
						{
							System.Threading.Monitor.Wait(idle);
						}
						catch (System.Threading.ThreadInterruptedException)
						{
							// If we were interrupted just return null
							return null;
						}
					}
				}
				// Decrease the idle count and return one of the idle threads
				nidle--;
				return idle[nidle];
			}
		}
	}
}


text:
{{company.company}}

Company:  {{company.company}}

Email:  {{company.email.main}}

Other Email:  {{company.email.other}}

Main Phone:  {{company.phone.main}}

Fax:  {{company.phone.fax}}

Facebook:  {{company.web.facebook}}

Twitter:  {{company.web.twitter}}

Vimeo:  {{company.web.vimeo}}

YouTube:  {{company.web.youtube}}

Instagram:  {{company.web.instagram}}

GooglePlus:  {{company.web.googleplus}}

Other:  {{company.web.other}}

Population:  {{company.population}}

Brand:  {{company.brand}}

Type:  {{company.companyType}}

Status:  {{company.status}}

Main - Street Address:  {{company.address.main.street}}

Main - City:  {{company.address.main.city}}

Main - State:  {{company.address.main.state}}

Main - Zip:  {{company.address.main.zip}}

Mailing - Street Address:  {{company.address.mailing.street}}

Mailing - City:  {{company.address.mailing.city}}

Mailing - State:  {{company.address.mailing.state}}

Mailing - Zip:  {{company.address.mailing.zip}}

Other - Street Address:  {{company.address.other.street}}

Other - City:  {{company.address.other.city}}

Other - State:  {{company.address.other.state}}

Other - Zip:  {{company.address.other.zip}}

Timezone:  {{company.timezone}}

Notes:  {{company.notes}}

Contacts

              #
              Name
              Role
              Email

              {{contact._id}}
                {{contact.first_name}} {{contact.last_name}}
                {{contact.role}}
                {{contact.main.email}}
                Details Edit <button id="deleteContact" class="btn btn-danger">Delete

redpajama_set_name: RedPajamaGithub


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef MEMORY_H_INCLUDED
#define MEMORY_H_INCLUDED

#ifdef MEM_USE_FLASH

/* if dual bank flash */
#ifndef IFLASH_ADDR
#  define IFLASH_ADDR      IFLASH0_ADDR
#endif
/* if dual bank flash */
#ifndef IFLASH_PAGE_SIZE
#  define IFLASH_PAGE_SIZE IFLASH0_PAGE_SIZE
#endif

#define memory_init        mem_flash_init
#define memory_cleanup     mem_flash_cleanup
#define memory_erase       mem_flash_erase
#define memory_write       mem_flash_page_write
#define memory_next        mem_flash_page_next
#define memory_lock        mem_flash_lock
#define memory_unlock      mem_flash_unlock
#define memory_flush()

void mem_flash_init(void);
void mem_flash_cleanup(void);
uint32_t mem_flash_erase(void * addr,uint32_t size);
bool mem_flash_page_write(void * addr,void * data);
void *mem_flash_page_next(void * addr);
bool mem_flash_lock(void * start,void * end);
bool mem_flash_unlock(void * start,void * end);

#endif /* #ifdef MEM_USE_FLASH */

#endif


text:
current_dir = File.dirname(File.expand_path(__FILE__))
lib_path = File.join(current_dir, '..', 'lib')
$LOAD_PATH.unshift lib_path

require 'rubygems'

require 'idclight'

include IDConverter::Light

code = 0
puts "\n"
puts "IDCLight (IDConverter Light) command-line converter utility, by Preston Lee. (Screen scapes http://idclight.bioinfo.cnio.es for data.)"
if ARGV.length == 1
	id = ARGV[0]
	r = hugo_id_to_ensembl_id(id)
	if r.nil?
	  puts "No result. Bad input, perhaps? :("
	  code = 1
	else
		puts "\n#{r}"
	end
else
	puts "\n\tUsage: #{__FILE__} <id>"
end
puts "\n"

exit(code)


text:
Semaphore CI: [![Build Status](https://semaphoreci.com/api/v1/timduly4/pyglow/branches/master/badge.svg)](https://semaphoreci.com/timduly4/pyglow)

Travis CI: [![Build Status](https://travis-ci.com/timduly4/pyglow.svg?branch=master)](https://travis-ci.com/timduly4/pyglow)

<img src="./logo.png" width="400">

[_(airglow viewed aboard the ISS)_](http://en.wikipedia.org/wiki/File:Cupola_above_the_darkened_Earth.jpg)

# Overview

`pyglow` is a Python module that wraps several upper atmosphere climatological models written in FORTRAN, such as the Horizontal Wind Model (HWM), the International Geomagnetic Reference Field (IGRF), the International Reference Ionosphere (IRI), and the Mass Spectrometer and Incoherent Scatter Radar (MSIS).

It includes the following upper atmospheric models:

  * HWM 1993
  * HWM 2007
  * HWM 2014
  * IGRF 11
  * IGRF 12
  * IRI 2012
  * IRI 2016
  * MSIS 2000

pyglow also provides access to the the following geophysical indices:
  * AP
  * Kp
  * F10.7
  * DST
  * AE

`pyglow` offers access to these models & indices in a convenient, high-level object-oriented interface within Python.

# Prerequisites

`pyglow` requires the following packages for installation:

1. `gfortran` (`$ sudo apt-get install gfortran`)
2. `f2py` (`$ pip install numpy --upgrade`)
3. Python packages listed in `requirements.txt` (`$ pip install -r requirements.txt`)

# Installation

### I'm Feeling Lucky:

First, checkout the repository:

```
$ git clone git://github.com/timduly4/pyglow.git pyglow
```

Change directories into the repository folder, compile the f2py bindings, then install the Python package:
```
$ cd pyglow/
$ make -C src/pyglow/models source
$ python3 setup.py install --user
```

### Trouble in downloading model files:

If you have problems downloading files from the official websites,  follow the next steps:

(1) Create the local http server:

```
$ cd static/
$ python3 -m http.server 8080
```

(2) Edit the file `src/pyglow/models/Makefile`, replace the appropriate line with the following code:

```
download:
  python get_models_offline.py
```

(3) Compile the f2py bindings, then install the Python package:

```
$ cd pyglow/
$ make -C src/pyglow/models source
$ python3 setup.py install --user
```

Note: The model files may not be latest.

### Individual installation steps:

If you have troubles, follow the individual installation steps:

(1) Download the package:
```
$ git clone git://github.com/timduly4/pyglow.git
$ cd pyglow/
```

(2) Download the climatological models and wrap them with f2py:
```
$ cd ./src/pyglow/models/
$ make all
```
  * If successful, there should be a `*.so` file in each of the `./models/dl_models/<model>/` directories:

    ```
    $ find . -name "*.so"
    ./dl_models/hwm07/hwm07py.so
    ./dl_models/hwm93/hwm93py.so
    ./dl_models/hwm14/hwm14py.so
    ./dl_models/igrf11/igrf11py.so
    ./dl_models/igrf12/igrf12py.so
    ./dl_models/iri12/iri12py.so
    ./dl_models/iri16/iri16py.so
    ./dl_models/msis/msis00py.so
    ```

(3) Install the Python package
```
$ cd ../../../   # get back to root directory
$ python3 setup.py install --user
```
  * On a mac, the folder `pyglow` and `*.so` files from `./models/dl_models/<model>/` should be in `/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages`
  * The `--user` flag installs the package locally (i.e., you do not need `sudo` access)

# Unit tests

See unit tests in `./test`.  For example, run the unittest suite with:

`$ pytest test/`

(Be sure that the f2py modules have been compiled via `$ make -C src/pyglow/models source`, first.)

# Examples

See example scripts located in `./examples` for example calls to `pyglow`.

# Docker

We've included a Dockerfile for `pyglow`.  To build the image:

`$ docker build -t pyglow .`

This will compile and install pyglow within the Docker container.

Run the unit tests within the container via:

`$ docker run pyglow`

# Hints

### General
1. Use tab completion in ipython to view the full set of member data and variables available in the Point class.
  * For example, in the test code, run `pt.<TAB><TAB>` and class information will be listed.

### Updating geophysical indices with `pyglow.update_indices()`
You'll need to download the geophysical indices as they become available.  The `update_indices()` function is available in pyglow that enables you do this:

```
# Grabs indices between 2016 and 2018:
$ python3 -c "import pyglow; pyglow.update_indices(2016, 2018)"
```

Note: you only need to run this function when you would like to update the indices.

You can check if you have geophysical indices between dates with:
```
$ python3 -c "import pyglow;  pyglow.check_stored_indices('2015-01-01', '2019-01-01')"

Checking: input date range:
  2015-01-01
  to
  2019-01-01
>> We have all of the geophysical indices files between these dates.
```

# Uninstallation

The install directory for pyglow can be outputted via `python3 -c "import pyglow; print(pyglow.__file__)"`.  For example:
```
~ $ python3 -c "import pyglow; print(pyglow.__file__)"
/Users/duly/Library/Python/3.7/lib/python/site-packages/pyglow/__init__.pyc
```
This tells you the installation location, and then you can remove the package with:
```
~ $ rm -rf /Users/duly/Library/Python/3.7/lib/python/site-packages/pyglow
```


text:
package com.llb.nature.domain;

public class GridViewItemBean {
	private String imageUrl;//图片的地址
	private String name;
	private String url;

	public GridViewItemBean(String imageUrl,String name,String url){
		this.url=url;
		this.imageUrl=imageUrl;
		this.name=name;
	}

	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getImageUrl() {
		return imageUrl;
	}
	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}


text:
#ifndef _ARK_PKTCHKR_H_
#define _ARK_PKTCHKR_H_

#include <stdint.h>
#include <inttypes.h>

#define ARK_PKTCHKR_BASE_ADR  0x90000

typedef void *ark_pkt_chkr_t;

/* The packet checker is an internal Arkville hardware module, which
 * verifies packet streams generated from the corresponding packet
 * generator.  This module is used for Arkville testing.
 * This module is *not* intended for end-user manipulation, hence
 * there is minimal documentation.
 */

/*
 * This are overlay structures to a memory mapped FPGA device.  These
 * structs will never be instantiated in ram memory
 */
struct ark_pkt_chkr_stat_regs {
	uint32_t r0;
	uint32_t pkt_start_stop;
	uint32_t pkt_ctrl;
	uint32_t pkts_rcvd;
	uint64_t bytes_rcvd;
	uint32_t pkts_ok;
	uint32_t pkts_mismatch;
	uint32_t pkts_err;
	uint32_t first_mismatch;
	uint32_t resync_events;
	uint32_t pkts_missing;
	uint32_t min_latency;
	uint32_t max_latency;
} __attribute__ ((packed));

struct ark_pkt_chkr_ctl_regs {
	uint32_t pkt_ctrl;
	uint32_t pkt_payload;
	uint32_t pkt_size_min;
	uint32_t pkt_size_max;
	uint32_t pkt_size_incr;
	uint32_t num_pkts;
	uint32_t pkts_sent;
	uint32_t src_mac_addr_l;
	uint32_t src_mac_addr_h;
	uint32_t dst_mac_addr_l;
	uint32_t dst_mac_addr_h;
	uint32_t eth_type;
	uint32_t hdr_dw[7];
} __attribute__ ((packed));

struct ark_pkt_chkr_inst {
	struct rte_eth_dev_info *dev_info;
	volatile struct ark_pkt_chkr_stat_regs *sregs;
	volatile struct ark_pkt_chkr_ctl_regs *cregs;
	int l2_mode;
	int ordinal;
};

/*  packet checker functions */
ark_pkt_chkr_t ark_pktchkr_init(void *addr, int ord, int l2_mode);
void ark_pktchkr_uninit(ark_pkt_chkr_t handle);
void ark_pktchkr_run(ark_pkt_chkr_t handle);
int ark_pktchkr_stopped(ark_pkt_chkr_t handle);
void ark_pktchkr_stop(ark_pkt_chkr_t handle);
int ark_pktchkr_is_running(ark_pkt_chkr_t handle);
int ark_pktchkr_get_pkts_sent(ark_pkt_chkr_t handle);
void ark_pktchkr_set_payload_byte(ark_pkt_chkr_t handle, uint32_t b);
void ark_pktchkr_set_pkt_size_min(ark_pkt_chkr_t handle, uint32_t x);
void ark_pktchkr_set_pkt_size_max(ark_pkt_chkr_t handle, uint32_t x);
void ark_pktchkr_set_pkt_size_incr(ark_pkt_chkr_t handle, uint32_t x);
void ark_pktchkr_set_num_pkts(ark_pkt_chkr_t handle, uint32_t x);
void ark_pktchkr_set_src_mac_addr(ark_pkt_chkr_t handle, uint64_t mac_addr);
void ark_pktchkr_set_dst_mac_addr(ark_pkt_chkr_t handle, uint64_t mac_addr);
void ark_pktchkr_set_eth_type(ark_pkt_chkr_t handle, uint32_t x);
void ark_pktchkr_set_hdr_dW(ark_pkt_chkr_t handle, uint32_t *hdr);
void ark_pktchkr_parse(char *args);
void ark_pktchkr_setup(ark_pkt_chkr_t handle);
void ark_pktchkr_dump_stats(ark_pkt_chkr_t handle);
int ark_pktchkr_wait_done(ark_pkt_chkr_t handle);

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="assets/css/bootstrap.min.css" rel="stylesheet">

Timer


text:
//
//  Copyright (c) 2014 VK.com
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//  the Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

package com.vk.sdk.api.model;

import android.os.Parcel;
import android.os.Parcelable;
import org.json.JSONArray;
import org.json.JSONObject;
import static com.vk.sdk.api.model.VKAttachments.*;

/**
 * Describes a photo album
 */
@SuppressWarnings("unused")
public class VKApiPhotoAlbum extends VKAttachments.VKApiAttachment implements Parcelable, Identifiable {

    /**
     * URL for empty album cover with max width at 75px
     */
    public final static String COVER_S = "http://vk.com/images/s_noalbum.png";

    /**
     * URL of empty album cover with max width at 130px
     */
    public final static String COVER_M = "http://vk.com/images/m_noalbum.png";

    /**
     * URL of empty album cover with max width at 604px
     */
    public final static String COVER_X = "http://vk.com/images/x_noalbum.png";

    /**
     * Album ID.
     */
    public int id;

    /**
     * Album title.
     */
    public String title;

    /**
     * Number of photos in the album.
     */
    public int size;

    /**
     * Privacy settings for the album.
     */
    public int privacy;

    /**
     * Album description.
     */
    public String description;

    /**
     * ID of the user or community that owns the album.
     */
    public int owner_id;

    /**
     * Whether a user can upload photos to this album(false — cannot, true — can).
     */
    public boolean can_upload;

    /**
     * Date (in Unix time) the album was last updated.
     */
    public long updated;

    /**
     * Album creation date (in Unix time).
     */
    public long created;

    /**
     * ID of the photo which is the cover.
     */
    public int thumb_id;

    /**
     * Link to album cover photo.
     */
    public String thumb_src;

    /**
     * Links to to cover photo.
     */
    public VKPhotoSizes photo = new VKPhotoSizes();

    /**
     * Creates a PhotoAlbum instance from JSONObject.
     */
    public VKApiPhotoAlbum parse(JSONObject from) {
        id = from.optInt("id");
        thumb_id = from.optInt("thumb_id");
        owner_id = from.optInt("owner_id");
        title = from.optString("title");
        description = from.optString("description");
        created = from.optLong("created");
        updated = from.optLong("updated");
        size = from.optInt("size");
        can_upload = ParseUtils.parseBoolean(from, "can_upload");
        thumb_src = from.optString("thumb_src");
        if(from.has("privacy")) {
            privacy = from.optInt("privacy");
        } else {
            privacy = VKPrivacy.parsePrivacy(from.optJSONObject("privacy_view"));
        }
        JSONArray sizes = from.optJSONArray("sizes");
        if(sizes != null) {
            photo.fill(sizes);
        } else {
            photo.add(VKApiPhotoSize.create(COVER_S, 75, 55));
            photo.add(VKApiPhotoSize.create(COVER_M, 130, 97));
            photo.add(VKApiPhotoSize.create(COVER_X, 432, 249));
            photo.sort();
        }
        return this;
    }

    /**
     * Creates a PhotoAlbum instance from Parcel.
     */
    public VKApiPhotoAlbum(Parcel in) {
        this.id = in.readInt();
        this.title = in.readString();
        this.size = in.readInt();
        this.privacy = in.readInt();
        this.description = in.readString();
        this.owner_id = in.readInt();
        this.can_upload = in.readByte() != 0;
        this.updated = in.readLong();
        this.created = in.readLong();
        this.thumb_id = in.readInt();
        this.thumb_src = in.readString();
        this.photo = in.readParcelable(VKPhotoSizes.class.getClassLoader());
    }

    /**
     * Creates empty PhotoAlbum instance.
     */
    public VKApiPhotoAlbum() {

    }

    public boolean isClosed() {
        return privacy != VKPrivacy.PRIVACY_ALL;
    }

    @Override
    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return title;
    }

    @Override
    public CharSequence toAttachmentString() {
        return new StringBuilder(TYPE_ALBUM).append(owner_id).append('_').append(id);
    }

    @Override
    public String getType() {
        return TYPE_ALBUM;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
        dest.writeString(this.title);
        dest.writeInt(this.size);
        dest.writeInt(this.privacy);
        dest.writeString(this.description);
        dest.writeInt(this.owner_id);
        dest.writeByte(can_upload ? (byte) 1 : (byte) 0);
        dest.writeLong(this.updated);
        dest.writeLong(this.created);
        dest.writeInt(this.thumb_id);
        dest.writeString(this.thumb_src);
        dest.writeParcelable(this.photo, flags);
    }

    public static Creator<VKApiPhotoAlbum> CREATOR = new Creator<VKApiPhotoAlbum>() {
        public VKApiPhotoAlbum createFromParcel(Parcel source) {
            return new VKApiPhotoAlbum(source);
        }

        public VKApiPhotoAlbum[] newArray(int size) {
            return new VKApiPhotoAlbum[size];
        }
    };

}


text:
package br.com.maplink.webservices.places.client.service;

import br.com.maplink.webservices.places.client.builder.RequestAuthorizationBuilder;
import br.com.maplink.webservices.places.client.entity.ApiRequest;
import br.com.maplink.webservices.places.client.entity.RequestAuthorization;
import br.com.maplink.webservices.places.client.exception.PlacesApiClientRequestException;
import br.com.maplink.webservices.places.client.resource.Category;
import br.com.maplink.webservices.places.client.wrapper.XmlSerializerWrapper;
import br.com.tealdi.httpclient.Header;
import br.com.tealdi.httpclient.Response;
import org.junit.Before;
import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.*;

public class ResourceRequestRetrieverImplTest {

	private ResourceRequestRetriever retriever;
	private RequestAuthorizationBuilder mockedRequestAuthorizationBuilder;
	private HttpResponseRetriever mockedHttpResponseRetriever;
	private XmlSerializerWrapper mockedXmlSerializerWrapper;
	private Category resourceRetrieved;
	private Category resource;
	private ApiRequest apiRequest;
	private RequestAuthorization requestAuthorizationBuit;
	private Response validResponseRetrieved;
	private Response invalidResponseRetrieved;

	@Before
	public void setUp() {
		apiRequest = new ApiRequest();

		mockedRequestAuthorizationBuilder = mock(RequestAuthorizationBuilder.class);
		mockedHttpResponseRetriever = mock(HttpResponseRetriever.class);
		mockedXmlSerializerWrapper = mock(XmlSerializerWrapper.class);

		retriever = new ResourceRequestRetrieverImpl(
				mockedRequestAuthorizationBuilder,
				mockedHttpResponseRetriever,
				mockedXmlSerializerWrapper);
	}

	@Test
	public void shouldRetrieveResource() throws Exception {
		givenRequestAuthorizationWasBuilt()
			.andValidResponseWereRetrieved()
			.andResponseWasSerialized()
			.whenRetrievingResource();

		assertThat(resource)
			.isEqualTo(resourceRetrieved);
	}

	@Test
	public void shouldBuildRequestAuthorizationWhenRetrievingResource() throws Exception {
		givenRequestAuthorizationWasBuilt()
			.andValidResponseWereRetrieved()
			.andResponseWasSerialized()
			.whenRetrievingResource();

		verify(mockedRequestAuthorizationBuilder, times(1))
			.build(apiRequest);
	}

	@Test
	public void shouldRetrieveHttpResponseWhenRetrievingResource() throws Exception {
		givenRequestAuthorizationWasBuilt()
			.andValidResponseWereRetrieved()
			.andResponseWasSerialized()
			.whenRetrievingResource();

		verify(mockedHttpResponseRetriever, times(1))
			.retrieveFor(requestAuthorizationBuit);
	}

	@Test
	public void shouldDeserializeResponseBodyWhenRetrievingResource() throws Exception {
		givenRequestAuthorizationWasBuilt()
			.andValidResponseWereRetrieved()
			.andResponseWasSerialized()
			.whenRetrievingResource();

		verify(mockedXmlSerializerWrapper, times(1))
			.deserialize(Category.class, validResponseRetrieved.getBody());
	}

	@Test(expected=PlacesApiClientRequestException.class)
	public void shouldThrowExceptionWhenRetrievingResourceWithAInvalidResponse() throws Exception {
		givenRequestAuthorizationWasBuilt()
			.andInvalidResponseWereRetrieved()
			.whenRetrievingResource();
	}

	private ResourceRequestRetrieverImplTest andInvalidResponseWereRetrieved() throws Exception {
		invalidResponseRetrieved = new Response(400, "body", new Header());

		when(mockedHttpResponseRetriever.retrieveFor(isA(RequestAuthorization.class)))
			.thenReturn(invalidResponseRetrieved);

		return this;
	}

	private void whenRetrievingResource() throws Exception {
		resource = retriever.retrieve(Category.class, apiRequest);
	}

	private ResourceRequestRetrieverImplTest andResponseWasSerialized() {
		resourceRetrieved = new Category();

		when(mockedXmlSerializerWrapper.deserialize(eq(Category.class), anyString()))
			.thenReturn(resourceRetrieved);

		return this;
	}

	private ResourceRequestRetrieverImplTest andValidResponseWereRetrieved() throws Exception {
		validResponseRetrieved = new Response(200, "body", new Header());

		when(mockedHttpResponseRetriever.retrieveFor(isA(RequestAuthorization.class)))
			.thenReturn(validResponseRetrieved);

		return this;
	}

	private ResourceRequestRetrieverImplTest givenRequestAuthorizationWasBuilt() throws Exception {
		requestAuthorizationBuit = new RequestAuthorization();

		when(mockedRequestAuthorizationBuilder.build(isA(ApiRequest.class)))
			.thenReturn(requestAuthorizationBuit);

		return this;
	}
}


text:
static BOOL descriptionWasRun = false;

void testDescription(void) {
  descriptionWasRun = true;

  [OCDSpecOutputter withRedirectedOutput:^{
    describe(@"MyFakeTest",
            it(@"succeeds", ^{
            }),
            it(@"Fails", ^{
              FAIL(@"FAILURE IN TEST");
            }),
            nil
    );
  }];
}

void testContextWithTwoDescribes(void) {
  [OCDSpecOutputter withRedirectedOutput:^{
    describe(@"MyFakeTest",
            it(@"succeeds", ^{
            }),
            it(@"Fails", ^{
              FAIL(@"FAILURE IN TEST");
            }),
            nil
    );

    describe(@"Empty Description", nil);
  }];
}

@interface FakeDescription : OCDSpecDescription
{
  bool wasRun;
}

@property(assign) bool wasRun;
@end

@implementation FakeDescription
@synthesize wasRun;

-(void) describe
{
  wasRun = true;
}
@end

CONTEXT(OCDSpecDescriptionRunner){
  __block OCDSpecDescriptionRunner *runner;
  describe(@"OCDSpecDescriptionRunner",

          beforeEach(^{
            runner = [[OCDSpecDescriptionRunner alloc] init];
          }),

          it(@"runs the passed in C function", ^{
            [runner runContext:testDescription];

            expectTruth(descriptionWasRun);
          }),

          it(@"returns the results from runContext", ^{
            OCDSpecResults results = [runner runContext:testDescription];

            [expect([NSNumber numberWithInt:results.failures]) toBeEqualTo:[NSNumber numberWithInt:1]];
            [expect([NSNumber numberWithInt:results.successes]) toBeEqualTo:[NSNumber numberWithInt:1]];
          }),

          it(@"Runs an individual description", ^{
            FakeDescription *desc = [[FakeDescription alloc] init];
            desc.wasRun = false;

            [runner runDescription:desc];

            expectTruth(desc.wasRun);
          }),

          it(@"stores the results of a description on itself", ^{
            OCDSpecDescription *description = [[OCDSpecDescription alloc] init];
            description.failures = [NSNumber numberWithInt:8];
            description.successes = [NSNumber numberWithInt:6];

            [runner runDescription:description];

            [expect(runner.failures) toBeEqualTo:[NSNumber numberWithInt:8]];
            [expect(runner.successes) toBeEqualTo:[NSNumber numberWithInt:6]];
          }),

          it(@"Totals up the runDescriptions on multiple runs", ^{
            OCDSpecDescription *descriptionOne = [[OCDSpecDescription alloc] init];
            descriptionOne.failures = [NSNumber numberWithInt:8];
            descriptionOne.successes = [NSNumber numberWithInt:1];
            OCDSpecDescription *descriptionTwo = [[OCDSpecDescription alloc] init];
            descriptionTwo.successes = [NSNumber numberWithInt:8];

            [runner runDescription:descriptionOne];
            [runner runDescription:descriptionTwo];

            [expect(runner.failures) toBeEqualTo:[NSNumber numberWithInt:8]];
            [expect(runner.successes) toBeEqualTo:[NSNumber numberWithInt:9]];
          }),

          it(@"Does not overwrite counts when two describes are nested in a context", ^{
            OCDSpecResults results = [runner runContext:testContextWithTwoDescribes];

            [expect([NSNumber numberWithInt:results.failures]) toBeEqualTo:[NSNumber numberWithInt:1]];
            [expect([NSNumber numberWithInt:results.successes]) toBeEqualTo:[NSNumber numberWithInt:1]];
          }),
          nil
  );
}


text:
import {
  AsyncTestCompleter,
  describe,
  it,
  iit,
  ddescribe,
  expect,
  inject,
  beforeEach,
  SpyObject
} from 'angular2/test_lib';

import {Map, StringMap, StringMapWrapper} from 'angular2/src/facade/collection';

import {RouteRecognizer, RouteMatch} from 'angular2/src/router/route_recognizer';

export function main() {
  describe('RouteRecognizer', () => {
    var recognizer;
    var handler = {'component': DummyCmpA};
    var handler2 = {'component': DummyCmpB};

    beforeEach(() => { recognizer = new RouteRecognizer(); });

    it('should recognize a static segment', () => {
      recognizer.addConfig('/test', handler);
      var solution = recognizer.recognize('/test')[0];
      expect(getComponentType(solution)).toEqual(handler['component']);
    });

    it('should recognize a single slash', () => {
      recognizer.addConfig('/', handler);
      var solution = recognizer.recognize('/')[0];
      expect(getComponentType(solution)).toEqual(handler['component']);
    });

    it('should recognize a dynamic segment', () => {
      recognizer.addConfig('/user/:name', handler);
      var solution = recognizer.recognize('/user/brian')[0];
      expect(getComponentType(solution)).toEqual(handler['component']);
      expect(solution.params()).toEqual({'name': 'brian'});
    });

    it('should recognize a star segment', () => {
      recognizer.addConfig('/first/*rest', handler);
      var solution = recognizer.recognize('/first/second/third')[0];
      expect(getComponentType(solution)).toEqual(handler['component']);
      expect(solution.params()).toEqual({'rest': 'second/third'});
    });

    it('should throw when given two routes that start with the same static segment', () => {
      recognizer.addConfig('/hello', handler);
      expect(() => recognizer.addConfig('/hello', handler2))
          .toThrowError('Configuration \'/hello\' conflicts with existing route \'/hello\'');
    });

    it('should throw when given two routes that have dynamic segments in the same order', () => {
      recognizer.addConfig('/hello/:person/how/:doyoudou', handler);
      expect(() => recognizer.addConfig('/hello/:friend/how/:areyou', handler2))
          .toThrowError(
              'Configuration \'/hello/:friend/how/:areyou\' conflicts with existing route \'/hello/:person/how/:doyoudou\'');
    });

    it('should recognize redirects', () => {
      recognizer.addRedirect('/a', '/b');
      recognizer.addConfig('/b', handler);
      var solutions = recognizer.recognize('/a');
      expect(solutions.length).toBe(1);

      var solution = solutions[0];
      expect(getComponentType(solution)).toEqual(handler['component']);
      expect(solution.matchedUrl).toEqual('/b');
    });

    it('should not perform root URL redirect on a non-root route', () => {
      recognizer.addRedirect('/', '/foo');
      recognizer.addConfig('/bar', handler);
      var solutions = recognizer.recognize('/bar');
      expect(solutions.length).toBe(1);

      var solution = solutions[0];
      expect(getComponentType(solution)).toEqual(handler['component']);
      expect(solution.matchedUrl).toEqual('/bar');
    });

    it('should perform a root URL redirect when only a slash or an empty string is being processed',
       () => {
         recognizer.addRedirect('/', '/matias');
         recognizer.addConfig('/matias', handler);

         recognizer.addConfig('/fatias', handler);

         var solutions;

         solutions = recognizer.recognize('/');
         expect(solutions[0].matchedUrl).toBe('/matias');

         solutions = recognizer.recognize('/fatias');
         expect(solutions[0].matchedUrl).toBe('/fatias');

         solutions = recognizer.recognize('');
         expect(solutions[0].matchedUrl).toBe('/matias');
       });

    it('should generate URLs with params', () => {
      recognizer.addConfig('/app/user/:name', handler, 'user');
      expect(recognizer.generate('user', {'name': 'misko'})['url']).toEqual('app/user/misko');
    });

    it('should generate URLs with numeric params', () => {
      recognizer.addConfig('/app/page/:number', handler, 'page');
      expect(recognizer.generate('page', {'number': 42})['url']).toEqual('app/page/42');
    });

    it('should throw in the absence of required params URLs', () => {
      recognizer.addConfig('app/user/:name', handler, 'user');
      expect(() => recognizer.generate('user', {})['url'])
          .toThrowError('Route generator for \'name\' was not included in parameters passed.');
    });

    describe('matrix params', () => {
      it('should recognize matrix parameters within the URL path', () => {
        var recognizer = new RouteRecognizer();
        recognizer.addConfig('profile/:name', handler, 'user');

        var solution = recognizer.recognize('/profile/matsko;comments=all')[0];
        var params = solution.params();
        expect(params['name']).toEqual('matsko');
        expect(params['comments']).toEqual('all');
      });

      it('should recognize multiple matrix params and set parameters that contain no value to true',
         () => {
           var recognizer = new RouteRecognizer();
           recognizer.addConfig('/profile/hello', handler, 'user');

           var solution =
               recognizer.recognize('/profile/hello;modal;showAll=true;hideAll=false')[0];
           var params = solution.params();

           expect(params['modal']).toEqual(true);
           expect(params['showAll']).toEqual('true');
           expect(params['hideAll']).toEqual('false');
         });

      it('should only consider the matrix parameters at the end of the path handler', () => {
        var recognizer = new RouteRecognizer();
        recognizer.addConfig('/profile/hi/:name', handler, 'user');

        var solution = recognizer.recognize('/profile;a=1/hi;b=2;c=3/william;d=4')[0];
        var params = solution.params();

        expect(params).toEqual({'name': 'william', 'd': '4'});
      });

      it('should generate and populate the given static-based route with matrix params', () => {
        var recognizer = new RouteRecognizer();
        recognizer.addConfig('forum/featured', handler, 'forum-page');

        var params = StringMapWrapper.create();
        params['start'] = 10;
        params['end'] = 100;

        var result = recognizer.generate('forum-page', params);
        expect(result['url']).toEqual('forum/featured;start=10;end=100');
      });

      it('should generate and populate the given dynamic-based route with matrix params', () => {
        var recognizer = new RouteRecognizer();
        recognizer.addConfig('forum/:topic', handler, 'forum-page');

        var params = StringMapWrapper.create();
        params['topic'] = 'crazy';
        params['total-posts'] = 100;
        params['moreDetail'] = null;

        var result = recognizer.generate('forum-page', params);
        expect(result['url']).toEqual('forum/crazy;total-posts=100;moreDetail');
      });

      it('should not apply any matrix params if a dynamic route segment takes up the slot when a path is generated',
         () => {
           var recognizer = new RouteRecognizer();
           recognizer.addConfig('hello/:name', handler, 'profile-page');

           var params = StringMapWrapper.create();
           params['name'] = 'matsko';

           var result = recognizer.generate('profile-page', params);
           expect(result['url']).toEqual('hello/matsko');
         });
    });
  });
}

function getComponentType(routeMatch: RouteMatch): any {
  return routeMatch.recognizer.handler.componentType;
}

class DummyCmpA {}
class DummyCmpB {}


text:
 ALTER TABLE posts
ADD user_id INT NOT NULL;

ALTER TABLE comments
ADD user_id INT NOT NULL;

ALTER TABLE posts
ADD FOREIGN KEY (user_id) REFERENCES users(id);

ALTER TABLE comments
ADD FOREIGN KEY (user_id) REFERENCES users(id);


text:
require 'setup'
require 'fileutils'
require 'stringio'
require 'test/unit'

class DummyConfig
  def initialize(config)
    @config = config
  end

  def [](key)
    @config[key]
  end

  def no_harm?
    false
  end

  def verbose?
    false
  end
end

class TestInstaller #< Test::Unit::TestCase

  include FileUtils

  def setup
    rm_rf %w(srcdir objdir)
    mkdir %w(srcdir objdir)
    Dir.chdir 'objdir'
    $stderr, $orig_stderr = StringIO.new, $stderr
  end

  def teardown
    $stderr = $orig_stderr
    Dir.chdir '..'
    rm_rf %w(srcdir objdir)
  end

  def setup_installer(config = {})
    @installer = Installer.new(DummyConfig.new(config), '../srcdir', '.')
  end

  def do_update_shebang_line(id, str)
    create id, str
    @installer.update_shebang_line "../srcdir/#{id}"
    read(id)
  end

  def create(filename, content)
    File.open("../srcdir/#{filename}", 'wb') {|f|
      f.write content
    }
  end

  def read(filename)
    path = File.exist?(filename) ? filename : "../srcdir/#{filename}"
    File.open(path, 'rb') {|f|
      return f.read
    }
  end

  def test_update_shebang_line__never
    setup_installer 'shebang' => 'never', 'rubypath' => 'ERROR'
    assert_equal "#!/usr/local/bin/ruby\nprogram",
        do_update_shebang_line('ruby', "#!/usr/local/bin/ruby\nprogram")
    assert_equal "#! /usr/local/bin/ruby\nprogram",
        do_update_shebang_line('ruby-sp', "#! /usr/local/bin/ruby\nprogram")
    assert_equal "#!/usr/local/bin/ruby -Ke\nprogram",
        do_update_shebang_line('ruby-arg', "#!/usr/local/bin/ruby -Ke\nprogram")
    assert_equal "#!/usr/bin/ruby -n -p\nprogram",
        do_update_shebang_line('ruby-args', "#!/usr/bin/ruby -n -p\nprogram")
    assert_equal "#!/usr/bin/env ruby\nprogram",
        do_update_shebang_line('env-ruby', "#!/usr/bin/env ruby\nprogram")
    assert_equal "#!/usr/bin/env perl\nprogram",
        do_update_shebang_line('env-noruby', "#!/usr/bin/env perl\nprogram")
    assert_equal "#!/bin/sh\nprogram",
        do_update_shebang_line('interp', "#!/bin/sh\nprogram")
    assert_equal "#!/bin/sh -l -r -\nprogram",
        do_update_shebang_line('interp-args', "#!/bin/sh -l -r -\nprogram")
    assert_equal "program",
        do_update_shebang_line('bare', "program")
    assert_equal "\001\002\003\n\004\005\006",
        do_update_shebang_line('binary', "\001\002\003\n\004\005\006")
  end

  def test_update_shebang_line__all
    setup_installer 'shebang' => 'all', 'rubypath' => 'RUBYPATH'
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('ruby', "#!/usr/local/bin/ruby\nprogram")
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('ruby-sp', "#! /usr/local/bin/ruby\nprogram")
    assert_equal "#! RUBYPATH -Ke\nprogram",
        do_update_shebang_line('ruby-arg', "#!/usr/local/bin/ruby -Ke\nprogram")
    assert_equal "#! RUBYPATH -n -p\nprogram",
        do_update_shebang_line('ruby-args', "#!/usr/bin/ruby -n -p\nprogram")
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('env-ruby', "#!/usr/bin/env ruby\nprogram")
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('env-noruby', "#!/usr/bin/env perl\nprogram")
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('interp', "#!/bin/sh\nprogram")
    assert_equal "#! RUBYPATH\nprogram",   # args removed
        do_update_shebang_line('interp-args', "#!/bin/sh -l -r -\nprogram")
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('bare', "program")
    assert_equal "#! RUBYPATH\n\001\002\003\n\004\005\006",
        do_update_shebang_line('binary', "\001\002\003\n\004\005\006")
  end

  def test_update_shebang_line__ruby
    setup_installer 'shebang' => 'ruby', 'rubypath' => 'RUBYPATH'
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('ruby', "#!/usr/local/bin/ruby\nprogram")
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('ruby-sp', "#! /usr/local/bin/ruby\nprogram")
    assert_equal "#! RUBYPATH -Ke\nprogram",
        do_update_shebang_line('ruby-arg', "#!/usr/local/bin/ruby -Ke\nprogram")
    assert_equal "#! RUBYPATH -n -p\nprogram",
        do_update_shebang_line('ruby-args', "#!/usr/bin/ruby -n -p\nprogram")
    assert_equal "#! RUBYPATH\nprogram",
        do_update_shebang_line('env-ruby', "#!/usr/bin/env ruby\nprogram")
    assert_equal "#!/usr/bin/env perl\nprogram",
        do_update_shebang_line('env-noruby', "#!/usr/bin/env perl\nprogram")
    assert_equal "#!/bin/sh\nprogram",
        do_update_shebang_line('interp', "#!/bin/sh\nprogram")
    assert_equal "#!/bin/sh -l -r -\nprogram",
        do_update_shebang_line('interp-args', "#!/bin/sh -l -r -\nprogram")
    assert_equal "program",
        do_update_shebang_line('bare', "program")
    assert_equal "\001\002\003\n\004\005\006",
        do_update_shebang_line('binary', "\001\002\003\n\004\005\006")
  end

end


text:
require "benchmark"

$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "public_suffix"


text:
/* @flow weak */
import detect from 'detect-port'
import Hapi from 'hapi'
import opn from 'opn'
import rl from 'readline'

const rlInterface = rl.createInterface({
  input: process.stdin,
  output: process.stdout,
})

const debug = require('debug')('gatsby:application')

function startServer (program, launchPort) {
  const directory = program.directory
  const serverPort = launchPort || program.port

  debug('Serving /public')
  const server = new Hapi.Server()

  server.connection({
    host: program.host,
    port: serverPort,
  })

  server.route({
    method: 'GET',
    path: '/{path*}',
    handler: {
      directory: {
        path: `${directory}/public`,
        listing: false,
        index: true,
      },
    },
  })

  server.start((e) => {
    if (e) {
      if (e.code === 'EADDRINUSE') {
        // eslint-disable-next-line max-len
        console.log(`Unable to start Gatsby on port ${serverPort} as there's already a process listing on that port.`)
      } else {
        console.log(e)
      }

      process.exit()
    } else {
      if (program.open) {
        opn(server.info.uri)
      }
      console.log('Listening at:', server.info.uri)
    }
  })
}

module.exports = (program) => {
  detect(program.port, (err, _port) => {
    if (err) {
      console.error(err)
      process.exit()
    }

    if (program.port !== _port) {
      // eslint-disable-next-line max-len
      const question = `Something is already running at port ${program.port} \nWould you like to run the app at another port instead? [Y/n] `

      return rlInterface.question(question, (answer) => {
        let launchPort = program.port
        if (answer.length === 0 || answer.match(/^yes|y$/i)) {
          launchPort = _port
        }

        return startServer(program, launchPort)
      })
    }

    return startServer(program)
  })
}


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.aurora.scheduler.app.local.simulator.events;

/**
 * Event indicating that the driver has started.
 */
public class Started {
}


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_TEST_H_INCLUDED
#define CONF_TEST_H_INCLUDED

/** USART Interface  : Console UART */
#define CONF_TEST_USART       COM_PORT_USART
/** Baudrate setting : 115200bps */
#define CONF_TEST_BAUDRATE    (115200UL)
/** Char setting     : 8-bit character length (don't care for UART) */
#define CONF_TEST_CHARLENGTH  US_MR_CHRL_8_BIT
/** Parity setting   : No parity check */
#define CONF_TEST_PARITY      US_MR_PAR_NO
/** Stopbit setting  : No extra stopbit, i.e., use 1 (don't care for UART) */
#define CONF_TEST_STOPBITS    US_MR_NBSTOP_1_BIT

#endif /* CONF_TEST_H_INCLUDED */


text:
<?php
/**
 * Created by PhpStorm.
 * User: buuug7
 * Date: 2015/12/23
 * Time: 14:36
 * Desc:
 */

namespace frontend\controllers\user;

use common\models\Message;
use common\models\UserHistory;
use common\util\DzHelper;
use Yii;
use yii\data\ActiveDataProvider;
use yii\data\SqlDataProvider;
use yii\filters\AccessControl;

class ProfileController extends \dektrium\user\controllers\ProfileController
{

	public function behaviors()
	{
		return [
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					['allow' => true, 'actions' => ['index', 'user-history', 'credits', 'user-message','delete-user-message-by-user-id'], 'roles' => ['@']],
					['allow' => true, 'actions' => ['show'], 'roles' => ['?', '@']],
				],
			],
		];
	}

	/**
	 * Redirects to current user's profile.
	 *
	 * @return \yii\web\Response
	 */
	public function actionIndex()
	{
		return $this->redirect(['show', 'id' => Yii::$app->user->getId()]);
	}

	public function actionUserHistory()
	{
		$user = Yii::$app->user->identity;
		$query = UserHistory::find()->where(['status' => UserHistory::STATUS_IN_USE, 'user_id' => $user->getId()])->orderBy('created_at DESC');
		$dataProvider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' => 10
			]
		]);

		return $this->render('user-history', [
			'dataProvider' => $dataProvider,
		]);
	}

	public function actionCredits()
	{

		return $this->render('credits', [
			'dzUser' => (new DzHelper())->getDzUserByUsername(Yii::$app->user->identity->username)]);
	}

	/**
	 * 用户消息控制器
	 * @return string
	 */
	public function actionUserMessage()
	{
		$user = Yii::$app->user->identity;

		$query = Message::find()->where("NOT FIND_IN_SET({$user->getId()},`deleted`)");
		$query=$query->andFilterWhere(['status' => Message::STATUS_ACTIVE])->orderBy('created_at DESC');
		$dataProvider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' =>10
			]
		]);
		return $this->render('user-message', [
			'dataProvider' => $dataProvider,
		]);
	}

	/**
	 * ajax 删除用户的消息
	 * @return string
	 */
	public function actionDeleteUserMessageByUserId(){
		$post=Yii::$app->request->post();
		$user=Yii::$app->user->identity;
		$data=[];

		if($post['messageId']){
			if(Message::deleteMessageByUserId($post['messageId'],$user->getId())){
				$data['msg']='成功删除一条消息!';
			}else{
				$data['msg']='删除失败,请稍后再试!';
			}
		}else{
			$data['msg']='系统异常!';
		}
		return json_encode($data);
	}

}


text:
package com.github.stone.leaf.server.service;

import java.util.List;

import com.github.stone.leaf.server.entity.LeafSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * leaf current service factory
 *
 * @author stone
 */
@Service
public class LeafCurrentServiceFactory {

    @Autowired
    List<LeafCurrentService> currentServices;

    public LeafCurrentService getCurrentService(LeafSettings settings) {
        for (LeafCurrentService currentService : currentServices) {
            if (currentService.support(settings)) {
                return currentService;
            }
        }
        throw new IllegalArgumentException("not support leaf");
    }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>NM3</title>


text:
//https://github.com/inexorabletash/polyfill/blob/master/web.js
  if (!document.querySelectorAll) {
    document.querySelectorAll = function (selectors) {
      var style = document.createElement('style'), elements = [], element;
      document.documentElement.firstChild.appendChild(style);
      document._qsa = [];

      style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
      window.scrollBy(0, 0);
      style.parentNode.removeChild(style);

      while (document._qsa.length) {
        element = document._qsa.shift();
        element.style.removeAttribute('x-qsa');
        elements.push(element);
      }
      document._qsa = null;
      return elements;
    };
  }

  if (!document.querySelector) {
    document.querySelector = function (selectors) {
      var elements = document.querySelectorAll(selectors);
      return (elements.length) ? elements[0] : null;
    };
  }

  if (!document.getElementsByClassName) {
    document.getElementsByClassName = function (classNames) {
      classNames = String(classNames).replace(/^|\s+/g, '.');
      return document.querySelectorAll(classNames);
    };
  }

//https://github.com/inexorabletash/polyfill
// ES5 15.2.3.14 Object.keys ( O )
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
  Object.keys = function (o) {
    if (o !== Object(o)) { throw TypeError('Object.keys called on non-object'); }
    var ret = [], p;
    for (p in o) {
      if (Object.prototype.hasOwnProperty.call(o, p)) {
        ret.push(p);
      }
    }
    return ret;
  };
}

//https://github.com/inexorabletash/polyfill/blob/master/web.js
(function (global) {
  var B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  global.atob = global.atob || function (input) {
    input = String(input);
    var position = 0,
        output = [],
        buffer = 0, bits = 0, n;

    input = input.replace(/\s/g, '');
    if ((input.length % 4) === 0) { input = input.replace(/=+$/, ''); }
    if ((input.length % 4) === 1) { throw Error('InvalidCharacterError'); }
    if (/[^+/0-9A-Za-z]/.test(input)) { throw Error('InvalidCharacterError'); }

    while (position < input.length) {
      n = B64_ALPHABET.indexOf(input.charAt(position));
      buffer = (buffer << 6) | n;
      bits += 6;

      if (bits === 24) {
        output.push(String.fromCharCode((buffer >> 16) & 0xFF));
        output.push(String.fromCharCode((buffer >>  8) & 0xFF));
        output.push(String.fromCharCode(buffer & 0xFF));
        bits = 0;
        buffer = 0;
      }
      position += 1;
    }

    if (bits === 12) {
      buffer = buffer >> 4;
      output.push(String.fromCharCode(buffer & 0xFF));
    } else if (bits === 18) {
      buffer = buffer >> 2;
      output.push(String.fromCharCode((buffer >> 8) & 0xFF));
      output.push(String.fromCharCode(buffer & 0xFF));
    }

    return output.join('');
  };

  global.btoa = global.btoa || function (input) {
    input = String(input);
    var position = 0,
        out = [],
        o1, o2, o3,
        e1, e2, e3, e4;

    if (/[^\x00-\xFF]/.test(input)) { throw Error('InvalidCharacterError'); }

    while (position < input.length) {
      o1 = input.charCodeAt(position++);
      o2 = input.charCodeAt(position++);
      o3 = input.charCodeAt(position++);

      // 111111 112222 222233 333333
      e1 = o1 >> 2;
      e2 = ((o1 & 0x3) << 4) | (o2 >> 4);
      e3 = ((o2 & 0xf) << 2) | (o3 >> 6);
      e4 = o3 & 0x3f;

      if (position === input.length + 2) {
        e3 = 64; e4 = 64;
      }
      else if (position === input.length + 1) {
        e4 = 64;
      }

      out.push(B64_ALPHABET.charAt(e1),
               B64_ALPHABET.charAt(e2),
               B64_ALPHABET.charAt(e3),
               B64_ALPHABET.charAt(e4));
    }

    return out.join('');
  };
}(this));

//https://gist.github.com/jimeh/332357
if (!Object.prototype.hasOwnProperty){
    /*jshint -W001, -W103 */
    Object.prototype.hasOwnProperty = function(prop) {
		var proto = this.__proto__ || this.constructor.prototype;
		return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
	};
    /*jshint +W001, +W103 */
}

//requestAnimationFrame polyfill for older Firefox/Chrome versions
if (!window.requestAnimationFrame) {
  if (window.webkitRequestAnimationFrame) {
	//https://github.com/Financial-Times/polyfill-service/blob/master/polyfills/requestAnimationFrame/polyfill-webkit.js
	(function (global) {
	  // window.requestAnimationFrame
	  global.requestAnimationFrame = function (callback) {
		  return webkitRequestAnimationFrame(function () {
			  callback(global.performance.now());
		  });
	  };

	  // window.cancelAnimationFrame
	  global.cancelAnimationFrame = webkitCancelAnimationFrame;
	}(this));
  } else if (window.mozRequestAnimationFrame) {
	  //https://github.com/Financial-Times/polyfill-service/blob/master/polyfills/requestAnimationFrame/polyfill-moz.js
	(function (global) {
	  // window.requestAnimationFrame
	  global.requestAnimationFrame = function (callback) {
		  return mozRequestAnimationFrame(function () {
			  callback(global.performance.now());
		  });
	  };

	  // window.cancelAnimationFrame
	  global.cancelAnimationFrame = mozCancelAnimationFrame;
	}(this));
  } else {
	(function (global) {
	  global.requestAnimationFrame = function (callback) {
		return global.setTimeout(callback, 1000 / 60);
	  };

	  global.cancelAnimationFrame = global.clearTimeout;
	})(this);
  }
}


text:
describe("stepLibSearchService", function() {
	let stepLibSearchService, mockStepLibSearchInstance;

	beforeEach(module("BitriseWorkflowEditor"));
	beforeEach(inject(function(_stepLibSearchService_) {
		stepLibSearchService = _stepLibSearchService_;
	}));
	beforeEach(inject(function(_stepLibSearchInstance_) {
		mockStepLibSearchInstance = _stepLibSearchInstance_;
	}));

	describe("list", () => {
		beforeEach(() => {
			spyOn(mockStepLibSearchInstance, "list").and.returnValue(Promise.resolve([]));
		});

		it("works with a given step list", () => {
			stepLibSearchService.list({ stepCVSs: ["a-step-cvs@1.0.0"], includeInputs: true });

			expect(mockStepLibSearchInstance.list).toHaveBeenCalledWith(
				jasmine.objectContaining({
					stepIds: ["a-step-cvs@1.0.0"],
					includeInputs: true,
					algoliaOptions: {
						attributesToRetrieve: ["*"]
					}
				})
			);
		});

		it("works with custom attributes", () => {
			stepLibSearchService.list({
				stepCVSs: ["a-step-cvs@1.0.0"],
				includeInputs: false,
				attributesToRetrieve: ["abc", "def"]
			});

			expect(mockStepLibSearchInstance.list).toHaveBeenCalledWith(
				jasmine.objectContaining({
					stepIds: ["a-step-cvs@1.0.0"],
					includeInputs: false,
					algoliaOptions: {
						attributesToRetrieve: ["abc", "def"]
					}
				})
			);
		});

		it("loads latest steps only", () => {
			stepLibSearchService.list({
				latestOnly: true
			});

			expect(mockStepLibSearchInstance.list).toHaveBeenCalledWith(
				jasmine.objectContaining({
					latestOnly: true
				})
			);
		});

		it("fetches selected project types", () => {
			stepLibSearchService.list({
				projectTypes: ["symbian", "bada", "blackberry"]
			});

			expect(mockStepLibSearchInstance.list).toHaveBeenCalledWith(
				jasmine.objectContaining({ projectTypes: ["symbian", "bada", "blackberry"] })
			);
		});
	});

	describe("getStepVersions", () => {
		beforeEach(() => {
			spyOn(mockStepLibSearchInstance, "list").and.returnValue(Promise.resolve([]));
		});

		it("works with a step id", () => {
			stepLibSearchService.getStepVersions("some-step");

			expect(mockStepLibSearchInstance.list).toHaveBeenCalledWith({
				query: "some-step",
				includeInputs: true,
				algoliaOptions: {
					attributesToRetrieve: ["*"]
				}
			});
		});

		it("works with custom attributes", () => {
			stepLibSearchService.getStepVersions("some-step", ["aaa", "bbb"]);

			expect(mockStepLibSearchInstance.list).toHaveBeenCalledWith({
				query: "some-step",
				includeInputs: true,
				algoliaOptions: {
					attributesToRetrieve: ["aaa", "bbb"]
				}
			});
		});
	});

	describe("fuzzySearch", () => {
		beforeEach(() => {
			spyOn(mockStepLibSearchInstance, "list").and.returnValue(Promise.resolve([]));
		});

		it("fetches step with the correct config", () => {
			stepLibSearchService.fuzzySearch({ query: "Anbroib", latestOnly: true });

			expect(mockStepLibSearchInstance.list).toHaveBeenCalledWith(
				jasmine.objectContaining({
					query: "Anbroib",
					latestOnly: true,
					algoliaOptions: {
						attributesToRetrieve: ["*"],
						restrictSearchableAttributes: ["step.title"],
						typoTolerance: true
					}
				})
			);
		});
	});

	describe("convertSteps", () => {
		it("converts an array of steps to an object", async () => {
			spyOn(mockStepLibSearchInstance, "list").and.returnValue(
				Promise.resolve([
					{
						id: "some-step",
						version: "1.0.0",
						info: { a: "b" }
					},
					{
						id: "some-step",
						version: "1.1.0",
						info: { c: "d" }
					},
					{
						id: "some-other-step",
						version: "2.1.0",
						info: { e: "f" }
					}
				])
			);

			const converted = await stepLibSearchService.list({
				stepCVSs: ["does"],
				includeInputs: false,
				attributesToRetrieve: ["matter"]
			});

			expect(converted).toEqual({
				"some-step": {
					info: {
						a: "b",
						c: "d"
					},
					versions: {
						"1.0.0": {
							id: "some-step",
							version: "1.0.0",
							info: {
								a: "b"
							},
							a: "b"
						},
						"1.1.0": {
							id: "some-step",
							version: "1.1.0",
							info: {
								c: "d"
							},
							c: "d"
						}
					}
				},
				"some-other-step": {
					info: {
						e: "f"
					},
					versions: {
						"2.1.0": {
							id: "some-other-step",
							version: "2.1.0",
							info: {
								e: "f"
							},
							e: "f"
						}
					}
				}
			});
		});
	});
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TwitterRuRu;
using TwitterRuRu.Controllers;

namespace TwitterRuRu.Tests.Controllers
{
    [TestClass]
    public class HomeControllerTest
    {
        [TestMethod]
        public void Index()
        {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.Index() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }

        [TestMethod]
        public void About()
        {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.About() as ViewResult;

            // Assert
            Assert.AreEqual("Your application description page.", result.ViewBag.Message);
        }

        [TestMethod]
        public void Contact()
        {
            // Arrange
            HomeController controller = new HomeController();

            // Act
            ViewResult result = controller.Contact() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }
    }
}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class DialogueActivateBehaviour : MonoBehaviour
{
    [SerializeField] private GameObject dialogueControllerObject;
    [SerializeField] private string dialogueId = "";
    [SerializeField] private bool activateOnce = true;
    [SerializeField] private bool freezeOnTrigger = false;

    private DialogueController controller;

    private bool activated = false;

    // Use this for initialization
    void Start()
    {
        if (dialogueControllerObject == null)
            dialogueControllerObject = GameObject.Find("DialogueController");
        controller = dialogueControllerObject.GetComponent<DialogueController>();
    }

    void Update()
    {

    }

    void OnTriggerEnter2D(Collider2D collider)
    {
        if (!isActiveAndEnabled) return;
        if ((activated && activateOnce) || !collider.gameObject.tag.Equals("Player")) return;

        controller.showDialogue(dialogueId, freezeOnTrigger);
        activated = true;
    }

}


text:
Extremely basic environment variable parser.

Prints parsed file to STDOUT.

If error, exits with non-zero code and no output.

##Usage:

    envparse ./some_file_name


text:
using System;
using System.Linq;
using System.Threading.Tasks.Dataflow;
using Gridsum.DataflowEx.Databases;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Gridsum.DataflowEx.Test.DatabaseTests
{
    using System.Runtime.InteropServices;
    using System.Text;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Storage;
    using System.Threading;

    [TestClass]
    public class BulkInserterTest
    {
        [TestMethod]
        public void TestDbBulkInserter()
        {
            //init db
            var connectString = TestUtils.GetLocalDBConnectionString();
            var context = new InsertContext(connectString);
            context.Inits.Add(new Init2());
            context.SaveChanges();

            var inserter = new DbBulkInserter<Entity2>(
                connectString,
                "dbo.Seods",
                DataflowOptions.Default,
                GSProduct.SEOD);

            var entities = new Entity2[]
                               {
                                   new Entity2(1) { Key = "a", Value = 0.5f },
                                   new Entity2(2) { Key = "b", MyLeg = new Leg() { LegInt = 5, LegString = "bleg" } },
                                   new Entity2(3) { Value = 0.7f },
                               };

            inserter.ProcessAsync(entities, true).Wait();

            //test result
            Assert.AreEqual(3, context.Seods.Count());
            Assert.AreEqual("b", context.Seods.Find(2).Name);
            Assert.AreEqual("b", context.Seods.Find(2).Name2);
            Assert.AreEqual(5, context.Seods.Find(2).LegInt);
            Assert.AreEqual("bleg", context.Seods.Find(2).LegString);
            Assert.AreEqual(-2f, context.Seods.First(s => s.Id == 2).Price);
            Assert.AreEqual("default", context.Seods.First(s => s.Id == 3).Name);
            Assert.AreEqual(0.7f, context.Seods.First(s => s.Id == 3).Price);
            Assert.AreEqual(2, context.Seods.Find(3).LegInt);
            Assert.AreEqual("LegString", context.Seods.Find(3).LegString);

        }

        [TestMethod]
        public void TestDbBulkInserter_NoNullCheck()
        {
            //init db
            var connectString = TestUtils.GetLocalDBConnectionString();
            var context = new InsertContext(connectString);
            context.Inits.Add(new Init2());
            context.SaveChanges();

            var inserter = new DbBulkInserter<Entity3>(
                connectString,
                "dbo.Seods",
                DataflowOptions.Default,
                GSProduct.SEOD);

            var guid = Guid.NewGuid();
            var entities = new Entity3[]
                               {
                                   new Entity3(1) { Key = "a", Value = 0.5f, MyLeg = new Leg() {}},
                                   new Entity3(2) { Key = "b", MyLeg = new Leg() { LegInt = 5, LegString = "bleg" } }
                               };

            var entities2 = new[]
                                {
                                    new Entity3(3)
                                        {
                                            Value = 0.7f,
                                            MyLeg = new Leg(),
                                            UID = guid,
                                            RawData = Encoding.ASCII.GetBytes("abc")
                                        }
                                };

            inserter.ProcessMultipleAsync(true, entities, entities2).Wait();

            //test result
            Assert.AreEqual(3, context.Seods.Count());
            Assert.AreEqual("b", context.Seods.Find(2).Name);
            Assert.AreEqual("b", context.Seods.Find(2).Name2);
            Assert.AreEqual(5, context.Seods.Find(2).LegInt);
            Assert.AreEqual("bleg", context.Seods.Find(2).LegString);
            Assert.AreEqual("LegString2", context.Seods.Find(2).LegString2);
            Assert.AreEqual(-2f, context.Seods.First(s => s.Id == 2).Price);
            Assert.AreEqual("default", context.Seods.First(s => s.Id == 3).Name);
            Assert.AreEqual(0.7f, context.Seods.First(s => s.Id == 3).Price);
            Assert.AreEqual(2, context.Seods.Find(3).LegInt);
            Assert.AreEqual("LegString", context.Seods.Find(3).LegString);
            Assert.AreEqual("LegString2", context.Seods.Find(3).LegString2);
            Assert.AreEqual(guid, context.Seods.Find(3).Uid);
            Assert.AreEqual("abc", Encoding.ASCII.GetString(context.Seods.Find(3).RawData));
        }

        [TestMethod]
        public void TestMultiDbBulkInserter()
        {
            var connectString = TestUtils.GetLocalDBConnectionString("TestMultiDbBulkInserter_{0}");
            //init db
            int profileIdCount = 3;
            InsertContext[] contexts = new InsertContext[profileIdCount + 1];
            for (int i = 1; i <= profileIdCount; ++i)
            {
                var init = new Init2();
                contexts[i] = new InsertContext(string.Format(connectString, i, i));
                contexts[i].Inits.Add(init);
                contexts[i].SaveChanges();
            }

            var profileDispatch = new Func<Entity2, int>(e => e.ProfileId);
            var connectionGetter = new Func<int, string>(id => string.Format(connectString, id, id));

            var multiDbBulkInserter = new MultiDbBulkInserter<Entity2>(DataflowOptions.Default, profileDispatch,
                connectionGetter, "dbo.Seods", GSProduct.SEOD);

            var entities = new[]
            {
                new Entity2(1, 1f, "a"),
                new Entity2(2, 2f, "b"),
                new Entity2(2, 2f, "c"),
                new Entity2(3, 3f, "d"),
                new Entity2(3, 3f, "e"),
                new Entity2(3, 3f, "f")
            };

            multiDbBulkInserter.ProcessAsync(entities).Wait();

            //assert result
            for (int i = 1; i <= profileIdCount; ++i)
            {
                Assert.AreEqual(i,  contexts[i].Seods.Count());
                Assert.AreEqual(i,  contexts[i].Seods.FirstOrDefault().Price);
                Assert.IsTrue(      contexts[i].Seods.FirstOrDefault().Name.Length == 1);
                Assert.IsTrue(      contexts[i].Seods.FirstOrDefault().Name2.Length == 1);
            }
        }
    }

    public class Entity2
    {
        public Entity2() { }

        public Entity2(int id)
        {
            this.ProfileId = id;
        }

        public Entity2(int id, float value, string key)
        {
            this.ProfileId = id;
            this.Value = value;
            this.Key = key;
        }

        public int ProfileId { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "Price", -2.0f)]
        public float? Value { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "Name", "default")]
        [DBColumnMapping(GSProduct.SEOD, "Name2", "default")]
        public string Key { get; set; }

        public Leg MyLeg { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "Uid")]
        public Guid UID { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "A Bad Column", null, ColumnMappingOption.Optional)]
        public string BadColumn { get; set; }
    }

    public class Entity3
    {
        public Entity3() { }

        public Entity3(int id)
        {
            this.ProfileId = id;
        }

        public Entity3(int id, float value, string key)
        {
            this.ProfileId = id;
            this.Value = value;
            this.Key = key;
        }

        public int ProfileId { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "Price", -2.0f)]
        public float? Value { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "Name", "default")]
        [DBColumnMapping(GSProduct.SEOD, "Name2", "default")]
        public string Key { get; set; }

        [DBColumnPath(DBColumnPathOptions.DoNotGenerateNullCheck)]
        public Leg MyLeg { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "Uid")]
        public Guid UID { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "Uid")]
        public Guid UID2 { get; set; }

        [DBColumnMapping(GSProduct.SEOD)]
        public byte[] RawData { get; set; }
    }

    public class Leg
    {
        [DBColumnMapping(GSProduct.SEOD, "LegInt", 2)]
        public int? LegInt { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "LegString", "LegString")]
        public string LegString { get; set; }

        [DBColumnMapping(GSProduct.SEOD, "LegString2", "LegString2")]
        public string LegString2 { get; set; }
    }

    #region test entity and dbcontext

    public class Init2
    {
        public int Id { get; set; }
    }

    public class Seod
    {
        public int Id { get; set; }

        public string Name { get; set; }
        public string Name2 { get; set; }

        public float Price { get; set; }

        public string LegString { get; set; }
        public string LegString2 { get; set; }
        public int LegInt { get; set; }

        public Guid Uid { get; set; }

        public byte[] RawData { get; set; }
    }

    public class InsertContext : DbContextBase<InsertContext>
    {
        public InsertContext(string conn)
            : base(conn)
        {
        }

        public DbSet<Init2> Inits { get; set; }
        public DbSet<Seod> Seods { get; set; }

    }
    #endregion
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="org.sakaiproject.conditions.api.ConditionService" class="org.sakaiproject.conditions.impl.BaseConditionService"
		init-method="init" singleton="true">
	</bean>
</beans>


text:
using Microsoft.EntityFrameworkCore.TestUtilities;
using System;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.EntityFrameworkCore.Query
{
    public class CompiledQuerySqlCeTest : CompiledQueryTestBase<NorthwindQuerySqlCeFixture<NoopModelCustomizer>>
    {
        public CompiledQuerySqlCeTest(NorthwindQuerySqlCeFixture<NoopModelCustomizer> fixture, ITestOutputHelper testOutputHelper)
            : base(fixture)
        {
            fixture.TestSqlLoggerFactory.Clear();
        }

        public override void DbSet_query()
        {
            base.DbSet_query();

            Assert.Equal(
                @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]",
                Sql);
        }

        public override void DbSet_query_first()
        {
            base.DbSet_query_first();

            Assert.Equal(
                @"SELECT TOP(1) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
ORDER BY [c].[CustomerID]",
                Sql);
        }

        public override void Untyped_context()
        {
            base.Untyped_context();

            Assert.Equal(
                @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]",
                Sql);
        }

        public override void Query_with_single_parameter()
        {
            base.Query_with_single_parameter();

            Assert.Equal(
                @"@__customerID='ALFKI' (Size = 5)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID

@__customerID='ANATR' (Size = 5)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID",
                Sql);
        }

        public override void First_query_with_single_parameter()
        {
            base.First_query_with_single_parameter();

            Assert.Equal(
                @"@__customerID='ALFKI' (Size = 5)

SELECT TOP(1) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID

@__customerID='ANATR' (Size = 5)

SELECT TOP(1) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID",
                Sql);
        }

        public override void Query_with_two_parameters()
        {
            base.Query_with_two_parameters();

            Assert.Equal(
                @"@__customerID='ALFKI' (Size = 5)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID

@__customerID='ANATR' (Size = 5)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID",
                Sql);
        }

        public override void Query_with_three_parameters()
        {
            base.Query_with_three_parameters();

            Assert.Equal(
                @"@__customerID='ALFKI' (Size = 5)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID

@__customerID='ANATR' (Size = 5)

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = @__customerID",
                Sql);
        }

        public override void Query_with_array_parameter()
        {
            base.Query_with_array_parameter();

            Assert.Equal(
                @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]",
                Sql);
        }

        public override void Query_with_contains()
        {
            base.Query_with_contains();

            Assert.Equal(
                @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] IN (N'ALFKI')

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] IN (N'ANATR')",
                Sql);
        }

        public override void Query_with_closure()
        {
            base.Query_with_closure();

            Assert.Equal(
                @"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = N'ALFKI'

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[CustomerID] = N'ALFKI'",
                Sql);
        }

        private const string FileLineEnding = @"
";

        private string Sql => Fixture.TestSqlLoggerFactory.Sql.Replace(Environment.NewLine, FileLineEnding);
    }
}


text:
#ifndef RUY_RUY_DENORMAL_H_
#define RUY_RUY_DENORMAL_H_

#include <cstdint>

namespace ruy {
// NOTE: the following 'fpu_state' struct is copied from
// pthreadpool/src/threadpool-utils.h that's not exposed by the pthreadpool
// library (https://github.com/Maratyszcza/pthreadpool).
struct fpu_state {
#if defined(__SSE__) || defined(__x86_64__) || defined(_M_X64) || \
    (defined(_M_IX86_FP) && _M_IX86_FP >= 1)
  std::uint32_t mxcsr;
#elif defined(__GNUC__) && defined(__arm__) && defined(__ARM_FP) && \
        (__ARM_FP != 0) ||                                          \
    defined(_MSC_VER) && defined(_M_ARM)
  std::uint32_t fpscr;
#elif defined(__GNUC__) && defined(__aarch64__) || \
    defined(_MSC_VER) && defined(_M_ARM64)
  std::uint64_t fpcr;
#endif
};

// While this class is active, denormal floating point numbers are suppressed.
// The destructor restores the original flags.
class ScopedSuppressDenormals {
 public:
  ScopedSuppressDenormals();
  ~ScopedSuppressDenormals();

 private:
  fpu_state restore_;

  ScopedSuppressDenormals(const ScopedSuppressDenormals&) = delete;
  void operator=(const ScopedSuppressDenormals&) = delete;
};
}  // namespace ruy

#endif  // RUY_RUY_DENORMAL_H_