text:
using System;
using System.CodeDom;
using System.Linq;
using System.Diagnostics;
using Fonlow.Reflection;
using Fonlow.Web.Meta;
using System.Collections.Generic;

namespace Fonlow.CodeDom.Web.Cs
{
	/// <summary>
	/// Generate a client function upon ApiDescription for C#
	/// </summary>
	internal class ClientApiFunctionGen
	{
		readonly WebApiDescription description;
		readonly string methodName;
		protected Type returnType;
		readonly bool returnTypeIsStream;
		readonly bool returnTypeIsDynamicObject;

		/// <summary>
		/// Decorated by NotNullAttribute
		/// </summary>
		readonly bool returnTypeDecoratedWithNotNullable = false;
		readonly bool returnTypeDecoratedWithMaybeNullable = false;
		CodeMemberMethod clientMethod;
		readonly Poco2Client.Poco2CsGen poco2CsGen;
		readonly bool forAsync;
		readonly bool stringAsString;
		readonly string statementOfEnsureSuccessStatusCode;
		readonly CodeGenOutputs settings;

		ClientApiFunctionGen(WebApiDescription description, Poco2Client.Poco2CsGen poco2CsGen, CodeGenOutputs settings, bool forAsync)
		{
			this.description = description;
			//this.sharedContext = sharedContext;
			this.poco2CsGen = poco2CsGen;
			this.settings = settings;
			this.forAsync = forAsync;
			this.stringAsString = settings.StringAsString;
			//this.diFriendly = settings.DIFriendly;
			statementOfEnsureSuccessStatusCode = settings.UseEnsureSuccessStatusCodeEx ? "EnsureSuccessStatusCodeEx" : "EnsureSuccessStatusCode";
			methodName = description.ActionDescriptor.ActionName;
			if (methodName.EndsWith("Async"))
				methodName = methodName.Substring(0, methodName.Length - 5);

			returnType = description.ResponseDescription?.ResponseType ?? description.ActionDescriptor.ReturnType;
			returnTypeIsStream = returnType != null && ((returnType.FullName == typeNameOfHttpResponseMessage)
				|| (returnType.FullName == typeOfIHttpActionResult)
				|| (returnType.FullName == typeOfIActionResult)
				|| (returnType.FullName == typeOfActionResult)
				|| (returnType.FullName.StartsWith("System.Threading.Tasks.Task`1[[Microsoft.AspNetCore.Mvc.IActionResult")) // .net core is not translating Task<IActionResult> properly.
				|| (returnType.FullName.StartsWith("System.Threading.Tasks.Task`1[[Microsoft.AspNetCore.Mvc.IHttpActionResult"))
				|| (returnType.FullName.StartsWith("System.Threading.Tasks.Task`1[[Microsoft.AspNetCore.Mvc.ActionResult"))
				);

			returnTypeIsDynamicObject = returnType != null && returnType.FullName != null && returnType.FullName.StartsWith("System.Threading.Tasks.Task`1[[System.Object");

			var methodInfo = description.ActionDescriptor.ControllerDescriptor.ControllerType.GetMethod(description.ActionDescriptor.MethodName, description.ActionDescriptor.MethodTypes);
			if (methodInfo != null)
			{
				if (settings.MaybeNullAttributeOnMethod)
				{
					returnTypeDecoratedWithMaybeNullable = returnType != null && Attribute.IsDefined(methodInfo.ReturnParameter, typeof(System.Diagnostics.CodeAnalysis.MaybeNullAttribute));
				} else if (settings.NotNullAttributeOnMethod)
				{
					returnTypeDecoratedWithNotNullable = returnType != null && Attribute.IsDefined(methodInfo.ReturnParameter, typeof(System.Diagnostics.CodeAnalysis.NotNullAttribute));
				}
			}
		}
		const string typeOfIHttpActionResult = "System.Web.Http.IHttpActionResult";
		const string typeOfIActionResult = "Microsoft.AspNetCore.Mvc.IActionResult"; //for .net core 2.1. I did not need this for .net core 2.0
		const string typeOfActionResult = "Microsoft.AspNetCore.Mvc.ActionResult"; //for .net core 2.1. I did not need this for .net core 2.0

		static readonly Type typeOfChar = typeof(char);

		public static CodeMemberMethod Create(WebApiDescription description, Poco2Client.Poco2CsGen poco2CsGen, CodeGenOutputs settings, bool forAsync)
		{
			var gen = new ClientApiFunctionGen(description, poco2CsGen, settings, forAsync);
			return gen.CreateApiFunction();
		}

		CodeMemberMethod CreateApiFunction()
		{
			//create method
			clientMethod = forAsync ? CreateMethodBasicForAsync() : CreateMethodBasic();

			CreateDocComments();
			if (settings.MaybeNullAttributeOnMethod && returnTypeDecoratedWithMaybeNullable)
			{
				clientMethod.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.CodeAnalysis.MaybeNullAttribute"));
			} else if (settings.NotNullAttributeOnMethod && returnTypeDecoratedWithNotNullable)
			{
				clientMethod.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.CodeAnalysis.NotNullAttribute"));
			}

			System.Globalization.TextInfo textInfo = new System.Globalization.CultureInfo("en-US", false).TextInfo;
			switch (description.HttpMethod)
			{
				case "GET":
				case "DELETE":
					RenderGetOrDeleteImplementation(textInfo.ToTitleCase(description.HttpMethod.ToLower()), forAsync);
					break;
				case "POST":
				case "PUT":
				case "PATCH":
					RenderPostOrPutImplementation(textInfo.ToTitleCase(description.HttpMethod.ToLower()), forAsync);
					break;
				default:
					Trace.TraceWarning("This HTTP method {0} is not yet supported", description.HttpMethod);
					break;
			}

			return clientMethod;
		}

		CodeMemberMethod CreateMethodBasic()
		{
			return new CodeMemberMethod()
			{
				Attributes = MemberAttributes.Public | MemberAttributes.Final,
				Name = methodName,
				ReturnType = poco2CsGen.TranslateToClientTypeReferenceForNullableReference(returnType),
			};
		}

		CodeMemberMethod CreateMethodBasicForAsync()
		{
			return new CodeMemberMethod()
			{
				Attributes = MemberAttributes.Public | MemberAttributes.Final,
				Name = methodName + "Async",
				ReturnType = returnType == null ? new CodeTypeReference("async Task")
				: new CodeTypeReference("async Task", poco2CsGen.TranslateToClientTypeReferenceForNullableReference(returnType)),
			};
		}

