text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using Hapil.Expressions;
using Hapil.Members;
using Hapil.Operands;
using Hapil.Statements;
using TT = Hapil.TypeTemplate;

namespace Hapil.Writers
{
	public abstract class MethodWriterBase : MemberWriterBase
	{
		private readonly ClassType m_OwnerClass;
		private readonly MethodMember m_OwnerMethod;
		private MethodWriterModes m_Mode;
		private AttributeWriter m_ReturnAttributeWriter;
		private IMutableOperand m_ReturnValueLocal;
		private LabelStatement m_LeaveLabel;
		private MethodWriterBase[] m_InnerWriters;

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

		protected MethodWriterBase(MethodMember ownerMethod)
			: this(ownerMethod, MethodWriterModes.Normal, attachToOwner: true)
		{
		}

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

		protected MethodWriterBase(ClassType ownerClass)
			: this(null, MethodWriterModes.Normal, attachToOwner: true)
		{
			m_OwnerClass = ownerClass;
		}

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

		protected MethodWriterBase(MethodMember ownerMethod, MethodWriterModes mode, bool attachToOwner)
		{
			m_OwnerMethod = ownerMethod;
			m_Mode = mode;
			m_ReturnValueLocal = null;
			m_InnerWriters = null;

			if ( ownerMethod != null )
			{
				m_OwnerClass = ownerMethod.OwnerClass;

				if ( attachToOwner )
				{
					ownerMethod.AddWriter(this);
				}
			}
		}

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

		public void Attribute<TAttribute>(Action<AttributeArgumentWriter<TAttribute>> values = null)
			where TAttribute : Attribute
		{
			ValidateNotAnonymousMethod();

			var builder = new AttributeArgumentWriter<TAttribute>(values);
			m_OwnerMethod.MethodFactory.SetAttribute(builder.GetAttributeBuilder());
		}

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

		public Operand<T> Default<T>()
		{
			var actualType = TypeTemplate.Resolve<T>();

			if ( actualType.IsPrimitive || !actualType.IsValueType )
			{
				var constant = Helpers.CreateConstant(actualType, actualType.GetDefaultValue());
				return constant.CastTo<T>();
			}
			else
			{
				return new NewStructExpression<T>();
			}
		}

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

		public Operand<T> Const<T>(T constantValue)
		{
			return new Constant<T>(constantValue);
		}

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

		public Local<T> Local<T>()
		{
			return new Local<T>(m_OwnerMethod);
		}

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

		public Local<T> Local<T>(IOperand<T> initialValue)
		{
			var local = new Local<T>(m_OwnerMethod);
			local.Assign(initialValue);
			return local;
		}

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

		public Local<T> Local<T>(T initialValueConst)
		{
			return Local<T>(new Constant<T>(initialValueConst));
		}

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

		public Argument<T> Argument<T>(int position)
		{
			return new Argument<T>(m_OwnerMethod, (byte)position);
		}

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

		public Argument<T> Arg1<T>()
		{
			return new Argument<T>(m_OwnerMethod, 1);
		}

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

		public Argument<T> Arg2<T>()
		{
			return new Argument<T>(m_OwnerMethod, 2);
		}

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

		public Argument<T> Arg3<T>()
		{
			return new Argument<T>(m_OwnerMethod, 3);
		}

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

		public Argument<T> Arg4<T>()
		{
			return new Argument<T>(m_OwnerMethod, 4);
		}

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

		public Argument<T> Arg5<T>()
		{
			return new Argument<T>(m_OwnerMethod, 5);
		}

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

		public Argument<T> Arg6<T>()
		{
			return new Argument<T>(m_OwnerMethod, 6);
		}

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

		public Argument<T> Arg7<T>()
		{
			return new Argument<T>(m_OwnerMethod, 7);
		}

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

		public Argument<T> Arg8<T>()
		{
			return new Argument<T>(m_OwnerMethod, 8);
		}

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

		public IHapilIfBody If(IOperand<bool> condition)
		{
			return AddStatement(new IfStatement(condition));
		}

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

		public IHapilIfBody If(IOperand<bool> condition, bool isTautology)
		{
			return AddStatement(new IfStatement(condition, isTautology));
		}

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

		public Operand<T> Iif<T>(IOperand<bool> condition, IOperand<T> onTrue, IOperand<T> onFalse)
		{
			return new TernaryConditionalOperator<T>(condition, onTrue, onFalse);
		}

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

		public Operand<T> Iif<T>(IOperand<bool> condition, bool isTautology, IOperand<T> onTrue, IOperand<T> onFalse)
		{
			if ( !isTautology )
			{
				return new TernaryConditionalOperator<T>(condition, onTrue, onFalse);
			}
			else
			{
				var scope = StatementScope.Current;
				scope.Consume(condition);
				scope.Consume(onFalse);

				return (Operand<T>)onTrue;
			}
		}

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

		public IHapilWhileSyntax While(IOperand<bool> condition)
		{
			return AddStatement(new WhileStatement(condition));
		}

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

		public IHapilDoWhileSyntax Do(Action<ILoopBody> body)
		{
			return AddStatement(new DoWhileStatement(body));
		}

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

		public HapilForShortSyntax For(Operand<int> from, IOperand<int> to, int increment = 1)
		{
			return new HapilForShortSyntax(this, from, to.CastTo<int>(), increment);
		}

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

		public HapilForShortSyntax For(IOperand<int> from, Operand<int> to, int increment = 1)
		{
			return new HapilForShortSyntax(this, from.CastTo<int>(), to, increment);
		}

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

		public HapilForShortSyntax For(IOperand<int> from, IOperand<int> to, int increment = 1)
		{
			return new HapilForShortSyntax(this, from.CastTo<int>(), to.CastTo<int>(), increment);
		}

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

		public HapilForShortSyntax For(Operand<int> from, Operand<int> to, int increment = 1)
		{
			return new HapilForShortSyntax(this, from, to, increment);
		}

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

		public IHapilForWhileSyntax For(Action precondition)
		{
			return AddStatement(new ForStatement(precondition));
		}

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

		public IHapilForeachInSyntax<T> Foreach<T>(Local<T> element)
		{
			return AddStatement(new ForeachStatement<T>(element));
		}

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

		public IHapilForeachDoSyntax<T> ForeachElementIn<T>(IOperand<IEnumerable<T>> collection)
		{
			var element = this.Local<T>();
			var statement = new ForeachStatement<T>(element);

			AddStatement(statement);
			statement.In(collection);

			return statement;
		}

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

		public IHapilUsingSyntax Using(IOperand<IDisposable> disposable)
		{
			return AddStatement(new UsingStatement(disposable));
		}

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

		public IHapilLockSyntax Lock(IOperand<object> syncRoot, int millisecondsTimeout)
		{
			return AddStatement(new LockStatement(syncRoot, millisecondsTimeout));
		}

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

		public IHapilCatchSyntax Try(Action body)
		{
			return AddStatement(new TryStatement(body));
		}

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

		public IHapilSwitchSyntax<T> Switch<T>(IOperand<T> value)
		{
			return AddStatement(new SwitchStatement<T>(value));
		}

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

        public ThisOperand<TBase> This<TBase>()
        {
            return new ThisOperand<TBase>(OwnerClass);
        }

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

		public void RaiseEvent(string eventName, IOperand<EventArgs> eventArgs)
		{
			var eventMember = m_OwnerClass.GetMemberByName<EventMember>(eventName);

			using ( eventMember.CreateTypeTemplateScope() )
			{
				If(eventMember.BackingField.AsOperand<TypeTemplate.TEventHandler>() != Const<TypeTemplate.TEventHandler>(null)).Then(() => {
					eventMember.BackingField.AsOperand<TypeTemplate.TEventHandler>().Invoke(This<TypeTemplate.TBase>(), eventArgs);
				});
			}
		}

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

		public IOperand<TObject> New<TObject>(params IOperand[] constructorArguments)
		{
			if ( TypeTemplate.Resolve<TObject>().IsValueType )
			{
				return new NewStructExpression<TObject>(constructorArguments);
			}
			else
			{
				return new NewObjectExpression<TObject>(constructorArguments);
			}
		}

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

		public IOperand<TElement[]> NewArray<TElement>(IOperand<int> length)
		{
			return new UnaryExpressionOperand<int, TElement[]>(
				@operator: new UnaryOperators.OperatorNewArray<TElement>(),
				operand: length);
		}

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

		public IOperand<TElement[]> NewArray<TElement>(params TElement[] constantValues)
		{
			return NewArray<TElement>(constantValues.Select(v => new Constant<TElement>(v)).ToArray());
		}

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

		public IOperand<TElement[]> NewArray<TElement>(params IOperand<TElement>[] values)
		{
			var arrayLocal = Local<TElement[]>(NewArray<TElement>(Const(values.Length)));

			for ( int i = 0 ; i < values.Length ; i++ )
			{
				arrayLocal.ElementAt(i).Assign(values[i]);
			}

			return arrayLocal;
		}

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

		public void Throw<TException>(string message) where TException : Exception
		{
			AddStatement(new ThrowStatement(typeof(TException), message));
		}

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

		public void Throw()
		{
			AddStatement(new RethrowStatement());
		}

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

		public Operand<TDelegate> MakeDelegate<TTarget, TDelegate>(IOperand<TTarget> target, Expression<Func<TTarget, TDelegate>> methodSelector)
		{
			var method = Helpers.ResolveMethodFromLambda(methodSelector);
			return new DelegateOperand<TDelegate>(target, method);
		}

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

		public Operand<TMethod> MakeDelegate<TTarget, TMethod, TDelegate>(IOperand<TTarget> target, Expression<Func<TTarget, TMethod>> methodSelector)
		{
			var method = Helpers.ResolveMethodFromLambda(methodSelector);
			return new DelegateOperand<TMethod>(target, method, delegateTypeOverride: TypeTemplate.Resolve<TDelegate>());
		}

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

