text:
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using Moq;
using NUnit.Framework;
using Saltarelle.Compiler.Compiler;
using Saltarelle.Compiler.JSModel.Expressions;
using Saltarelle.Compiler.ScriptSemantics;

namespace Saltarelle.Compiler.Tests.CompilerTests.MethodCompilation {
	[TestFixture]
	public class InlineCodeMethodCompilerTests : MethodCompilerTestBase {
		[Test]
		public void TheTokenizerWorks() {
			Compile("class C { public static void F(int ab, int c) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "X{ab}{{y}z}}Y{{{c}}}T", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] {
			                new InlineCodeToken(InlineCodeToken.TokenType.Text, "X"),
			                new InlineCodeToken(InlineCodeToken.TokenType.Parameter, index: 0),
			                new InlineCodeToken(InlineCodeToken.TokenType.Text, "{y}z}Y{"),
			                new InlineCodeToken(InlineCodeToken.TokenType.Parameter, index: 1),
			                new InlineCodeToken(InlineCodeToken.TokenType.Text, "}T"),
			            }));

			string msg = null;
			InlineCodeMethodCompiler.Tokenize(method, "Something {abcd", s => msg = s);
			Assert.That(msg, Is.StringContaining("'}'"));

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "X{}Y", s => Assert.Fail("Unexpected error " + s)), Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.Text, "X{}Y") }));
		}

		[Test]
		public void TokenizerCanDetectTypeReferences() {
			Compile("class C { public static void F() {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{$System.Type}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.TypeRef, "System.Type") }));
		}

		[Test]
		public void InvalidTypeNameIsReportedAsAnError() {
			Compile("class C { public static void F() {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			string msg = null;
			InlineCodeMethodCompiler.Tokenize(method, "{$Some[]-bad|type}", s => msg = s);
			Assert.That(msg, Is.StringContaining("Some[]-bad|type"));
		}

		[Test]
		public void TokenizerCanDetectThis() {
			Compile("class C { public static void F() {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{this}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.This) }));
		}

		[Test]
		public void TokenizerCanDetectParameterNames() {
			Compile("class C { public static void F(int p1, int p2) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{p1}{p2}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.Parameter, index: 0), new InlineCodeToken(InlineCodeToken.TokenType.Parameter, index: 1) }));
		}

		[Test]
		public void TokenizerCanDetectParameterNamePreceededByAtSign() {
			Compile("class C { public static void F(int @p1) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{p1}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.Parameter, index: 0) }));
		}

		[Test]
		public void TokenizerCanDetectLiteralStringParameterToUseAsIdentifier() {
			Compile("class C { public static void F(string p1, string p2) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{@p1}{@p2}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.LiteralStringParameterToUseAsIdentifier, index: 0), new InlineCodeToken(InlineCodeToken.TokenType.LiteralStringParameterToUseAsIdentifier, index: 1) }));
		}

		[Test]
		public void TokenizerCanDetectExpandedParamArrayParameter() {
			Compile("class C { public static void F(params string[] p1) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{*p1}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.Parameter, index: 0, isExpandedParamArray: true) }));
		}

		[Test]
		public void TokenizerCanDetectTypeTypeParameters() {
			Compile("class C<T1, T2> { public static void F(params string[] p1) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{T1}{T2}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.TypeParameter, index: 0, ownerType: SymbolKind.TypeDefinition), new InlineCodeToken(InlineCodeToken.TokenType.TypeParameter, index: 1, ownerType: SymbolKind.TypeDefinition) }));
		}

		[Test]
		public void TokenizerCanDetectMethodTypeParameters() {
			Compile("class C { public static void F<T1, T2>(params string[] p1) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{T1}{T2}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.TypeParameter, index: 0, ownerType: SymbolKind.Method), new InlineCodeToken(InlineCodeToken.TokenType.TypeParameter, index: 1, ownerType: SymbolKind.Method) }));
		}

		[Test]
		public void TokenizerCanDetectTypeParameterNamePreceededByAtSign() {
			Compile("class C<@T1> { public static void F<@T2>(params string[] p1) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.Tokenize(method, "{T1}{T2}", s => Assert.Fail("Unexpected error " + s)),
			            Is.EqualTo(new[] { new InlineCodeToken(InlineCodeToken.TokenType.TypeParameter, index: 0, ownerType: SymbolKind.TypeDefinition), new InlineCodeToken(InlineCodeToken.TokenType.TypeParameter, index: 0, ownerType: SymbolKind.Method) }));
		}

		[Test]
		public void UsingTextWithBracesInLiteralCodeWorks() {
			AssertCorrect(
@"public object F(int arg1, string arg2) {}
public void M() {
	// BEGIN
	F(45, ""test"");
	// END
}",
@"	({});
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{{ }}") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void UsingParametersFromLiteralCodeWorks() {
			AssertCorrect(
@"public object F(int arg1, string arg2) { return null; }
public void M() {
	// BEGIN
	F(45, ""test"");
	// END
}",
@"	({ item1: 45, item2: 'test' });
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{{ item1: {arg1}, item2: {arg2} }}") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void UsingThisInInlineCodeForInstanceMethodWorks() {
			AssertCorrect(
@"class C1 { public void F() {} }
public void M() {
	var c = new C1();
	// BEGIN
	c.F();
	// END
}",
@"	[$c];
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("[ {this} ]") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void UsingMethodTypeArgumentsFromLiteralCodeWorks() {
			AssertCorrect(
@"public object F<T1, T2>(T1 arg1, T2 arg2) { return null; }
public void M() {
	// BEGIN
	F(45, ""test"");
	// END
}",
@"	({ item1: {ga_Int32}, item2: {ga_String} });
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{{ item1: {T1}, item2: {T2} }}") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void UsingTypeTypeArgumentsFromLiteralCodeWorks() {
			AssertCorrect(
@"class C1<T1> {
	public class C2<T2> {
		public object F() {
		}
	}
}

public void M() {
	var c = new C1<int>.C2<string>();
	// BEGIN
	c.F();
	// END
}",
@"	({ item1: {ga_Int32}, item2: {ga_String} });
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{{ item1: {T1}, item2: {T2} }}") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void UsingTypeReferenceFromLiteralCodeWorks() {
			AssertCorrect(
@"public void F() {}
public void M() {
	// BEGIN
	F();
	// END
}",
@"	[{sm_String}, {sm_Int32}];
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("[ {$System.String}, {$System.Int32} ]") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void UsingLiteralStringParameterToUseAsIdentifierFromLiteralCodeWorks() {
			AssertCorrect(
@"public void F(string s) {}
public void M() {
	// BEGIN
	F(""X"");
	// END
}",
@"	invoke_X;
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("invoke_{@s}") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void InvokingMethodThatExpectsLiteralStringWithSomethingElseIsAnError() {
			var er = new MockErrorReporter(false);
			Compile(new[] {
@"class C {
	public void F(string myParameter) {}
	public void M() {
		string s = ""X"";
		// BEGIN
		F(s);
		// END
	}
}" }, metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("invoke_{@myParameter}") : MethodScriptSemantics.NormalMethod(m.Name) }, errorReporter: er);

			Assert.That(er.AllMessages.Count, Is.EqualTo(1));
			Assert.That(er.AllMessages.Any(m => m.FormattedMessage.Contains("myParameter") && m.FormattedMessage.Contains("literal string")));
		}

		[Test]
		public void InvokingMethodWithExpandedParamArrayWorksForFunctionCalls() {
			AssertCorrect(
@"public void F(string p1, int p2, params string[] p3) {}
public void M() {
	// BEGIN
	F(""x"", 4);
	F(""x"", 4, ""y"");
	F(""x"", 4, ""y"", ""z"");
	// END
}",
@"	'x' * 4();
	'x' * 4('y');
	'x' * 4('y', 'z');
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{p1}*{p2}({*p3})") : MethodScriptSemantics.NormalMethod(m.Name) });

			AssertCorrect(
@"public void F(string p1, int p2, params string[] p3) {}
public void M() {
	// BEGIN
	F(""x"", 4);
	F(""x"", 4, ""y"");
	F(""x"", 4, ""y"", ""z"");
	// END
}",
@"	'x' * 4(A);
	'x' * 4(A, 'y');
	'x' * 4(A, 'y', 'z');
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{p1}*{p2}(A, {*p3})") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void InvokingMethodWithExpandedParamArrayWorksForNewExpressions() {
			AssertCorrect(
@"public void F(string p1, int p2, params string[] p3) {}
public void M() {
	// BEGIN
	F(""x"", 4);
	F(""x"", 4, ""y"");
	F(""x"", 4, ""y"", ""z"");
	// END
}",
@"	'x' * new 4();
	'x' * new 4('y');
	'x' * new 4('y', 'z');
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{p1}* new {p2}({*p3})") : MethodScriptSemantics.NormalMethod(m.Name) });

			AssertCorrect(
@"public void F(string p1, int p2, params string[] p3) {}
public void M() {
	// BEGIN
	F(""x"", 4);
	F(""x"", 4, ""y"");
	F(""x"", 4, ""y"", ""z"");
	// END
}",
@"	'x' * new 4(A);
	'x' * new 4(A, 'y');
	'x' * new 4(A, 'y', 'z');
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{p1}* new {p2}(A, {*p3})") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void InvokingMethodWithExpandedParamArrayWorksForArrayLiterals() {
			AssertCorrect(
@"public void F(string p1, int p2, params string[] p3) {}
public void M() {
	// BEGIN
	F(""x"", 4);
	F(""x"", 4, ""y"");
	F(""x"", 4, ""y"", ""z"");
	// END
}",
@"	'x' * 4 + [];
	'x' * 4 + ['y'];
	'x' * 4 + ['y', 'z'];
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{p1}*{p2} + [{*p3}]") : MethodScriptSemantics.NormalMethod(m.Name) });

			AssertCorrect(
@"public void F(string p1, int p2, params string[] p3) {}
public void M() {
	// BEGIN
	F(""x"", 4);
	F(""x"", 4, ""y"");
	F(""x"", 4, ""y"", ""z"");
	// END
}",
@"	'x' * 4 + [A];
	'x' * 4 + [A, 'y'];
	'x' * 4 + [A, 'y', 'z'];
", metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{p1}*{p2} + [A, {*p3}]") : MethodScriptSemantics.NormalMethod(m.Name) });
		}

		[Test]
		public void UsingExpandedParamArrayInOtherContextIsAnError() {
			var er = new MockErrorReporter(false);
			Compile(new[] {
@"class C {
	public void F(string p1, int p2, params string[] p3) {}
	public void M() {
		string[] args = null;
		// BEGIN
		F(""x"", 1, ""y"", ""z"");
		// END
	}
}" }, metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{p1}*{p2} + {*p3}") : MethodScriptSemantics.NormalMethod(m.Name) }, errorReporter: er);

			Assert.That(er.AllMessages.Count, Is.EqualTo(1));
			Assert.That(er.AllMessages.Any(m => m.FormattedMessage.Contains("can only be used")));
		}

		[Test]
		public void InlineCodeWithSyntaxErrorIsAnError() {
			var er = new MockErrorReporter(false);
			Compile(new[] {
@"class C {
	public void F(string p1, int p2, params string[] p3) {}
	public void M() {
		string[] args = null;
		// BEGIN
		F(""x"", 1, ""y"", ""z"");
		// END
	}
}" }, metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{p1}*{p2}+") : MethodScriptSemantics.NormalMethod(m.Name) }, errorReporter: er);

			Assert.That(er.AllMessages.Count, Is.EqualTo(1));
			Assert.That(er.AllMessages.Any(m => m.FormattedMessage.Contains("syntax error")));
		}

		[Test]
		public void ValidateReturnsNoErrosWhenCalledWithAValidString() {
			Compile("class C<T1> { public void F<T2>(string s, int a, params string[] p) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			Assert.That(InlineCodeMethodCompiler.ValidateExpressionLiteralCode(method, "{$System.Object}({T1}, {T2}, {@s}, {this}, {a}, {*p})", n => JsExpression.Null, t => JsExpression.Null), Is.Empty);
		}

		[Test]
		public void ValidateReturnsAnErrorWhenThereIsAFormatStringError() {
			Compile("class C { public void F() {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			var result = InlineCodeMethodCompiler.ValidateExpressionLiteralCode(method, "{abc", n => JsExpression.Null, t => JsExpression.Null);
			Assert.That(result.Count, Is.EqualTo(1));
			Assert.That(result.Any(e => e.Contains("expected '}'")));
		}

		[Test]
		public void ValidateReturnsAnErrorWhenThisIsUsedForAStaticMethod() {
			Compile("class C { public static void F() {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			var result = InlineCodeMethodCompiler.ValidateExpressionLiteralCode(method, "{this}", n => JsExpression.Null, t => JsExpression.Null);
			Assert.That(result.Count, Is.EqualTo(1));
			Assert.That(result.Any(e => e.Contains("{this}") && e.Contains("static")));
		}

		[Test]
		public void ValidateReturnsAnErrorWhenTheAtModifierIsUsedWithAnArgumentThatIsNotAString() {
			Compile("class C { public static void F(int myArg) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			var result = InlineCodeMethodCompiler.ValidateExpressionLiteralCode(method, "{@myArg}", n => JsExpression.Null, t => JsExpression.Null);
			Assert.That(result.Count, Is.EqualTo(1));
			Assert.That(result.Any(e => e.Contains("'@'") && e.Contains("myArg")));
		}

		[Test]
		public void ValidateReturnsAnErrorWhenTheStarModifierIsUsedWithAnArgumentThatIsNotAParamArray() {
			Compile("class C { public static void F(string[] myArg) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			var result = InlineCodeMethodCompiler.ValidateExpressionLiteralCode(method, "{*myArg}", n => JsExpression.Null, t => JsExpression.Null);
			Assert.That(result.Count, Is.EqualTo(1));
			Assert.That(result.Any(e => e.Contains("*") && e.Contains("myArg") && e.Contains("param array")));
		}

		[Test]
		public void ValidateReturnsAnErrorWhenThereIsASyntaxError() {
			Compile("class C { public static void F(string x, int y) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			var result = InlineCodeMethodCompiler.ValidateExpressionLiteralCode(method, "{x} + ", n => JsExpression.Null, t => JsExpression.Null);
			Assert.That(result.Count, Is.EqualTo(1));
			Assert.That(result.Any(e => e.Contains("syntax error")));
		}

		[Test]
		public void ValidateReturnsAnErrorWhenAnExpandedParamArrayIsUsedInAnInvalidContext() {
			Compile("class C { public static void F(string p1, int p2, params string[] p3) {} }");
			var method = FindClass("C").CSharpTypeDefinition.Methods.Single(m => m.Name == "F");

			var result = InlineCodeMethodCompiler.ValidateExpressionLiteralCode(method, "{p1}*{p2} + {*p3}", n => JsExpression.Null, t => JsExpression.Null);
			Assert.That(result.Count, Is.EqualTo(1));
			Assert.That(result.Any(e => e.Contains("can only be used")));
		}

		[Test]
		public void InvokingInlineCodeMethodWithTypeParameterAsTypeArgumentWorks() {
			AssertCorrect(
@"public class C2<T1> {
	public void F<T2>() {}
}
public class C<T3> {
	public void M<T4>() {
		var c = new C2<T3>();
		// BEGIN
		c.F<T4>();
		// END
	}
}",
@"	$T3._($T4);
", addSkeleton: false, metadataImporter: new MockMetadataImporter { GetMethodSemantics = m => m.Name == "F" ? MethodScriptSemantics.InlineCode("{T1}._({T2})") : MethodScriptSemantics.NormalMethod(m.Name) });
		}
	}
}


text:
layout       : blocks/working-session
title        : TM - What can go wrong with Juice Shop?
type         : workshop
track        : Threat Model
technology   :
related-to   : Juice Shop
when-day     : Tue
when-time    : Eve
location     : Villa-4
status       : Improve outcomes; need-working materials
organizers   : Adam Shostack
participants : Dinis Cruz
---

Get together to use the models of Juice Shop to find problems with it, learn threat modelling, and deliver examples.

## Why

Dinis proposed a set of evening sessions to create threat model artefacts & examples for the Juice Shop vulnerable app.

## What

Using the diagrams that show various aspects of Juice Shop (model 1: What's the app?  model 2: How does it get deployed?  Model 3: How is it "developed and maintained"? etc.), apply various techniques to answer the question "what can go wrong?"
Techniques might include brainstorming, STRIDE, top-10, PASTA, CAPEC, attack trees, or your favourite.

## Outcomes

- Lists of attacks checked in
- Possibly sets of requirements or assumptions

## Who

The target audience for this Working Session is:

- Participants in the threat modeling track
- Participants interested in Juice Shop
- Those who want to learn to threat model

---

## Working materials

Here are the current 'work in progress' materials for this session

(please add as much information as possible before the sessions)

### Content

...add content...

redpajama_set_name: RedPajamaGithub


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

<title>Variance-Adjusted Patching for Divergent Texts</title>

Variance-Adjusted Patching for Divergent Texts

Karl Fogel <tt><kfogel@collab.net></tt>

Date of First Publication: 22 May, 2001

$LastChangedDate$

Canonical URL: http://svn.apache.org/repos/asf/subversion/trunk/www/variance-adjusted-patching.html

Version control systems that use traditional context diff / unidiff
format for branch merging tend to fail spuriously in high variance
situations.  A "high variance" situation is one where the branch text
differs from the source text by more than roughly 5-10%, counting
lines changed, deleted, and added against the source.  This appendix
describes a technique called "variance-adjusted patching", by which
such applications can be made to succeed, when a common ancestor of
the source and destination texts is available.

The problem with straight patch application is that it depends on the
affected text hunks and their context not having changed significantly
since source.  They may "float", that is, text may have been inserted
or deleted around them, thus changing their locations in the target
file.  But they themselves may not have changed, except for whitespace
adjustments or other trivial (i.e., automatically ignorable)
modifications.  If they have changed, the patch application will fail.

Variance adjustment is the process of transforming a patch to account
for differences that have arisen in the target text since the patch
was generated, so that the new patch will be applicable to the new
target text and yet still have the "same" effect as the old patch.  It
is, in essence, patching a patch.  For example, suppose a branch B
diverges from a trunk T, and an engineer wants to merge the change
from revision T:18 to T:19 into B:10, creating B:11.  If B:10 is too
dissimilar to T:18, the merge may fail due to textual conflicts, even
though there is no logical conflict.  Variance adjustment is about
changing the diff T:18-T:19 so that it applies cleanly to B:10.

This is possible because for any given line that a patch hunk expects
to see in the target text (e.g., in a context diff, these would be the
context lines, plus the "before" version of affected lines), the
version control system can know that line's history in both source
and target, if there is a common ancestor to examine.  The process is
very similar to the calculations done by "<tt>cvs annotate</tt>".
Informally speaking, one of the following is true for each such line,
ignoring floating due to out-of-bounds insertion and deletion:

The line exists unchanged in both source and target

If the line is still present in target and source, that means it
      has not been removed from either since the common ancestor, or
      if it was removed, it has been restored.  Nothing need be done
      to the diff.

The line has been changed in source but not in target

In the diff hunk, the line should be changed to reflect the
      target's version of the line, so that the diff will be
      applicable to the target.

      When we say that the line "has been changed", it just means
      that a different line appears where this line once appeared.
      Whether this is because the line has been edited, or because a
      new line has been inserted in target, does not matter.  (Another
      way to say it is that it need not matter whether the old version
      of the line still appears somewhere nearby in target.)  The
      important thing is that new text appears where the hunk is
      expecting old text, and that we have a way to change the hunk to
      expect the new text instead.

The line has been changed in target but not in source

Same as above: in the diff hunk, the line should be changed to
      reflect the target's version of the line, so that the diff will
      be applicable to the target.  If this seems counterintuitive,
      drink the Kool-Aid and read again.

The line does not exist in target

This could be for one of two reasons:

the line is new in source, having been added after
               target branched, or

the line was removed from target after the branch
               happened

Either way, the line needs to be changed to the "corresponding"
      line in the target text -- that is, the line that, in target,
      now occupies the place of the obsolete expected line.  The
      version control system has enough information to determine
      which of the two cases above applies, and can use that to
      decide which of the lines currently in target is the best
      candidate to substitute for the missing line.

Note that the case of the line not existing in source is impossible:
if it doesn't exist in the current source, it certainly can't appear
in the expected-text portions of the diff.

Although the patch program can adjust for floating at application
time, the version control system can also adjust the line numbers in
hunks to compensate for any insertions or deletions that have
happened, in either source or target, outside the areas covered by the
hunks.  This can result in a patch that applies perfectly, without any
offset adjustment, to the target as it is known to the revision
control system.  Of course, uncommitted local edits to the target
cannot be compensated for in the diff -- we must still rely on the
patch program's own offset adjustment and fuzz factor to handle those.

The above rules are an informal explanation of how variance adjustment
works.  Below, the algorithm is described somewhat more formally, to
show how the version control system would do variance adjustment in
any situation.  Note that the algorithm is actually too
powerful -- if taken to its logical limits, it can generate patches
that apply cleanly even when the user would almost certainly prefer a
conflict.  Thus it's necessary to offer an adjustment selectivity
level; a good default selectivity would probably allow compensation
for context variance, but not for variance in expected target lines.
Anyway, the complete, unselective algorithm is described below, as it
should be obvious where to attach the selectivity knobs if desired.

The Variance Adjustment Algorithm.

Some terminology:

insertion

A new line that has been added in either source or
      target since the common ancestor.

deletion

A line that has been deleted from either source or target
      since the common ancestor.

edit

A line that has been changed in either source or target
      since the common ancestor.

out-range

An event that happened to either source or target since the
      common ancestor, but to a line that is not covered in any of
      the diff hunks in the patch undergoing variance adjustment.  For
      example, an out-range insertion means a line was added in
      some region not directly touched by any of the hunks in the
      patch; an out-range deletion means a line was deleted
      from some region not in any hunk.

in-range

An event that happened to either source or target since the
      common ancestor, to a line covered in one of the diff hunks in
      the patch undergoing variance adjustment.  For example, an
      in-range insertion means a line was added in a region
      affected by one of the hunks; an in-range deletion means
      a line that was deleted from some region affected by a hunk.

context

A line included in a hunk for context only -- such lines are
      not affected by the patch.

destination line, affected line

(Used interchangeably).  A line that is actually affected by
      a patch.  For lines being edited or deleted, the line is already
      present in the target text; for lines being added, the line will
      only be present after the patch is applied.  In all cases it is
      present in a hunk in the patch.

Description of the scenario:

Although there is no requirement that there be a "trunk"/"branch"
relationship between the two lines, we will use that terminology below
to make the description easier to understand.  In reality, there are
simply two lines of development with a common ancestory.

Assume that branch B is rooted in trunk T at T:8; thus,
T:8 == B:1.  The youngest trunk revision is T:20, and the
youngest branch revision is B:15.  A user with working copy on branch
B wants to merge in the change T:19-T:20.  For brevity, we will call
this change P, for "patch".  (We may speak, without loss of
generality, as if only one file is being patched, as the same
algorithm holds for every file involved in the merge.)

There are two problems that prevent the direct application of the
unadjusted P to B:15.  P, being based on source text T:19,

contains certain changes not present in B:15, namely, changes T:9
   through T:19.

does not contain certain changes present in B:15, namely,
   changes B:2 through B:15.

To adjust P, we first walk over the diff T:8-T:19, adjusting hunks as
we go.  Each line in T:8-T:19 falls into one of the following
categories:

Out-range added line: decrement the line numbers in
       every hunk in P that comes after the addition.  This undoes the
       effect of the add, since the add never happened in B.

Out-range deleted line: increment the line numbers in
       every hunk in P that comes after the deletion.  This undoes the
       effect of the deletion, since the deletion never happened in
       B.

Out-range edited line: do nothing.  Out-range edits
       are irrelevant to P.

Added line in context range in P: remove the
       corresponding line from the context, optionally replacing it
       with new context based on that region in B:15, and
       adjust line numbers and mappings appropriately.

Added line in affected text range in P: this is a
       dependency problem -- part of the change T:18-T:19 depends on
       changes introduced to T after B branched.  There are several
       possible behaviors, depending on what the user wants.  One is
       to generate an informative error, stating that T:18-T:19
       depends on some other change (T:N-T:M, where N>=8, M<=18, and
       M-N == 1); the exact revisions can be discovered
       automatically using the same process as "cvs annotate", though
       it may take some time to do so.  Another option is to include
       the change in P, as an insertion of the "after" version of the
       text, and adjust line numbers and mappings accordingly.  (And
       if all this isn't sounding a lot like a directory merge
       algorithm, try drinking more of the Kool-Aid.)  A third option
       is to include it as an insertion, but with metadata (such as
       CVS-style conflict markers) indicating that the line attempting
       to be patched does not exist in B.

Deleted line that is in-range in P: request another
       universe -- this situation can't happen in ours.

In-range edited line: reverse that edit in the "before"
       version of the corresponding line in the appropriate hunk in
       P, to obtain the version of the line that will be found in
       B when P is applied.

Now walk over the diff B:1-B:15, further adjusting P:

Out-range added line: increment the line numbers in
       every hunk in P that comes after the addition.

Out-range deleted line: decrement the line numbers in
       every hunk in P that comes after the deletion.

Out-range edited line: do nothing.  Out-range edits
       are irrelevant to P.

Added line in context range in P: add that line to both
       sides of the context in the appropriate hunk, adjust line
       numbers in that hunk and all following hunks.

Added line in affected text range in P: add that line to
       the context in P and adjust numbers appropriately.

Deleted line in-range in P: dependency problem; see
       "Added line in affected text range in P" in the first
       pass above.

In-range edited line: apply that edit to the "before"
       version of the corresponding line in the appropriate hunk in
       P.

Now P is ready to apply to B:15, and even has enough context to apply
over local edits.

Some of the steps in both loops can be compressed.  For example, when
the number of added and deleted lines in a hunk is balanced, line
number adjustment in later hunks is unnecessary; and balance can be
quickly detected by inspecting only the line numbers of the hunk in
question.

The algorithm handles inherent conflicts flexibly without losing
information.  An "inherent" conflict is one where changes in T:8-T:19
overlap with changes in B:1-B:15.  They can be either papered over by
adjusting context and "before" lines as enthusiastically as possible;
reported as errors, with dependency information included; or both
sides of the overlap can be handed to the user, surrounded by
CVS-style conflict markers.  Or if conflict markers are not the
desired interface, the patch can hold the conflict in some other
metadata markup (using the patch format comment space), and other
tools can report on and help resolve it.

Let's take a brief look at what adjustment does to some patches.
Here's a simple case, arising from an attempt to port an individual
change from trunk to branch.  On trunk T, revision 1 looks like this:

int main (int argc, char **argv)
{
  /* line minus-five of context */
  /* line minus-four of context */
  /* line minus-three of context */
  /* line minus-two of context */
  /* line minus-one of context */
  printf ("Hello, world!\n");
  /* line plus-one of context */
  /* line plus-two of context */
  /* line plus-three of context */
  /* line plus-four of context */
  /* line plus-five of context */
}

A branch B also exists, rooted in the trunk at revision T:1.  On
branch B, we commit a change to the context (we replace the words with
numbers), so that B:2 looks like this:

int main (int argc, char **argv)
{
  /* line -5 of context */
  /* line -4 of context */
  /* line -3 of context */
  /* line -2 of context */
  /* line -1 of context */
  printf ("Hello, world!\n");
  /* line +1 of context */
  /* line +2 of context */
  /* line +3 of context */
  /* line +4 of context */
  /* line +5 of context */
}

Meanwhile on the trunk, we change only the middle line, so that T:2 is
committed as:

int main (int argc, char **argv)
{
  /* line minus-five of context */
  /* line minus-four of context */
  /* line minus-three of context */
  /* line minus-two of context */
  /* line minus-one of context */
  printf ("Good-bye, cruel world!\n");
  /* line plus-one of context */
  /* line plus-two of context */
  /* line plus-three of context */
  /* line plus-four of context */
  /* line plus-five of context */
}

Using a traditional context-based approach, an attempt to patch B:2
with the difference T:1->T:2 will fail, with a reject file if
vanilla `<tt>patch</tt>' was used, or with conflict markers if
`<tt>rcsmerge</tt>' was used:

$ cvs up -j 1.1 -j 1.2 foo.c
### Purists will note that -j HEAD would have been sufficient; however, ###
### two -j's more clearly reflects the intent of the example.           ###
RCS file: /usr/local/cvs/vap0/foo.c,v
retrieving revision 1.1
retrieving revision 1.2
Merging differences between 1.1 and 1.2 into foo.c
rcsmerge: warning: conflicts during merge
$ cat foo.c
int main (int argc, char **argv)
{
<<<<<<< foo.c
  /* line -5 of context */
  /* line -4 of context */
  /* line -3 of context */
  /* line -2 of context */
  /* line -1 of context */
  printf ("Hello, world!\n");
  /* line +1 of context */
  /* line +2 of context */
  /* line +3 of context */
  /* line +4 of context */
  /* line +5 of context */
=======
  /* line minus-five of context */
  /* line minus-four of context */
  /* line minus-three of context */
  /* line minus-two of context */
  /* line minus-one of context */
  printf ("Good-bye, cruel world!\n");
  /* line plus-one of context */
  /* line plus-two of context */
  /* line plus-three of context */
  /* line plus-four of context */
  /* line plus-five of context */
>>>>>>> 1.2
}

Because the context has changed, the change to the middle line cannot
be found.  If we adjust the patch T:1->T:2, it would look like
this:

*** foo.c	2001/05/18 08:15:28	1.1
--- foo.c	2001/05/18 08:20:59	1.2
***************
*** 5,11 ****
    /* line -3 of context */
    /* line -2 of context */
    /* line -1 of context */
!   printf ("Hello, world!\n");
    /* line +1 of context */
    /* line +2 of context */
    /* line +3 of context */
--- 5,11 ----
    /* line -3 of context */
    /* line -2 of context */
    /* line -1 of context */
!   printf ("Goodbye, cruel world!\n");
    /* line +1 of context */
    /* line +2 of context */
    /* line +3 of context */

and would now apply perfectly to B:2, even though this diff never
existed between any two committed revisions.

Let's try a slightly more complex case, starting with the same T:1 and
B:1:

int main (int argc, char **argv)
{
  /* line minus-five of context */
  /* line minus-four of context */
  /* line minus-three of context */
  /* line minus-two of context */
  /* line minus-one of context */
  printf ("Hello, world!\n");
  /* line plus-one of context */
  /* line plus-two of context */
  /* line plus-three of context */
  /* line plus-four of context */
  /* line plus-five of context */
}

T:2 has some inserted lines near the top:

#include <stdio.h>

int main (int argc, char **argv)
{
  /* line minus-five of context */
  /* line minus-four of context */
  /* line minus-three of context */
  /* line minus-two of context */
  /* line minus-one of context */
  printf ("Hello, world!\n");
  /* line plus-one of context */
  /* line plus-two of context */
  /* line plus-three of context */
  /* line plus-four of context */
  /* line plus-five of context */
}

And then another change was committed on the trunk, editing the middle
line, so that T:3 looks like this:

#include <stdio.h>

int main (int argc, char **argv)
{
  /* line minus-five of context */
  /* line minus-four of context */
  /* line minus-three of context */
  /* line minus-two of context */
  /* line minus-one of context */
  printf ("Good-bye, cruel world!\n");
  /* line plus-one of context */
  /* line plus-two of context */
  /* line plus-three of context */
  /* line plus-four of context */
  /* line plus-five of context */
}

Meanwhile, one complex change has been committed on the branch, so B:2
looks like this:

int main (int argc, char **argv)
{
  /* line minus-five of context */
  /* line minus-four of context */
  /* line minus-three of context */
  /* line -1 of context */
  printf ("Hello, world!\n");
  /* newly inserted line of context */
  /* line plus-one of context */
  /* line plus-two of context */
  /* line plus-three of context */
  /* line plus-four of context */
  /* line plus-five of context */
}

Line minus-two of context was removed, line minus-one was changed to
"-1", and a new line of context was inserted farther down.  Now the
branch developer wants to merge in the change T:2-T:3.  Unadjusted,
the patch looks like this:

Index: foo.c
===================================================================
RCS file: /usr/local/cvs/vap1/foo.c,v
retrieving revision 1.2
retrieving revision 1.3
diff -c -r1.2 -r1.3
*** foo.c	2001/05/22 21:17:14	1.2
--- foo.c	2001/05/22 21:19:42	1.3
***************
*** 7,13 ****
    /* line minus-three of context */
    /* line minus-two of context */
    /* line minus-one of context */
!   printf ("Hello, world!\n");
    /* line plus-one of context */
    /* line plus-two of context */
    /* line plus-three of context */
--- 7,13 ----
    /* line minus-three of context */
    /* line minus-two of context */
    /* line minus-one of context */
!   printf ("Good-bye, cruel world!\n");
    /* line plus-one of context */
    /* line plus-two of context */
    /* line plus-three of context */

Following the adjustment algorithm, it looks like this:

Index: foo.c
===================================================================
RCS file: /usr/local/cvs/vap1/foo.c,v
retrieving revision 1.2
retrieving revision 1.3
diff -c -r1.2 -r1.3
*** foo.c	2001/05/22 21:17:14	1.2
--- foo.c	2001/05/22 21:19:42	1.3
***************
*** 5,11 ****
    /* line minus-four of context */
    /* line minus-three of context */
    /* line -1 of context */
!   printf ("Hello, world!\n");
    /* newly inserted line of context */
    /* line plus-one of context */
    /* line plus-two of context */
--- 5,11 ----
    /* line minus-four of context */
    /* line minus-three of context */
    /* line -1 of context */
!   printf ("Good-bye, cruel world!\n");
    /* newly inserted line of context */
    /* line plus-one of context */
    /* line plus-two of context */

Note how the line numbers have been adjusted to compensate for the
absence of change T:1-T:2 (since the patch we're applying only
concerns T:2-T:3), and the context has been changed to include the
difference B:1-B:2.

Again, this patch never existed between any two revisions, but it
applies cleanly to B:2.

The cost of the adjustment algorithm is proportional to the size of
the diff from branch point to trunk head plus the diff from branch
point to branch head, plus the size (for time, number of hunks) in the
diff being adjusted.  This is comparable to the cost of using
reverse-delta storage in the first place.  Also, the user consuming
the final patch does not need access to all the intermediate changes
-- she only needs permissions on the endpoints of the diff, the common
ancestor of the two lines, and the revision to which the patch is
being applied.  Intermediate revisions need not be accessible by the
user.

Through variance-adjusted patching, any repository that stores
successive revisions can apply patches even between highly divergent
branches, as long as there is a common ancestor.

Addendum

For clarity, I have used line-based diffs to describe the process
of variance adjustment.  The algorithm applies equally well, of
course, to other kinds of diffs, including arbitrary binary diffs.  In
fact,
Dr. William Uther wrote:

I actually gave an example of a binary version of the VAP algorithm on
the svn-dev list a while back.  It used VAP at the byte level, instead
of at the line level.  It was similar to your suggested VAP algorithm
in that you could adjust the 'soft-conflict' zone around the changes.

The message he's referring to appears to be this one:

   http://svn.haxx.se/dev/archive-2002-02/1059.shtml
   From: William Uther
   To: dev@subversion.tigris.org
   Subject: Re: Merging
   Date: Sat, 16 Feb 2002 21:19:43 -0500
   Message-ID: <B8947D6F.787C%will=subversion@cs.cmu.edu>
   In-Reply-To: <51C7002B020CD411824E009027C469F782259A@cldxch01.hifn.com>

I mention this here in order to help anyone using this algorithm as
prior art in a patent challenge.  I doubt I was the first person to
describe variance-adjusted patching, but at the very least we can know
that the method was described as of 22 May 2001 — and
that both I and someone else "proficient in the art" (William Uther)
thought its applicability to binary diffs to be pretty obvious.


text:
namespace base {

// Returns whether the cpu cycle reduction experiment is running.
// The goal of this experiment is to better understand the relationship between
// total CPU cycles used across the fleet and top-line chrome metrics.
BASE_EXPORT bool IsRunningCpuReductionExperiment();

// Must be called after FeatureList initialization and while chrome is still
// single-threaded.
BASE_EXPORT void InitializeCpuReductionExperiment();

// Returns true if the next sample should be recorded to an histogram
// sub-sampled under the CPU reduction experiment. Returns true randomly for
// ~1/1000 calls when the experiment is enabled, or always returns true when the
// experiment is disabled.
BASE_EXPORT bool ShouldLogHistogramForCpuReductionExperiment();

}  // namespace base

#endif  // BASE_CPU_REDUCTION_EXPERIMENT_H_


text:
from JumpScale import j
import lz4

blocksize = 20 * 1024 * 1024
objects = []
new_objects = []

def _read_file(path, block_size=0):
    with open(path, 'rb') as f:
        while True:
            piece = f.read(block_size)
            if piece:
                yield piece
            else:
                return

def _dump2stor(store, bucketname, data, compress):
    if len(data) == 0:
        return ""
    key = j.data.hash.md5_string(data)
    if not key in objects or not key in new_objects:
        if compress:
            data = lz4.compress(data)
        store.set_object(bucketname, key, data)
        new_objects.append(key)
    return key

def store_metadata(store, mdbucketname, backupname, backupmetadata):
    mdbucketname = str(mdbucketname)
    backupname = str(backupname)
    pools = store.list_pools()
    if not mdbucketname in pools:
        store.create_pool(mdbucketname)
    store.set_object(mdbucketname, backupname, j.data.serializer.json.dumps(backupmetadata))

def read_metadata(store, mdbucketname, backupname):
    data = store.get_object(mdbucketname, backupname)
    return j.data.serializer.json.loads(data)

def backup(store, bucketname, f, compress=True):
    global objects
    bucketname = str(bucketname)
    hashes = []
    pools = store.list_pools()
    if not bucketname in pools:
        store.create_pool(bucketname)
    objects = store.list_objects(bucketname)
    for data in _read_file(f, blocksize):
        hashes.append(_dump2stor(store, bucketname, data, compress))
    return {'path': f, 'fileparts': hashes}

def restore(store, bucketname, restorepath, parts, compress=True):
    bucketname = str(bucketname)
    for part in parts:
        part_content = store.get_object(bucketname, part)
        if compress:
            uncompressed_part_content = lz4.decompress(part_content)
        else:
            uncompressed_part_content = part_content
        j.sal.fs.writeFile(restorepath, uncompressed_part_content, append=True)


text:
1. Requirements Analysis

- user needs; what must database do?

2. Conceptual Design

- high level description (often done w/ER model)

- Rails encourages you to work here

3. Logical Design

- translate ER into DBMS data model

- Rails requires you to work here too

4. Schema Refinement

- consistency, normalization

5. Physical Design

- indexes, disk layout

6. Security Design

- who accesses what, and how


text:
* Add a config for the method name (#6)

### [ver 0.0.2](https://github.com/shiraji/new-instance-inspection/releases/tag/v0.0.2)

* Fix #2

### [ver 0.0.1](https://github.com/shiraji/new-instance-inspection/releases/tag/v0.0.1)

* Initial release


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

package Persistence;
import farmaciaweb.Models.Clientes;
import farmaciaweb.Models.Fornecedores;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
/**
 *
 * @author Filipe
 */
public class PersisteCliente {

    public void InsertCliente(Clientes c)
    {
        Session session = DAOfarmaciaweb.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.save(c);
        session.getTransaction().commit();
    }

    public boolean ExistsClienteByLogin(String login, String senha)
    {
       Session session = DAOfarmaciaweb.getSessionFactory().getCurrentSession();
       session.beginTransaction();
       Query query = session.createQuery("from Clientes where login_cliente = :login and senha = :senha");
       query.setParameter("login", login);
       query.setParameter("senha", senha);
       Clientes cliente = (Clientes)query.uniqueResult();
       session.getTransaction().commit();
       if(cliente != null)
           return true;
       return false;
    }

     public List<Clientes> getAllCliente()
    {
        Session session = DAOfarmaciaweb.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query query = session.createQuery("from Clientes");
        List<Clientes> clientes = query.list();
        session.getTransaction().commit();
        return clientes;
    }

     public void updateClienteLogin(String login, String senha, int cod_cliente)
     {
         Session session = DAOfarmaciaweb.getSessionFactory().openSession();
         String hql = "UPDATE Clientes set login_cliente = :login ,senha = :senha "  +
             "WHERE id = :id";
          session.beginTransaction();
          Query query = session.createQuery(hql);
          query.setParameter("login", login);
          query.setParameter("senha", senha);
          query.setParameter("id", cod_cliente);
          int result = query.executeUpdate();
          session.getTransaction().commit();
     }

      public int getClienteID(String login)
    {
       Session session = DAOfarmaciaweb.getSessionFactory().getCurrentSession();
       session.beginTransaction();
       Query query = session.createQuery("codigo from Clientes where login_cliente = :login");
       query.setParameter("login", login);
       int cliente = (int)query.uniqueResult();
       session.getTransaction().commit();
       return cliente;
    }

       public void deleteClienteByID(int id)
    {
       Session session = DAOfarmaciaweb.getSessionFactory().getCurrentSession();
       session.beginTransaction();
       String hql = "DELETE FROM Clientes "  +
             "WHERE id = :id";
       Query query = session.createQuery(hql);
       query.setParameter("id", id);
       int result = query.executeUpdate();
       session.getTransaction().commit();
    }
}


text:
from numpy.testing import assert_equal, assert_array_equal
from nose.tools import assert_true, assert_raises, assert_not_equal
from copy import deepcopy
import os.path as op
import numpy as np
from scipy import sparse
import os
import warnings

from mne.utils import (set_log_level, set_log_file, _TempDir,
                       get_config, set_config, deprecated, _fetch_file,
                       sum_squared, estimate_rank,
                       _url_to_local_path, sizeof_fmt, _check_subject,
                       _check_type_picks, object_hash, object_diff,
                       requires_good_network, run_tests_if_main, md5sum,
                       ArgvSetter, _memory_usage, check_random_state,
                       _check_mayavi_version, requires_mayavi,
                       set_memmap_min_size, _get_stim_channel, _check_fname)
from mne.io import show_fiff
from mne import Evoked
from mne.externals.six.moves import StringIO

warnings.simplefilter('always')  # enable b/c these tests throw warnings

base_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data')
fname_evoked = op.join(base_dir, 'test-ave.fif')
fname_raw = op.join(base_dir, 'test_raw.fif')
fname_log = op.join(base_dir, 'test-ave.log')
fname_log_2 = op.join(base_dir, 'test-ave-2.log')

def clean_lines(lines=[]):
    # Function to scrub filenames for checking logging output (in test_logging)
    return [l if 'Reading ' not in l else 'Reading test file' for l in lines]

def test_misc():
    """Test misc utilities"""
    assert_equal(_memory_usage(-1)[0], -1)
    assert_equal(_memory_usage((clean_lines, [], {}))[0], -1)
    assert_equal(_memory_usage(clean_lines)[0], -1)
    assert_raises(ValueError, check_random_state, 'foo')
    assert_raises(ValueError, set_memmap_min_size, 1)
    assert_raises(ValueError, set_memmap_min_size, 'foo')
    assert_raises(TypeError, get_config, 1)
    assert_raises(TypeError, set_config, 1)
    assert_raises(TypeError, set_config, 'foo', 1)
    assert_raises(TypeError, _get_stim_channel, 1)
    assert_raises(TypeError, _get_stim_channel, [1])
    assert_raises(TypeError, _check_fname, 1)
    assert_raises(ValueError, _check_subject, None, None)
    assert_raises(ValueError, _check_subject, None, 1)
    assert_raises(ValueError, _check_subject, 1, None)

@requires_mayavi
def test_check_mayavi():
    """Test mayavi version check"""
    assert_raises(RuntimeError, _check_mayavi_version, '100.0.0')

def test_run_tests_if_main():
    """Test run_tests_if_main functionality"""
    x = []

    def test_a():
        x.append(True)

    @np.testing.dec.skipif(True)
    def test_b():
        return

    try:
        __name__ = '__main__'
        run_tests_if_main(measure_mem=False)  # dual meas causes problems

        def test_c():
            raise RuntimeError

        try:
            __name__ = '__main__'
            run_tests_if_main(measure_mem=False)  # dual meas causes problems
        except RuntimeError:
            pass
        else:
            raise RuntimeError('Error not raised')
    finally:
        del __name__
    assert_true(len(x) == 2)
    assert_true(x[0] and x[1])

def test_hash():
    """Test dictionary hashing and comparison functions"""
    # does hashing all of these types work:
    # {dict, list, tuple, ndarray, str, float, int, None}
    d0 = dict(a=dict(a=0.1, b='fo', c=1), b=[1, 'b'], c=(), d=np.ones(3),
              e=None)
    d0[1] = None
    d0[2.] = b'123'

    d1 = deepcopy(d0)
    assert_true(len(object_diff(d0, d1)) == 0)
    assert_true(len(object_diff(d1, d0)) == 0)
    assert_equal(object_hash(d0), object_hash(d1))

    # change values slightly
    d1['data'] = np.ones(3, int)
    d1['d'][0] = 0
    assert_not_equal(object_hash(d0), object_hash(d1))

    d1 = deepcopy(d0)
    assert_equal(object_hash(d0), object_hash(d1))
    d1['a']['a'] = 0.11
    assert_true(len(object_diff(d0, d1)) > 0)
    assert_true(len(object_diff(d1, d0)) > 0)
    assert_not_equal(object_hash(d0), object_hash(d1))

    d1 = deepcopy(d0)
    assert_equal(object_hash(d0), object_hash(d1))
    d1['a']['d'] = 0  # non-existent key
    assert_true(len(object_diff(d0, d1)) > 0)
    assert_true(len(object_diff(d1, d0)) > 0)
    assert_not_equal(object_hash(d0), object_hash(d1))

    d1 = deepcopy(d0)
    assert_equal(object_hash(d0), object_hash(d1))
    d1['b'].append(0)  # different-length lists
    assert_true(len(object_diff(d0, d1)) > 0)
    assert_true(len(object_diff(d1, d0)) > 0)
    assert_not_equal(object_hash(d0), object_hash(d1))

    d1 = deepcopy(d0)
    assert_equal(object_hash(d0), object_hash(d1))
    d1['e'] = 'foo'  # non-None
    assert_true(len(object_diff(d0, d1)) > 0)
    assert_true(len(object_diff(d1, d0)) > 0)
    assert_not_equal(object_hash(d0), object_hash(d1))

    d1 = deepcopy(d0)
    d2 = deepcopy(d0)
    d1['e'] = StringIO()
    d2['e'] = StringIO()
    d2['e'].write('foo')
    assert_true(len(object_diff(d0, d1)) > 0)
    assert_true(len(object_diff(d1, d0)) > 0)

    d1 = deepcopy(d0)
    d1[1] = 2
    assert_true(len(object_diff(d0, d1)) > 0)
    assert_true(len(object_diff(d1, d0)) > 0)
    assert_not_equal(object_hash(d0), object_hash(d1))

    # generators (and other types) not supported
    d1 = deepcopy(d0)
    d2 = deepcopy(d0)
    d1[1] = (x for x in d0)
    d2[1] = (x for x in d0)
    assert_raises(RuntimeError, object_diff, d1, d2)
    assert_raises(RuntimeError, object_hash, d1)

    x = sparse.eye(2, 2, format='csc')
    y = sparse.eye(2, 2, format='csr')
    assert_true('type mismatch' in object_diff(x, y))
    y = sparse.eye(2, 2, format='csc')
    assert_equal(len(object_diff(x, y)), 0)
    y[1, 1] = 2
    assert_true('elements' in object_diff(x, y))
    y = sparse.eye(3, 3, format='csc')
    assert_true('shape' in object_diff(x, y))
    y = 0
    assert_true('type mismatch' in object_diff(x, y))

def test_md5sum():
    """Test md5sum calculation
    """
    tempdir = _TempDir()
    fname1 = op.join(tempdir, 'foo')
    fname2 = op.join(tempdir, 'bar')
    with open(fname1, 'wb') as fid:
        fid.write(b'abcd')
    with open(fname2, 'wb') as fid:
        fid.write(b'efgh')
    assert_equal(md5sum(fname1), md5sum(fname1, 1))
    assert_equal(md5sum(fname2), md5sum(fname2, 1024))
    assert_true(md5sum(fname1) != md5sum(fname2))

def test_tempdir():
    """Test TempDir
    """
    tempdir2 = _TempDir()
    assert_true(op.isdir(tempdir2))
    x = str(tempdir2)
    del tempdir2
    assert_true(not op.isdir(x))

def test_estimate_rank():
    """Test rank estimation
    """
    data = np.eye(10)
    assert_array_equal(estimate_rank(data, return_singular=True)[1],
                       np.ones(10))
    data[0, 0] = 0
    assert_equal(estimate_rank(data), 9)

def test_logging():
    """Test logging (to file)
    """
    assert_raises(ValueError, set_log_level, 'foo')
    tempdir = _TempDir()
    test_name = op.join(tempdir, 'test.log')
    with open(fname_log, 'r') as old_log_file:
        old_lines = clean_lines(old_log_file.readlines())
    with open(fname_log_2, 'r') as old_log_file_2:
        old_lines_2 = clean_lines(old_log_file_2.readlines())

    if op.isfile(test_name):
        os.remove(test_name)
    # test it one way (printing default off)
    set_log_file(test_name)
    set_log_level('WARNING')
    # should NOT print
    evoked = Evoked(fname_evoked, condition=1)
    with open(test_name) as fid:
        assert_true(fid.readlines() == [])
    # should NOT print
    evoked = Evoked(fname_evoked, condition=1, verbose=False)
    with open(test_name) as fid:
        assert_true(fid.readlines() == [])
    # should NOT print
    evoked = Evoked(fname_evoked, condition=1, verbose='WARNING')
    with open(test_name) as fid:
        assert_true(fid.readlines() == [])
    # SHOULD print
    evoked = Evoked(fname_evoked, condition=1, verbose=True)
    with open(test_name, 'r') as new_log_file:
        new_lines = clean_lines(new_log_file.readlines())
    assert_equal(new_lines, old_lines)
    set_log_file(None)  # Need to do this to close the old file
    os.remove(test_name)

    # now go the other way (printing default on)
    set_log_file(test_name)
    set_log_level('INFO')
    # should NOT print
    evoked = Evoked(fname_evoked, condition=1, verbose='WARNING')
    with open(test_name) as fid:
        assert_true(fid.readlines() == [])
    # should NOT print
    evoked = Evoked(fname_evoked, condition=1, verbose=False)
    with open(test_name) as fid:
        assert_true(fid.readlines() == [])
    # SHOULD print
    evoked = Evoked(fname_evoked, condition=1)
    with open(test_name, 'r') as new_log_file:
        new_lines = clean_lines(new_log_file.readlines())
    with open(fname_log, 'r') as old_log_file:
        assert_equal(new_lines, old_lines)
    # check to make sure appending works (and as default, raises a warning)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        set_log_file(test_name, overwrite=False)
        assert len(w) == 0
        set_log_file(test_name)
        assert len(w) == 1
    evoked = Evoked(fname_evoked, condition=1)
    with open(test_name, 'r') as new_log_file:
        new_lines = clean_lines(new_log_file.readlines())
    assert_equal(new_lines, old_lines_2)

    # make sure overwriting works
    set_log_file(test_name, overwrite=True)
    # this line needs to be called to actually do some logging
    evoked = Evoked(fname_evoked, condition=1)
    del evoked
    with open(test_name, 'r') as new_log_file:
        new_lines = clean_lines(new_log_file.readlines())
    assert_equal(new_lines, old_lines)

def test_config():
    """Test mne-python config file support"""
    tempdir = _TempDir()
    key = '_MNE_PYTHON_CONFIG_TESTING'
    value = '123456'
    old_val = os.getenv(key, None)
    os.environ[key] = value
    assert_true(get_config(key) == value)
    del os.environ[key]
    # catch the warning about it being a non-standard config key
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        set_config(key, None, home_dir=tempdir)
    assert_true(len(w) == 1)
    assert_true(get_config(key, home_dir=tempdir) is None)
    assert_raises(KeyError, get_config, key, raise_error=True)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        set_config(key, value, home_dir=tempdir)
        assert_true(get_config(key, home_dir=tempdir) == value)
        set_config(key, None, home_dir=tempdir)
    if old_val is not None:
        os.environ[key] = old_val
    # Check if get_config with no input returns all config
    key = 'MNE_PYTHON_TESTING_KEY'
    config = {key: value}
    with warnings.catch_warnings(record=True):  # non-standard key
        warnings.simplefilter('always')
        set_config(key, value, home_dir=tempdir)
    assert_equal(get_config(home_dir=tempdir), config)

def test_show_fiff():
    """Test show_fiff
    """
    # this is not exhaustive, but hopefully bugs will be found in use
    info = show_fiff(fname_evoked)
    keys = ['FIFF_EPOCH', 'FIFFB_HPI_COIL', 'FIFFB_PROJ_ITEM',
            'FIFFB_PROCESSED_DATA', 'FIFFB_EVOKED', 'FIFF_NAVE',
            'FIFF_EPOCH']
    assert_true(all([key in info for key in keys]))
    info = show_fiff(fname_raw, read_limit=1024)

@deprecated('message')
def deprecated_func():
    pass

@deprecated('message')
class deprecated_class(object):
    def __init__(self):
        pass

def test_deprecated():
    """Test deprecated function
    """
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        deprecated_func()
    assert_true(len(w) == 1)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        deprecated_class()
    assert_true(len(w) == 1)

@requires_good_network
def test_fetch_file():
    """Test file downloading
    """
    tempdir = _TempDir()
    urls = ['http://martinos.org/mne/',
            'ftp://surfer.nmr.mgh.harvard.edu/pub/data/bert.recon.md5sum.txt']
    with ArgvSetter(disable_stderr=False):  # to capture stdout
        for url in urls:
            archive_name = op.join(tempdir, "download_test")
            _fetch_file(url, archive_name, verbose=False)
            assert_raises(Exception, _fetch_file, 'NOT_AN_ADDRESS',
                          op.join(tempdir, 'test'), verbose=False)
            resume_name = op.join(tempdir, "download_resume")
            # touch file
            with open(resume_name + '.part', 'w'):
                os.utime(resume_name + '.part', None)
            _fetch_file(url, resume_name, resume=True, verbose=False)
            assert_raises(ValueError, _fetch_file, url, archive_name,
                          hash_='a', verbose=False)
            assert_raises(RuntimeError, _fetch_file, url, archive_name,
                          hash_='a' * 32, verbose=False)

def test_sum_squared():
    """Test optimized sum of squares
    """
    X = np.random.randint(0, 50, (3, 3))
    assert_equal(np.sum(X ** 2), sum_squared(X))

def test_sizeof_fmt():
    """Test sizeof_fmt
    """
    assert_equal(sizeof_fmt(0), '0 bytes')
    assert_equal(sizeof_fmt(1), '1 byte')
    assert_equal(sizeof_fmt(1000), '1000 bytes')

def test_url_to_local_path():
    """Test URL to local path
    """
    assert_equal(_url_to_local_path('http://google.com/home/why.html', '.'),
                 op.join('.', 'home', 'why.html'))

def test_check_type_picks():
    """Test checking type integrity checks of picks
    """
    picks = np.arange(12)
    assert_array_equal(picks, _check_type_picks(picks))
    picks = list(range(12))
    assert_array_equal(np.array(picks), _check_type_picks(picks))
    picks = None
    assert_array_equal(None, _check_type_picks(picks))
    picks = ['a', 'b']
    assert_raises(ValueError, _check_type_picks, picks)
    picks = 'b'
    assert_raises(ValueError, _check_type_picks, picks)

run_tests_if_main()


text:
/*
 * Aironet 4500/4800 802.11 PCMCIA/ISA/PCI driver for FreeBSD.
 *
 * Written by Bill Paul <wpaul@ctr.columbia.edu>
 * Electrical Engineering Department
 * Columbia University, New York City
 */

#include "opt_inet.h"

#ifdef INET
#define ANCACHE
#endif

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/socket.h>
#include <sys/kernel.h>

#include <sys/module.h>
#include <sys/bus.h>
#include <machine/bus.h>
#include <sys/rman.h>
#include <machine/resource.h>

#include <net/if.h>
#include <net/if_arp.h>
#include <net/ethernet.h>
#include <net/if_dl.h>
#include <net/if_types.h>

#include <dev/an/if_aironet_ieee.h>
#include <dev/an/if_anreg.h>

/*
 * Support for PCMCIA cards.
 */
static int  an_pccard_probe(device_t);
static int  an_pccard_attach(device_t);
static int  an_pccard_detach(device_t);

static device_method_t an_pccard_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		an_pccard_probe),
	DEVMETHOD(device_attach,	an_pccard_attach),
	DEVMETHOD(device_detach,	an_pccard_detach),
	DEVMETHOD(device_shutdown,	an_shutdown),

	{ 0, 0 }
};

static driver_t an_pccard_driver = {
	"an",
	an_pccard_methods,
	sizeof(struct an_softc)
};

static devclass_t an_pccard_devclass;

DRIVER_MODULE(if_an, pccard, an_pccard_driver, an_pccard_devclass, 0, 0);

static int
an_pccard_detach(device_t dev)
{
	struct an_softc		*sc = device_get_softc(dev);
	struct ifnet		*ifp = &sc->arpcom.ac_if;

	if (sc->an_gone) {
		device_printf(dev,"already unloaded\n");
		return(0);
	}
	an_stop(sc);
	ifp->if_flags &= ~IFF_RUNNING;
	if_detach(ifp);
	sc->an_gone = 1;
	bus_teardown_intr(dev, sc->irq_res, sc->irq_handle);
	an_release_resources(dev);
	device_printf(dev,"unloaded\n");
	return (0);
}

static int
an_pccard_probe(device_t dev)
{
	int     error;

	error = an_probe(dev); /* 0 is failure for now */
	if (error != 0) {
		device_set_desc(dev, "Aironet PC4500/PC4800");
		error = an_alloc_irq(dev, 0, 0);
	} else
	        error = 1;
	an_release_resources(dev);
	return (error);
}

static int
an_pccard_attach(device_t dev)
{
	struct an_softc *sc = device_get_softc(dev);
	int flags = device_get_flags(dev);
	int error;

	an_alloc_port(dev, sc->port_rid, AN_IOSIZ);
	an_alloc_irq(dev, sc->irq_rid, 0);

	error = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_NET,
			       an_intr, sc, &sc->irq_handle);
	if (error) {
		printf("setup intr failed %d \n", error);
		an_release_resources(dev);
		return (error);
	}

	sc->an_bhandle = rman_get_bushandle(sc->port_res);
	sc->an_btag = rman_get_bustag(sc->port_res);

	error = an_attach(sc, device_get_unit(dev), flags);
	return (error);
}


text:
package org.kasource.commons.reflection.filter.impl;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class AnnotatedFilterTest {

    private AnnotatedFilter filter = new AnnotatedFilter(MyAnnotation.class);

    @Test
    public void passClassTrue() {
        assertThat(filter.apply(MyClass.class), is(true));
    }

    @Test
    public void passClassFalse() {
        assertThat(filter.apply(MyAnnotation.class), is(false));
    }

    @Test
    public void passConstructorTrue() throws SecurityException, NoSuchMethodException {
        Constructor<?> cons = MyClass.class.getConstructor(null);
        assertThat(filter.apply(cons), is(true));
    }

    @Test
    public void passConstructorFalse() throws SecurityException, NoSuchMethodException {
        Constructor<?> cons = MyClass.class.getConstructor(String.class);
        assertThat(filter.apply(cons), is(false));
    }

    @Test
    public void passFieldTrue() throws SecurityException, NoSuchFieldException {
        Field field = MyClass.class.getField("annotated");
        assertThat(filter.apply(field), is(true));
    }

    @Test
    public void passFieldFalse() throws SecurityException, NoSuchFieldException {
        Field field = MyClass.class.getField("notAnnotated");
        assertThat(filter.apply(field), is(false));
    }

    @Test
    public void passTrue() throws SecurityException, NoSuchMethodException {
        Method method = MyClass.class.getMethod("annotated");
        assertThat(filter.apply(method), is(true));
    }

    @Test
    public void passFalse() throws SecurityException, NoSuchMethodException {
        Method method = MyClass.class.getMethod("notAnnotated");
        assertThat(filter.apply(method), is(false));
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD})
    @interface MyAnnotation {

    }

    @MyAnnotation
    private static class MyClass {
        @SuppressWarnings("unused")
        @MyAnnotation
        public int annotated;
        @SuppressWarnings("unused")
        public int notAnnotated;

        @MyAnnotation
        public MyClass() {
        }

        public MyClass(String name) {
        }

        @SuppressWarnings("unused")
        @MyAnnotation
        public void annotated() {

        }

        @SuppressWarnings("unused")
        public void notAnnotated() {

        }
    }

}


text:
class Cliente < ActiveRecord::Base
  module Validations
    extend ActiveSupport::Concern

    included do
      validates :tipo_id, presence: true
      validates :identificacion, presence: true,
                               uniqueness: true
      # validates :nombres, presence: true
      validates :email, uniqueness: true, allow_blank: true
    end

    def has_compras_or_ventas?
      compras.any? or ventas.any?
    end

    def can_destroy?
      not has_compras_or_ventas?
    end

    def why_cant_destroy
      details = {compra: compras.count, venta: ventas.count}.map do |key, count|
        "#{count} #{key.to_s.pluralize count}" if count > 0
      end.compact
      "No se puede eliminar. Está asociado a #{details.join(" y ")}"
    end
  end
end


text:
thetadoc
========

A documentation generator using JSDoc and Angular.js.


text:
package com.texasgamer.zephyr.fragment;

import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.texasgamer.zephyr.R;
import com.texasgamer.zephyr.ZephyrApplication;
import com.texasgamer.zephyr.util.config.IConfigManager;
import com.texasgamer.zephyr.util.eventbus.EventBusEvent;
import com.texasgamer.zephyr.util.preference.IPreferenceManager;
import com.texasgamer.zephyr.util.preference.PreferenceKeys;
import com.texasgamer.zephyr.util.theme.IThemeManager;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Menu fragment.
 */
public class DebugFragment extends RoundedBottomSheetDialogFragment {

    @Inject
    IConfigManager configManager;
    @Inject
    IPreferenceManager preferenceManager;
    @Inject
    IThemeManager themeManager;

    @BindView(R.id.debug_switch_show_all_cards)
    SwitchCompat mShowAllCardsSwitch;
    @BindView(R.id.debug_switch_enable_mock_data)
    SwitchCompat mEnableMockDataSwitch;
    @BindView(R.id.debug_theme)
    TextView mTheme;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_debug, container, false);
        ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        ZephyrApplication.getApplicationComponent().inject(this);

        mShowAllCardsSwitch.setChecked(preferenceManager.getBoolean(PreferenceKeys.PREF_DEBUG_SHOW_ALL_CARDS));
        mEnableMockDataSwitch.setChecked(preferenceManager.getBoolean(PreferenceKeys.PREF_DEBUG_ENABLE_MOCK_DATA));
        updateThemeText();
    }

    @OnClick(R.id.debug_switch_show_all_cards)
    public void onClickShowAllCards(@NonNull SwitchCompat view) {
        preferenceManager.putBoolean(PreferenceKeys.PREF_DEBUG_SHOW_ALL_CARDS, view.isChecked());
        EventBus.getDefault().post(EventBusEvent.SHELL_REFRESH_CARDS);
    }

    @OnClick(R.id.debug_switch_enable_mock_data)
    public void onClickEnableMockData(@NonNull SwitchCompat view) {
        preferenceManager.putBoolean(PreferenceKeys.PREF_DEBUG_ENABLE_MOCK_DATA, view.isChecked());
    }

    @OnClick(R.id.debug_theme)
    public void onClickTheme(@NonNull TextView view) {
        if (getActivity() == null) {
            return;
        }

        Resources resources = getActivity().getResources();
        final CharSequence[] themeChoices = {
                resources.getString(R.string.menu_debug_theme_system),
                resources.getString(R.string.menu_debug_theme_light),
                resources.getString(R.string.menu_debug_theme_dark)};

        AlertDialog alertDialog = new MaterialAlertDialogBuilder(getActivity())
                .setTitle(R.string.menu_debug_theme_title)
                .setSingleChoiceItems(themeChoices, themeManager.getCurrentThemeSetting(), (dialog, which) -> {
                    themeManager.setCurrentThemeSetting(which);
                    updateThemeText();
                    dialog.dismiss();
                }).create();
        alertDialog.show();
    }

    @Override
    protected int getInitialBottomSheetState() {
        return BottomSheetBehavior.STATE_EXPANDED;
    }

    @Override
    protected boolean shouldSkipCollapsedState() {
        return true;
    }

    private void updateThemeText() {
        mTheme.setText(getString(R.string.menu_debug_theme_setting, getString(themeManager.getThemeNameStringResource(themeManager.getCurrentThemeSetting()))));
    }
}


text:
import sys

sys.stderr.write('It failed!\n')
raise SystemExit(1)


text:
angular.module('srvSynchroStatus', [])

.factory('srvSynchroStatus',  function ($q) {
  return new SrvSynchroStatus($q);
});

var SrvSynchroStatus = (function (qService) {
    'use strict';
    // Constructor
    function Service() {
        this.version = "0.2";

        this.PUB = {};
        this.PUB.NEW = 3;
        this.PUB.QUEUE = 2;
        this.PUB.NETWORK = 1;
        this.PUB.NONE = 0;// Must be ZERO (false test in srvData to know if synchro running or not)

        this.PUB.CLOUD_WAITFOR = 0;
        this.PUB.CLOUD_PB = 1;
        this.PUB.CLOUD_INPROGRESS = 2;
        this.PUB.CLOUD_IN = 3;

        this.PUB.CHANNEL_CREATE      = 'creating';
        this.PUB.CHANNEL_SHARE       = 'sharing';
        this.PUB.CHANNEL_WRITE       = 'writing';
        this.PUB.CHANNEL_READ        = 'reading';
        this.PUB.CHANNEL_DELETE      = 'deleting';
        this.PUB.CHANNEL_CLOUD       = 'cloud';
    }

    Service.prototype.resetChannels = function(object) {
        if (!object) return false;

        object.c4pSynchroStatus = {};
        object.c4pSynchroStatus[this.PUB.CHANNEL_CREATE] = this.PUB.NONE;
        object.c4pSynchroStatus[this.PUB.CHANNEL_SHARE] = this.PUB.NONE;
        object.c4pSynchroStatus[this.PUB.CHANNEL_WRITE] = this.PUB.NONE;
        object.c4pSynchroStatus[this.PUB.CHANNEL_READ] = this.PUB.NONE;
        object.c4pSynchroStatus[this.PUB.CHANNEL_DELETE] = this.PUB.NONE;
        object.c4pSynchroStatus[this.PUB.CHANNEL_CLOUD] = {     progress   : 0,
                                                                status     : this.PUB.CLOUD_WAITFOR,
                                                                hasBeenCanceled : false,
                                                                log        : 'init'};

        return true;
    };

    Service.prototype.hasChannels = function(object) {
        if (!object || !object.c4pSynchroStatus || a4p.isUndefinedOrNull(object.c4pSynchroStatus)) return false;

        return true;
    };

    Service.prototype.removeStatus = function(object) {
        if (!object || !object.c4pSynchroStatus || a4p.isUndefinedOrNull(object.c4pSynchroStatus)) return true;

        delete object.c4pSynchroStatus;  //delete the reference
        //object.c4pSynchroStatus = null;

        return true;
    };

    Service.prototype.isInInstableMode = function(object) {
        if (!object || !object.c4pSynchroStatus || a4p.isUndefinedOrNull(object.c4pSynchroStatus)) return true;

        if (    object.c4pSynchroStatus[this.PUB.CHANNEL_CREATE]  ||
                object.c4pSynchroStatus[this.PUB.CHANNEL_READ]  ||
                object.c4pSynchroStatus[this.PUB.CHANNEL_DELETE])
            return true;

        return false;
    };

    Service.prototype.hasToBeDeleted = function(object) {
        if (!object || !object.c4pSynchroStatus || a4p.isUndefinedOrNull(object.c4pSynchroStatus)) return false;

        var deleteChanel = this.PUB.CHANNEL_DELETE;
        if (object.c4pSynchroStatus[deleteChanel] != this.PUB.NONE) return true;

        return false;
    };

    Service.prototype.hasBeenCanceled = function(object) {
        if (!object || !object.c4pSynchroStatus || a4p.isUndefinedOrNull(object.c4pSynchroStatus)) return false;

        var cloudChanel = this.PUB.CHANNEL_CLOUD;
        if (object.c4pSynchroStatus[cloudChanel].hasBeenCanceled) return true;

        return false;
    };

    Service.prototype.copyChannels = function(object, objectToCopy) {
        if (!object) return false;

        if (a4p.isUndefinedOrNull(objectToCopy.c4pSynchroStatus))
            return this.resetChannels(object);

        object.c4pSynchroStatus[this.PUB.CHANNEL_CREATE] = objectToCopy.c4pSynchroStatus[this.PUB.CHANNEL_CREATE];
        object.c4pSynchroStatus[this.PUB.CHANNEL_SHARE] = objectToCopy.c4pSynchroStatus[this.PUB.CHANNEL_SHARE];
        object.c4pSynchroStatus[this.PUB.CHANNEL_WRITE] = objectToCopy.c4pSynchroStatus[this.PUB.CHANNEL_WRITE];
        object.c4pSynchroStatus[this.PUB.CHANNEL_READ] = objectToCopy.c4pSynchroStatus[this.PUB.CHANNEL_READ];
        object.c4pSynchroStatus[this.PUB.CHANNEL_DELETE] = objectToCopy.c4pSynchroStatus[this.PUB.CHANNEL_DELETE];
        object.c4pSynchroStatus[this.PUB.CHANNEL_CLOUD] = angular.copy(objectToCopy.c4pSynchroStatus[this.PUB.CHANNEL_CLOUD]);

        return true;
    };

    Service.prototype.pushChannelToLevel = function(object, channel, level, bForce) {
        if (!object || !channel || !a4p.isDefined(object.c4pSynchroStatus) || !a4p.isDefined(object.c4pSynchroStatus[channel])) return false;

        // Check that it was relevant with previous level
        var previous = object.c4pSynchroStatus[channel];
        var doChange = false;
        if (level == this.PUB.NEW && previous == this.PUB.NONE)           doChange = true;
        else if (level == this.PUB.QUEUE && previous == this.PUB.NEW)     doChange = true;
        else if (level == this.PUB.NETWORK && previous == this.PUB.QUEUE) doChange = true;
        else if (level == this.PUB.NONE && previous == this.PUB.NETWORK)  doChange = true;

        if (!doChange) {
            a4p.InternalLog.log('SrvSynchroStatus','pushChannelToLevel pb doChange:'+channel+' from '+previous+' to '+level);
        }

        // Do something special for DELETE : stop all other activities & channel
        if ((doChange || bForce) && channel == this.PUB.CHANNEL_DELETE) this.resetChannels(object);

        if (doChange || bForce) object.c4pSynchroStatus[channel] = level;
        if ((doChange || bForce) && level == this.PUB.NETWORK) {
            object.c4pSynchroStatus[this.PUB.CHANNEL_CLOUD] = {
                                progress    : 0,
                                status     : this.PUB.CLOUD_WAITFOR,
                                hasBeenCanceled : false,
                                log        : 'wait...'
                                };
        }

        return doChange;
    };
    Service.prototype.successChannel = function(object, channel, bForce) {
        if (!object || !channel || !a4p.isDefined(object.c4pSynchroStatus) || !a4p.isDefined(object.c4pSynchroStatus[channel])) return false;

        var previous = object.c4pSynchroStatus[channel];
        if (previous == this.PUB.NETWORK || bForce) object.c4pSynchroStatus[channel] = this.PUB.NONE;

        var sumChannel =    (object.c4pSynchroStatus[this.PUB.CHANNEL_CREATE] == this.PUB.NONE) +
                            (object.c4pSynchroStatus[this.PUB.CHANNEL_SHARE] == this.PUB.NONE) +
                            (object.c4pSynchroStatus[this.PUB.CHANNEL_WRITE] == this.PUB.NONE) +
                            (object.c4pSynchroStatus[this.PUB.CHANNEL_READ] == this.PUB.NONE) +
                            (object.c4pSynchroStatus[this.PUB.CHANNEL_DELETE] == this.PUB.NONE);
        var percent = sumChannel / 5 * 100;
        if (percent == 100) {
            object.c4pSynchroStatus[this.PUB.CHANNEL_CLOUD] = {   progress    : percent,
                                                                  status     : this.PUB.CLOUD_IN,
                                                                  hasBeenCanceled : false,
                                                                  log        : 'in!'
                                                                };
        }
        else if (percent > 0) {
            object.c4pSynchroStatus[this.PUB.CHANNEL_CLOUD] = {    progress    : percent,
                                                                    status     : this.PUB.CLOUD_INPROGRESS,
                                                                    hasBeenCanceled : false,
                                                                    log        : 'in progress...'
                                                                };
        }

        return true;
    };
    Service.prototype.cancelChannel = function(object, channel, log, bForce) {
        if (!object || !channel || !a4p.isDefined(object.c4pSynchroStatus) || !a4p.isDefined(object.c4pSynchroStatus[channel])) return false;

        var doChange = false;
        var previous = object.c4pSynchroStatus[channel];
        if (previous != this.PUB.NONE || bForce) {

            object.c4pSynchroStatus[channel] = this.PUB.NONE;
            object.c4pSynchroStatus[this.PUB.CHANNEL_CLOUD] = {    progress    : 0,
                                                                    status     : this.PUB.CLOUD_PB,
                                                                    hasBeenCanceled : true,
                                                                    log        : ':'+log
                                                                };
            doChange = true;
        }

        return doChange;
    };

    return Service;
})();


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\HistorySearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'description') ?>

    <?= $form->field($model, 'date') ?>

    <?= $form->field($model, 'taskid') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
typedef std::string String;
typedef std::map<std::string, std::string> StringMap;

String getVSConfigurationPlatform(const String& configName, const String& platformName) {
    return configName + "|" + platformName;
}

String getVSConfigurationPlatformCond(const String& configName, const String& platformName) {
    return String("'$(Configuration)|$(Platform)'=='") + getVSConfigurationPlatform(configName, platformName) + "'";
}

String formatVSGUID(const String& guid) {
    return String("{") + strToUpper(guid) + "}";
}

pugi::xml_node appendNodeWithText(pugi::xml_node& parent, const String& nodeName, const String& nodeText, const String& nodeCond) {
    pugi::xml_node node = parent.append_child(nodeName.c_str());
    node.append_child(pugi::node_pcdata).set_value(nodeText.c_str());
    if (!nodeCond.empty()) {
        node.append_attribute("Condition") = nodeCond.c_str();
    }

    return node;
}

void writePropertiesMap(const StringMap& props, pugi::xml_node& parent) {
    for (auto propKV : props) {
        if (!propKV.first.empty()) {
            appendNodeWithText(parent, propKV.first, propKV.second);
        }
    }
}

void writePropertiesMap(const ConditionalValueListMap& props, pugi::xml_node& parent) {
    for (auto propKV : props) {
        if (propKV.first.empty())
            continue;

        for (auto cvalue : propKV.second) {
            appendNodeWithText(parent, propKV.first, cvalue.value, cvalue.condition);
        }
    }
}

void removeNode(pugi::xml_node& node) {
    pugi::xml_node nodeToRemove = node;
    node = node.previous_sibling();
    nodeToRemove.parent().remove_child(nodeToRemove);
}

static pugi::xml_node findSimilarNode(pugi::xml_node searchNode, pugi::xml_node searchRoot, unsigned maxDistance) {
    std::string searchNodeName = searchNode.name();
    pugi::xml_node match;

    // Examine children of searchRoot that have matching names to searchNode
    unsigned i = 0;
    pugi::xml_node child = searchRoot.first_child();
    for (; child && i < maxDistance && !match; child = child.next_sibling(), i++) {
        // Ignore nodes with non-matching names
        if (searchNodeName != child.name())
            continue;

        // Assume child is a match, until shown otherwise
        match = child;

        // Check that all attributes of searchNode match the child node's attributes
        for (pugi::xml_attribute attr : searchNode.attributes()) {
            std::string searchNodeAttr = attr.value();
            std::string matchAttr = child.attribute(attr.name()).value();
            if (searchNodeAttr != matchAttr) {
                match = pugi::xml_node();
                break;
            }
        }
    }

    return match;
}

void mergeNodes(pugi::xml_node toNode, pugi::xml_node& fromNode) {
    // Base case = both nodes are text nodes
    pugi::xml_text fromNodeText = fromNode.text();
    pugi::xml_text toNodeText = toNode.text();
    if (fromNodeText && toNodeText) {
        SBLog::info() << "Overwriting template value of \"" << toNode.name() << "\" from \"" << toNodeText.get() << "\" to \""
                      << fromNodeText.get() << "\"." << std::endl;
        toNodeText.set(fromNodeText.get());
        return;
    }

    // Calculate number of children in toNode
    unsigned maxDistance = std::distance(toNode.begin(), toNode.end());

    // Merge children
    for (pugi::xml_node fromNodeChild = fromNode.first_child(); fromNodeChild;) {
        // Figure out next sibling immediately, in case of node removal
        pugi::xml_node nextSibling = fromNodeChild.next_sibling();

        // Find appropriate merge point
        pugi::xml_node toNodeChild = findSimilarNode(fromNodeChild, toNode, maxDistance);
        if (toNodeChild) {
            mergeNodes(toNodeChild, fromNodeChild);
        } else {
            toNode.append_copy(fromNodeChild);
        }

        // Proceed to next sibling
        fromNodeChild = nextSibling;
    }

    // Erase fromNode
    removeNode(fromNode);
}


text:
/**
* <auto-generated />
* This file was generated by a StringTemplate 4 template.
* Don't change it directly as your change would get overwritten. Instead, make changes
* to the .stg file (i.e. the StringTemplate 4 template file) and save it to regenerate this file.
*
* For more infor on StringTemplate 4 template please go to -
* https://github.com/antlr/antlrcs
*
* @author  Kola Oyewumi
* @version 1.0.0
* @since   2017-01-03
*
* A class which represents the job_queue table.
*/

package com.sugaronrest.modules;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.sugaronrest.restapicalls.Module;
import com.sugaronrest.restapicalls.CustomDateDeserializer;
import com.sugaronrest.restapicalls.CustomDateSerializer;

import java.util.Date;

@Module(name = "SchedulersJobs", tablename = "job_queue")
@JsonRootName(value = "job_queue")
@JsonIgnoreProperties(ignoreUnknown = true)
public class SchedulersJobs {
    public String getAssignedUserId() {
        return assignedUserId;
    }

    public void setAssignedUserId(String value) {
        assignedUserId = value;
    }
    public String getId() {
        return id;
    }

    public void setId(String value) {
        id = value;
    }
    public String getName() {
        return name;
    }

    public void setName(String value) {
        name = value;
    }
    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer value) {
        deleted = value;
    }
    public Date getDateEntered() {
        return dateEntered;
    }

    public void setDateEntered(Date value) {
        dateEntered = value;
    }
    public Date getDateModified() {
        return dateModified;
    }

    public void setDateModified(Date value) {
        dateModified = value;
    }
    public String getSchedulerId() {
        return schedulerId;
    }

    public void setSchedulerId(String value) {
        schedulerId = value;
    }
    public Date getExecuteTime() {
        return executeTime;
    }

    public void setExecuteTime(Date value) {
        executeTime = value;
    }
    public String getStatus() {
        return status;
    }

    public void setStatus(String value) {
        status = value;
    }
    public String getResolution() {
        return resolution;
    }

    public void setResolution(String value) {
        resolution = value;
    }
    public String getMessage() {
        return message;
    }

    public void setMessage(String value) {
        message = value;
    }
    public String getTarget() {
        return target;
    }

    public void setTarget(String value) {
        target = value;
    }
    public String getData() {
        return data;
    }

    public void setData(String value) {
        data = value;
    }
    public Integer getRequeue() {
        return requeue;
    }

    public void setRequeue(Integer value) {
        requeue = value;
    }
    public Integer getRetryCount() {
        return retryCount;
    }

    public void setRetryCount(Integer value) {
        retryCount = value;
    }
    public Integer getFailureCount() {
        return failureCount;
    }

    public void setFailureCount(Integer value) {
        failureCount = value;
    }
    public Integer getJobDelay() {
        return jobDelay;
    }

    public void setJobDelay(Integer value) {
        jobDelay = value;
    }
    public String getClient() {
        return client;
    }

    public void setClient(String value) {
        client = value;
    }
    public Integer getPercentComplete() {
        return percentComplete;
    }

    public void setPercentComplete(Integer value) {
        percentComplete = value;
    }

    @JsonProperty("assigned_user_id")
    private String assignedUserId;

    @JsonProperty("id")
    private String id;

    @JsonProperty("name")
    private String name;

    @JsonProperty("deleted")
    private Integer deleted;

    @JsonProperty("date_entered")
    @JsonDeserialize(using = CustomDateDeserializer.class)
    @JsonSerialize(using = CustomDateSerializer.class)
    private Date dateEntered;

    @JsonProperty("date_modified")
    @JsonDeserialize(using = CustomDateDeserializer.class)
    @JsonSerialize(using = CustomDateSerializer.class)
    private Date dateModified;

    @JsonProperty("scheduler_id")
    private String schedulerId;

    @JsonProperty("execute_time")
    @JsonDeserialize(using = CustomDateDeserializer.class)
    @JsonSerialize(using = CustomDateSerializer.class)
    private Date executeTime;

    @JsonProperty("status")
    private String status;

    @JsonProperty("resolution")
    private String resolution;

    @JsonProperty("message")
    private String message;

    @JsonProperty("target")
    private String target;

    @JsonProperty("data")
    private String data;

    @JsonProperty("requeue")
    private Integer requeue;

    @JsonProperty("retry_count")
    private Integer retryCount;

    @JsonProperty("failure_count")
    private Integer failureCount;

    @JsonProperty("job_delay")
    private Integer jobDelay;

    @JsonProperty("client")
    private String client;

    @JsonProperty("percent_complete")
    private Integer percentComplete;

}


text:
Yum Yum !

**_tl;dr_** : The project is deployed [here](https://meny-demo.netlify.com), but beware that it is a work in progress so expect a lot of unfinished stuff, and also note that all text is in french.

### What is this repo about ?

The goal of this project is to provide a way for me and my wife to store recipes that we have tried and tweaked to our liking, share them, and be able to edit / delete them as needed.
Ultimately anybody could come to the site and use the app to browse the recipes or even add their own recipes.

Nothing fancy or new, but it was a good idea for me to build a decent-sized app and try some new technologies / libs in the process.

### Is it finished ?

Well, no, not at all :D

The basic functionnality is there, so one can come to the site and browse / add / edit recipes, but some key features are not yet implemented:

- Auth : the idea is to add an actual authentification process with firebase (since I am using firebase for the data), and some user profile page / option. For now there is a simple dummy menu in the nav to simulate different users in the client.
- Images : having customized images for each recipe that one can upload / edit / tweak, for now most of the recipe specifics images display a pug wrapped in a scarf.
- Animations / Transitions / Polish : I haven't had a chance to pay too much attention to this so far so the UI is a bit rough (especially on small devices), but improvement is definitely planned.
- Production optimizations / PWA features : offline support, app manifest, bundle size reduction, all of this and more is on the list but this will come after the other features.

The list will be updated as I make progress on these.

### Can I see where we are now ?

Sure, right now the repo is hooked up to a dummy firebase project with a few recipes for external testing, and thanks to the awesome guys at netlify, the app is deployed and updated on each git push.

Here is the url : [https://meny-demo.netlify.com](https://meny-demo.netlify.com)

You can choose a dummy user and add recipes if you want. You can also edit the recipes that you have added and browse the other ones.
Note that the users will all be french so it is all in french language for now.

### Anything else ?

You can contact me if you have any questions.

If you want to know more about what I learned when working on this project, see [this file](/THOUGHTS.md).


text:
class DVector {

public:

  DVector();
  DVector(long N_);
  DVector(const DVector &G);
  DVector& operator= (const DVector &G);
  ~DVector();

  void Init(void);
  void Init(long N_); // Initialized as a zero vector
  void ReleaseAllMemory(void);
  void DeepCopy(const DVector &G);

  //-------------------- Utilities --------------------

  // Get length
  long GetN(void) const;

  // Get a(i)
  double GetEntry(long i) const;
  // b = a(RowStart:RowStart+nRow-1)
  void GetBlock(long RowStart, long nRow, DVector &b) const;
  void GetBlock(long RowStart, long nRow, double *b) const;
  // b = a(idx)
  void GetBlock(long *idx, long n, DVector &b) const;
  // Get the double* pointer
  double* GetPointer(void) const;

  // Set a(i) = b
  void SetEntry(long i, double b);
  // a(RowStart:RowStart+nRow-1) = b
  void SetBlock(long RowStart, long nRow, const DVector &b);
  void SetBlock(long RowStart, long nRow, const double *b);

  // a = c
  void SetConstVal(double c);
  // a = rand()
  void SetUniformRandom01(void);
  // a = randn()
  void SetStandardNormal(void);
  // a = trnd(1); each element is a student-t of degree 1
  void SetStudentT1(void);
  // The whole vector is a multivariate student-t of degree 1
  void SetMultivariateStudentT1(void);

  // Permutation
  // a(i) = a(Perm(i))
  void Permute(const long *Perm, long N_);
  // a(iPerm(i)) = a(i)
  void iPermute(const long *iPerm, long N_);
  // Note the following two sets of calling patterns:
  //   (1)  Permute(Perm, N) is equivalent to iPermute(iPerm, N);
  //   (2)  Permute(iPerm, N) is equivalent to iPermute(Perm, N).
  // Moreover, the effect of (1) is opposite to that of (2)

  // Sorting
  // a = sort(a, type)
  void Sort(SortType type);
  // a = sort(a, type). Sort accoding to |a|
  void SortByMagnitude(SortType type);

  // Find elements larger than tol. The array idx contains the indices
  // of the elements that satisfy the requirement. The return value is
  // the number of such elements. Memory of idx must be
  // preallocated. For safety, it is recommended that idx has the
  // length as the vector itself.
  long FindLargerThan(double tol, long *idx) const;

  // Print the vector in the Matlab form
  void PrintVectorMatlabForm(const char *name) const;

  //-------------------- Vector computations --------------------

  // a = -a  or  b = -a
  void Negate(void);
  void Negate(DVector &b) const;

  // a = a + b  or  c = a + b
  void Add(double b);
  void Add(const DVector &b);
  void Add(double b, DVector &c) const;
  void Add(const DVector &b, DVector &c) const;

  // a = a - b  or  c = a - b
  void Subtract(double b);
  void Subtract(const DVector &b);
  void Subtract(double b, DVector &c) const;
  void Subtract(const DVector &b, DVector &c) const;

  // a = a * b  or  c = a * b
  void Multiply(double b);
  void Multiply(double b, DVector &c) const;
  // a = a .* b  or  c = a .* b
  void Multiply(const DVector &b);
  void Multiply(const DVector &b, DVector &c) const;

  // a = a / b  or  a = a / b
  void Divide(double b);
  void Divide(double b, DVector &c) const;
  // a = a ./ b  or  a = a ./ b
  void Divide(const DVector &b);
  void Divide(const DVector &b, DVector &c) const;

  // a' * b
  double InProd(const DVector &b) const;

  // a = abs(a)  or  b = abs(a)
  void Abs(void);
  void Abs(DVector &b) const;

  // a = sqrt(a)  or  b = sqrt(a)
  void Sqrt(void);
  void Sqrt(DVector &b) const;

  // a = 1./a  or  b = 1./a
  void Inv(void);
  void Inv(DVector &b) const;

  // norm(a,2)
  double Norm2(void) const;

  // min(a). idx is the location of the min
  double Min(void) const;
  double Min(long &idx) const;

  // max(a). idx is the location of the max
  double Max(void) const;
  double Max(long &idx) const;

  // sum(a)
  double Sum(void) const;

  // mean(a)
  double Mean(void) const;

protected:

private:

  long N;    // Vector length
  double *a; // Vector data

};

#endif


text:
{-# LANGUAGE CPP #-}

module CodeGen.Platform.PPC where

#define MACHREGS_NO_REGS 0
#define MACHREGS_powerpc 1
#include "../../../../includes/CodeGen.Platform.hs"