		void CreateDocComments()
		{
			void CreateDocComment(string elementName, string doc)
			{
				if (string.IsNullOrWhiteSpace(doc))
					return;

				clientMethod.Comments.Add(new CodeCommentStatement("<" + elementName + ">" + doc + "</" + elementName + ">", true));
			}

			void CreateParamDocComment(string paramName, string doc)
			{
				if (String.IsNullOrWhiteSpace(doc))
					return;

				clientMethod.Comments.Add(new CodeCommentStatement("<param name=\"" + paramName + "\">" + doc + "</param>", true));
			}

			clientMethod.Comments.Add(new CodeCommentStatement("<summary>", true));
			var methodFullName = description.ActionDescriptor.MethodFullName;
			if (description.ParameterDescriptions.Length > 0)
			{
				methodFullName += "(" + description.ParameterDescriptions.Select(d =>
				{
					string typeText;
					if (TypeHelper.IsSimpleType(d.ParameterDescriptor.ParameterType))
					{
						typeText = d.ParameterDescriptor.ParameterType.FullName;
					}
					else if (d.ParameterDescriptor.ParameterType.IsGenericType)
					{
						typeText = poco2CsGen.TranslateToClientTypeReferenceTextForDocComment(d.ParameterDescriptor.ParameterType);
					}
					else if (d.ParameterDescriptor.ParameterType.IsArray)
					{
						typeText = poco2CsGen.TranslateToClientTypeReferenceTextForDocComment(d.ParameterDescriptor.ParameterType);
					}
					else
					{
						typeText = d.ParameterDescriptor.ParameterType.FullName;
					};

					return typeText;
				}).Aggregate((c, n) => c + "," + n) + ")";

				Console.WriteLine("FullName: " + methodFullName);
			}

			Fonlow.DocComment.docMember methodComments = null;
			if (WebApiDocSingleton.Instance.Lookup != null)
			{
				methodComments = WebApiDocSingleton.Instance.Lookup.GetMember("M:" + methodFullName);
				var noIndent = Fonlow.DocComment.StringFunctions.TrimIndentedMultiLineTextToArray(Fonlow.DocComment.DocCommentHelper.GetSummary(methodComments));
				if (noIndent != null)
				{
					foreach (var item in noIndent)
					{
						clientMethod.Comments.Add(new CodeCommentStatement(item, true));
					}
				}
			}

			clientMethod.Comments.Add(new CodeCommentStatement(description.HttpMethod + " " + description.RelativePath, true));
			clientMethod.Comments.Add(new CodeCommentStatement("</summary>", true));
			foreach (var item in description.ParameterDescriptions)
			{
				var parameterComment = Fonlow.DocComment.DocCommentHelper.GetParameterComment(methodComments, item.Name);
				if (!String.IsNullOrEmpty(parameterComment))
				{
					CreateParamDocComment(item.Name, parameterComment);
				}
			}

			var returnComment = Fonlow.DocComment.DocCommentHelper.GetReturnComment(methodComments);
			if (returnComment != null)
			{
				CreateDocComment("returns", returnComment);
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="httpMethod">GET, DELETE, POST, PUT</param>
		/// <param name="forAsync"></param>
		void RenderGetOrDeleteImplementation(string httpMethod, bool forAsync)
		{
			CodeParameterDeclarationExpression[] parameters = description.ParameterDescriptions.Where(p => p.ParameterDescriptor.ParameterBinder == ParameterBinder.FromUri
			|| p.ParameterDescriptor.ParameterBinder == ParameterBinder.FromQuery || p.ParameterDescriptor.ParameterBinder == ParameterBinder.None)
				.Select(d =>
				new CodeParameterDeclarationExpression(poco2CsGen.TranslateToClientTypeReference(d.ParameterDescriptor.ParameterType), d.Name))
				.ToArray();
			clientMethod.Parameters.AddRange(parameters);

			if (settings.CancellationTokenEnabled)
			{
				clientMethod.Parameters.Add(new CodeParameterDeclarationExpression("System.Threading.CancellationToken", "cancellationToken"));
			}

			if (settings.HandleHttpRequestHeaders)
			{
				clientMethod.Parameters.Add(new CodeParameterDeclarationExpression("Action<System.Net.Http.Headers.HttpRequestHeaders>", "handleHeaders = null"));
			}

			var jsUriQuery = UriQueryHelper.CreateUriQuery(description.RelativePath, description.ParameterDescriptions);
			string uriText = jsUriQuery == null ? $"\"{description.RelativePath}\"" : RemoveTrialEmptyString($"\"{jsUriQuery}\"");

			clientMethod.Statements.Add(new CodeVariableDeclarationStatement(
				new CodeTypeReference("var"), "requestUri",
				new CodeSnippetExpression(uriText)));

			clientMethod.Statements.Add(new CodeSnippetStatement(ThreeTabs + $"using var httpRequestMessage = new HttpRequestMessage(HttpMethod.{httpMethod}, requestUri);"));

			if (settings.HandleHttpRequestHeaders)
			{
				clientMethod.Statements.Add(new CodeSnippetStatement("\t\t\thandleHeaders?.Invoke(httpRequestMessage.Headers);"));
			}

			AddResponseMessageSendAsync(clientMethod);

			CodeVariableReferenceExpression resultReference = new CodeVariableReferenceExpression("responseMessage");

			//Statement: result.EnsureSuccessStatusCode();
			if (returnTypeIsStream)
			{
				clientMethod.Statements.Add(new CodeMethodInvokeExpression(resultReference, statementOfEnsureSuccessStatusCode));

				if (returnType != null)
				{
					AddReturnStatement(clientMethod.Statements);
				}

				//Add3TEndBacket(clientMethod);
			}
			else
			{
				CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement();
				try1.TryStatements.Add(new CodeMethodInvokeExpression(resultReference, statementOfEnsureSuccessStatusCode));
				clientMethod.Statements.Add(try1);

				//Statement: return something;
				if (returnType != null)
				{
					AddReturnStatement(try1.TryStatements);
				}

				try1.FinallyStatements.Add(new CodeMethodInvokeExpression(resultReference, "Dispose"));
				//Add3TEndBacket(clientMethod);
			}
		}

		static void Add3TEndBacket(CodeMemberMethod method)
		{
			method.Statements.Add(new CodeSnippetStatement("\t\t\t}"));
		}

		string ThreeTabs => "\t\t\t";

		void AddResponseMessageSendAsync(CodeMemberMethod method)
		{
			var cancellationToken = settings.CancellationTokenEnabled ? ", cancellationToken" : String.Empty;
			method.Statements.Add(new CodeVariableDeclarationStatement(
				new CodeTypeReference("var"), "responseMessage", forAsync ? new CodeSnippetExpression($"await client.SendAsync(httpRequestMessage{cancellationToken})") : new CodeSnippetExpression($"client.SendAsync(httpRequestMessage{cancellationToken}).Result")));
		}

		void RenderPostOrPutImplementation(string httpMethod, bool forAsync)
		{
			//Create function parameters in prototype
			var parameters = description.ParameterDescriptions.Where(p => p.ParameterDescriptor.ParameterBinder == ParameterBinder.FromUri
			|| p.ParameterDescriptor.ParameterBinder == ParameterBinder.FromQuery || p.ParameterDescriptor.ParameterBinder == ParameterBinder.FromBody
			|| p.ParameterDescriptor.ParameterBinder == ParameterBinder.None).Select(d => new CodeParameterDeclarationExpression()
			{
				Name = d.Name,
				Type = poco2CsGen.TranslateToClientTypeReference(d.ParameterDescriptor.ParameterType),

			}).ToArray();
			clientMethod.Parameters.AddRange(parameters);

			if (settings.CancellationTokenEnabled)
			{
				clientMethod.Parameters.Add(new CodeParameterDeclarationExpression("System.Threading.CancellationToken", "cancellationToken"));
			}

			if (settings.HandleHttpRequestHeaders)
			{
				clientMethod.Parameters.Add(new CodeParameterDeclarationExpression("Action<System.Net.Http.Headers.HttpRequestHeaders>", "handleHeaders = null"));
			}

			var fromBodyParameterDescriptions = description.ParameterDescriptions.Where(d => d.ParameterDescriptor.ParameterBinder == ParameterBinder.FromBody
				|| (TypeHelper.IsComplexType(d.ParameterDescriptor.ParameterType) && (!(d.ParameterDescriptor.ParameterBinder == ParameterBinder.FromUri) || (d.ParameterDescriptor.ParameterBinder == ParameterBinder.None)))).ToArray();
			if (fromBodyParameterDescriptions.Length > 1)
			{
				throw new CodeGenException("Bad Api Definition")
				{
					Description = String.Format("This API function {0} has more than 1 FromBody bindings in parameters", description.ActionDescriptor.ActionName)
				};
			}

			var singleFromBodyParameterDescription = fromBodyParameterDescriptions.FirstOrDefault();

			void AddRequestUriWithQueryAssignmentStatement()
			{

				var jsUriQuery = UriQueryHelper.CreateUriQuery(description.RelativePath, description.ParameterDescriptions);
				string uriText = jsUriQuery == null ? $"\"{description.RelativePath}\"" : RemoveTrialEmptyString($"\"{jsUriQuery}\"");

				clientMethod.Statements.Add(new CodeVariableDeclarationStatement(
					new CodeTypeReference("var"), "requestUri",
					new CodeSnippetExpression(uriText)));
			}

			AddRequestUriWithQueryAssignmentStatement();

			clientMethod.Statements.Add(new CodeSnippetStatement(
				ThreeTabs + $"using var httpRequestMessage = new HttpRequestMessage(HttpMethod.{httpMethod}, requestUri);"));

			if (singleFromBodyParameterDescription != null)
			{
				if (settings.UseSystemTextJson)
				{
					clientMethod.Statements.Add(new CodeSnippetStatement(ThreeTabs + $"var contentJson = JsonSerializer.Serialize({singleFromBodyParameterDescription.ParameterDescriptor.ParameterName}, jsonSerializerSettings);"));
					clientMethod.Statements.Add(new CodeSnippetStatement(ThreeTabs + @"var content = new StringContent(contentJson, System.Text.Encoding.UTF8, ""application/json"");"));
				}
				else
				{
					clientMethod.Statements.Add(new CodeSnippetStatement(
	@"			using var requestWriter = new System.IO.StringWriter();
			var requestSerializer = JsonSerializer.Create(jsonSerializerSettings);"
	));
					clientMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeSnippetExpression("requestSerializer"), "Serialize",
						new CodeSnippetExpression("requestWriter"),
						new CodeSnippetExpression(singleFromBodyParameterDescription.ParameterDescriptor.ParameterName)));

					clientMethod.Statements.Add(new CodeSnippetStatement(
	@"			var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, ""application/json"");"
						));
				}

				clientMethod.Statements.Add(new CodeSnippetStatement("\t\t\thttpRequestMessage.Content = content;"));
				if (settings.HandleHttpRequestHeaders)
				{
					clientMethod.Statements.Add(new CodeSnippetStatement("\t\t\thandleHeaders?.Invoke(httpRequestMessage.Headers);"));
				}
			}

			AddResponseMessageSendAsync(clientMethod);

			var resultReference = new CodeVariableReferenceExpression("responseMessage");

			if (returnTypeIsStream)
			{
				clientMethod.Statements.Add(new CodeMethodInvokeExpression(resultReference, statementOfEnsureSuccessStatusCode));

				//Statement: return something;
				if (returnType != null)
				{
					AddReturnStatement(clientMethod.Statements);
				}
			}
			else
			{
				CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement();
				clientMethod.Statements.Add(try1);
				try1.TryStatements.Add(new CodeMethodInvokeExpression(resultReference, statementOfEnsureSuccessStatusCode));

				//Statement: return something;
				if (returnType != null)
				{
					AddReturnStatement(try1.TryStatements);
				}

				try1.FinallyStatements.Add(new CodeMethodInvokeExpression(resultReference, "Dispose"));
			}

			if (singleFromBodyParameterDescription != null && !settings.UseSystemTextJson)
			{
				//Add3TEndBacket(clientMethod);
			}

			//Add3TEndBacket(clientMethod);
		}

		static void Add4TEndBacket(CodeStatementCollection statementCollection)
		{
			statementCollection.Add(new CodeSnippetStatement("\t\t\t\t}"));
		}

		static void Add4TStartBacket(CodeStatementCollection statementCollection)
		{
			statementCollection.Add(new CodeSnippetStatement("\t\t\t\t{"));
		}

		static void AddNewtonSoftJsonTextReader(CodeStatementCollection statementCollection)
		{
			statementCollection.Add(new CodeSnippetStatement("\t\t\t\tusing JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream));"));
		}

		void AddNewtonSoftJsonSerializerDeserialize(CodeStatementCollection statementCollection)
		{
			//statementCollection.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression( this had been working well, however, there's not built-in way of supporting nullable in codedom.
			//	new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("serializer"), "Deserialize", poco2CsGen.TranslateToClientTypeReference(returnType)),
			//		new CodeSnippetExpression("jsonReader"))));

			statementCollection.Add(new CodeSnippetStatement($"\t\t\t\treturn serializer.Deserialize<{poco2CsGen.TranslateTypeToCSharp(returnType)}>(jsonReader);"));

		}

		static void AddNewtonSoftJsonSerializer(CodeStatementCollection statementCollection)
		{
			statementCollection.Add(new CodeVariableDeclarationStatement(
				new CodeTypeReference("var"), "serializer", new CodeSnippetExpression("JsonSerializer.Create(jsonSerializerSettings)")));
		}