		public Operand<Action> Delegate(Action<VoidMethodWriter> body)
		{
			return new AnonymousActionOperand(OwnerClass, body);
		}
		public Operand<Action<TA1>> Delegate<TA1>(Action<VoidMethodWriter, Argument<TA1>> body)
		{
			return new AnonymousActionOperand<TA1>(OwnerClass, body);
		}
		public Operand<Action<TA1, TA2>> Delegate<TA1, TA2>(Action<VoidMethodWriter, Argument<TA1>, Argument<TA2>> body)
		{
			return new AnonymousActionOperand<TA1, TA2>(m_OwnerClass, body);
		}
		public Operand<Action<TA1, TA2, TA3>> Delegate<TA1, TA2, TA3>(Action<VoidMethodWriter, Argument<TA1>, Argument<TA2>, Argument<TA3>> body)
		{
			return new AnonymousActionOperand<TA1, TA2, TA3>(m_OwnerClass, body);
		}
		public Operand<Action<TA1, TA2, TA3, TA4>> Delegate<TA1, TA2, TA3, TA4>(Action<VoidMethodWriter, Argument<TA1>, Argument<TA2>, Argument<TA3>, Argument<TA4>> body)
		{
			return new AnonymousActionOperand<TA1, TA2, TA3, TA4>(m_OwnerClass, body);
		}

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

		public Operand<Func<TReturn>> Delegate<TReturn>(Action<FunctionMethodWriter<TReturn>> body)
		{
			return new AnonymousFuncOperand<TReturn>(OwnerClass, body);
		}
		public Operand<Func<TA1, TReturn>> Delegate<TA1, TReturn>(Action<FunctionMethodWriter<TReturn>, Argument<TA1>> body)
		{
			return new AnonymousFuncOperand<TA1, TReturn>(OwnerClass, body);
		}
		public Operand<Func<TA1, TA2, TReturn>> Delegate<TA1, TA2, TReturn>(Action<FunctionMethodWriter<TReturn>, Argument<TA1>, Argument<TA2>> body)
		{
			return new AnonymousFuncOperand<TA1, TA2, TReturn>(m_OwnerClass, body);
		}
		public Operand<Func<TA1, TA2, TA3, TReturn>> Delegate<TA1, TA2, TA3, TReturn>(Action<FunctionMethodWriter<TReturn>, Argument<TA1>, Argument<TA2>, Argument<TA3>> body)
		{
			return new AnonymousFuncOperand<TA1, TA2, TA3, TReturn>(m_OwnerClass, body);
		}
		public Operand<Func<TA1, TA2, TA3, TA4, TReturn>> Delegate<TA1, TA2, TA3, TA4, TReturn>(Action<FunctionMethodWriter<TReturn>, Argument<TA1>, Argument<TA2>, Argument<TA3>, Argument<TA4>> body)
		{
			return new AnonymousFuncOperand<TA1, TA2, TA3, TA4, TReturn>(m_OwnerClass, body);
		}

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

		public Operand<Func<TResult>> Lambda<TResult>(Func<IOperand<TResult>> expression)
		{
			return Delegate<TResult>(w => w.Return(expression()));
		}
		public Operand<Func<TA1, TResult>> Lambda<TA1, TResult>(Func<Operand<TA1>, IOperand<TResult>> expression)
		{
			return Delegate<TA1, TResult>((w, arg1) => w.Return(expression(arg1)));
		}
		public Operand<Func<TA1, TA2, TResult>> Lambda<TA1, TA2, TResult>(Func<Operand<TA1>, Operand<TA2>, IOperand<TResult>> expression)
		{
			return Delegate<TA1, TA2, TResult>((w, arg1, arg2) => w.Return(expression(arg1, arg2)));
		}
		public Operand<Func<TA1, TA2, TA3, TResult>> Lambda<TA1, TA2, TA3, TResult>(Func<Operand<TA1>, Operand<TA2>, Operand<TA3>, IOperand<TResult>> expression)
		{
			return Delegate<TA1, TA2, TA3, TResult>((w, arg1, arg2, arg3) => w.Return(expression(arg1, arg2, arg3)));
		}
		public Operand<Func<TA1, TA2, TA3, TA4, TResult>> Lambda<TA1, TA2, TA3, TA4, TResult>(Func<Operand<TA1>, Operand<TA2>, Operand<TA3>, Operand<TA4>, IOperand<TResult>> expression)
		{
			return Delegate<TA1, TA2, TA3, TA4, TResult>((w, arg1, arg2, arg3, arg4) => w.Return(expression(arg1, arg2, arg3, arg4)));
		}

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

		public Operand<IntPtr> MethodOf(MethodInfo method)
		{
			return new MethodOf(method);
		}

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

		public Operand<IntPtr> MethodOf(MethodMember method)
		{
			return new MethodOf(method);
		}

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

		public Operand<IntPtr> MethodOf<TTarget, TMethod>(IOperand<TTarget> target, Expression<Func<TTarget, TMethod>> methodSelector)
		{
			var method = Helpers.ResolveMethodFromLambda(methodSelector);
			return new MethodOf(method);
		}

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

		//public void EmitFromLambda(Expression<Action> lambda)
		//{
		//	var callInfo = (MethodCallExpression)lambda.Body;
		//	var methodInfo = callInfo.Method;
		//	var arguments = callInfo.Arguments.Select(Helpers.GetLambdaArgumentAsConstant).ToArray();
		//	var happilExpression = new HapilUnaryExpression<object, object>(
		//		ownerMethod: this,
		//		@operator: new UnaryOperators.OperatorCall<object>(methodInfo, arguments),
		//		operand: null);

		//	//var arguments = new IHapilOperandInternals[callInfo.Arguments.Count];

		//	//for ( int i = 0 ; i < arguments.Length ; i++ )
		//	//{
		//	//	//var argument = callInfo.Arguments[i];

		//	//	//Expression<Func<object>> argumentLambda = Expression.Lambda<Func<object>>(argument);
		//	//	//var argumentValueFunc = argumentLambda.Compile();
		//	//	//var argumentValue = argumentValueFunc();

		//	//	arguments[i] = Helpers.GetLambdaArgumentAsConstant(callInfo.Arguments[i]);
		//	//}

		//	//m_HapilClass.CurrentScope.AddStatement();
		//}

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

		public void ForEachArgument(Action<Argument<TypeTemplate.TArgument>> action)
		{
			ValidateNotAnonymousMethod();

			//TODO: refactor to reuse the overloaded method
			var argumentTypes = OwnerMethod.Signature.ArgumentType;
			var indexBase = (OwnerMethod.Signature.IsStatic ? 0 : 1);

			for ( byte i = 0 ; i < argumentTypes.Length ; i++ )
			{
				using ( TypeTemplate.CreateScope<TypeTemplate.TArgument>(argumentTypes[i]) )
				{
					var argument = this.Argument<TypeTemplate.TArgument>((byte)(i + indexBase));
					action(argument);
				}
			}
		}

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

		//TODO: refactor to reuse the overloaded method
		public void ForEachArgument(Action<Argument<TypeTemplate.TArgument>, int> action)
		{
			ValidateNotAnonymousMethod();

			var argumentTypes = OwnerMethod.Signature.ArgumentType;

			for ( int index = 0 ; index < argumentTypes.Length ; index++ )
			{
				using ( TypeTemplate.CreateScope<TypeTemplate.TArgument>(argumentTypes[index]) )
				{
					var argument = this.Argument<TypeTemplate.TArgument>(position: index + 1);
					action(argument, index);
				}
			}
		}

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

		public Operand<TResult> Proceed<TResult>()
		{
			ValidateNotAnonymousMethod();

			if ( !m_Mode.HasFlag(MethodWriterModes.Decorator) )
			{
				throw new InvalidOperationException("Proceed is only allowed in the Decorator mode.");
			}

			var returnValueLocal = (m_OwnerMethod.Signature.IsVoid ? null : m_OwnerMethod.AddLocal<TResult>());
			AddStatement(new ProceedStatement(m_OwnerMethod, m_InnerWriters, returnValueLocal));

			return returnValueLocal;
		}

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

		public Operand<TResult> PropagateCall<TResult>(IOperand target)
		{
			ValidateNotAnonymousMethod();

			Local<TResult> returnValueLocal = null;

			if ( !OwnerMethod.IsVoid )
			{
				returnValueLocal = Local<TResult>();
			}

			StatementScope.Current.AddStatement(new PropagateCallStatement(OwnerMethod, target, returnValueLocal));

			if ( !OwnerMethod.IsVoid )
			{
				AddReturnStatement<TResult>(returnValueLocal);
			}

			return returnValueLocal;
		}

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

        public void ProceedToTarget(IOperand target)
        {
            var returnValueLocal = PropagateCall<TT.TReturn>(target);

            if (!OwnerMethod.IsVoid)
            {
                AddReturnStatement(returnValueLocal);
            }
        }

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

        public void ProceedToBaseIfAny()
        {
            if ( OwnerMethod.HasInvokableBaseMethod )
            {
                ProceedToBase();
            }
            else if (!OwnerMethod.IsVoid)
            {
                AddReturnStatement(Default<TT.TReturn>());
            }
        }

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

        public void ProceedToBase()
        {
            var arguments = new IOperand[this.OwnerMethod.Signature.ArgumentCount];

            this.ForEachArgument((arg, index) => {
                arguments[index] = arg;
            });

            if (this.OwnerMethod.IsVoid)
            {
                 InternalBase(arguments);
            }
            else
            {
                AddReturnStatement(InternalBase(arguments));
            }
        }

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

		public void RawIL(Action<ILGenerator> script)
		{
			StatementScope.Current.AddStatement(new RawILStatement(script));
		}

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

		public ClassType OwnerClass
		{
			get
			{
				return m_OwnerClass;
			}
		}

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

		public MethodMember OwnerMethod
		{
			get
			{
				return m_OwnerMethod;
			}
		}

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

		public AttributeWriter ReturnAttributes
		{
			get
			{
				if ( m_ReturnAttributeWriter == null )
				{
					m_ReturnAttributeWriter = new AttributeWriter();
				}

				return m_ReturnAttributeWriter;
			}
		}

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

		public MethodWriterModes Mode
		{
			get
			{
				return m_Mode;
			}
		}

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

		public bool IsDecorator
		{
			get
			{
				return m_Mode.HasFlag(MethodWriterModes.Decorator);
			}
		}

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

		public bool IsDecorated
		{
			get
			{
				return m_Mode.HasFlag(MethodWriterModes.Decorated);
			}
		}

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

		protected internal override void Flush()
		{
			WriteReturnAttributesIfAny();
			base.Flush();
		}

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

		protected internal void AddAttributes(Func<MethodMember, AttributeWriter> attributeWriterFactory)
		{
			ValidateNotAnonymousMethod();

			if ( attributeWriterFactory != null )
			{
				AttributeWriter.Include(attributeWriterFactory(m_OwnerMethod));
			}
		}

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

		protected override void SetCustomAttribute(CustomAttributeBuilder attribute)
		{
			ValidateNotAnonymousMethod();
			m_OwnerMethod.MethodFactory.SetAttribute(attribute);
		}

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

	    protected MethodInfo GetValidBaseMethod(IOperand[] arguments)
	    {
	        var baseMethod = OwnerMethod.MethodFactory.InvokableBaseMethod;

	        if ( baseMethod == null )
	        {
	            throw new InvalidOperationException("Current method has no base which can be invoked.");
	        }

	        if ( arguments.Length != OwnerMethod.Signature.ArgumentCount )
	        {
	            throw new ArgumentException("Number of arguments does not match method signature.");
	        }

	        for ( int i = 0 ; i < OwnerMethod.Signature.ArgumentCount ; i++ )
	        {
	            var parameterType = GetValidatableType(OwnerMethod.Signature.ArgumentUnderlyingType[i]);
	            var argumentType = GetValidatableType(arguments[i].OperandType);

	            if ( !parameterType.IsAssignableFrom(argumentType) )
	            {
	                throw new ArgumentException(string.Format(
	                    "Argument at index {0}: argument of type '{1}' cannot be assigned to parameter of type '{2}'.",
	                    i,
	                    argumentType.FriendlyName(),
	                    parameterType.FriendlyName()));
	            }
	        }

	        return baseMethod;
	    }

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

		internal TStatement AddStatement<TStatement>(TStatement statement) where TStatement : StatementBase
		{
			StatementScope.Current.AddStatement(statement);
			return statement;
		}

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

		protected internal void AddReturnStatement()
		{
			if ( IsDecorated )
			{
				StatementScope.Current.AddStatement(new GotoStatement(m_LeaveLabel));
			}
			else
			{
				StatementScope.Current.AddStatement(new ReturnStatement());
			}
		}

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

		protected internal void AddReturnStatement<TReturn>(IOperand<TReturn> returnValue)
		{
			if ( IsDecorated )
			{
				m_ReturnValueLocal.Assign(returnValue);
				StatementScope.Current.AddStatement(new GotoStatement(m_LeaveLabel));
			}
			else
			{
				StatementScope.Current.AddStatement(new ReturnStatement<TReturn>(returnValue));
			}
		}

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

	    protected internal IOperand<TT.TReturn> InternalBase(params IOperand[] arguments)
        {
            var baseMethod = GetValidBaseMethod(arguments);

            using (TT.CreateScope<TT.TBase>(baseMethod.DeclaringType))
            {
                if (baseMethod.IsVoid())
                {
                    AddStatement(new CallStatement(This<TT.TBase>(), baseMethod, disableVirtual: true, arguments: arguments));
                    return null;
                }
                else
                {
                    var @operator = new UnaryOperators.OperatorCall<TT.TBase>(baseMethod, disableVirtual: true, arguments: arguments);
                    return new UnaryExpressionOperand<TT.TBase, TT.TReturn>(@operator, This<TT.TBase>());
                }
            }
        }

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

		internal void SetupDecoratedMode(IMutableOperand returnValueLocal, LabelStatement leaveLabel)
		{
			m_Mode |= MethodWriterModes.Decorated;
			m_ReturnValueLocal = returnValueLocal;
			m_LeaveLabel = leaveLabel;
		}

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

		internal void SetupDecoratorMode(MethodWriterBase[] innerWriters)
		{
			m_Mode |= MethodWriterModes.Decorator;
			m_InnerWriters = innerWriters;
		}

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

		internal protected MethodWriterBase[] InnerWriters
		{
			get
			{
				return m_InnerWriters;
			}
		}

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

		private void WriteReturnAttributesIfAny()
		{
			if ( m_ReturnAttributeWriter == null )
			{
				return;
			}

			ValidateNotAnonymousMethod();

			if ( m_OwnerMethod.MethodFactory.ReturnParameter != null )
			{
				foreach ( var attribute in m_ReturnAttributeWriter.GetAttributes() )
				{
					m_OwnerMethod.MethodFactory.ReturnParameter.SetCustomAttribute(attribute);
				}
			}
		}

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

	    private Type GetValidatableType(Type type)
	    {
	        var resolvedType = TypeTemplate.Resolve(type);
            var nonRefType = (resolvedType.IsByRef ? resolvedType.GetElementType() : resolvedType);
            var resolvedNonRefType = TypeTemplate.Resolve(nonRefType);

            return resolvedNonRefType;
	    }

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

		private void ValidateNotAnonymousMethod()
		{
			if ( m_OwnerMethod == null )
			{
				throw new InvalidOperationException("Requested operation is not available within anonymous delegate or lambda expression.");
			}
		}
	}
}


text:
import sys

from Tkinter import*

class ValidatingEntry(Entry):
    # base class for validating entry widgets

    def __init__(self, master, value="", **kw):
        apply(Entry.__init__, (self, master), kw)
        self.__value = value
        self.__variable = StringVar()
        self.__variable.set(value)
        self.__variable.trace("w", self.__callback)
        self.config(textvariable=self.__variable)

    def __callback(self, *dummy):
        value = self.__variable.get()
        newvalue = self.validate(value)
        if newvalue is None:
            self.__variable.set(self.__value)
        elif newvalue != value:
            self.__value = newvalue
            self.__variable.set(self.newvalue)
        else:
            self.__value = value

    def validate(self, value):
        # override: return value, new value, or None if invalid
        return value

class FloatEntry(ValidatingEntry):

    def validate(self, value):
        try:
            if value:
                v = float(value)
            return value
        except ValueError:
            return None

redpajama_set_name: RedPajamaGithub


text:
package ru.pavlenov.scala.homework.rosalind.ngs

import ru.pavlenov.scala.utils.File
import scala.sys.process._

/**
 * ⓭ + 47
 * Какой сам? by Pavlenov Semen 30.08.14.
 * Base Filtration by Quality
 * http://rosalind.info/problems/Bfil/
 *
 * Given:
 * FASTQ file, quality cut-off value q, Phred33 quality score assumed.
 *
 * Return:
 * FASTQ file trimmed from the both ends (removed leading and trailing bases with quality lower then q)
 */

object Bfil {

  def start() {

    println("Base Filtration by Quality")
    println("from http://rosalind.info/problems/Bfil/")
    println("==========================")

    val data = File.fromData(this)

    val delta = 33
    val threshold = data.head.toInt
    val list = data.tail

    File.toFile(this, "in.fq", list.mkString("\n"))

    val inFile = File.getClassDir(this) + ".in.fq"
    val outFile = File.getClassDir(this) + ".out.fq"

    //java -jar trimmomatic-0.30.jar PE --phred33 input_forward.fq.gz input_reverse.fq.gz output_forward_paired.fq.gz
    val cmdline = "java -jar /home/laser13/bioinf/Trimmomatic-0.32/trimmomatic-0.32.jar SE -phred33 %s %s LEADING:%s TRAILING:%s".format(inFile, outFile, threshold, threshold)
    cmdline.!

  }

}


text:
"""Test configuration files"""

import os
import sys

from pyrseas.config import Config
from pyrseas.cmdargs import cmd_parser, parse_args
from pyrseas.yamlutil import yamldump

USER_CFG_DATA = {'database': {'port': 5433},
                 'output': {'version_comment': True}}
CFG_TABLE_DATA = {'schema public': ['t1', 't2']}
CFG_DATA = {'datacopy': CFG_TABLE_DATA}
CFG_FILE = 'testcfg.yaml'

def test_defaults():
    "Create a configuration with defaults"
    cfg = Config()
    for key in ['audit_columns', 'functions', 'function_templates', 'columns',
                'triggers']:
        assert key in cfg['augmenter']
    for key in ['metadata', 'data']:
        assert key in cfg['repository']

def test_user_config(tmpdir):
    "Test a user configuration file"
    f = tmpdir.join(CFG_FILE)
    f.write(yamldump(USER_CFG_DATA))
    os.environ["PYRSEAS_USER_CONFIG"] = f.strpath
    cfg = Config()
    assert cfg['database'] == {'port': 5433}
    assert cfg['output'] == {'version_comment': True}

def test_repo_config(tmpdir):
    "Test a repository configuration file"
    ucfg = tmpdir.join(CFG_FILE)
    ucfg.write(yamldump({'repository': {'path': tmpdir.strpath}}))
    f = tmpdir.join("config.yaml")
    f.write(yamldump(CFG_DATA))
    os.environ["PYRSEAS_USER_CONFIG"] = ucfg.strpath
    cfg = Config()
    assert cfg['datacopy'] == CFG_TABLE_DATA

def test_cmd_parser(tmpdir):
    "Test parsing a configuration file specified on the command line"
    f = tmpdir.join(CFG_FILE)
    f.write(yamldump(CFG_DATA))
    sys.argv = ['testprog', 'testdb', '--config', f.strpath]
    os.environ["PYRSEAS_USER_CONFIG"] = ''
    parser = cmd_parser("Test description", '0.0.1')
    cfg = parse_args(parser)
    assert cfg['datacopy'] == CFG_TABLE_DATA

def test_parse_repo_config(tmpdir):
    "Test parsing a repository configuration file in the current directory"
    f = tmpdir.join('config.yaml')
    f.write(yamldump(CFG_DATA))
    os.chdir(tmpdir.strpath)
    sys.argv = ['testprog', 'testdb']
    os.environ["PYRSEAS_USER_CONFIG"] = ''
    parser = cmd_parser("Test description", '0.0.1')
    cfg = parse_args(parser)
    assert cfg['datacopy'] == CFG_TABLE_DATA

def test_repo_user_config(tmpdir):
    "Test a repository path specified in the user config"
    usercfg = {'repository': {'path': tmpdir.strpath}}
    userf = tmpdir.join("usercfg.yaml")
    userf.write(yamldump(usercfg))
    os.environ["PYRSEAS_USER_CONFIG"] = userf.strpath
    repof = tmpdir.join("config.yaml")
    repof.write(yamldump(CFG_DATA))
    cfg = Config()
    assert cfg['datacopy'] == CFG_TABLE_DATA


text:
package com.ait.tooling.nativetools.client;

import com.ait.tooling.common.api.json.JSONType;
import com.google.gwt.core.client.JavaScriptObject;

public interface NValue<T extends JavaScriptObject> extends NHasJSO<T>, NJSONStringify
{
    public JSONType getNativeTypeOf();

    public boolean is(JSONType type);

    public NValue<T> asNValue();

    public NArray asNArray();

    public NObject asNObject();
}


text:
package Noosphere;
use strict;

use Noosphere::StatCache;