		void DeserializeContentString(CodeStatementCollection statementCollection)
		{
			statementCollection.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(
				new CodeMethodReferenceExpression(
				new CodeVariableReferenceExpression("JsonSerializer"), "Deserialize", poco2CsGen.TranslateToClientTypeReference(returnType)),
				new CodeSnippetExpression("contentString"), new CodeSnippetExpression("jsonSerializerSettings"))));
		}

		void AddResponseMessageRead(CodeStatementCollection statementCollection)
		{
			if (TypeHelper.IsStringType(returnType)) //ASP.NET Core return null as empty body with status code 204, whether to produce JSON or plain text.
			{
				statementCollection.Add(new CodeSnippetStatement("\t\t\t\tif (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; }"));
			}

			if (settings.UseSystemTextJson)
			{
				if (returnType != null && TypeHelper.IsStringType(returnType) && this.stringAsString)
				{
					statementCollection.Add(new CodeSnippetStatement(forAsync
					? "\t\t\t\tvar stream = await responseMessage.Content.ReadAsStreamAsync();"
					: "\t\t\t\tvar stream = responseMessage.Content.ReadAsStreamAsync().Result;"));
				}
				else
				{
					statementCollection.Add(new CodeSnippetStatement(forAsync
					? "\t\t\t\tvar contentString = await responseMessage.Content.ReadAsStringAsync();"
					: "\t\t\t\tvar contentString = responseMessage.Content.ReadAsStringAsync().Result;"));
				}
			}
			else
			{
				statementCollection.Add(new CodeSnippetStatement(forAsync
					? "\t\t\t\tvar stream = await responseMessage.Content.ReadAsStreamAsync();"
					: "\t\t\t\tvar stream = responseMessage.Content.ReadAsStreamAsync().Result;"));
			}
		}

		const string typeNameOfHttpResponseMessage = "System.Net.Http.HttpResponseMessage";

		void AddReturnStatement(CodeStatementCollection statementCollection)
		{
			if (returnTypeIsStream)
			{
				statementCollection.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("responseMessage")));
				return;
			}
			else if (returnTypeIsDynamicObject) // .NET Core ApiExplorer could get return type out of Task<> in most cases, however, not for dynamic and anynomous, while .NET Framework ApiExplorer is fine.
			{
				AddResponseMessageRead(statementCollection);
				if (settings.UseSystemTextJson)
				{
					DeserializeContentString(statementCollection); //todo: may not be good
				}
				else
				{
					AddNewtonSoftJsonTextReader(statementCollection);
					//Add4TStartBacket(statementCollection);

					AddNewtonSoftJsonSerializer(statementCollection);

					//var invokeExpression = new CodeMethodInvokeExpression(
					//	new CodeMethodReferenceExpression(
					//		new CodeVariableReferenceExpression("serializer"),
					//		"Deserialize",
					//		poco2CsGen.TranslateToClientTypeReference(returnType)
					//	),

					//	new CodeSnippetExpression("jsonReader")
					//);
					//statementCollection.Add(new CodeMethodReturnStatement(invokeExpression));

					statementCollection.Add(new CodeSnippetStatement($"\t\t\t\treturn serializer.Deserialize<{poco2CsGen.TranslateTypeToCSharp(returnType)}>(jsonReader);"));

					//Add4TEndBacket(statementCollection);
				}

				return;
			}
			else if (returnType.IsGenericType)
			{
				Type genericTypeDefinition = returnType.GetGenericTypeDefinition();
				if (genericTypeDefinition == typeof(System.Threading.Tasks.Task<>))
				{
					statementCollection.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("responseMessage")));
					Trace.TraceWarning("There could be something to improve: " + returnType.GenericTypeArguments[0].ToString());
					return;
				}
			}

			AddResponseMessageRead(statementCollection);

			if (returnType != null && TypeHelper.IsStringType(returnType))
			{
				if (this.stringAsString)
				{
					statementCollection.Add(new CodeSnippetStatement("\t\t\t\tusing System.IO.StreamReader streamReader = new System.IO.StreamReader(stream);"));
					//Add4TStartBacket(statementCollection); for C# 6, no backets needed
					statementCollection.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("streamReader.ReadToEnd();")));
					//Add4TEndBacket(statementCollection);
				}
				else
				{
					if (settings.UseSystemTextJson)
					{
						statementCollection.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(
							new CodeMethodReferenceExpression(
								new CodeVariableReferenceExpression("JsonSerializer"), "Deserialize", new CodeTypeReference(typeof(System.String))),
							new CodeSnippetExpression("contentString"),
							new CodeSnippetExpression("jsonSerializerSettings"))));
					}
					else
					{
						AddNewtonSoftJsonTextReader(statementCollection);
						//Add4TStartBacket(statementCollection);
						statementCollection.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("jsonReader.ReadAsString()")));
						//Add4TEndBacket(statementCollection);
					}
				}
			}
			else if (returnType == typeOfChar)
			{
				if (settings.UseSystemTextJson)
				{
					DeserializeContentString(statementCollection);
				}
				else
				{
					AddNewtonSoftJsonTextReader(statementCollection);
					//Add4TStartBacket(statementCollection);
					AddNewtonSoftJsonSerializer(statementCollection);
					statementCollection.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("serializer.Deserialize<char>(jsonReader)")));
					//Add4TEndBacket(statementCollection);
				}
			}
			else if (returnType.IsPrimitive)
			{
				if (settings.UseSystemTextJson)
				{
					DeserializeContentString(statementCollection);
				}
				else
				{
					AddNewtonSoftJsonTextReader(statementCollection);
					//Add4TStartBacket(statementCollection);
					statementCollection.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(String.Format("{0}.Parse(jsonReader.ReadAsString())", returnType.FullName))));
					//Add4TEndBacket(statementCollection);
				}
			}
			else if (returnType.IsGenericType || TypeHelper.IsComplexType(returnType) || returnType.IsEnum)
			{
				if (settings.UseSystemTextJson)
				{
					DeserializeContentString(statementCollection);
				}
				else
				{
					AddNewtonSoftJsonTextReader(statementCollection);
					//Add4TStartBacket(statementCollection);
					AddNewtonSoftJsonSerializer(statementCollection);
					AddNewtonSoftJsonSerializerDeserialize(statementCollection);
					//Add4TEndBacket(statementCollection);
				}
			}
			else
			{
				Trace.TraceWarning("This type is not yet supported: {0}", returnType.FullName);
			}
		}

		private static string RemoveTrialEmptyString(string s)
		{
			var p = s.IndexOf("+\"\"");
			if (p >= 0)
			{
				return s.Remove(p, 3);
			}

			var p2 = s.IndexOf("))\"");
			if (p2 >= 0)
			{
				return s.Remove(p2 + 2, 1);
			}

			return s;
		}

	}

}


text:
namespace Far_Off_Wanderer;

using System;