# get the content RSS feed.
#
# various object types/views are all presented as channels, from which the user
# can select.
#
sub getRSS {
	my $params = shift;

	my $channel = lc($params->{'channel'} || 'all');

	my $proj = getConfig('projname');
	my $site = getConfig('main_url');

	my $xml =  "<?xml version=\"1.0\"?>
<rss version=\"2.0\">\n";

	$xml .= "\t<channel>\n";

	if ($channel eq 'all') {
		$xml .= "\t\t<title>".$proj.": Latest Activity</title>\n";
		$xml .= "\t\t<link>$site/</link>\n";

		my $la = getLatestEntries_RSS('latestadds', 1);
		my $lm = getLatestEntries_RSS('latestmods', 1);
		my $m = getLatestMessages_RSS(1);

		$xml .= makeRSS_XML(combine_RSS_data($lm, $la, $m));
	}

	# latest (encyclopedia) additions
	#
	elsif ($channel eq 'latestadds') {

		$xml .= "\t\t<title>".$proj.": Latest Encyclopedia Additions</title>\n";
		$xml .= "\t\t<link>$site/?op=enlist&mode=created</link>\n";

		$xml .= makeRSS_XML(linearize_datewise_RSS_stats(getLatestEntries_RSS('latestadds')));
	}

	# latest (encyclopedia) modifications
	#
	elsif ($channel eq 'latestmods') {

		$xml .= "\t\t<title>".$proj.": Latest Encyclopedia Revisions</title>\n";
		$xml .= "\t\t<link>$site/?op=enlist&mode=modified</link>\n";

		$xml .= makeRSS_XML(linearize_datewise_RSS_stats(getLatestEntries_RSS('latestadds')));

	}

	# latest messages
	#
	elsif ($channel eq 'latestmsgs') {

		$xml .= "\t\t<title>".$proj.": Latest Messages</title>\n";
		$xml .= "\t\t<link>$site/?op=messageschrono</link>\n";

		$xml .= makeRSS_XML(linearize_datewise_RSS_stats(getLatestMessages_RSS()));
	}

	$xml .= "\t</channel>\n";

	$xml .= "</rss>\n";;

	return $xml;
}

# format cached latest entry data as linear RSS channel data
# (this does not make the XML)
#
sub getLatestEntries_RSS {
	my $statkey = shift;
	my $prefix = shift;

	my %phash = ('latestadds' => 'new', 'latestmods' => 'rev');

	my @rsslist;
	my $metadata = $stats->get($statkey);

	# set prefix for multiplexed RSS feed
	#
	my $pstring = '';
	$pstring = "($phash{$statkey}) " if $prefix;

	# make into RSS data structure
	#
	foreach my $daylist (@$metadata) {
		my ($date) = keys %$daylist;

		my ($items) = $daylist->{$date};

		foreach my $item (@$items) {

			# add title-type prefix (may be blank)
			#
			$item->{'title'} = $pstring.$item->{'title'};

			$item->{'link'} = $item->{'url'};		# rename
			delete $item->{'url'};

			# leave timestamp in tact
		}
	}

	return $metadata;
}

# take a date-based stats RSS hash and turn it into a linear list
#
sub linearize_datewise_RSS_stats {
	my $metadata = shift;

	my @rsslist;

	foreach my $daylist (@$metadata) {
		my ($date) = keys %$daylist;

		my ($items) = $daylist->{$date};

		foreach my $item (@$items) {

			# note we are dropping the timestamp, which was only really useful
			# for sorting
			#
			push @rsslist, {
				'title' => htmlescape($item->{'title'}),
				'link' => $item->{'link'},
				'author' => $item->{'author'},
				'pubDate' => $date,
				'description' => htmlescape($item->{'description'})
				};
		}
	}

	return [@rsslist];
}

# turn an RSS items list into channel XML
#
sub makeRSS_XML {
	my $rssptr = shift;

	my @rsslist = @{$rssptr};

	my $xml = '';

	foreach my $item (@rsslist[0..($#rsslist > 19 ? 19 : $#rsslist)]) {

		$xml .= "\t<item>\n";

		foreach my $key (keys %$item) {
			$xml .= "\t\t<$key>$item->{$key}</$key>\n";
		}
		$xml .= "\t</item>\n";

	}

	return $xml;
}

# combine and linearize RSS data from many separate sources
#
sub combine_RSS_data {
	my @sourcedata = @_;

	my @prelimlist;
	my @rsslist;

	# dump all the separate lists into a single flat list
	# (not sorted)
	#
	foreach my $metadata (@sourcedata) {
		foreach my $daylist (@$metadata) {
			my ($date) = keys %$daylist;

			my ($items) = $daylist->{$date};

			foreach my $item (@$items) {

				my $newitem = {%$item};
				$newitem->{'pubDate'} = $date;

				push @prelimlist, $newitem;
			}
		}
	}

	# sort the list; dump it into the final one
	#
	foreach my $item (sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @prelimlist) {
		delete $item->{'timestamp'};	# don't need this anymore
		push @rsslist, $item;
	}

	return [@rsslist];
}

# get count of unproven theorems
#
sub unprovenCount {
	my $en = getConfig('en_tbl');
	my ($rv, $sth) = dbLowLevelSelect($dbh, "select o1.uid from $en as o1 left outer join $en as o2 on (o1.uid=o2.parentid and o2.type=".PROOF.") where o1.type=".THEOREM." and (o1.self is NULL or o1.self = 0) and o2.uid is NULL");
	my $total = $sth->rows();
	$sth->finish();

	return $total;
}

# getUnprovenTheorems - returns a hash containing all theorem objects that
# do not have any proof objects attached to them
#
sub getUnprovenTheorems
{
		my $en = getConfig('en_tbl');
		my ($rv, $sth) = dbLowLevelSelect($dbh, "select o1.* from $en as o1 left outer join $en as o2 on (o1.uid=o2.parentid and o2.type=".PROOF.") where o1.type=".THEOREM." and (o1.self is NULL or o1.self = 0) and o2.uid is NULL");
	my @rows = dbGetRows($sth);
		my $theorems = {};

		foreach my $row (@rows) {
			$theorems->{$row->{'uid'}} = $row;
		}
		return $theorems;
}

# unprovenTheorems - lists theorems that have not yet been proven
#
sub unprovenTheorems {
	my ($params, $userinf) = @_;

	my $limit = $userinf->{'prefs'}->{'pagelength'};
	my $offset = $params->{'offset'} || 0;

	my $unpts = getUnprovenTheorems();
	my %bytitle;
	my @titles;
	my $html = "";

	foreach my $uid (keys(%$unpts)) {
		my $i = "";
		my $title = $unpts->{$uid}->{title};

		$i++ while $bytitle{"$title$i"};
		push @titles, "$title$i";
		$bytitle{"$title$i"} = $uid;
	}

	@titles = sort { humanReadableCmp($a, $b); } @titles;
	my $total = scalar @titles;

	my $template = new XSLTemplate('unproven.xsl');

	$template->addText('<unprovenlist>');

	for (my $i = 0; $i < $limit && $offset + $i < scalar @titles; $i++) {
		my $row = $unpts->{$bytitle{$titles[$i + $offset]}};
		my $uenct = urlescape($row->{'title'});

		my $ord = $offset + $i + 1;
		my $ourl = getConfig("main_url")."/?op=getobj&from=objects&id=$row->{uid}";
		my $purl = getConfig("main_url")."/?op=adden&request=$row->{uid}&title=proof+of+$uenct&type=Proof&parent=$row->{name}";

		my $mathtitle = mathTitleXSL($row->{'title'}, 'highlight');

		$template->addText("	<item>");
		$template->addText("		<series ord=\"$ord\"/>");
		$template->addText("		<object href=\"$ourl\"/>");
		$template->addText("		<prove href=\"$purl\"/>");
		$template->addText("		<title>$mathtitle</title>");
		#$template->addText("		<user name=\"".qhtmlescape($row->{'username'})."\" href=\"".getConfig("main_url")."/?op=getuser;id=$row->{userid}\"/>");
		$template->addText("	</item>");

		$ord++;
	}

	$template->addText('</unprovenlist>');

	$params->{'total'} = $total;
	$params->{'offset'} = $offset;

	getPageWidgetXSLT($template, $params, $userinf);

	return $template->expand();
}

# show hit statistics
#
sub getHitInfo {
	my $params = shift;

	my $periods = [
		['total',"<=CURRENT_TIMESTAMP"],
		['last day',">CURRENT_TIMESTAMP+'-1 day'"],
		['last week',">CURRENT_TIMESTAMP+'-1 week'"],
		['last month',">CURRENT_TIMESTAMP+'-1 month'"],
		['last year',">CURRENT_TIMESTAMP+'-1 year'"]
	];

	my $html="";

	$html .= "
";
	$html .= "
";
	$html .= " 	";
	$html .= "hits	";
	$html .= "
";
	foreach my $period (@$periods) {
		my $tid = tableid($params->{'from'});

		$html .= "
";
		$html .= "$period->[0]	";
		my $cnt = dbRowCount(getConfig('hit_tbl'),"objectid=$params->{id} and tblid=$tid and at$period->[1]");
		$html .= "$cnt	";
		$html .= "
";
	}
	$html .= "
";

	my $title = lookupfield($params->{from},'title',"uid=$params->{id}");
	return paddingTable(clearBox("Access Stats for '$title'",$html));
}

# get a count of unclassified objects
#
sub unclassifiedCount {
	my ($rv,$sth) = dbLowLevelSelect($dbh,"select distinct o.uid from objects as o left outer join classification as c on (o.uid=c.objectid) where c.objectid is null");
	my $total = $sth->rows();

	$sth->finish();

	return $total;
}

# get a list of unclassified objects
#
sub unclassifiedObjects {
	my $params = shift;
	my $userinf = shift;

	my $template = new XSLTemplate("unclassified.xsl");

	# init paging
	my $total = $params->{'total'} || -1;
	my $offset = $params->{'offset'} || 0;
	my $limit = $userinf->{'prefs'}->{'pagelength'};

	# grab the data
	#
	my ($rv, $sth);
	($rv,$sth) = dbLowLevelSelect($dbh,"select distinct o.title, lower(o.title), o.uid, o.userid, u.username from users as u, objects as o left outer join classification as c on (o.uid=c.objectid) where c.objectid is null and u.uid=o.userid order by lower(o.title) limit $limit offset $offset")
		if (getConfig('dbms') eq 'pg');
	($rv,$sth) = dbLowLevelSelect($dbh,"select distinct o.title, lower(o.title), o.uid, o.userid, u.username from users as u, objects as o left outer join classification as c on (o.uid=c.objectid) where c.objectid is null and u.uid=o.userid order by lower(o.title) limit $offset, $limit")
		if (getConfig('dbms') eq 'mysql');

	#my $total = $sth->rows();
	$template->addText("<unclassifiedlist>");

	my $ord = $offset + 1;
	$total = 0;
	while (my $row = $sth->fetchrow_hashref()) {
		if ( is_deleted( $row->{'uid'} ) ){
			next;
		}
		$total++;
		my $authors = get_authors_html($row->{'uid'}, 'objects');
		my $mathtitle = mathTitleXSL($row->{'title'}, 'highlight');

		$template->addText("	<item>");
		$template->addText("		<series ord=\"$ord\"/>");
		#$template->addText("		<object title=\"".qhtmlescape($row->{'title'})."\" href=\"".getConfig("main_url")."/?op=getobj;from=".getConfig('en_tbl').";id=$row->{uid}\"/>");
		$template->addText("		<object href=\"".getConfig("main_url")."/?op=getobj;from=".getConfig('en_tbl').";id=$row->{uid}\"/>");
		$template->addText("		<title>$mathtitle</title>");
		$template->addText("            <authors>$authors</authors>");
#		$template->addText("		<user name=\"".qhtmlescape($row->{'username'})."\" href=\"".getConfig("main_url")."/?op=getuser;id=$row->{userid}\"/>");
		$template->addText("	</item>");

		$ord++;
	}
	$sth->finish();
	$template->addText("</unclassifiedlist>");

	# get total
	#

	$params->{'offset'} = $offset;
	$params->{'total'} = $total;

	getPageWidgetXSLT($template, $params, $userinf);

	return $template->expand();
}

# hitObject - add a hit for an object
#
sub hitObject {
	my $objectid = shift;# uid of object
	my $table = shift;	 # table object is in
	my $field = shift;	 # field to increment in object (optional)

	#TODO: we need a transaction to both increment field and add to
	# hits table at the same time

	# add to hits table
	#
	my $tid = tableid($table);
	my ($rv,$sth) = dbInsert($dbh,{
		INTO => 'hits',
		COLS => 'objectid,tblid',
		VALUES => "$objectid,$tid"});

	$sth->finish();

	# increment hit count in the object (we dont *really* need this, but it
	# saves us from doing a possibly huge summation over a huge table later)
	#
	if (defined $field) {
		($rv,$sth) = dbUpdate($dbh,{
		 WHAT=>$table,
		 SET=>'hits=hits+1',
		 WHERE=>"uid=$objectid"});

		 $sth->finish();
	}
}

# getSystemStats - get the system stats page
#
sub getSystemStats {
	my $html = '';
	my $periods;

	$periods = [
		['total',"<=CURRENT_TIMESTAMP"],
		['last day',">CURRENT_TIMESTAMP+'-1 day'"],
		['last week',">CURRENT_TIMESTAMP+'-1 week'"],
		['last month',">CURRENT_TIMESTAMP+'-1 month'"],
		['last year',">CURRENT_TIMESTAMP+'-1 year'"]
	] if getConfig('dbms') eq 'pg';

	$periods = [
		['total',"<= now()"],
		['last day',">now() - interval 1 DAY"],
		['last week',">now() - interval 7 DAY"],
		['last month',">now() - interval 30 DAY"],
		['last year',">now() - interval 365 DAY"]
	] if getConfig('dbms') eq 'mysql';

	my $timefields = {
		'objects'=>'created',
		'users'=>'joined',
		'corrections'=>'filed',
		'messages'=>'created',
		'hits'=>'at'
	};

	$html .= "
";
	$html .= "
";
	$html .= " 	";
	foreach my $table (keys %$timefields) {
		$html .= "$table	";
	}
	$html .= "
";
	foreach my $period (@$periods) {
		$html .= "
";
		$html .= "$period->[0]	";
		foreach my $lookup (keys %$timefields) {
			my $cnt = dbRowCount($lookup,"$timefields->{$lookup}$period->[1]");
			$html .= "$cnt	";
		}
		$html .= "
";
	}
	$html .= "
";

	$html .= "";

	my $uptime = `/usr/bin/uptime`;
	$uptime =~ /up ([0-9]+ [a-z]+),/;
	$html .= "
System uptime : $1

";

	$html .= "";

	return paddingTable(clearBox(getConfig('projname').' Stats',$html));
}

# getTopUsers - get the top users box that shows top users by score
#
sub getTopUsers {

	# grab the cached statistics
	#
	my $topusers = $stats->get('topusers');

	# TODO - redo top user stuff with XML and XSLT

	my $topa = '';
	my $topw = '';

	# do top users of all time
	#
	my $rows = $topusers->{'toparows'};

	if (@$rows) {
		$topa .= "
\n";
		foreach my $row (@$rows) {

			if ($row->{'uid'} > 0) {
				$topa .= "
\n";

				$topa .= "\n";
				$topa .= "{'uid'}."\">".$row->{'username'}."\n";
				$topa .= "	\n";
				$topa .= "$row->{'score'}	\n";
				$topa .= "
\n";
			}
		}
		$topa .= "
\n";
	}
	else {
		$topa = "No data.\n";
	}

	# do top users of the past 2 weeks
	#
	$rows = $topusers->{'topwrows'};

	if (@$rows) {
		$topw .= "
\n";
		foreach my $row (@$rows) {

			if ($row->{uid} > 0 && $row->{sum} > 0) {
				$topw .= "
\n";

				$topw .= "\n";
				$topw .= "{'uid'}."\">".$row->{'username'}."\n";
				$topw .= "	\n";
				$topw .= "".$row->{'sum'}."	\n";
				$topw .= "
\n";
			}
		}
		$topw .= "
\n";
	} else {
		$topw = "No data.\n";
	}

#	$topa .= "\n";
#	$topw .= "\n";

	my $template = new Template("topusers.html");

	$template->setKeys('alltime' => $topa, 'twoweeks' => $topw);

	return clearBox("Top Users", $template->expand());
}

# grab the data needed to print top users statistics.	returns a hashref to two
#	arrayrefs
#
sub getTopUsers_callback {
	my $limita = getConfig('topusers_alltime');
	my $limitw = getConfig('topusers_2weeks');

	(my $rv, my $sth) = dbSelect($dbh,{WHAT => 'username,uid,score',
		 FROM => 'users',
		 'ORDER BY' => 'score',
		 'DESC' => '',
		 LIMIT => $limita});

	if (! $rv) {
		dwarn "no users found for top users statistics!\n";
	return [];
	}

	my $where;
	$where = "score.userid=users.uid and occured>(CURRENT_TIMESTAMP+'-2 weeks')" if getConfig('dbms') eq 'pg';
	$where = "score.userid=users.uid and occured>now()-interval 14 DAY" if getConfig('dbms') eq 'mysql';

	my ($rv2, $sth2) = dbSelect($dbh,{WHAT => 'sum(score.delta) as sum,users.username,users.uid',
		FROM => 'score,users',
		WHERE => $where,
		'ORDER BY'=> 'sum',
		'GROUP BY'=> 'users.username,users.uid',
		DESC => '',
		LIMIT => $limitw});

	my @toparows = dbGetRows($sth);

	my @topwrows = dbGetRows($sth2);

	return {toparows=>[@toparows], topwrows=>[@topwrows]};
}

# get and prepare the data for the latest additions/modifications marquee
#
# this returns a structure of the form:
#
# [
#	{dateheader1 => [
#		{objtitle1 => url},
#		{objtitle2 => url},
#		{objtitle3 => url},
#				... ]
#	},
#	{dateheader2 => [
#		{objtitle1 => url},
#		{objtitle2 => url},
#		{objtitle3 => url},
#				... ]
#	},
#	...
# ]
#
sub getLatestEntry_data {
	my $type = shift || 'additions';

	my $limit = getConfig('latest_additions');
	if ($type ne 'additions') {
		$limit = getConfig('latest_revisions');
	}
	my $html = '';

	my $datefield = ($type eq 'additions') ? 'created' : 'modified';

	my ($rv, $sth);

	my $en = getConfig('en_tbl');
	my $u = getConfig('user_tbl');

	($rv, $sth) = dbSelect($dbh,{WHAT=>"$en.uid,$en.name,$en.title,$en.data, extract(EPOCH FROM $en.$datefield) as unixtime, date_part('dow',$en.$datefield) as dow, date_part('year',$en.$datefield)||'-'||date_part('month',$en.$datefield)||'-'||date_part('day', $en.$datefield) as ymd, $u.username", FROM=>"$en, $u", 'ORDER BY'=>"$en.$datefield", DESC=>'', WHERE=>"$u.uid = $en.userid ".($type eq 'modifications' ? 'and modified > created' : '') . "and tags.objectid = $en.uid and tags.tag = 'NS:published'", LIMIT=>$limit})
		if getConfig('dbms') eq 'pg';

	($rv, $sth) = dbSelect($dbh,{WHAT=>"$en.uid,$en.name,$en.title,$en.data, unix_timestamp($en.$datefield) as unixtime, dayofweek($en.$datefield)-1 as dow, concat(extract(YEAR from $en.$datefield), '-', extract(MONTH from $en.$datefield), '-', extract(DAY from $en.$datefield)) as ymd, $u.username", FROM=>"$en, $u, tags", 'ORDER BY'=>$datefield, DESC=>'', WHERE=>"$u.uid = $en.userid ".($type eq 'modifications' ? 'and modified > created' : '') . "and tags.objectid = $en.uid and tags.tag = 'NS:published'"  , LIMIT=>$limit})
		if getConfig('dbms') eq 'mysql';

	if (! $rv) {
		warn "latest $type query error\n";
		return "query error";
	}

	my @rows = dbGetRows($sth);

	my @daystruct;

	my $date = '';
	my $daylist;

	foreach my $row (@rows) {

		# create a day list
		#
		my $day = dowtoa($row->{dow},'long');
		if ($row->{ymd} ne $date) {
			$date = $row->{ymd};
			my $dateheader = "$day, $date";
			$daylist = [];
			push @daystruct, {$dateheader => $daylist};
		}

		# create the new object entry and add to list for this day
		#
		my $url = getConfig('main_url')."/encyclopedia/$row->{name}.html";
		my $title = $row->{'title'};
		my $desc = getLaTeXSynopsis($row->{'data'}, 'ascii');

		# make this a reasonable length
		if (length($desc) > 256) {
			$desc = substr($desc, 0, 256)." ...";
		}

		# literal quotes can break Data::Denter?
		$title =~ s/"/"/g;
		$desc =~ s/"/"/g;

		push @$daylist, {title => $title, url  => $url, description => $desc, author => $row->{'username'}, timestamp => $row->{'unixtime'} };
	}

	# return a ref to the statistics
	return [@daystruct];
}

# pass-throughs to call the above for either modifications or additions
#
sub getLatestAdditions_data {
	return getLatestEntry_data('additions');
}
sub getLatestModifications_data {
	return getLatestEntry_data('modifications');
}
# format and output the data from above for either additions or modifications
#
sub getLatest {
	my $type = shift || 'additions';

	my $limit = getConfig('latest_additions');
	if ($type ne 'additions') {
		$limit = getConfig('latest_revisions');
	}
	my $html = '';

	my $statkey = ($type eq 'additions' ? 'latestadds' : 'latestmods');
	my $latestadds = $stats->get($statkey);

	# TODO : XML/XSLTify this all
	if ( ref ($latestadds) ) {

	my $date = '';
	my $table = '';
	foreach my $daylist (@$latestadds) {
		my ($day) = keys %$daylist;

		$table .= "
";
		$table .= "$day";
		$table .= "
";

		my ($items) = $daylist->{$day};

		foreach my $item (@$items) {

			my $title = $item->{'title'};
			my $url = $item->{'url'};

			$table .= "
";
			$table .= "
";
			$table .= "[ ".mathTitle($title, 'highlight')." ]";
			$table .= "
";
			$table .= "
";
		}
	}

	if ($table) {
		$html .= "
$table";
		$html .= "
";
	}
	} else {
		$html .= "No data.";
	}

	my $title = ($type eq 'additions' ? 'Latest Additions' : 'Latest Revisions');

	return clearBox($title ,$html);
}

# pass-throughs to call the above for either additions or modifications
#
sub getLatestAdditions {
	return getLatest('additions');
}
sub getLatestModifications {
	return getLatest('modifications');
}

1;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Blastenia ochraceoferruginea B. de Lesd.

### Remarks
null


text:
import os
from cuttsum.resources import MultiProcessWorker
from cuttsum.pipeline import DedupedArticlesResource, SentenceFeaturesResource
import cuttsum.judgements
import gzip
import pandas as pd
import numpy as np

class InputStreamResource(MultiProcessWorker):
    def __init__(self):
        #Resource.__init__(self)
        self.dir_ = os.path.join(
            os.getenv(u'TREC_DATA', u'.'), u'input-streams')
        if not os.path.exists(self.dir_):
            os.makedirs(self.dir_)

    def get_path(self, event, corpus, extractor, threshold, delay, topk):
        path = os.path.join(
            self.dir_, corpus.fs_name(), extractor,
            "dedupe-" + str(threshold), "delay-" + str(delay),
            "top-"+str(topk), "{}.tsv.gz".format(event.fs_name()))
        return path

    def get_dataframes(self, event, corpus, extractor,
                       threshold, delay, topk):
        path = self.get_path(
            event, corpus, extractor, threshold, delay, topk)
        if not os.path.exists(path): return []

        with gzip.open(path, "r") as f:
            df = pd.read_csv(f, converters={"nuggets": lambda x: eval(x) if x != "" else set(), "nugget probs": lambda x: eval(x) if x != "" else {},
                                            "lemmas stopped": eval, "stems": eval}, sep="\t")
            stream = [(sid, group)
                      for sid, group in df.groupby("stream id")]
            stream.sort(key=lambda x: x[0])
            return [df.reset_index(drop=True) for sid, df in stream]

    def get_job_units(self, event, corpus, **kwargs):
        thresh = kwargs.get("dedupe-sim-threshold", .8)
        extractor = kwargs.get("extractor", "goose")
        delay = kwargs.get("delay", None)
        topk = kwargs.get("top-k", 20)

        if delay is not None:
            raise Exception("Delay must be None")
        path = self.get_path(
            event, corpus, extractor, thresh, delay, topk)
        if not os.path.exists(path): return [0]

        return []

    def do_job_unit(self, event, corpus, unit, **kwargs):

        if unit != 0:
            raise Exception("Job unit {} out of range".format(unit))

        thresh = kwargs.get("dedupe-sim-threshold", .8)
        extractor = kwargs.get("extractor", "goose")
        delay = kwargs.get("delay", None)
        topk = kwargs.get("top-k", 20)

        if delay is not None:
            raise Exception("Delay must be None")

        feats_df = SentenceFeaturesResource().get_dataframe(
            event, corpus, extractor, thresh)
        ded_articles_res = DedupedArticlesResource()
        dfiter = ded_articles_res.dataframe_iter(
            event, corpus, extractor, None, thresh)

        all_matches = cuttsum.judgements.get_merged_dataframe()
        matches = all_matches[all_matches["query id"] == event.query_id]

        from cuttsum.classifiers import NuggetClassifier
        classify_nuggets = NuggetClassifier().get_classifier(event)
        eval_corpus = False
        if event.query_id.startswith("TS13"):
            judged = cuttsum.judgements.get_2013_updates()
            judged = judged[judged["query id"] == event.query_id]
            judged_uids = set(judged["update id"].tolist())
        elif event.query_id.startswith("TS14"):
            judged = cuttsum.judgements.get_2014_sampled_updates()
            judged = judged[judged["query id"] == event.query_id]
            judged_uids = set(judged["update id"].tolist())

        elif event.query_id.startswith("TS15"):
            judged = cuttsum.judgements.get_2015_sampled_updates()
            judged = judged[judged["query id"] == event.query_id]
            judged_uids = set(judged["update id"].tolist())
        else:
            raise Exception("Bad corpus!")

        if eval_corpus is False:
            feats_df["nuggets"] = feats_df["update id"].apply(
                lambda x: set(
                    matches[matches["update id"] == x]["nugget id"].tolist()))
            feats_df["n conf"] = feats_df["update id"].apply(lambda x: 1 if x in judged_uids else None)

                #if include_matches == "soft":
                    ### NOTE BENE: geting an array of indices to index unjudged
                    # sentences so I can force pandas to return a view and not a
                    # copy.
            I = np.where(
                feats_df["update id"].apply(lambda x: x not in judged_uids))[0]

            unjudged = feats_df[
                feats_df["update id"].apply(lambda x: x not in judged_uids)]
            #unjudged_sents = unjudged["sent text"].tolist()
            #assert len(unjudged_sents) == I.shape[0]
            feats_df["nugget probs"] = [dict() for x in xrange(len(feats_df))]
            if I.shape[0] > 0:
                nuggets, conf, nugget_probs = classify_nuggets(unjudged)
                feats_df.loc[I, "nuggets"] = nuggets
                feats_df.loc[I, "n conf"] = conf
                feats_df.loc[I, "nugget probs"] = nugget_probs
        else:
            feats_df["nuggets"] = None
            feats_df["n conf"] = None
            feats_df["nugget probs"] = None

        path = self.get_path(event, corpus, extractor, thresh, delay, topk)
        dirname = os.path.dirname(path)
        if not os.path.exists(dirname): os.makedirs(dirname)

        cols = ["update id", "stream id", "sent id", "timestamp",
                "sent text",]
        nugget_cols = ["nuggets", "n conf", "nugget probs"]

        ling_cols = [
            "pretty text", "tokens", "lemmas", "stems", "pos", "ne", "tokens stopped",
            "lemmas stopped"]

        basic_cols = ["BASIC length", "BASIC char length",
            "BASIC doc position", "BASIC all caps ratio",
            "BASIC upper ratio", "BASIC lower ratio",
            "BASIC punc ratio", "BASIC person ratio",
            "BASIC location ratio",
            "BASIC organization ratio", "BASIC date ratio",
            "BASIC time ratio", "BASIC duration ratio",
            "BASIC number ratio", "BASIC ordinal ratio",
            "BASIC percent ratio", "BASIC money ratio",
            "BASIC set ratio", "BASIC misc ratio"]

        lm_cols = ["LM domain lp", "LM domain avg lp",
                   "LM gw lp", "LM gw avg lp"]

        query_cols = [
            "Q_query_sent_cov",
            "Q_sent_query_cov",
            "Q_syn_sent_cov",
            "Q_sent_syn_cov",
            "Q_hyper_sent_cov",
            "Q_sent_hyper_cov",
            "Q_hypo_sent_cov",
            "Q_sent_hypo_cov",
        ]

        sum_cols = [
            "SUM_sbasic_sum",
            "SUM_sbasic_amean",
            "SUM_sbasic_max",
            "SUM_novelty_gmean",
            "SUM_novelty_amean",
            "SUM_novelty_max",
            "SUM_centrality",
            "SUM_pagerank",
            "SUM_sem_novelty_gmean",
            "SUM_sem_novelty_amean",
            "SUM_sem_novelty_max",
            "SUM_sem_centrality",
            "SUM_sem_pagerank",

        ]

        stream_cols = [
            "STREAM_sbasic_sum",
            "STREAM_sbasic_amean",
            "STREAM_sbasic_max",
            "STREAM_per_prob_sum",
            "STREAM_per_prob_max",
            "STREAM_per_prob_amean",
            "STREAM_loc_prob_sum",
            "STREAM_loc_prob_max",
            "STREAM_loc_prob_amean",
            "STREAM_org_prob_sum",
            "STREAM_org_prob_max",
            "STREAM_org_prob_amean",
            "STREAM_nt_prob_sum",
            "STREAM_nt_prob_max",
            "STREAM_nt_prob_amean",
        ]

        output_cols = cols + nugget_cols + ling_cols + basic_cols + lm_cols + query_cols + sum_cols + stream_cols

        with gzip.open(path, "w") as f:
            f.write("\t".join(output_cols) + "\n")
            for df in dfiter:
                df = df.head(topk)
                df["sent text"] = df["sent text"].apply(lambda x: x.encode("utf-8"))
                merged = pd.merge(
                    df[cols],
                    feats_df,
                    on=["update id", "stream id", "sent id", "timestamp"])
                if len(merged) == 0:
                    print "Warning empty merge"

                merged[output_cols].to_csv(f, index=False, header=False, sep="\t")


text:
layout: post
subheadline:
title: "Unveiling the Carpentries Logo"
teaser:
header:
    image_fullwidth: "light-blue-wood-texture.jpg"
categories:
    - blog
comments: true
show_meta: true
authors: ["Belinda Weaver"]
redirect_from: /blog/new-carpentries-logo/
---

Now that Software and Data Carpentry have merged, we wanted a new logo to celebrate our coming together as the Carpentries,
and to give that project its own distinct identity.

![So ... here is our new logo!](/images/TheCarpentries.png)

The new logo retains a 'Carpentry' feel - at the basic level, it represents a wrench around a hexagonal bolt.
Yet it also conveys a sense of exhilaration and celebration - that magic moment when you 'get' something and your arms
shoot up in celebration. There are many such 'aha!' moments in Carpentries' workshops, so it is fitting that our logo
represent not just the hard work of learning (the wrench) but the satisfaction of achievement and mastery that
we gain (the 'Yay!').

### The same, but different

While we have a new logo, and one that we like very much, as far as our community goes, much of what we do will seem unchanged.

As The Carpentries, we will continue to teach foundational computational and data skills to researchers.
We will continue to observe and evolve our [Code of Conduct](https://software-carpentry.org/conduct/).
We will continue to grow our memberships,
and we will continue to mint new instructors through our [Instructor Training program](http://carpentries.github.io/instructor-training/).

The individual 'Carpentries' will remain as distinct lesson organizations, and we plan to communicate more as the year
goes on about how these projects are evolving. The Software and Data Carpentry logos will remain the same,
with The Carpentries an umbrella under which they come together.

Some things *are* different. Tracy Teal is now our [Executive Director](http://www.datacarpentry.org/blog/exec-dir-message/), our two staffs have merged with some reshuffling
of roles, and we are working as The Carpentries
with a [new fiscal sponsor](https://software-carpentry.org/blog/2018/01/fiscal-sponsor-transition.html),
[Community Initiatives](https://software-carpentry.org/blog/2018/01/fiscal-sponsor-transition.html). Our governance has
merged - from having two separate Steering Committees, we now have a brand new [Executive Council](http://www.datacarpentry.org/blog/exec-council-announce/).

These changes should only enhance what we do by streamlining communications and making our working practices more
efficient. We will still support the growth and spread of our community - that will never change.

[CarpentryCon 2018](http://www.carpentrycon.org/) in Dublin will be a celebration of just how far we have come as a
community. We hope to see you there.

Keep an eye out for our new website soon!


text:
package com.jimandreas.aarch.popm.db;

import android.arch.persistence.room.TypeConverter;
import android.arch.persistence.room.util.StringUtil;

import java.util.Collections;
import java.util.List;

public class GithubTypeConverters {
    @TypeConverter
    public static List<Integer> stringToIntList(String data) {
        if (data == null) {
            return Collections.emptyList();
        }
        return StringUtil.splitToIntList(data);
    }

    @TypeConverter
    public static String intListToString(List<Integer> ints) {
        return StringUtil.joinIntoString(ints);
    }
}


text:
package com.team687.frc2017.commands;

import com.team687.frc2017.Robot;
import com.team687.frc2017.utilities.PGains;

import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 * An arc turn that drift turns to an angle near the end of a specified
 * distance. Similar to the logic behind 973's hopper auto controller. Loop is
 * closed on heading but not on straight power.
 *
 * @author tedlin
 *
 */

public class DriftTurnToAngle extends Command {

    private double m_straightPower;
    private double m_desiredAngle;
    private double m_distance;
    private boolean m_isHighGear;
    private PGains m_rotPGains;

    /**
     * @param straightPower
     * @param angle
     * @param distance
     *            (absolute value)
     * @param isHighGear
     * @param kRotP
     */
    public DriftTurnToAngle(double straightPower, double angle, double distance, boolean isHighGear, double kRotP) {
	m_straightPower = straightPower;
	m_desiredAngle = angle;
	m_distance = distance;
	m_isHighGear = isHighGear;
	m_rotPGains.setP(kRotP);

	requires(Robot.drive);
    }

    @Override
    protected void initialize() {
	SmartDashboard.putString("Current Command", "DriftTurnToAngle");

	if (m_isHighGear) {
	    Robot.drive.shiftUp();
	} else if (!m_isHighGear) {
	    Robot.drive.shiftDown();
	}
    }

    @Override
    protected void execute() {
	double doneness = Math.abs(Robot.drive.getDrivetrainPosition() / m_distance);
	// doneness = Math.sqrt(doneness); // this makes the arc turn more gradual

	double robotAngle = (360 - Robot.drive.getCurrentYaw()) % 360;
	double rotError = -m_desiredAngle - robotAngle;
	rotError = (rotError > 180) ? rotError - 360 : rotError;
	rotError = (rotError < -180) ? rotError + 360 : rotError;
	double rotPower = m_rotPGains.getP() * rotError * doneness;

	Robot.drive.setPower(rotPower + m_straightPower, rotPower - m_straightPower);
    }

    @Override
    protected boolean isFinished() {
	return Math.abs(Robot.drive.getDrivetrainPosition()) >= m_distance;
    }

    @Override
    protected void end() {
	Robot.drive.stopDrive();
    }

    @Override
    protected void interrupted() {
	end();
    }

}


text:
import test from 'ava';
import parse from '@commitlint/parse';
import scopeEmpty from './scope-empty';

const messages = {
	plain: 'foo(bar): baz',
	superfluous: 'foo(): baz',
	empty: 'foo: baz'
};

const parsed = {
	plain: parse(messages.plain),
	superfluous: parse(messages.superfluous),
	empty: parse(messages.empty)
};

test('with plain message it should succeed for empty keyword', async t => {
	const [actual] = scopeEmpty(await parsed.plain);
	const expected = true;
	t.deepEqual(actual, expected);
});

test('with plain message it should succeed for "never"', async t => {
	const [actual] = scopeEmpty(await parsed.plain, 'never');
	const expected = true;
	t.deepEqual(actual, expected);
});

test('with plain message it should fail for "always"', async t => {
	const [actual] = scopeEmpty(await parsed.plain, 'always');
	const expected = false;
	t.deepEqual(actual, expected);
});

test('with superfluous message it should fail for empty keyword', async t => {
	const [actual] = scopeEmpty(await parsed.superfluous);
	const expected = false;
	t.deepEqual(actual, expected);
});

test('with superfluous message it should fail for "never"', async t => {
	const [actual] = scopeEmpty(await parsed.superfluous, 'never');
	const expected = false;
	t.deepEqual(actual, expected);
});

test('with superfluous message it should fail for "always"', async t => {
	const [actual] = scopeEmpty(await parsed.superfluous, 'always');
	const expected = true;
	t.deepEqual(actual, expected);
});

test('with empty message it should fail for empty keyword', async t => {
	const [actual] = scopeEmpty(await parsed.empty);
	const expected = false;
	t.deepEqual(actual, expected);
});

test('with empty message it should fail for "never"', async t => {
	const [actual] = scopeEmpty(await parsed.empty, 'never');
	const expected = false;
	t.deepEqual(actual, expected);
});

test('with empty message it should fail for "always"', async t => {
	const [actual] = scopeEmpty(await parsed.empty, 'always');
	const expected = true;
	t.deepEqual(actual, expected);
});


text:
<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * e.g., it puts together the home page when no home.php file exists.
 *
 * Learn more: {@link https://codex.wordpress.org/Template_Hierarchy}
 *
 * @category TacticalWP-Theme
 * @package TacticalWP
 * @author Tyler Kemme <dev@tylerkemme.com>
 * @license MIT https://opensource.org/licenses/MIT
 * @version 1.0.4
 * @link https://github.com/tpkemme/tacticalwp-theme
 * @since 1.0.0
 */

get_header(); ?>

    <?php if (have_posts() ) : ?>

    <?php ;/* Start the Loop */ ?>
    <?php
    while ( have_posts() ) :
the_post();
?>
    <?php get_template_part('template-parts/content', get_post_format()); ?>
    <?php endwhile; ?>

    <?php else : ?>
    <?php get_template_part('template-parts/content', 'none'); ?>

    <?php
			// End have_posts() check.
			endif;
            ?>

    <?php ;/* Display navigation to next/previous pages when applicable */ ?>
    <?php
    if (function_exists('twp_pagination') ) :
        twp_pagination();
        elseif (is_paged() ) :
    ?>

<?php next_posts_link(__('← Older posts', 'twp')); ?>

<?php previous_posts_link(__('Newer posts →', 'twp')); ?>

        <?php endif; ?>

    <?php get_sidebar(); ?>

<?php
get_footer();


text:
namespace chromeos {

// A stub implementation of ShillIPConfigClient.
class ShillIPConfigClientStub : public ShillIPConfigClient {
 public:
  ShillIPConfigClientStub();
  virtual ~ShillIPConfigClientStub();

  // ShillIPConfigClient overrides:
  virtual void AddPropertyChangedObserver(
      const dbus::ObjectPath& ipconfig_path,
      ShillPropertyChangedObserver* observer) OVERRIDE;
  virtual void RemovePropertyChangedObserver(
      const dbus::ObjectPath& ipconfig_path,
      ShillPropertyChangedObserver* observer) OVERRIDE;
  virtual void Refresh(const dbus::ObjectPath& ipconfig_path,
                       const VoidDBusMethodCallback& callback) OVERRIDE;
  virtual void GetProperties(const dbus::ObjectPath& ipconfig_path,
                             const DictionaryValueCallback& callback) OVERRIDE;
  virtual base::DictionaryValue* CallGetPropertiesAndBlock(
      const dbus::ObjectPath& ipconfig_path) OVERRIDE;
  virtual void SetProperty(const dbus::ObjectPath& ipconfig_path,
                           const std::string& name,
                           const base::Value& value,
                           const VoidDBusMethodCallback& callback) OVERRIDE;
  virtual void ClearProperty(const dbus::ObjectPath& ipconfig_path,
                             const std::string& name,
                             const VoidDBusMethodCallback& callback) OVERRIDE;
  virtual void Remove(const dbus::ObjectPath& ipconfig_path,
                      const VoidDBusMethodCallback& callback) OVERRIDE;

 private:
  // Runs callback with |values|.
  void PassProperties(const base::DictionaryValue* values,
                      const DictionaryValueCallback& callback) const;

  // Dictionary of <ipconfig_path, property dictionaries>
  base::DictionaryValue ipconfigs_;

  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<ShillIPConfigClientStub> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(ShillIPConfigClientStub);
};

}  // namespace chromeos

#endif  // CHROMEOS_DBUS_SHILL_IPCONFIG_CLIENT_STUB_H_


text:
class Api::AssessmentResultsController < Api::ApiController

  # TODO Might have to cheat and make this a index or show so we can use a GET request to record the data. This will avoid cross origin issues.
  def create
    rendered_time, referer, user = tracking_info
    assessment_result = user.assessment_results.create!(
      assessment_id: params[:assessment_id],
      eid: params[:eid],
      src_url: params[:src_url],
      external_user_id: params[:external_user_id],
      identifier: params['identifier'],
      rendered_datestamp: rendered_time,
      referer: referer,
      ip_address: request.ip,
      session_status: 'initial')

    assessment_result.keyword_list.add(params[:keywords], parse: true) if params[:keywords]
    assessment_result.objective_list.add(params[:objectives], parse: true) if params[:objectives]
    assessment_result.save! if params[:objectives] || params[:keywords]
    respond_with(:api, assessment_result)
  end

end


text:
import utils from './utils'

export function uploadImg(params) {
  return utils.postView('upload/image/', params)
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Security-Policy" content="connect-src 'self'; script-src 'self' 'unsafe-inline';">
    <title>connect-src-websocket-blocked</title>


text:
package org.jetbrains.plugins.scala.findUsages.factory

import java.lang.reflect.Method
import java.net.URL

import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.CompilerModuleExtension
import com.intellij.psi.{PsiElement, PsiManager}
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil
import org.jetbrains.plugins.scala.lang.psi.api.expr._
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScNamedElement
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory.createExpressionFromText
import org.jetbrains.plugins.scala.lang.refactoring.rename.RenameSuperMembersUtil.allSuperMembers

import scala.reflect.internal.util.ScalaClassLoader.URLClassLoader

sealed trait SugarType {}
object ImplicitConversion extends SugarType {}
object ImplicitParameter  extends SugarType {}
object TypeParameter      extends SugarType {}

// Hopefully some day semantic.Database#sugars will provide this information
object SugarType {
  def apply(sugar: String): SugarType =
    if (sugar.startsWith("("))
      ImplicitParameter
    else if (sugar.startsWith("["))
      TypeParameter
    else
      ImplicitConversion
}

case class SemanticDbInterop(project: Project) {
  private def usageToElement(filePath: String, offset: Int, value: String): PsiElement = {
    val virtualFile = project.getBaseDir.findFileByRelativePath(filePath)
    val file        = inReadAction(PsiManager.getInstance(project).findFile(virtualFile))
    val properOffset = SugarType(value) match {
      case ImplicitConversion => offset
      case _                  => offset - 1
    }
    val elem         = file.findElementAt(properOffset)
    val parentMethod = inReadAction(ScalaPsiUtil.getParentOfType(elem, classOf[ScMethodCall], classOf[ScGenericCall]))
    parentMethod match {
      case null => elem
      case mc   => mc
    }
  }

  private val classpath: Array[String] = ModuleManager
    .getInstance(project)
    .getModules
    .map(module => new URL(CompilerModuleExtension.getInstance(module).getCompilerOutputUrl).getPath)

  private val sourcepath: String = project.getBasePath

  def findImplicitUsages(target: ScNamedElement): Seq[PsiElement] = {
    def elemMatches(elem: PsiElement): Boolean =
      elem match {
        case ne: ScNamedElement        => elemMatches(ne) || allSuperMembers(ne, withSelfType = false).exists(elemMatches(_))
        case re: ScReferenceExpression => inReadAction(re.resolve.getNavigationElement) == target
        case mc: ScMethodCall          => elemMatches(mc.getInvokedExpr) || mc.argumentExpressions.exists(elemMatches)
        case gc: ScGenericCall         => elemMatches(gc.referencedExpr)
        case _                         => false
      }

    SemanticDbInterop.findUsages
      .invoke(
        SemanticDbInterop.instance,
        inReadAction(target.getName),
        classpath,
        sourcepath
      )
      .asInstanceOf[Array[Array[AnyRef]]]
      .flatMap {
        case Array(path: String, offset: Integer, sugar: String) =>
          val usageElement = usageToElement(path, offset, sugar)
          val matches = SugarType(sugar) match {
            case TypeParameter => false
            case _ =>
              val expr = inReadAction(createExpressionFromText(sugar.replace(".this.", "."), usageElement))
              expr match {
                case par: ScParenthesisedExpr => par.expr.exists(elemMatches(_))
                case tpl: ScTuple             => tpl.exprs.exists(elemMatches(_))
                case _                        => elemMatches(expr)
              }
          }
          if (matches) Some(usageElement)
          else None
      }
  }
}

object SemanticDbInterop {
  private[this] val pluginCP = new URL(
    getClass
      .getResource(".")
      .toString
      .replaceAll("^jar:", "")
      .replaceAll("!/.+$", "")
      .replaceAll(getClass.getPackage.getName.replace(".", "/") + "/$", "")
      .replaceAll("/[^/]*$", "")
  )

  private[this] val clazz: Class[_] = new URLClassLoader(
    Seq(
      new URL(s"$pluginCP/scalameta120.jar"),
      new URL(s"$pluginCP/scala-library.jar"),
      new URL(s"$pluginCP/scala-plugin.jar"),
      new URL(s"$pluginCP/isolated/scalapb-runtime.jar"),
      new URL(s"$pluginCP/isolated/protobuf-java.jar"),
      new URL(s"$pluginCP/isolated/lenses.jar")
    ),
    null
  ).loadClass(SemanticDbUsagesProvider.getClass.getName)

  private val instance: AnyRef = clazz.getField("MODULE$").get(null)

  private val findUsages: Method = clazz.getDeclaredMethod(
    "findUsages",
    classOf[String],
    classOf[Array[String]],
    classOf[String]
  )
}


text:
class AccountPresenter < SimplePresenter
  def export_data
    data = {
      :uri => account_path(self),
      :name => name,
      :type => account_type.name,
      :position => position,
      :currency => currency.name,
      :status => Constants::Status.string_for(status).downcase
    }
    if balance
      data.update(
        :balance => {
          :display => Money.new(balance, currency).to_s,
          :value => balance
        },
        :last_balance_at => last_balance && last_balance.created_at)
    end

    return data
  end

  def to_json
    export_data.to_json
  end
end


text:
package me.curlpipesh.pipe.gui.api.model.base.controls;

import me.curlpipesh.pipe.gui.api.controller.registry.TagRegistry;
import me.curlpipesh.pipe.gui.api.controller.registry.Taggable;
import me.curlpipesh.pipe.gui.api.model.Area;
import me.curlpipesh.pipe.gui.api.model.base.controls.interfaces.IControl;
import lombok.Getter;
import lombok.Setter;
import me.curlpipesh.pipe.gui.api.view.layout.ILayout;

/**
 * The basic implementation of
 * {@link IControl}. Whilst
 * this class in and of itself is not very complicated, it allows for the basic
 * specifications laid down by {@code IControl} to be fulfilled completely;
 * this is accomplished through extension of
 * {@link Taggable}, which
 * allows for easy tag management.
 *
 * @author c
 * @since 08.19.2014
 */
public class Control extends Taggable implements IControl {
    /**
     * The area that this control takes up. A {@code Control}'s
     * {@link Area} is determined by the
     * container itself, as
     * {@link ILayout}s are only
     * meant to be used to control sizes/positions of a container's child
     * widgets, not the controls. Note that this area must always be set prior
     * to the container it is attached to is used, else a
     * {@link java.lang.NullPointerException} will be thrown (for obvious
     * reasons).
     *
     * TODO Make layouts control control locations (Sideways windows? :O)?
     * TODO This would require messing with how the window resizes, though.
     * TODO Should do?
     */
    @Getter
    @Setter
    private Area area;

    /**
     * Creates a new {@code Control} with the given type. The type is first
     * validated by
     * {@link TagRegistry},
     * so any invalid type(s) being passed in here will likely cause the
     * program to crash through a {@link java.lang.IllegalArgumentException}
     * being thrown.
     *
     * @param type The type of the control. Can be either "close," "pin," or
     *             "minimize."
     */
    public Control(String type) {
        if(!TagRegistry.validateTagValue("control-type", type)) {
            throw new IllegalArgumentException(String.format("%s is an invalid control type!", type));
        }
        // Probably shouldn't be doing this in the constructor, but meh.
        addTag("control-type", type);
        setState(false);
        setArea(new Area(0, 0, 0, 0));
    }

    @Override
    public boolean getState() {
        return Boolean.parseBoolean(getTagValue("state"));
    }

    @Override
    public void setState(String state) {
        if(getTags().containsKey("state")) {
            editTag("state", state);
        } else {
            addTag("state", state);
        }
    }

    @Override
    public void setState(boolean state) {
        setState(Boolean.toString(state));
    }

    @Override
    public String toString() {
        return String.format("control[\"type: %s\", \"state: %s\"]", getTagValue("control-type"), getTagValue("state"));
    }

    @Override
    public String getType() {
        return getTagValue("control-type");
    }
}


text:
package resolve

import (
	"github.com/spf13/cast"
	"mynewt.apache.org/newt/newt/parse"
	"mynewt.apache.org/newt/newt/ycfg"
	"mynewt.apache.org/newt/util"
)

func getExprMapStringSlice(
	yc ycfg.YCfg, key string, settings map[string]string) (
	map[*parse.Node][]string, string, error) {

	var warning string

	entries, getErr := yc.GetSlice(key, settings)
	if getErr != nil {
		warning = getErr.Error()
	}

	if len(entries) == 0 {
		return nil, warning, nil
	}

	m := make(map[*parse.Node][]string, len(entries))
	for _, e := range entries {
		slice, err := cast.ToStringSliceE(e.Value)
		if err != nil {
			return nil, warning, util.FmtNewtError(
				"ycfg node \"%s\" contains unexpected type; "+
					"have=%T want=[]string", e.Value)
		}

		m[e.Expr] = append(m[e.Expr], slice...)
	}

	return m, warning, nil
}

func revExprMapStringSlice(
	ems map[*parse.Node][]string) map[string][]*parse.Node {

	m := map[string][]*parse.Node{}

	for expr, vals := range ems {
		for _, val := range vals {
			m[val] = append(m[val], expr)
		}
	}

	return m
}

func readExprMap(yc ycfg.YCfg, key string, settings map[string]string) (
	parse.ExprMap, string, error) {

	ems, warning, err := getExprMapStringSlice(yc, key, settings)
	if err != nil {
		return nil, warning, err
	}

	em := parse.ExprMap{}

	rev := revExprMapStringSlice(ems)
	for v, exprs := range rev {
		sub := parse.ExprSet{}
		for _, expr := range exprs {
			sub[expr.String()] = expr
		}
		em[v] = sub
	}

	return em, warning, nil
}