public static class Program
{
    [STAThread]
    static void Main()
    {
        using Startup game = new();
        game.Run();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<html>
<head>
  <script src="script.js"></script>
</head>
<body>
  <input type="text" id="a" />
  <script>

  function onChangeCallback(res){
    console.log("multi select callback: " + res);
  }

  var input = document.querySelector("#a");

  var options = {
    options: ['a','b','c'],
    shouldAddOther: true,
    onChange: onChangeCallback
  }
  var multiSelect = new MultiChoiceSelector(input, options);

  /* when ever you want just trye input.value and you'll get the values */

  </script>
</body>
</html>


text:
Maps in Elixir are the data structure for storing information in key-value pairs. In other languages, these might also be known as associative arrays (PHP), hashes (Perl 5, Raku), or dictionaries (Python).

Keys and values can be of any data type, but if the key is an atom we can use a shorthand syntax. Maps do not guarantee the order of their entries when accessed or returned.

## Literal forms

An empty map is simply declared with `%{}`. If we want to add items to a map literal, we can use two forms:

```elixir
# If the key is an atom:
%{atom_key: 1}

# If the key is a different type:
%{1 => :atom_value}

# You can even mix these if the atom form comes second:
%{"first_form" => :a, atom_form: :b}
```

While there is no canonical format, choose a consistent way to represent the key-value literal pairs.

## Map module functions

Elixir provides many functions for working with maps in the _Map module_. Some _Map module_ functions require an _anonymous_ function to be passed into the function to assist with the map transformation.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CecilViewInterface</title>
<meta name="date" content="2013-11-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.raspberrypi.cecil.view

Interface CecilViewInterface

All Known Implementing Classes:

Frame

public interface CecilViewInterface

Method Summary

Methods

Modifier and Type
Method and Description

void
setAccStack(java.util.ArrayList<java.lang.String> values)

void
setCarryFlag(boolean flagIsOn)

void
setConsoleText(java.util.ArrayList<java.lang.String> text)

void
setInstructionList(java.util.ArrayList<CecilInstruction> instructions)

void
setMemoryAllocation(java.util.HashMap<java.lang.Integer,java.lang.Integer> values)

void
setNegativeFlag(boolean flagIsOn)

void
setXStack(java.util.ArrayList<java.lang.String> values)

void
setYStack(java.util.ArrayList<java.lang.String> values)

void
setZeroFlag(boolean flagIsOn)

Method Detail

setInstructionList

void setInstructionList(java.util.ArrayList<CecilInstruction> instructions)

setAccStack

void setAccStack(java.util.ArrayList<java.lang.String> values)

setXStack

void setXStack(java.util.ArrayList<java.lang.String> values)

setYStack

void setYStack(java.util.ArrayList<java.lang.String> values)

setCarryFlag

void setCarryFlag(boolean flagIsOn)

setZeroFlag

void setZeroFlag(boolean flagIsOn)

setNegativeFlag

void setNegativeFlag(boolean flagIsOn)

setConsoleText

void setConsoleText(java.util.ArrayList<java.lang.String> text)

setMemoryAllocation

void setMemoryAllocation(java.util.HashMap<java.lang.Integer,java.lang.Integer> values)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?xml version="1.0" encoding="UTF-8"?>
<CQLQuery xmlns="http://CQL.caBIG/1/gov.nih.nci.cagrid.CQLQuery">
<Target name="edu.wustl.catissuecore.domain.SpecimenArray"/>
</CQLQuery>


text:
[![Gitter chat](https://badges.gitter.im/woothemes/FlexSlider.png)](https://gitter.im/woothemes/FlexSlider)

# FlexSlider 2.6.4
http://www.woocommerce.com/flexslider/ - Copyright (c) 2015 WooThemes

## Releases

The `master` branch of this repository is always the latest development version of FlexSlider. Please view the [Releases](https://github.com/woocommerce/FlexSlider/releases) section for a list of official FlexSlider builds.

### Contributing

We encourage contributions to FlexSlider and will review all pull requests submitted.

Before contributing, please see our [Contributing Guide](https://github.com/woocommerce/FlexSlider/blob/master/CONTRIBUTING.md).

### Roadmap

To keep up to date with how FlexSlider's development roadmap looks, please see our [development roadmap](https://github.com/woocommerce/FlexSlider/wiki/Roadmap).

## Updates

** Version 2.6.4 **

** Fixes resize method call for orientationchange. **

** Version 2.6.3 **

** Rollback fade fixes, due to harsh fade reports. **

** Version 2.6.2 **

** Minor update to fix issues with varying heights and overflow onto content below the slider. Fixes the visibility of the pagination and the navigation in the "fade" mode. **

** Version 2.6.1 **

** SmoothHeight now uses innerHeight() instead of height() to account for padding in calculation. Defining var altText to prevent error. bower.json add fonts folder on main field. Changed true to false in order to make sure whether or not to allow a slider comprised of a single slide. **

** Version 2.6.0 **

** Adds composer json file, scope fix for focused keyword, fixes bower demo folder exclusion, z-index fix for disabled nav arrow, play/pause accessibility fix, itemMargin fix for slider items, fixes accessibility for in focus elements and pagination controls, firefox fix for text selection on slider carousel, adds data-thumb-alt image alt attribute. **

** Version 2.5.0 **

** Bumped compatibility support starting with jQuery 1.7+. pausePlay icon fix. Firefox touch event fix. Adds customDirectionNav param. **

** Version 2.4.0 **

** Update for improved standards. Adds classes to li nav elements. Reset for li elements in stylesheet. **

** Version 2.3.0 **

** Fixes pauseInvisible attribute issue with Chrome and the Page Visibility API. **

** Version 2.2.2 **

** Fixes minified JavaScript file to remove merge conflicts. **

** Version 2.2.0 **

- Fixed event handler conflicts with devices that are both click and touch enabled. e.g., Windows 8.
- Made all slider variables public, stored in `slider.vars`. This allows manipulation of `slider.vars.minItems` and `slider.vars.maxItems` on the fly to create different fluid grids at certain breakpoints. [Check out this example demonstrating a basic technique](http://flexslider.woothemes.com/dynamic-carousel-min-max.html)
- Fixed calculations that were causing strange issues with paging and certain FlexSliders to move out of alignment.

*Be sure to test v2.2.0 with your current slider, before pushing live, to ensure everything is playing nicely.*

-----

## General Notes
FlexSlider is no longer licensed under the MIT license. FlexSlider now uses the license, GPLv2 and later.

In an effort to move the plugin forward, support for jQuery 1.4.2 has been dropped. The plugin now requires jQuery 1.7.0+. If you don't have access to the later versions of jQuery, [FlexSlider 1.8](https://github.com/woocommerce/FlexSlider/tree/flexslider1) should be a perfectly suitable substitute for your needs!

Your old styles and properties *might not work out of the box*. Some property names have been changed, noted below, as well as namespacing prefixes being applied to all elements. This means that `.flex-direction-nav .next` is now `.flex-direction-nav .flex-next` by default. The namespacing property is exposed, free for you to change.

No more overflow hidden woes! The plugin now generates a viewport element to handle the tedious task of working around overflow hidden. Yay!

The slider element is now accessible outside of the callback API via the jQuery .data() method. Example use: `$('#slider').data('flexslider')`

Helper strings have been added for performing actions quickly on FlexSlider elements. Example uses:

- `$('#slider').flexslider("play")  //Play slideshow`
- `$('#slider').flexslider("pause") //Pause slideshow`
- `$('#slider').flexslider("stop") //Stop slideshow`
- `$('#slider').flexslider("next")  //Go to next slide`
- `$('#slider').flexslider("prev")  //Go to previous slide`
- `$('#slider').flexslider(3)       //Go fourth slide`

Two new methods are available for adding/removing slides, `slider.addSlide()` and `slider.removeSlide()`. More details about this coming soon.

- `slider.addSlide(obj, pos)` accepts two parameters, a string/jQuery object and an index.
- `slider.removeSlide(obj)` accepts one parameter, either an object to be removed, or an index.

## Examples

- [Basic Slider](http://flexslider.woothemes.com/)
- [Basic Slider customDirectionNav](http://flexslider.woothemes.com/basic-slider-with-custom-direction-nav.html)
- [Slider w/thumbnail controlNav pattern](http://flexslider.woothemes.com/thumbnail-controlnav.html)
- [Slider w/thumbnail slider](http://flexslider.woothemes.com/thumbnail-slider.html)
- [Basic Carousel](http://flexslider.woothemes.com/basic-carousel.html)
- [Carousel with min and max ranges](http://flexslider.woothemes.com/carousel-min-max.html)
- [Video with Vimeo API](http://flexslider.woothemes.com/video.html)
- [Video with Wistia API](http://flexslider.woothemes.com/video-wistia.html)

## Properties

### namespace: *{new}*
`namespace` controls the prefixes attached to elements created by the plugin. In previous releases, only certain elements were tagged with a prefix class, which was causing class generalization issues for some users. FlexSlider now prefixes all generated elements with the appropriate namespace.

*Hint: `namespace` can be an empty string.*

### selector: *{new}*
The markup structure for FlexSlider has been limited to a "ul.slide li" pattern in previous versions of FlexSlider; no longer. You can now take full control of the markup structure used for your FlexSlider. The `selector` pattern "{container} > {slide}" is mandatory, allowing the plugin to predictably interpret the selector property. Omitting the ">" from the selector is not suggested, but is possible if your markup doesn't follow the immediate descendant pattern.

*Examples: "section > article", ".slides > .slide", "#hero .slide"*

### easing: *{new}*
`easing` allows support for jQuery easing! Default options provided by jQuery are "swing" and "linear," but more can be used by included the jQuery Easing plugin. *If you chose a non-existent easing method, the slider will break.*

*Note: You need to set `useCSS: false` to force transitions in browsers that support translate3d.*
*Optional: [jQuery Easing Plugin](http://gsgd.co.uk/sandbox/jquery/easing/)*

### direction: *{changed}*
Previously called "slideDirection" in v1.8 and below.

### reverse: *{new}*
`reverse` will reverse the animation direction of the slider. Meaning, horizontal sliders can move from right to left, and vertical sliders can move bottom to top.

### smoothHeight: *{new}*
`smoothHeight` allows for smooth height transitions between slides. This property currently works for the fade and horizontal slide animation. The property has no effect on horizontal sliding carousels, however.

### startAt: *{changed}*
Previously called "slideToStart" in v1.8 and below.

### animationSpeed: *{changed}*
Previously called "animationDuration" in v1.8 and below.

### initDelay: *{new}*
`initDelay` will delay the initial slideshow of a slider, given in milliseconds. The slider will still initialize, generating controls and displaying the first image, but the slideshow will wait until the `initDelay` time has completed before starting the slideshow.

### useCSS: *{new}*
`useCSS` allow users to override using CSS3 for animation. Translate3d still has numerous bugs that can crop up and wreak havoc, so this is a great property to play with if you are experiencing unexplainable issues in Webkit browsers.

*Hint: Use conditionals to enable/disable the use of CSS3 on desktops and mobile devices. Mobile devices, in my experience, do not share many of the translate3d bugs seen on desktop browsers.*

### touch: *{new}*
`touch` allows users to exclude touch swipe functionality from their sliders.

### keyboard: *{changed}*
Previously called "keyboardNav" in v1.8 and below.

### multipleKeyboard *{new}*
`multipleKeyboard` allows users to override the default plugin keyboard behavior, enabling keyboard control of more than one slider on the page. This means that all visible sliders will animate, at the same time, via keyboard input.

*Hint: You can use `multipleKeyboard` to allow keyboard navigation on pages where multiple sliders are present, but only one is visible.*

### mousewheel: *{updated}*
`mousewheel` now requires the jQuery Mousewheel plugin. There are a few reasons for this, but primarily because there is no need for FlexSlider itself to reinvent the awkward complexity of mousewheel interactivity that is handled perfectly by the Mousewheel plugin.

*Required: [jQuery Mousewheel Plugin](https://github.com/brandonaaron/jquery-mousewheel)*

### controlsContainer: *{updated}*
`controlsContainer` is one of the more painstaking, potentially confusing properties within FlexSlider. First, the property is no longer required to workaround `overflow: hidden` on slide animation. Second, the property now accepts a **jQuery object**, giving you precise control over the object you want. The plugin no longer attempts to guess what element you are selecting.

### customDirectionNav: *{new}*
`customDirectionNav` allows the ability to add custom directional navigation elements. Can be used in conjunction with controlsContainer for pagination controls container.

*[Example of customDirectionNav being used](http://flexslider.woothemes.com/basic-slider-with-custom-direction-nav.html)*

### sync: *{new}*
`sync` is a new property that will allow other slider(s) to hook into the current slider via a given selector. The selector should describe an object that has already been initialized as a FlexSlider. Right now, `sync` will synchronize animation, play, and pause behaviors. More behaviors can be added in the future as the property matures.

*[Example of sync being used](http://flex.madebymufffin.com/examples/basic-carousel.html)*

### asNavFor: *{new}*
Description to be added.

### itemWidth: *{new}*
`itemWidth` is the primary property for the new carousel options. Without this property, your slider is not considered a carousel. To use `itemWidth`, give an integer value of the width of your individual slides. This should include borders and paddings applied to your slides; a total width measurement.

### itemMargin: *{new}*
`itemMargin` describes the gutter between the slide elements. If each slide has a margin-left of 10px, your itemMargin value would be 10. If elements have margin: 0 10px, your itemMargin would be 20.

### minItems: *{new}*
`minItems` describes the minimum number of slide elements that should be visible in the carousel. When the slider reaches the minimum item count, the slides will resize fluidly with the slider.

### maxItems: *{new}*
`maxItems` describes the maximum number of slide elements that should be visible in the carousel. When the slider reaches the maximum item count, the slides will resize fluidly with the sider.

### move: *{new}*
`move` determines how many slides should be animated within the carousel. When left at 0, the slider will animate the number of visible slides. If any value greater than 0 is given, the slider will animate that number of slides in the carousel on each animation interval.

*Hint: The move property will be ignored if the value is higher than the number of visible slides, which can be utilized in responsive design.*

### added: *{new}*
`added()` is a new callback event fired in the new slider.addSlide() function.

### removed: *{new}*
`removed()` is a new callback event fired in the new slider.removeSlide() function.

### allowOneSlide: *{new}*
Boolean. Whether or not you'd like FlexSlider to initialize as usual if only one slide is present.


text:
#ifndef __SFNT_H
#define __SFNT_H

#include "LETypes.h"

#ifndef ANY_NUMBER
#define ANY_NUMBER 1
#endif

struct DirectoryEntry
{
    le_uint32   tag;
    le_uint32   checksum;
    le_uint32   offset;
    le_uint32   length;
};

struct SFNTDirectory
{
    le_uint32       scalerType;
    le_uint16       numTables;
    le_uint16       searchRange;
    le_uint16       entrySelector;
    le_uint16       rangeShift;
    DirectoryEntry  tableDirectory[ANY_NUMBER];
};

struct CMAPEncodingSubtableHeader
{
    le_uint16   platformID;
    le_uint16   platformSpecificID;
    le_uint32   encodingOffset;
};

struct CMAPTable
{
    le_uint16   version;
    le_uint16   numberSubtables;
    CMAPEncodingSubtableHeader encodingSubtableHeaders[ANY_NUMBER];
};

struct CMAPEncodingSubtable
{
    le_uint16   format;
    le_uint16   length;
    le_uint16   language;
};

struct CMAPFormat0Encoding : CMAPEncodingSubtable
{
    le_uint8    glyphIndexArray[256];
};

struct CMAPFormat2Subheader
{
    le_uint16   firstCode;
    le_uint16   entryCount;
    le_int16    idDelta;
    le_uint16   idRangeOffset;
};

struct CMAPFormat2Encoding : CMAPEncodingSubtable
{
    le_uint16  subHeadKeys[256];
    CMAPFormat2Subheader subheaders[ANY_NUMBER];
};

struct CMAPFormat4Encoding : CMAPEncodingSubtable
{
    le_uint16   segCountX2;
    le_uint16   searchRange;
    le_uint16   entrySelector;
    le_uint16   rangeShift;
    le_uint16   endCodes[ANY_NUMBER];
//  le_uint16   reservedPad;
//  le_uint16   startCodes[ANY_NUMBER];
//  le_uint16   idDelta[ANY_NUMBER];
//  le_uint16   idRangeOffset[ANY_NUMBER];
//  le_uint16   glyphIndexArray[ANY_NUMBER];
};

struct CMAPFormat6Encoding : CMAPEncodingSubtable
{
    le_uint16   firstCode;
    le_uint16   entryCount;
    le_uint16   glyphIndexArray[ANY_NUMBER];
};

struct CMAPEncodingSubtable32
{
    le_uint32   format;
    le_uint32   length;
    le_uint32   language;
};

struct CMAPGroup
{
    le_uint32   startCharCode;
    le_uint32   endCharCode;
    le_uint32   startGlyphCode;
};

struct CMAPFormat8Encoding : CMAPEncodingSubtable32
{
    le_uint32   is32[65536/32];
    le_uint32   nGroups;
    CMAPGroup   groups[ANY_NUMBER];
};

struct CMAPFormat10Encoding : CMAPEncodingSubtable32
{
    le_uint32   startCharCode;
    le_uint32   numCharCodes;
    le_uint16   glyphs[ANY_NUMBER];
};

struct CMAPFormat12Encoding : CMAPEncodingSubtable32
{
    le_uint32   nGroups;
    CMAPGroup   groups[ANY_NUMBER];
};

typedef le_int32 fixed;

struct BigDate
{
    le_uint32   bc;
    le_uint32   ad;
};

struct HEADTable
{
    fixed       version;
    fixed       fontRevision;
    le_uint32   checksumAdjustment;
    le_uint32   magicNumber;
    le_uint16   flags;
    le_uint16   unitsPerEm;
    BigDate     created;
    BigDate     modified;
    le_int16    xMin;
    le_int16    yMin;
    le_int16    xMax;
    le_int16    yMax;
    le_int16    lowestRecPPEM;
    le_int16    fontDirectionHint;
    le_int16    indexToLocFormat;
    le_int16    glyphDataFormat;
};

struct MAXPTable
{
    fixed       version;
    le_uint16   numGlyphs;
    le_uint16   maxPoints;
    le_uint16   maxContours;
    le_uint16   maxComponentPoints;
    le_uint16   maxComponentContours;
    le_uint16   maxZones;
    le_uint16   maxTwilightPoints;
    le_uint16   maxStorage;
    le_uint16   maxFunctionDefs;
    le_uint16   maxInstructionDefs;
    le_uint16   maxStackElements;
    le_uint16   maxSizeOfInstructions;
    le_uint16   maxComponentElements;
    le_uint16   maxComponentDepth;
};

struct HHEATable
{
    fixed       version;
    le_int16    ascent;
    le_int16    descent;
    le_int16    lineGap;
    le_uint16   advanceWidthMax;
    le_int16    minLeftSideBearing;
    le_int16    minRightSideBearing;
    le_int16    xMaxExtent;
    le_int16    caretSlopeRise;
    le_int16    caretSlopeRun;
    le_int16    caretOffset;
    le_int16    reserved1;
    le_int16    reserved2;
    le_int16    reserved3;
    le_int16    reserved4;
    le_int16    metricDataFormat;
    le_uint16   numOfLongHorMetrics;
};

struct LongHorMetric
{
    le_uint16   advanceWidth;
    le_int16    leftSideBearing;
};

struct HMTXTable
{
    LongHorMetric hMetrics[ANY_NUMBER];        // ANY_NUMBER = numOfLongHorMetrics from hhea table
//  le_int16      leftSideBearing[ANY_NUMBER]; // ANY_NUMBER = numGlyphs - numOfLongHorMetrics
};

#endif


text:
package net.lr.tutorial.karaf.vote.command.impl;

import net.lr.tutorial.karaf.vote.model.VoteService;
import net.lr.tutorial.karaf.vote.model.Voting;

import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.karaf.shell.console.OsgiCommandSupport;

/**
 * Displays the last log entries
 */
@Command(scope = "vote", name = "stats", description = "list existing votes")
public class VoteStats extends OsgiCommandSupport {
	protected VoteService voteService;

	@Argument(index = 0, name="topic", description = "Voting topic to show", required = true, multiValued = false)
	private String topic;

    public void setVoteService(VoteService voteService) {
		this.voteService = voteService;
	}

	protected Object doExecute() throws Exception {
         System.out.println("Executing command list");
         Voting voting = voteService.getVoting(topic);
         System.out.println(voting.getStats());
         return null;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/dialog_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="选择地址"
        android:textSize="25sp"
        android:padding="10dp"
        android:textColor="@color/white"
        android:gravity="center"
        android:background="@color/blue_gray"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <com.deeal.exchange.view.wheel.WheelView
            android:id="@+id/wl_express_city"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <com.deeal.exchange.view.wheel.WheelView
            android:id="@+id/wl_express_college"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

    <Button
        android:id="@+id/btEnsure"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:textSize="20sp"
        android:textColor="#ffffff"
        android:layout_margin="10dp"
        android:background="@drawable/bt_seletor_bluegray"
        android:text="@string/text_ensure"/>

</LinearLayout>


text:
<?php

/**
 * Class Leviathan_Facebook
 *
 * @see https://github.com/facebook/facebook-php-sdk
 */
class Leviathan_Facebook {
	const SIGNED_REQUEST_ALGORITHM = 'HMAC-SHA256';

	/**
	 * @var string
	 */
	private $appSecret = '';

	/**
	 * @param string $appSecret
	 */
	public function __construct($appSecret) {
		$this->appSecret = $appSecret;
	}

	/**
	 * @param string $input
	 * @return string
	 */
	protected function base64UrlDecode($input) {
		return base64_decode(
			strtr($input, '-_', '+/')
		);
	}

	/**
	 * @param string $signedRequest
	 * @return array
	 * @throws InvalidArgumentException
	 */
	public function parseSignedRequest($signedRequest) {
		if (!$signedRequest || strpos($signedRequest, '.') === false) {
			throw new InvalidArgumentException('Signed request was invalid!');
		}

		list($encodedSignature, $payload) = explode('.', $signedRequest, 2);

		// decode the data
		$signature = $this->base64UrlDecode($encodedSignature);
		$data = json_decode(
			$this->base64UrlDecode($payload),
			true
		);

		if (
			!isset($data['algorithm']) ||
			strtoupper($data['algorithm']) !==  self::SIGNED_REQUEST_ALGORITHM
		) {
			$message = 'Unknown algorithm. Expected ' . self::SIGNED_REQUEST_ALGORITHM;
			throw new InvalidArgumentException($message);
		}

		// check sig
		$expectedSignature = hash_hmac(
			'sha256',
			$payload,
			$this->appSecret,
			$raw = true
		);

		if (strlen($expectedSignature) !== strlen($signature)) {
			throw new InvalidArgumentException('Bad Signed JSON signature!');
		}

		$result = 0;
		for ($i = 0; $i < strlen($expectedSignature); $i++) {
			$result |= ord($expectedSignature[$i]) ^ ord($signature[$i]);
		}

		if ($result !== 0) {
			throw new InvalidArgumentException('Bad Signed JSON signature!');
		}

		return $data;
	}
}


text:
package mark_marker

class SainsburyException extends Exception("Unexpected item in bagging area")


text:
#ifdef USE_TI_UIACTIVITYINDICATOR

#import "TiUIActivityIndicatorProxy.h"
#import "TiUIActivityIndicator.h"

@implementation TiUIActivityIndicatorProxy

-(TiUIView*)newView
{
	TiUIActivityIndicator * result = [[TiUIActivityIndicator alloc] init];
	return result;
}

USE_VIEW_FOR_AUTO_WIDTH

USE_VIEW_FOR_AUTO_HEIGHT

@end

#endif


text:
require 'spec_helper'

RSpec.describe Servant::Base do
  let(:service_class) do
    Class.new(Servant::Base) do
      context do
        argument :x, type: Integer, presence: true
        argument :y, type: Integer, presence: true
      end

      def perform
        halt!('Cannot divide lower value by higher') if context.y > context.x
        halt_with!(another_errors) if context.y == context.x

        context.x / context.y
      end

      private

      def another_errors
        Servant::Errors.new(self).tap do |e|
          e.add(:x, 'Some error')
          e.add(:x, 'Some another error')
          e.add(:y, 'Yet another error')
        end
      end
    end
  end

  describe '.perform' do
    subject { service_class.perform(x: 20, y: 10) }

    it { is_expected.to be_instance_of(Servant::Result) }
    its(:value) { is_expected.to eq(2) }
    its(:success?) { is_expected.to be true }

    context 'with validation error' do
      subject { service_class.perform(x: 20, y: '10') }

      it { is_expected.to be_instance_of(Servant::Result) }
      its(:value) { is_expected.to be nil }
      its(:success?) { is_expected.to be false }
      its(:errors) { is_expected.to have(1).error }
      it { expect(subject.errors[:y]).to eq(['must be any of these types: Integer'])  }
    end

    context 'with halt error' do
      subject { service_class.perform(x: 20, y: 200) }

      it { is_expected.to be_instance_of(Servant::Result) }
      its(:value) { is_expected.to be nil }
      its(:success?) { is_expected.to be false }
      its(:errors) { is_expected.to have(1).error }
      it { expect(subject.errors[:base]).to eq(['Cannot divide lower value by higher'])  }
    end

    context 'with halt errors' do
      subject { service_class.perform(x: 20, y: 20) }

      it { is_expected.to be_instance_of(Servant::Result) }
      its(:value) { is_expected.to be nil }
      its(:success?) { is_expected.to be false }
      its(:errors) { is_expected.to have(3).error }
      it { expect(subject.errors[:x]).to eq(['Some error', 'Some another error']) }
      it { expect(subject.errors[:y]).to eq(['Yet another error']) }
    end

    context 'with an exception error' do
      subject { service_class.perform(x: 20, y: 0) }

      it { expect { subject }.to raise_error(ZeroDivisionError, 'divided by 0') }
    end
  end

  describe '.perform!' do
    subject { service_class.perform!(x: 20, y: 10) }

    it { is_expected.to be_instance_of(Servant::Result) }
    its(:value) { is_expected.to eq(2) }
    its(:success?) { is_expected.to be true }

    context 'with validation error' do
      subject { service_class.perform!(x: 20, y: '10') }

      it { expect { subject }.to raise_error(Servant::Exceptions::ExecutionFailed, 'Got errors: Y must be any of these types: Integer') }
      it 'raises an exception that contains errors object' do
        begin
          subject
        rescue => ex
          expect(ex).to be_instance_of(Servant::Exceptions::ExecutionFailed)
          expect(ex.errors.to_a).to eq(['Y must be any of these types: Integer'])
        end
      end
    end

    context 'with halt error' do
      subject { service_class.perform!(x: 20, y: 200) }

      it { expect { subject }.to raise_error(Servant::Exceptions::ExecutionFailed, 'Got errors: Cannot divide lower value by higher') }
      it 'raises an exception that contains errors object' do
        begin
          subject
        rescue => ex
          expect(ex).to be_instance_of(Servant::Exceptions::ExecutionFailed)
          expect(ex.errors.to_a).to eq(['Cannot divide lower value by higher'])
        end
      end
    end

    context 'with halt errors' do
      subject { service_class.perform!(x: 20, y: 20) }

      it { expect { subject }.to raise_error(Servant::Exceptions::ExecutionFailed, 'Got errors: X Some error, X Some another error, Y Yet another error') }
      it 'raises an exception that contains errors object' do
        begin
          subject
        rescue => ex
          expect(ex).to be_instance_of(Servant::Exceptions::ExecutionFailed)
          expect(ex.errors.to_a).to eq(['X Some error', 'X Some another error', 'Y Yet another error'])
        end
      end
    end

    context 'with an exception error' do
      subject { service_class.perform!(x: 20, y: 0) }

      it { expect { subject }.to raise_error(ZeroDivisionError, 'divided by 0') }
    end
  end

  describe '.call' do
    subject { service_class.call(x: 20, y: 10) }

    it { is_expected.to eq(2) }

    context 'with validation error' do
      subject { service_class.call(x: 20, y: '10') }

      it { expect { subject }.to raise_error(Servant::Exceptions::ExecutionFailed, 'Got errors: Y must be any of these types: Integer') }
      it 'raises an exception that contains errors object' do
        begin
          subject
        rescue => ex
          expect(ex).to be_instance_of(Servant::Exceptions::ExecutionFailed)
          expect(ex.errors.to_a).to eq(['Y must be any of these types: Integer'])
        end
      end
    end

    context 'with halt error' do
      subject { service_class.call(x: 20, y: 200) }

      it { expect { subject }.to raise_error(Servant::Exceptions::ExecutionFailed, 'Got errors: Cannot divide lower value by higher') }
      it 'raises an exception that contains errors object' do
        begin
          subject
        rescue => ex
          expect(ex).to be_instance_of(Servant::Exceptions::ExecutionFailed)
          expect(ex.errors.to_a).to eq(['Cannot divide lower value by higher'])
        end
      end
    end

    context 'with halt errors' do
      subject { service_class.call(x: 20, y: 20) }

      it { expect { subject }.to raise_error(Servant::Exceptions::ExecutionFailed, 'Got errors: X Some error, X Some another error, Y Yet another error') }
      it 'raises an exception that contains errors object' do
        begin
          subject
        rescue => ex
          expect(ex).to be_instance_of(Servant::Exceptions::ExecutionFailed)
          expect(ex.errors.to_a).to eq(['X Some error', 'X Some another error', 'Y Yet another error'])
        end
      end
    end

    context 'with an exception error' do
      subject { service_class.call(x: 20, y: 0) }

      it { expect { subject }.to raise_error(ZeroDivisionError, 'divided by 0') }
    end
  end
end


text:
struct Edge;

struct Vertex {
	// coordinates
	float x;
	float y;
	//additional variable for searching curves
	//true - if vertex is already visited
	bool f;

	std::list<std::list<Edge>::iterator> edges;

	void addVertex(float x, float y) {
		this->x = x;
		this->y = y;
	}
};

struct Edge {
	//vertexes on the edge
	std::list<Vertex>::iterator v1;
	std::list<Vertex>::iterator v2;
	//indexes of pixels-neighbours
	// -1 - if there are no neighbour
	int ind1;
	int ind2;

	void addEdge(int ind1, int ind2, std::list<Vertex>::iterator v1, std::list<Vertex>::iterator v2) {
		this->ind1 = ind1;
		this->ind2 = ind2;
		this->v1 = v1;
		this->v2 = v2;
	}
};

#endif // CELLS_H


text:
class CPathMapper {
public:
    char mappedPath[4096];
    char fixedPath[4096];
    bool fixedValid, mappedValid;

    static char currentDir[4096];

    static void setCWD(const char* directory) {
        if (directory[0] != '/') {
            strcat_s(currentDir, directory);
        } else {
            strcpy_s(currentDir, directory);
        }
    }

    static void getCWD(char* directory) {
        strcpy_s(directory, 4095, currentDir);
    }

    char* FixedPath();
    char* MappedPath();

    CPathMapper(const char* path);
    operator const char*() {
        return mappedPath;
    }
};


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_UILineInfo : LuaObject {
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int constructor(IntPtr l) {
		return 0;
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int get_startCharIdx(IntPtr l) {
		UnityEngine.UILineInfo o = checkSelf<UnityEngine.UILineInfo>(l);
		pushValue(l,o.startCharIdx);
		return 1;
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int set_startCharIdx(IntPtr l) {
		UnityEngine.UILineInfo o = checkSelf<UnityEngine.UILineInfo>(l);
		System.Int32 v;
		checkType(l,2,out v);
		o.startCharIdx=v;
		setBack(l,o);
		return 0;
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int get_height(IntPtr l) {
		UnityEngine.UILineInfo o = checkSelf<UnityEngine.UILineInfo>(l);
		pushValue(l,o.height);
		return 1;
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int set_height(IntPtr l) {
		UnityEngine.UILineInfo o = checkSelf<UnityEngine.UILineInfo>(l);
		System.Int32 v;
		checkType(l,2,out v);
		o.height=v;
		setBack(l,o);
		return 0;
	}
	static public void reg(IntPtr l) {
		getTypeTable(l,"UnityEngine.UILineInfo");
		addMember(l,get_startCharIdx, "get_startCharIdx");
		addMember(l,set_startCharIdx, "set_startCharIdx");
		addMember(l,get_height, "get_height");
		addMember(l,set_height, "set_height");
		newType(l, constructor);
		createTypeMetatable(l, typeof(UnityEngine.UILineInfo));
		LuaDLL.lua_pop(l, 1);
	}
}


text:
RakeDeployLib includes methods for deploying und syncing files to a remote host.
The Gem depends on rsync! The OS (Operating System) needs support for the rsync command (e.q. Linux, Unix, OS X).
* deploy = transfare local (repository) files to remote server
* sync = transfare remote server files to local (repository)

## Status
This is an alpha stage version of the Gem. More methods are follow.
[![Gem Version](https://badge.fury.io/rb/rake_deploy_lib.svg)](https://badge.fury.io/rb/rake_deploy_lib)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'rake_deploy_lib'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rake_deploy_lib

## Usage
### .deploy

```
RakeDeployLib.deploy(@local, @user, @host, @remote, @excludes)
```

Deploys local (repository) files, excepts excludes, to the remote server.
Please be aware, that files will be deleted at remote host, if they don't exist local! With excludes you are able to prevent deletion.
* local (mendetory) - directory relative to the project root without / (slash) at the end.
* user (mendetory) - ssh user name at the remote server. Use of ssh certificate authentication is recommanded.
* host (mendetory) - server domain like example.com
* remote (mendetory) - absolute directory path without / (slash) at the end.
* excludes (optional) - an arrey of files or directories to exclude.
* Files: e.g. "myfile.txt" or ".gitignore"
* Directories: e.g. "mydirectory/" be aware of the trailing / (slash)

### .task_delimiter
Retuns a formated title. You can use this title to output formated messages.

**Example**
```
RakeDeployLib.task_delimiter(task_title, line_break_delimiter=3, header_char = "*", footer_char = "-")
RakeDeployLib.task_delimiter("Install npm packages", 3, "*", "-")
```

Output:
```
************************
* Install npm packages *
------------------------
```
**Paramters**
* task_title (mendotory) - string "Install npm packages"
* line_break_delimiter (optional) - line breaks before output Title as integer (default is 3)
* header_char (optional) - one character as upper frame (default is *)
* footer_char (optional) - one character as bottom frame (default is -)

**Return**
Returns a string with line breaks

### .are_you_sure
Outputs a question to the user and prompst for answer with yes.
User are able to use "y", "Y", "yes", "Yes", "YES" as positiv answer.

**Example**
```
RakeDeployLib.are_you_sure("Are you sure you want to deploy? (yes|no):")
```
**Paramters**
* question (optional) - string (default is "Are you sure? (yes|no):")

**Return**
If answer is not yes, an exit command will stop the whole script.

**Dependencies**
Methode uses RakeDeployLib.task_delimiter for prompting the question

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rake_deploy_lib. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
package com.google.j2objc.annotations;

public @interface Action {

  String value();

}


text:
import time

from . import platform_detect

# Define error constants.
DHT_SUCCESS        =  0
DHT_ERROR_TIMEOUT  = -1
DHT_ERROR_CHECKSUM = -2
DHT_ERROR_ARGUMENT = -3
DHT_ERROR_GPIO     = -4
TRANSIENT_ERRORS = [DHT_ERROR_CHECKSUM, DHT_ERROR_TIMEOUT]

# Define sensor type constants.
DHT11  = 11
DHT22  = 22
AM2302 = 22
SENSORS = [DHT11, DHT22, AM2302]

def get_platform():
    """Return a DHT platform interface for the currently detected platform."""
    plat = platform_detect.platform_detect()
    if plat == platform_detect.RASPBERRY_PI:
        # Check for version 1 or 2 of the pi.
        version = platform_detect.pi_version()
        if version == 1:
            from . import Raspberry_Pi
            return Raspberry_Pi
        elif version == 2:
            from . import Raspberry_Pi_2
            return Raspberry_Pi_2
        else:
            raise RuntimeError('No driver for detected Raspberry Pi version available!')
    elif plat == platform_detect.BEAGLEBONE_BLACK:
        from . import Beaglebone_Black
        return Beaglebone_Black
    else:
        raise RuntimeError('Unknown platform.')

def read(sensor, pin, platform=None):
    """Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
    specified pin and return a tuple of humidity (as a floating point value
    in percent) and temperature (as a floating point value in Celsius). Note that
    because the sensor requires strict timing to read and Linux is not a real
    time OS, a result is not guaranteed to be returned!  In some cases this will
    return the tuple (None, None) which indicates the function should be retried.
    Also note the DHT sensor cannot be read faster than about once every 2 seconds.
    Platform is an optional parameter which allows you to override the detected
    platform interface--ignore this parameter unless you receive unknown platform
    errors and want to override the detection.
    """
    if sensor not in SENSORS:
        raise ValueError('Expected DHT11, DHT22, or AM2302 sensor value.')
    if platform is None:
        platform = get_platform()
    return platform.read(sensor, pin)

def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None):
    """Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
    specified pin and return a tuple of humidity (as a floating point value
    in percent) and temperature (as a floating point value in Celsius).
    Unlike the read function, this read_retry function will attempt to read
    multiple times (up to the specified max retries) until a good reading can be
    found. If a good reading cannot be found after the amount of retries, a tuple
    of (None, None) is returned. The delay between retries is by default 2
    seconds, but can be overridden.
    """
    for i in range(retries):
        humidity, temperature = read(sensor, pin, platform)
        if humidity is not None and temperature is not None:
            return (humidity, temperature)
        time.sleep(delay_seconds)
    return (None, None)


text:
class Sitesucker < Cask
  url 'http://www.sitesucker.us/archive/latest/SiteSucker.zip'
  homepage 'http://www.sitesucker.us/mac/mac.html'
  version 'latest'
  no_checksum
  link 'SiteSucker/SiteSucker.app'
end


text:
package com.wso2.msf4j.samples.service;

import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.tools.ant.filters.StringInputStream;
import org.milyn.Smooks;
import org.milyn.smooks.edi.unedifact.UNEdifactReaderConfigurator;

/**
 * @author Edgar Silva - edgar.silva@gmail.com
 * */

public class EDIFactParser {

	public String parse(String in) {

        Smooks smooks = new Smooks();

        smooks.setReaderConfig(new UNEdifactReaderConfigurator("urn:org.milyn.edi.unedifact:d03b-mapping:*"));
       // smooks.setReaderConfig(new UNEdifactReaderConfigurator("urn:org.milyn.edi.unedifact:d96a-mapping:*"));

        try {

             StringWriter writer = new StringWriter();

              InputStream is = new StringInputStream(in);

             smooks.filterSource(new StreamSource(is), new StreamResult(writer));

            return writer.toString();
        }
          catch (Exception e) {
			e.printStackTrace();
			return "ERRO NO SMOOKS : /n "  + e.getMessage();

        } finally {
            smooks.close();
        }
	}

	public String parseFromMapping(String in, String mapping) {

        Smooks smooks = new Smooks();

       // smooks.setReaderConfig(new UNEdifactReaderConfigurator("urn:org.milyn.edi.unedifact:d03b-mapping:*"));
        smooks.setReaderConfig(new UNEdifactReaderConfigurator(mapping));

        try {

             StringWriter writer = new StringWriter();

              InputStream is = new StringInputStream(in);

             smooks.filterSource(new StreamSource(is), new StreamResult(writer));

            return writer.toString();
        }
          catch (Exception e) {
			e.printStackTrace();
			return "ERRO NO SMOOKS : /n "  + e.getMessage();

        } finally {
            smooks.close();
        }
	}

}


text:
About this site

Contact us

Questions or comments?

About

About the Web Experience Toolkit

About the Web Standards

News

Recent project activity

Project statistics

Stay connected

Twitter

About this site

Social media

Mobile applications

About Canada.ca

Terms and conditions

Privacy

                    Top of Page

                    <object type="image/svg+xml" tabindex="-1" role="img" data="{{ .Site.BaseURL }}/lib/{{ .Site.Params.Theme }}/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>


text:
class CreateEnjuRootManifestations < ActiveRecord::Migration
  def change
    create_table :enju_root_manifestations do |t|
      t.string :manifestation_url

      t.timestamps null: false
    end
    add_index :enju_root_manifestations, :manifestation_url
  end
end


text:
var express = require('express');
var app = express();
app.use('/assets',express.static('assets'));
app.use('/example',express.static('example'));
app.use('/bower_components',express.static('bower_components'));
app.get('/', function (req, res) {
    res.set('Content-Type', 'text/html');
    res.sendfile('index.html');
});
var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});


text:
{-# LANGUAGE ForeignFunctionInterface #-}
module T11983 where

{-# INCLUDE T11983.h #-}

import Foreign.Ptr

foreign import ccall "intptr_example"
    intPtrExample :: IntPtr -> IO ()
foreign import ccall "uintptr_example"
    wordPtrExample :: WordPtr -> IO ()


text:
<?php

/* @var $this \yii\web\View */
/* @var $model \skeeks\cms\models\CmsContentElement */
?>
<?= $this->render('@template/include/breadcrumbs', [
    'model' => $model
])?>

                                <a class="lightbox bottom-right" href="<?= $model->image->src; ?>" data-plugin-options="{"type":"image"}">

                                <img class="img-responsive" src="<?= $model->image->src; ?>" width="1200" height="1500" alt="This is the product title">
                                <img src="<?= $model->image->src; ?>" class="zoomImg" style="position: absolute; top: -268.488px; left: -84.3509px; opacity: 0; width: 1000px; height: 1500px; border: none; max-width: none; max-height: none;">

                            $98.00
                            $78.00

                             In Stock

                            SKU: UY7321987

<?= $model->description_short; ?>

                        <form class="clearfix form-inline nomargin" method="get" action="shop-cart.html">
                            <input type="hidden" name="product_id" value="1">

                            <input type="hidden" id="color" name="color" value="yellow">
                            <input type="hidden" id="qty" name="qty" value="1">
                            <input type="hidden" id="size" name="size" value="5">

                                <button type="button" class="btn btn-default dropdown-toggle product-color-dd noradius" data-toggle="dropdown">

                                </button>

                                <button type="button" class="btn btn-default dropdown-toggle product-size-dd noradius" data-toggle="dropdown">

                                    Size (5)
                                </button>

5

5.5

6

6.5

7

7.7

8

8.5

9

9.5

10

10.5

11

11.5

12

13

14

                                <button type="button" class="btn btn-default dropdown-toggle product-qty-dd noradius" data-toggle="dropdown">

                                    Qty (5)
                                </button>

1

2

3

4

5

6

7

8

9

10

                            <button class="btn btn-primary pull-left product-add-cart noradius">ADD TO CART</button>

                        </form>

                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus nulla,
                            commodo a sodales sed, dignissim pretium nunc. Nam et lacus neque. Ut enim
                            massa, sodales tempor convallis et.

                    <? if ($model->description_full) : ?>

Описание

                    <? endif; ?>

Specifications

Reviews (2)

                        <?= $model->description_full; ?>

                                        Column name
                                        Column name

                                        Size
                                        2XL

                                        Color
                                        Red

                                        Weight
                                        132lbs

                                        Height
                                        74cm

                                        Bluetooth
                                         YES

                                        Wi-Fi
                                         NO

                                    John Doe –
                                    June 29, 2014 - 11:23 –

                                    Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Pellentesque in ipsum id orci porta dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus nulla, commodo a sodales sed, dignissim pretium nunc. Nam et lacus neque.

                                    John Doe –
                                    June 29, 2014 - 11:23 –

                                    Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Pellentesque in ipsum id orci porta dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus nulla, commodo a sodales sed, dignissim pretium nunc. Nam et lacus neque.

ADD A REVIEW

                        <form method="post" action="#" id="form">

                                    <input type="text" name="name" id="name" class="form-control" placeholder="Name *" maxlength="100" required="">

                                    <input type="email" name="email" id="email" class="form-control" placeholder="Email *" maxlength="100" required="">

                                <textarea name="text" id="text" class="form-control" rows="6" placeholder="Comment" maxlength="1000"></textarea>

                                    <input type="radio" name="product-review-vote" value="1">
                                     1 Star

                                    <input type="radio" name="product-review-vote" value="2">
                                     2 Stars

                                    <input type="radio" name="product-review-vote" value="3">
                                     3 Stars

                                    <input type="radio" name="product-review-vote" value="4">
                                     4 Stars

                                    <input type="radio" name="product-review-vote" value="5">
                                     5 Stars

                            <button type="submit" class="btn btn-primary"> Send Review</button>

                        </form>

Related products:

                                NEW
                                SALE

Cotton 100% - Pink Shirt

                                $98.00
                                $78.00

                                 Add to Cart

Pink Dress 100% Cotton

                                $44.00

                                 Add to Cart

                                NEW
                                SALE

Black Fashion Hat

                                $77.00
                                $65.00

                                 Add to Cart

823days15hour1Minute32sec

Beach Black Lady Suit

                                $56.00

                                 Add to Cart

Town Dress - Black

                                $154.00

                                 Add to Cart

Chick Lady Fashion

                                $167.00

                                 Add to Cart

Black Long Lady Shirt

                                $128.00

                                 Add to Cart

                    <?= trim(\skeeks\cms\cmsWidgets\treeMenu\TreeMenuCmsWidget::widget([
                        'namespace'         => 'TreeMenuCmsWidget-leftmenu',
                        'viewFile'          => '@template/widgets/TreeMenuCmsWidget/left-menu',
                        'treePid'           => $model->id,
                        'enabledRunCache'   => \skeeks\cms\components\Cms::BOOL_N,
                        'label'             => 'Каталог',
                    ])); ?>


text:
/**
 * External dependencies
 */
import { shallowEqualArrays, shallowEqualObjects } from 'shallow-equal';

function shallowEqual(a: unknown, b: unknown): boolean {
  if (a === b) {
    return true;
  }

  if (Array.isArray(a) && Array.isArray(b)) {
    return shallowEqualArrays(a, b);
  }

  if (typeof a === 'object' && typeof b === 'object') {
    return shallowEqualObjects(a, b);
  }

  return false;
}

export default shallowEqual;


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Changed nullable for median duration, renamed statuscount to responsescount
 */
class Version20121103014303 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql("ALTER TABLE PhotoStat CHANGE medianDuration medianDuration DOUBLE PRECISION DEFAULT NULL");
        $this->addSql("ALTER TABLE UserStat ADD statusCount_ALL INT NOT NULL, CHANGE medianDuration medianDuration DOUBLE PRECISION DEFAULT NULL");
        $this->addSql("ALTER TABLE PhotoStat CHANGE statuscount_all responsesCount_ALL INT NOT NULL");
        $this->addSql("ALTER TABLE UserStat CHANGE statuscount_all responsesCount_ALL INT NOT NULL");
    }

    public function down(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql("ALTER TABLE PhotoStat CHANGE medianDuration medianDuration DOUBLE PRECISION NOT NULL");
        $this->addSql("ALTER TABLE UserStat DROP statusCount_ALL, CHANGE medianDuration medianDuration DOUBLE PRECISION NOT NULL");
        $this->addSql("ALTER TABLE PhotoStat CHANGE responsescount_all statusCount_ALL INT NOT NULL");
        $this->addSql("ALTER TABLE UserStat CHANGE responsescount_all statusCount_ALL INT NOT NULL");
    }
}


text:
#import "USLImageProcessor.h"
#import "USLVImageBufferRGBX8888.h"
#import "USLVImageBufferRGBFFF.h"
#import "USLFunctions.h"
@implementation USLImageProcessor
+ (void)opticalBlurWithCGImage:(CGImageRef)srcImage
                        kernel:(USLOpticalBlurKernel *)kernel
               fechnerConstant:(float)fechnerConstant
               optimizeByScale:(float)optimizeByScale
                       reciver:(void(^)(CGImageRef bluredImage))reciver
{
    if(fabsf(optimizeByScale - 1.0f) < FLT_EPSILON)
    {
        USLVImageBufferRGBX8888 *srcRGBA8888 = [[USLVImageBufferRGBX8888 alloc] initWithCGImage:srcImage];

        USLVImageBufferRGBFFF *willBlur = [[USLVImageBufferRGBFFF alloc] initWithVImageBufferRGBX8888:srcRGBA8888];
        USLVImageBufferRGBFFF *didBlur = [[USLVImageBufferRGBFFF alloc] initWithWidth:willBlur.vImageBufferR->width
                                                                               height:willBlur.vImageBufferR->height];

        [USLImageProcessor intensityToPhysicalQuantity:willBlur fechnerConstant:fechnerConstant];
        [USLImageProcessor convolveRGBFFFWith:willBlur dst:didBlur kernel:kernel];
        [USLImageProcessor physicalQuantityToIntensity:didBlur fechnerConstant:fechnerConstant];

        USLVImageBufferRGBX8888 *dstRGBA8888 = [[USLVImageBufferRGBX8888 alloc] initWithRGBFFF:didBlur];
        [dstRGBA8888 generateCGImageWithReciver:reciver];
    }
    else
    {
        USLVImageBufferRGBX8888 *srcRGBA8888 = [[USLVImageBufferRGBX8888 alloc] initWithCGImage:srcImage];
        USLVImageBufferRGBX8888 *oSrcRGBA8888 = [[USLVImageBufferRGBX8888 alloc] initWithWidth:(size_t)roundf(srcRGBA8888.vImageBuffer->width * optimizeByScale)
                                                                                height:(size_t)roundf(srcRGBA8888.vImageBuffer->height * optimizeByScale)];
        [USLImageProcessor scaleRGBX8888With:srcRGBA8888 dst:oSrcRGBA8888];

        USLVImageBufferRGBFFF *willBlur = [[USLVImageBufferRGBFFF alloc] initWithVImageBufferRGBX8888:oSrcRGBA8888];
        USLVImageBufferRGBFFF *didBlur = [[USLVImageBufferRGBFFF alloc] initWithWidth:willBlur.vImageBufferR->width
                                                                               height:willBlur.vImageBufferR->height];

        [USLImageProcessor intensityToPhysicalQuantity:willBlur fechnerConstant:fechnerConstant];
        [USLImageProcessor convolveRGBFFFWith:willBlur dst:didBlur kernel:kernel];
        [USLImageProcessor physicalQuantityToIntensity:didBlur fechnerConstant:fechnerConstant];

        USLVImageBufferRGBX8888 *oDstRGBA8888 = [[USLVImageBufferRGBX8888 alloc] initWithRGBFFF:didBlur];
        USLVImageBufferRGBX8888 *dstRGBA8888 = [[USLVImageBufferRGBX8888 alloc] initWithWidth:srcRGBA8888.vImageBuffer->width
                                                                                height:srcRGBA8888.vImageBuffer->height];
        [USLImageProcessor scaleRGBX8888With:oDstRGBA8888 dst:dstRGBA8888];
        [dstRGBA8888 generateCGImageWithReciver:reciver];
    }
}
+ (void)scaleRGBX8888With:(USLVImageBufferRGBX8888 *)src dst:(USLVImageBufferRGBX8888 *)dst
{
    vImage_Error error;
    error = vImageScale_ARGB8888(src.vImageBuffer,
                                 dst.vImageBuffer,
                                 NULL,
                                 kvImageNoFlags);
    VIMAGE_ERROR_HADNLE(error);
}
+ (void)convolveRGBFFFWith:(USLVImageBufferRGBFFF *)src dst:(USLVImageBufferRGBFFF *)dst kernel:(USLOpticalBlurKernel *)kernel
{
    vImage_Buffer *srcvImageBuffers[] = {src.vImageBufferR, src.vImageBufferG, src.vImageBufferB};
    vImage_Buffer *dstvImageBuffers[] = {dst.vImageBufferR, dst.vImageBufferG, dst.vImageBufferB};
    for(int i = 0 ; i < 3 ; ++i)
    {
        vImage_Buffer *srcBuffer = srcvImageBuffers[i];
        vImage_Buffer *dstBuffer = dstvImageBuffers[i];
        vImage_Error error;
        error = vImageConvolve_PlanarF(srcBuffer,
                                       dstBuffer,
                                       NULL, 0, 0,
                                       kernel.kernel,
                                       kernel.width, kernel.height,
                                       0.0f,
                                       kvImageEdgeExtend);
        VIMAGE_ERROR_HADNLE(error);
    }
}

/**
 * ヴェーバー‐フェヒナーの法則による変換
 * E = C * log(R)
 */
+ (void)intensityToPhysicalQuantity:(USLVImageBufferRGBFFF *)image fechnerConstant:(float)fechnerConstant
{
    // R = 10^(E/C)
    float divide = 1.0f / fechnerConstant;
    vImage_Buffer *vImageBuffers[] = {image.vImageBufferR, image.vImageBufferG, image.vImageBufferB};
    int length = (int)vImageBuffers[0]->width;
    float *bottom = malloc(sizeof(float) * length);
    float fill = 10.0f;
    vDSP_vfill(&fill, bottom, 1, length);

    for(int i = 0 ; i < 3 ; ++i)
    {
        vImage_Buffer *buffer = vImageBuffers[i];
        int length = (int)buffer->width;
        for(int y = 0 ; y < buffer->height ; ++y)
        {
            float *rowHead = (float *)((uint8_t *)buffer->data + buffer->rowBytes * y);
            vDSP_vsmul(rowHead, 1, &divide, rowHead, 1, length);
            vvpowf(rowHead, rowHead, bottom, &length);
        }
    }
}
+ (void)physicalQuantityToIntensity:(USLVImageBufferRGBFFF *)image fechnerConstant:(float)fechnerConstant
{
    // E = C * log(R)
    vImage_Buffer *vImageBuffers[] = {image.vImageBufferR, image.vImageBufferG, image.vImageBufferB};
    int length = (int)vImageBuffers[0]->width;
    for(int i = 0 ; i < 3 ; ++i)
    {
        vImage_Buffer *buffer = vImageBuffers[i];
        for(int y = 0 ; y < buffer->height ; ++y)
        {
            float *rowHead = (float *)((uint8_t *)buffer->data + buffer->rowBytes * y);
            vvlog10f(rowHead, rowHead, &length);
            vDSP_vsmul(rowHead, 1, &fechnerConstant, rowHead, 1, length);
        }
    }
}
@end


text:
#!/bin/bash
# Robert A. Baykov <baykovr@gmail.com>
# Template for bash scripts.

# echo "# arguments called with ---->  ${@}     "
# echo "# \$1 ---------------------->  $1       "
# echo "# \$2 ---------------------->  $2       "
# echo "# path to me --------------->  ${0}     "
# echo "# parent path -------------->  ${0%/*}  "
# echo "# my name ------------------>  ${0##*/} "
# cite [1]
#
# You can processes all but n arguments with
#  ${@:n} e.g. echo "${@:2}" # will echo all but first arg
DEPENDENCIES=( one two three )

function usage()
{
    # ${0##*/} : this scripts name (see the template for details)

    echo ${0##*/} : "a template"
    echo "Usage"
    echo -e '\t' "something"
    exit 0
}

function check_dependencies()
{
    pass=true
    for d in "${DEPENDENCIES[@]}"; do
        hash "$d" &>/dev/null
        if [ $? != 0 ]; then
            echo "[ ! ] $d required"
            pass=false
        fi
    done

    if [ $pass == false ]; then
        echo '[ ! ] unmet dependencies, aborting. '
        exit -1
    fi
}

function argparse()
{
    while getopts ":-:h?" opt; do
        case "$opt" in
            -)
                case "${OPTARG}" in
                    verbose) echo "verbose" ;;
                    *)
                        if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
                            echo "unknown option $OPTARG"
                            usage
                        fi ;;
                esac  ;;
            h|\?) usage "$@" ;;
        esac
    done
}

function back_dir()
{
    # Since the backup directory is not under version
    # control, create it if its missing.
    if [ ! -d "$BACKUP_DIR" ]; then
        mkdir -p $BACKUP_DIR
    fi

    DATE=`date +%m-%d-%Y-%H-%M-%S`
    FILENAME="backup-"$DATE".tar.gz"
    echo "Saving to : " $FILENAME
    # use --ignore-failed-read after tar if you do not have permission to some folders
    # otherwise all of tar will fail.
    tar -cvzf ../target/$FILENAME $SITE_ROOT/*
}

function require_root()
{
    if [ "$EUID" -ne "0" ] ; then
        echo "[ ! ] script requires root, aborting."
        exit -1
    fi
}

function action()
{
    echo "hello world."
}

function main()
{
    argparse "$@"
    action   "$@"
}
main "$@"

# Side notes:
# if you need to handle arguments from command line, pass them using "$@"
#     alternatively use the argparse getops functions.
# argument count can be accessed via $#
# interstingly enough, it does not include the program itself
# i.e. "./script arg1 arg2" produces an argument count of 2, not 3 as would in C style argc


text:
/** Inline FRAME/IFRAME replacement. */
(function($, win, undef) {

var $win = $(win),
        doc = win.document,
        formTargetIndex = 0;

$.plugin2('frame', {
    '_defaultOptions': {
        'frameClassName': 'dari-frame',
        'loadingClassName': 'dari-frame-loading',
        'loadedClassName': 'dari-frame-loaded',
        'bodyClassName': 'dari-frame-body',
        'setBody': function(body) {
            $(this).html(body);
        }
    },

    '_init': function(selector, options) {
        var plugin = this,
                $caller = plugin.$caller,
                frameClassName = options.frameClassName,
                loadingClassName = options.loadingClassName,
                loadedClassName = options.loadedClassName,
                bodyClassName = options.bodyClassName,
                findTargetFrame,
                beginLoad,
                endLoad,
                loadPage;

        // Finds the target frame, creating one if necessary.
        findTargetFrame = function(element, callback) {
            var $element = $(element),
                    target = $element.attr('target'),
                    $frame;

            // Standard HTML elements that can handle the target.
            if (target && $('frame[name="' + target + '"], iframe[name="' + target + '"]').length > 0) {
                return true;
            }

            // Skip processing on special target names.
            if (target !== '_top' && target !== '_blank') {
                if (target === '_parent') {
                    $frame = $element.frame('container').parent().frame('container');

                } else if (target) {
                    $frame = $('.' + frameClassName + '[name="' + target + '"]');

                    if ($frame.length === 0) {
                        $frame = $('<div/>', { 'class': frameClassName, 'name': target });
                        $(doc.body).append($frame);
                        $frame.popup();
                    }

                } else {
                    $frame = $element.frame('container');
                }

                if ($frame.length > 0) {
                    return callback($element, $frame);
                }
            }

            // Natural browser event.
            return true;
        };

        // Begins loading $frame using $source.
        beginLoad = function($frame, $source) {
            var version = ($frame.data('frame-loadVersion') || 0) + 1,
                    $popup = $frame.popup('container'),
                    $oldSource;

            $frame.add($popup).removeClass(loadedClassName).addClass(loadingClassName);
            $frame.data('frame-loadVersion', version);
            $frame.data('frame-$source', $source);

            // Source change on popup?
            $oldSource = $frame.popup('source');

            if ($popup[0] && (!$oldSource || $oldSource[0] != $source[0]) && (!$source[0] || !$.contains($popup[0], $source[0]))) {
                $frame.popup('source', $source);
                $frame.empty();
            }

            $frame.popup('open');

            return version;
        };

        // Ends loading $frame by setting it using data.
        endLoad = function($frame, version, data) {
            var $popup,
                    $wrapper,
                    $bodyContainer,
                    body;

            if (version >= $frame.data('frame-loadVersion')) {
                $popup = $frame.popup('container');
                $wrapper = $('<div/>', { 'html': data });
                $bodyContainer = $wrapper.find('.' + bodyClassName + '[name="' + $frame.attr('name') + '"]');

                if ($bodyContainer.length > 0) {
                    body = $bodyContainer.text();

                } else {
                    body = $wrapper.html();
                    body = body.replace(/^[^]*?<body[^>]*>/ig, '');
                    body = body.replace(/<\/body>[^]*?$/ig, '');
                }

                $frame.add($popup).removeClass(loadingClassName).addClass(loadedClassName);
                options.setBody.call($frame[0], body);

                $frame.trigger('create');
                $frame.trigger('load');
                $win.resize();
            }
        };

        // Loads the page at url into the $frame.
        loadPage = function($frame, $source, url) {
            var plugin = this,
                    version = beginLoad($frame, $source),
                    extraFormData = $frame.attr('data-extra-form-data');

            $.data($frame[0], 'frame-reload', function() {
                loadPage($frame, $source, url);
            });

            $.ajax({
                'cache': false,
                'url': url + (url.indexOf('?') < 0 ? '?' : '&') + extraFormData,
                'complete': function(response) {
                    endLoad($frame, version, response.responseText);
                }
            });
        };

        // Intercept anchor clicks to see if it's targeted.
        $caller.delegate('a', 'click.frame', function(event) {
            return findTargetFrame(this, function($anchor, $frame) {
                loadPage($frame, $anchor, $anchor.attr('href'));
                return false;
            });
        });

        // Intercept form submits to see if it's targeted.
        $caller.delegate('form', 'submit.frame', function() {
            return findTargetFrame(this, function($form, $frame) {
                var action = $form.attr('action'),
                        extraFormData = $frame.attr('data-extra-form-data');

                if ($form.attr('method') === 'get') {
                    loadPage($frame, $form, action + (action.indexOf('?') > -1 ? '&' : '?') + $form.serialize());
                    return false;
                }

                $form.attr('action', action + (action.indexOf('?') < 0 ? '?' : '&') + extraFormData);

                var $isFrame = $form.find(':hidden[name=_isFrame]');
                if ($isFrame.length === 0) {
                    $isFrame = $('<input name="_isFrame" type="hidden" value="true"/>');
                    $form.prepend($isFrame);
                }

                // Add a target for $submitFrame later in case one doesn't exist.
                var target = $form.attr('target');
                var hasTarget = true;
                if (!target) {
                    formTargetIndex += 1;
                    target = 'frameTarget' + formTargetIndex + (+new Date());
                    $form.attr('target', target);
                    hasTarget = false;
                }

                var $submitFrame = $('iframe[name=' + target + ']');
                if ($submitFrame.length === 0) {
                    $submitFrame = $('<iframe/>', { 'name': target });
                    $submitFrame.hide();
                    $(doc.body).append($submitFrame);
                }

                var version = beginLoad($frame, $form);
                $submitFrame.unbind('.frame');
                $submitFrame.bind('load.frame', function() {
                    $form.attr('action', action);
                    endLoad($frame, version, $submitFrame.contents().find('body').html());
                    if (!hasTarget) {
                        $form.removeAttr('target');
                        setTimeout(function() { $submitFrame.remove(); }, 0);
                    }
                });

                return true;
            });
        });

        // Any existing frame should be loaded.
        $caller.onCreate('.' + frameClassName, function() {
            var $frame = $(this),
                    $anchor;

            plugin._initElement(this, options);

            if ($frame.is(':not(.' + loadingClassName + '):not(.' + loadedClassName + ')')) {
                $anchor = $frame.find('a:only-child:not([target])');

                if ($anchor.length > 0) {
                    $anchor.click();

                } else {
                    $frame.find('form:only-child:not([target])').submit();
                }
            }
        });

        return $caller;
    },

    // Returns the enclosing element that contains the frame.
    'container': function() {
        return this.$init;
    },

    'reload': function() {
        var $frame = this.container(),
                reload;

        if ($frame && $frame.length > 0) {
            reload = $.data($frame[0], 'frame-reload');

            if (reload) {
                reload();
            }
        }

        return this.$caller;
    },

    // Returns the source element that triggered the frame to be populated.
    'source': function() {
        return this.container().data('frame-$source');
    }
});

}(jQuery, window));