text:
#include "android/wrap/wml_bridge.h"
#include "android/base/jni/android_jni.h"
#include "android/base/jni_type.h"
#include "android/base/log_utils.h"
#include "android/base/string/string_utils.h"
#include "android/utils/params_utils.h"
#include "core/manager/weex_core_manager.h"

static intptr_t jDoubleValueMethodId = 0;
static jint InitAppFramework(JNIEnv* env, jobject jcaller, jstring jinstanceid,
                             jstring jframwork, jobjectArray jargs) {
  WeexCore::WMLBridge::Instance()->Reset(env, jcaller);
  ScopedJStringUTF8 id(env, jinstanceid);
  ScopedJStringUTF8 framework(env, jframwork);
  int length = jargs == NULL ? 0 : env->GetArrayLength(jargs);
  std::vector<INIT_FRAMEWORK_PARAMS*> params;

  for (int i = 0; i < length; i++) {
    auto jArg = std::unique_ptr<WXJSObject>(
        new WXJSObject(env, env->GetObjectArrayElement(jargs, i)));
    jint jTypeInt = jArg->GetType(env);
    auto jDataObj = jArg->GetData(env);
    auto jKeyStr = jArg->GetKey(env);

    if (jTypeInt == 1) {
      jclass jDoubleClazz = env->FindClass("java/lang/Double");
      jmethodID method_id = nullptr;
      if (jDoubleValueMethodId != 0) {
        method_id = reinterpret_cast<jmethodID>(jDoubleValueMethodId);
      } else {
        method_id = base::android::GetMethod(
                env, jDoubleClazz,
                base::android::INSTANCE_METHOD,
                "doubleValue",
                "()D",
                &jDoubleValueMethodId);
      }

      jdouble jDoubleObj = env->CallDoubleMethod(jDataObj.Get(), method_id);
      const auto size = sizeof(jDoubleObj) + 1;
      char * charData = (char *) malloc(size);
      if(charData == nullptr){
        continue;
      }

      memset(charData, 0, size);
      snprintf(charData, size, "%f", jDoubleObj);

      ScopedJStringUTF8 jni_key(env, jKeyStr.Get());
      params.push_back(genInitFrameworkParams(jni_key.getChars(), charData));
      free(charData);
    } else if (jTypeInt == 2) {
      jstring jDataStr = (jstring)jDataObj.Get();
      ScopedJStringUTF8 jni_key(env, jKeyStr.Get());
      ScopedJStringUTF8 jni_data(env, jDataStr);
      params.push_back(
          genInitFrameworkParams(jni_key.getChars(), jni_data.getChars()));
    } else if (jTypeInt == 3) {
      jstring jDataStr = (jstring)jDataObj.Get();
      ScopedJStringUTF8 jni_key(env, jKeyStr.Get());
      ScopedJStringUTF8 jni_data(env, jDataStr);
      params.push_back(
          genInitFrameworkParams(jni_key.getChars(), jni_data.getChars()));
    }
  }

  auto result =
      WeexCoreManager::Instance()
          ->getPlatformBridge()
          ->core_side()
          ->InitAppFramework(id.getChars(), framework.getChars(), params);
  freeParams(params);
  return result;
}

static jint DestoryAppContext(JNIEnv* env, jobject jcaller,
                              jstring jinstanceid) {
  ScopedJStringUTF8 id(env, jinstanceid);
  return WeexCoreManager::Instance()
      ->getPlatformBridge()
      ->core_side()
      ->DestroyAppContext(id.getChars());
}

static jint CreateAppContext(JNIEnv* env, jobject jcaller, jstring jinstanceid,
                             jstring jbundle, jobject jargs) {
  ScopedJStringUTF8 id(env, jinstanceid);
  ScopedJStringUTF8 bundle(env, jbundle);
  return WeexCoreManager::Instance()
      ->getPlatformBridge()
      ->core_side()
      ->CreateAppContext(id.getChars(), bundle.getChars());
}

static jbyteArray ExecJsOnAppWithResult(JNIEnv* env, jobject jcaller,
                                        jstring jinstanceid, jstring jbundle,
                                        jobject jargs) {
  ScopedJStringUTF8 id(env, jinstanceid);
  ScopedJStringUTF8 bundle(env, jbundle);
  auto ret = WeexCoreManager::Instance()
                 ->getPlatformBridge()
                 ->core_side()
                 ->ExecJSOnAppWithResult(id.getChars(), bundle.getChars());
  if (ret.get() != nullptr && ret->data.get() != nullptr) {
    jbyteArray array = env->NewByteArray(ret->length);
    env->SetByteArrayRegion(array, 0, ret->length,
                            reinterpret_cast<const jbyte*>(ret->data.get()));
    return array;
  }

  return nullptr;
}

static jint ExecJsOnApp(JNIEnv* env, jobject jcaller, jstring jinstanceid,
                        jstring jfunction, jobjectArray jargs) {
  //  return WeexProxy::execJsOnApp(env, jcaller, jinstanceid, jfunction,
  //  jargs);

  ScopedJStringUTF8 id(env, jinstanceid);
  ScopedJStringUTF8 function(env, jfunction);

  int length = 0;
  if (jargs != NULL) {
    length = env->GetArrayLength(jargs);
  }
  std::vector<VALUE_WITH_TYPE*> params;

  for (int i = 0; i < length; i++) {
    auto jArg = std::unique_ptr<WXJSObject>(
        new WXJSObject(env, env->GetObjectArrayElement(jargs, i)));
    jint jTypeInt = jArg->GetType(env);
    auto jDataObj = jArg->GetData(env);

    VALUE_WITH_TYPE* param = nullptr;

    param = getValueWithTypePtr();

    if (jTypeInt == 1) {
      jdouble jDoubleObj =
          base::android::JNIType::DoubleValue(env, jDataObj.Get());
      param->type = ParamsType::DOUBLE;
      param->value.doubleValue = jDoubleObj;

    } else if (jTypeInt == 2) {
      jstring jDataStr = (jstring)jDataObj.Get();
      param->type = ParamsType::STRING;
      param->value.string = jstring2WeexString(env, jDataStr);
    } else if (jTypeInt == 3) {
      jstring jDataStr = (jstring)jDataObj.Get();
      param->type = ParamsType::JSONSTRING;
      param->value.string = jstring2WeexString(env, jDataStr);
    } else {
      param->type = ParamsType::JSUNDEFINED;
    }
    params.push_back(param);
  }

  return WeexCoreManager::Instance()
      ->getPlatformBridge()
      ->core_side()
      ->CallJSOnAppContext(id.getChars(), function.getChars(), params);
}

namespace WeexCore {

WMLBridge* WMLBridge::g_instance = nullptr;

const char kWMLBridgeClassPath[] = "com/taobao/windmill/bridge/WMLBridge";
jclass g_WMLBridge_clazz = nullptr;

static JNINativeMethod gWMMethods[] = {
    {"nativeInitAppFramework",
     "(Ljava/lang/String;Ljava/lang/String;[Lcom/taobao/weex/bridge/"
     "WXJSObject;)I",
     (void*)InitAppFramework},
    {"nativeCreateAppContext",
     "(Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)I",
     (void*)CreateAppContext},
    {"nativeExecJsOnApp",
     "(Ljava/lang/String;Ljava/lang/String;"
     "[Lcom/taobao/weex/bridge/WXJSObject;)I",
     (void*)ExecJsOnApp},
    {"nativeExecJsOnAppWithResult",
     "(Ljava/lang/String;Ljava/lang/String;"
     "Ljava/util/Map;)[B",
     (void*)ExecJsOnAppWithResult},
    {"nativeDestoryAppContext", "(Ljava/lang/String;)I", (void*)DestoryAppContext},
};

static int registerWMLBridgeNativeMethods(JNIEnv* env, JNINativeMethod* methods,
                                          int numMethods) {
  if (g_WMLBridge_clazz == NULL) {
    LOGE("registerWMLBridgeNativeMethods failed to find bridge class.");
    return JNI_FALSE;
  }
  if ((env)->RegisterNatives(g_WMLBridge_clazz, methods, numMethods) < 0) {
    LOGE(
        "registerWMLBridgeNativeMethods failed to register native methods for "
        "bridge class.");
    return JNI_FALSE;
  }

  return JNI_TRUE;
}

static intptr_t g_WMLBridge_dispatchMessage = 0;
static void Java_WMLBridge_dispatchMessage(JNIEnv* env, jobject obj,
                                           jstring clientID, jstring vmID,
                                           jbyteArray data, jstring callback) {
  jmethodID method_id = base::android::GetMethod(
      env, g_WMLBridge_clazz, base::android::INSTANCE_METHOD, "dispatchMessage",
      "(Ljava/lang/String;Ljava/lang/String;[BLjava/lang/String;)V",
      &g_WMLBridge_dispatchMessage);

  env->CallVoidMethod(obj, method_id, clientID, vmID, data, callback);
  base::android::CheckException(env);
}

static intptr_t g_WMLBridge_dispatchMessageSync = 0;
static base::android::ScopedLocalJavaRef<jbyteArray>
Java_WMLBridge_dispatchMessageSync(JNIEnv* env, jobject obj, jstring clientID,
                                   jstring vmID, jbyteArray data) {
  jmethodID method_id = base::android::GetMethod(
      env, g_WMLBridge_clazz, base::android::INSTANCE_METHOD,
      "dispatchMessageSync", "(Ljava/lang/String;Ljava/lang/String;[B)[B",
      &g_WMLBridge_dispatchMessageSync);

  auto result = env->CallObjectMethod(obj, method_id, clientID, vmID, data);
  base::android::CheckException(env);
  return base::android::ScopedLocalJavaRef<jbyteArray>(
      env, static_cast<jbyteArray>(result));
}

static intptr_t g_WMLBridge_postMessage = 0;

static void Java_WMLBridge_postMessage(JNIEnv* env, jobject obj, jstring vmID,
                                       jbyteArray data) {
  jmethodID method_id = base::android::GetMethod(
      env, g_WMLBridge_clazz, base::android::INSTANCE_METHOD, "postMessage",
      "(Ljava/lang/String;[B)V", &g_WMLBridge_postMessage);

  env->CallVoidMethod(obj, method_id, vmID, data);
  base::android::CheckException(env);
}

bool WMLBridge::RegisterJNIUtils(JNIEnv* env) {
  jclass temp_class = env->FindClass(kWMLBridgeClassPath);

  // use to check WMLBridge has already on env
  if (env->ExceptionOccurred()) {
    LOGE("failed find class WMBridge");
    env->ExceptionDescribe();
    env->ExceptionClear();
    return false;
  } else if (temp_class != nullptr) {
    g_WMLBridge_clazz = (jclass)env->NewGlobalRef(temp_class);
    env->DeleteLocalRef(temp_class);
    LOGE("success find class WMBridge");
    registerWMLBridgeNativeMethods(env, gWMMethods,
                                   sizeof(gWMMethods) / sizeof(gWMMethods[0]));
    return true;
  }
}

void WMLBridge::PostMessage(JNIEnv* env, const char* vm_id, const char* data, int dataLength) {
  if (jni_object() != NULL) {
    auto jni_str = base::android::ScopedLocalJavaRef<jstring>(
        env, env->NewStringUTF(vm_id));
    auto jni_array = base::android::ScopedLocalJavaRef<jbyteArray>(
        env, newJByteArray(env, data, dataLength));

    Java_WMLBridge_postMessage(env, jni_object(), jni_str.Get(),
                               jni_array.Get());
  }
}

void WMLBridge::DispatchMessage(JNIEnv *env, const char *client_id,
                                    const char *data, int dataLength, const char *callback, const char* vm_id) {
  if (jni_object() != NULL) {
    auto jni_client_id = base::android::ScopedLocalJavaRef<jstring>(
        env, newJString(env, client_id));
    auto jni_array = base::android::ScopedLocalJavaRef<jbyteArray>(
        env, newJByteArray(env, data, dataLength));
    auto jni_callback = base::android::ScopedLocalJavaRef<jstring>(
        env, newJString(env, callback));
    auto jni_vm_id = base::android::ScopedLocalJavaRef<jstring>(env, newJString(env, vm_id));
    Java_WMLBridge_dispatchMessage(env, jni_object(), jni_client_id.Get(),
                                   jni_vm_id.Get(), jni_array.Get(),
                                   jni_callback.Get());
  }
}

base::android::ScopedLocalJavaRef<jbyteArray> WMLBridge::DispatchMessageSync(
    JNIEnv* env, const char* client_id, const char* data, int dataLength,
    const char* vm_id) {
  if (jni_object() != NULL) {
    auto jni_client_id = base::android::ScopedLocalJavaRef<jstring>(
        env, newJString(env, client_id));
    auto jni_array = base::android::ScopedLocalJavaRef<jbyteArray>(
        env, newJByteArray(env, data, dataLength));
    auto jni_vm_id =
        base::android::ScopedLocalJavaRef<jstring>(env, newJString(env, vm_id));
    return Java_WMLBridge_dispatchMessageSync(env, jni_object(),
                                              jni_client_id.Get(),
                                              jni_vm_id.Get(), jni_array.Get());
  }
  return base::android::ScopedLocalJavaRef<jbyteArray>();
}

}  // namespace WeexCore


text:
from werkzeug import exceptions

from urllib import quote
from xml.sax.saxutils import escape,unescape

from mizwiki.hostvalidator import HostValidator
from mizwiki import config, misc, svnrep
from mizwiki.local import local

from werkzeug import BaseRequest

class RequestInfo(BaseRequest):
    def __init__(self,environ):
        super(RequestInfo, self).__init__(environ)

        "logger"
        self._logger = self.environ.get('wsgi.errors')

        "host validation"
        self._ip = self.remote_addr or '0.0.0.0'
        self._v = HostValidator(config.RBL_LIST,
                                config.WHITELIST,
                                config.BLACKLIST,
                                config.SPAMBLOCK,
                                self.log)

    @property
    @misc.memoize
    def hostname(self):
        hostname = ''
        if self.environ.get('HTTP_HOST'):
            hostname += self.environ['HTTP_HOST']
        else:
            hostname += self.environ['SERVER_NAME']

            if self.environ['wsgi.url_scheme'] == 'https':
                if self.environ['SERVER_PORT'] != '443':
                    hostname += ':' + self.environ['SERVER_PORT']
                else:
                    if self.environ['SERVER_PORT'] != '80':
                        hostname += ':' + self.environ['SERVER_PORT']
        return hostname

    @property
    def is_spam(self):
        "if spam, reject editing"
        return self._v.is_spam(self._ip)
    @property
    def is_valid_host(self):
        "if not spam but not valid_host, allow editing but reject committing without correct answer"
        return self._v.is_valid_host(self._ip)
    @property
    def user(self):
        return 'www-data@%s'%self._ip

    def log(self, msg):
        if self._logger:
            self._logger.write(msg+'\n')

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using AlexPilotti.FTPS.Client;
using AlexPilotti.FTPS.Common;
using VirtualPath.Common;

namespace VirtualPath.AlexFTPS
{
	[Export("AlexFTPS", typeof(IVirtualPathProvider))]
	[Export("FTP", typeof(IVirtualPathProvider))]
	public class FtpVirtualPathProvider : IVirtualPathProvider
	{
		protected string Host;
		protected string Username;
		protected string Password;
        protected bool IsConnected;
		protected int? Port;

		private readonly Dictionary<string, IVirtualNode> nodes;
		private readonly HashSet<string> listedPaths;

        public FTPSClient Client { get; protected set; }

        private FTPSClient ConnectedClient
        {
            get
            {
                if (!IsConnected)
                {
                    Connect();
                }
                return Client;
            }
        }

        public FtpVirtualPathProvider(FTPSClient client, string host, int? port, string username, string password)
        {
            this.Client = client;
            this.Host = host;
            this.Username = username;
            this.Password = password;
            this.Port = port;

			this.nodes = new Dictionary<string, IVirtualNode>();
			this.listedPaths = new HashSet<string>();
        }

        public FtpVirtualPathProvider(string host, string username, string password)
            : this(new FTPSClient(), host, null, username, password)
        {

        }

		public FtpVirtualPathProvider(string host, int port, string username, string password)
            : this(new FTPSClient(), host, port, username, password)
        {

        }

        protected virtual void Connect()
        {
			Client.Connect(
				this.Host,
				this.Port ?? 21,
				new NetworkCredential(this.Username, this.Password),
				ESSLSupportMode.ClearText,
				null, null, 0, 0, 0, null);

            IsConnected = true;
        }

        public void Dispose()
        {
            Client.Dispose();
            IsConnected = false;
        }

		public IVirtualDirectory RootDirectory
		{
			get { return this.GetDirectory("/"); }
		}

		public string VirtualPathSeparator
		{
			get { return "/"; }
		}

		public string RealPathSeparator
		{
			get { return "/"; }
		}

		public string CombineVirtualPath(string basePath, string relativePath)
		{
			basePath = basePath.TrimEnd('/');
			relativePath = relativePath.TrimStart('/');
			return String.Concat(basePath, VirtualPathSeparator, relativePath);
		}

		internal string GetParentPath(string path)
		{
			if (path == "/") return null;
			var parts = path.Split(new [] { this.VirtualPathSeparator }, StringSplitOptions.RemoveEmptyEntries);
			return this.VirtualPathSeparator + String.Join(this.VirtualPathSeparator, parts.Take(parts.Count() - 1));
		}

		public bool FileExists(string virtualPath)
		{
			virtualPath = NormalizeAbsolutePath(virtualPath);
			return GetFile(virtualPath) != null;
		}

		public bool DirectoryExists(string virtualPath)
		{
			virtualPath = NormalizeAbsolutePath(virtualPath);
			return GetDirectory(virtualPath) != null;
		}

		public IVirtualFile GetFile(string virtualPath)
		{
			virtualPath = NormalizeAbsolutePath(virtualPath);
			var directoryPath = this.GetParentPath(virtualPath);
			this.FetchListing(directoryPath);

			var node = default(IVirtualNode);
			var exists = this.nodes.TryGetValue(virtualPath, out node);
			return (IVirtualFile)node;
		}

		public string GetFileHash(string virtualPath)
		{
			virtualPath = NormalizeAbsolutePath(virtualPath);
			return GetFile(virtualPath).GetFileHash();
		}

		public IVirtualDirectory GetDirectory(string virtualPath)
		{
			virtualPath = NormalizeAbsolutePath(virtualPath);
			var node = default(IVirtualNode);
			var exists = this.nodes.TryGetValue(virtualPath, out node);
			if (!exists)
			{
				var parentPath = this.GetParentPath(virtualPath);
				// We already listed the parent and it was not there
				if (listedPaths.Contains(parentPath)) return null;

				// We check the directory exists by listing its content (don't use parent because we may not have access)
				this.FetchListing(virtualPath);

				node = GetOrAddDirectory(virtualPath);
			}

			return (IVirtualDirectory)node;
		}

		private FtpVirtualDirectory GetOrAddDirectory(string virtualPath)
		{
			var node = new FtpVirtualDirectory(this, virtualPath);
			return this.AddOrGetNode(node);
		}

		private FtpVirtualFile GetOrAddFile(string virtualPath)
		{
			var node = new FtpVirtualFile(this, virtualPath);
			return this.AddOrGetNode(node);
		}

		private void FetchListing(string virtualPath)
		{
			if (this.listedPaths.Contains(virtualPath)) return;

			var contents = ConnectedClient.GetDirectoryList(virtualPath);
			foreach (var content in contents)
			{
				var path = this.CombineVirtualPath(virtualPath, content.Name);
				var node = content.IsDirectory
					? GetOrAddDirectory(path)
					: (IVirtualNode)GetOrAddFile(path);
			}

			this.listedPaths.Add(virtualPath);
		}

		private T AddOrGetNode<T>(T node) where T : IVirtualNode
		{
			var path = node.VirtualPath;
			var existingNode = default(IVirtualNode);
			var exists = this.nodes.TryGetValue(path, out existingNode);
			if (!exists)
			{
				this.nodes.Add(path, node);
				return (T)node;
			}
			return (T)existingNode;
		}

		public IEnumerable<IVirtualFile> GetAllMatchingFiles(string globPattern, int maxDepth = 1)
		{
            if (maxDepth == 0)
                yield break;

            foreach (var match in this.GetAllMatchingFiles("/", globPattern, maxDepth))
			{
				yield return match;
			}
		}

		internal IEnumerable<IVirtualFile> GetAllMatchingFiles(string path, string globPattern, int maxDepth = 1)
		{
			path = NormalizeAbsolutePath(path);
			this.FetchListing(path);

			var dir = this.GetDirectory(path);
			var matchesInDir = dir.Files.Where(f => f.Name.Glob(globPattern));
			foreach (var match in matchesInDir)
			{
				yield return match;
			}

			foreach (var childDir in dir.Directories)
			{
				var matchInChildDir = this.GetAllMatchingFiles(childDir.VirtualPath, globPattern, maxDepth - 1);
				foreach (var m in matchInChildDir)
					yield return m;
			}
		}

		public System.IO.Stream CreateFile(string filePath)
		{
			filePath = NormalizeAbsolutePath(filePath);

			if (this.nodes.ContainsKey(filePath)) throw new ArgumentException("File already exists", "filePath");

			var node = this.GetOrAddFile(filePath);

			return ConnectedClient.PutFile(filePath);
		}

		private string NormalizeAbsolutePath(string path)
		{
			path = path.TrimEnd('/');
			if (!path.StartsWith("/")) return "/" + path;
			return path;
		}

		public IVirtualFile CreateFile(string filePath, byte[] contents)
		{
			filePath = NormalizeAbsolutePath(filePath);
			using (var stream = CreateFile(filePath))
			{
				stream.Write(contents, 0, contents.Length);
			}

			return (IVirtualFile)this.nodes[filePath];
		}

		public IVirtualFile CreateFile(string filePath, string contents)
		{
			filePath = NormalizeAbsolutePath(filePath);
			var bytes = System.Text.Encoding.UTF8.GetBytes(contents);
			return this.CreateFile(filePath, bytes);
		}

		public IVirtualDirectory CreateDirectory(string virtualPath)
		{
			virtualPath = NormalizeAbsolutePath(virtualPath);
			var parentPath = this.GetParentPath(virtualPath);

			try
			{
				this.FetchListing(parentPath);
			}
			catch (FTPCommandException)
			{
				// Parent directory do not exists
				this.CreateDirectory(parentPath);
			}

			var node = default(IVirtualNode);
			var exists = this.nodes.TryGetValue(virtualPath, out node);
			if (node == null)
			{
				ConnectedClient.MakeDir(virtualPath);
				node = this.GetOrAddDirectory(virtualPath);
			}
			return (IVirtualDirectory)node;
		}

		internal System.IO.Stream OpenRead(string path)
		{
			path = NormalizeAbsolutePath(path);
			return ConnectedClient.GetFile(path);
		}

		internal Stream OpenWrite(string path, WriteMode mode)
		{
			path = NormalizeAbsolutePath(path);
			if (mode == WriteMode.Truncate)
			{
				return ConnectedClient.PutFile(path);
			}
			else if (mode == WriteMode.Append)
			{
				return ConnectedClient.AppendFile(path);
			}
			else if (mode == WriteMode.Overwrite)
			{
				var bytes = default(byte[]);
				using (var readStream = ConnectedClient.GetFile(path))
				{
					bytes = StreamExtensions.ReadStreamToEnd(readStream);
				}

				var stream = new InMemory.InMemoryStream((data) =>
				{
					using (var remoteStream = ConnectedClient.PutFile(path))
					{
						remoteStream.Write(data, 0, data.Length);
					}
				}, bytes);

				return stream;
			}
			else
			{
				throw new NotSupportedException();
			}
		}

		internal void DeleteFile(string path)
		{
			path = NormalizeAbsolutePath(path);
			ConnectedClient.DeleteFile(path);

			if (this.nodes.ContainsKey(path))
			{
				this.nodes.Remove(path);
			}
		}

		internal void DeleteDirectory(string path)
		{
			path = NormalizeAbsolutePath(path);

			var node = this.GetDirectory(path);

			if (node == null) return;

			var directories = node.Directories.ToArray();
			foreach (var subDir in directories)
			{
				this.DeleteDirectory(subDir.VirtualPath);
			}

			var files = node.Files.ToArray();
			foreach (var file in files)
			{
				this.DeleteFile(file.VirtualPath);
			}

			ConnectedClient.RemoveDir(path);

			if (this.nodes.ContainsKey(path))
			{
				this.nodes.Remove(path);
			}
		}

		internal IEnumerator<IVirtualNode> GetChildren(string path)
		{
			path = NormalizeAbsolutePath(path);
			this.FetchListing(path);
			return this.nodes.Values
				.Where(n => this.GetParentPath(n.VirtualPath) == path)
				.GetEnumerator();
		}

		internal IVirtualFile Move(FtpVirtualFile source, IVirtualDirectory destination, string destFilename)
		{
			if (destination.VirtualPathProvider == this)
			{
				var destPath = this.CombineVirtualPath(destination.VirtualPath, destFilename);
				this.ConnectedClient.RenameFile(source.VirtualPath, destPath);
				this.nodes.Remove(NormalizeAbsolutePath(source.VirtualPath));
				return this.GetOrAddFile(destPath);
			}
			else
			{
				var copy = source.CopyTo(destination, destFilename);
				source.Delete();
				return copy;
			}
		}
	}

	internal class FtpVirtualDirectory : IVirtualDirectory
	{
		private readonly FtpVirtualPathProvider provider;
		private readonly string path;
		private DateTime lastModified;

		public FtpVirtualDirectory(FtpVirtualPathProvider provider, string path)
		{
			this.provider = provider;
			this.path = path;
			this.lastModified = DateTime.MinValue;
		}

		public bool IsRoot
		{
			get { return this.path == "/"; }
		}

		public IVirtualDirectory ParentDirectory
		{
			get
			{
				if (IsRoot) return null;
				return provider.GetDirectory(provider.GetParentPath(this.path));
			}
		}

		public IEnumerable<IVirtualFile> Files
		{
			get { return this.OfType<IVirtualFile>(); }
		}

		public IEnumerable<IVirtualDirectory> Directories
		{
			get { return this.OfType<IVirtualDirectory>(); }
		}

		public IVirtualFile GetFile(string virtualPath)
		{
			return provider.GetFile(provider.CombineVirtualPath(this.path, virtualPath));
		}

		public IVirtualDirectory GetDirectory(string virtualPath)
		{
			return provider.GetDirectory(provider.CombineVirtualPath(this.path, virtualPath));
		}

		public IEnumerable<IVirtualFile> GetAllMatchingFiles(string globPattern, int maxDepth = 1)
		{
			return this.provider.GetAllMatchingFiles(this.path, globPattern, maxDepth);
		}

		public System.IO.Stream CreateFile(string virtualPath)
		{
			return this.provider.CreateFile(provider.CombineVirtualPath(this.path, virtualPath));
		}

		public IVirtualFile CreateFile(string virtualPath, byte[] contents)
		{
			return this.provider.CreateFile(provider.CombineVirtualPath(this.path, virtualPath), contents);
		}

		public IVirtualFile CreateFile(string virtualPath, string contents)
		{
			return this.provider.CreateFile(provider.CombineVirtualPath(this.path, virtualPath), contents);
		}

		public IVirtualDirectory CreateDirectory(string virtualPath)
		{
			return provider.CreateDirectory(provider.CombineVirtualPath(this.path, virtualPath));
		}

		public void Delete(string virtualPath)
		{
			provider.DeleteDirectory(virtualPath);
		}

		public IVirtualPathProvider VirtualPathProvider
		{
			get { return provider; }
		}

		public IVirtualDirectory Directory
		{
			get { return this; }
		}

		public string Name
		{
			get { return Path.GetFileName(this.path); }
		}

		public string VirtualPath
		{
			get { return path; }
		}

		public string RealPath
		{
			get { return path; }
		}

		public bool IsDirectory
		{
			get { return true; }
		}

		public DateTime LastModified
		{
			get { return this.lastModified; }
		}

		public void Delete()
		{
			provider.DeleteDirectory(this.path);
		}

		public IEnumerator<IVirtualNode> GetEnumerator()
		{
			return provider.GetChildren(this.path);
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return this.GetEnumerator();
		}
	}

	internal class FtpVirtualFile : IVirtualFile
	{
		private readonly FtpVirtualPathProvider provider;
		private string path;
		private DateTime lastModified;

		public FtpVirtualFile(FtpVirtualPathProvider provider, string path)
		{
			this.provider = provider;
			this.path = path;
			this.lastModified = DateTime.MinValue;
		}

		public string Extension
		{
			get { return Path.GetExtension(this.path); }
		}

		public string GetFileHash()
		{
			using (var stream = OpenRead())
			{
				return StreamExtensions.ToMd5Hash(stream);
			}
		}

		public System.IO.Stream OpenRead()
		{
			return this.provider.OpenRead(this.path);
		}

		public System.IO.StreamReader OpenText()
		{
			return OpenText(Encoding.UTF8);
		}

		public System.IO.StreamReader OpenText(Encoding encoding)
		{
			return new StreamReader(OpenRead(), encoding);
		}

		public string ReadAllText()
		{
			return ReadAllText(Encoding.UTF8);
		}

		public string ReadAllText(Encoding encoding)
		{
			using (var reader = OpenText(encoding))
			{
				var text = reader.ReadToEnd();
				return text;
			}
		}

		public System.IO.Stream OpenWrite()
		{
			return OpenWrite(WriteMode.Overwrite);
		}

		public System.IO.Stream OpenWrite(WriteMode mode)
		{
			return this.provider.OpenWrite(this.path, mode);
		}

		public IVirtualFile CopyTo(IVirtualDirectory destination)
		{
			return CopyTo(destination, this.Name);
		}

		public IVirtualFile CopyTo(IVirtualDirectory destination, string destFilename)
		{
			return destination.CopyFile(this, destFilename);
		}

		public IVirtualFile CopyTo(string destDirVirtualPath)
		{
			return CopyTo(destDirVirtualPath, this.Name);
		}

		public IVirtualFile CopyTo(string destDirVirtualPath, string destFilename)
		{
			var destination = provider.GetDirectory(destDirVirtualPath);
			return CopyTo(destination, destFilename);
		}

		public IVirtualFile MoveTo(IVirtualDirectory destination)
		{
			return MoveTo(destination, this.Name);
		}

		public IVirtualFile MoveTo(IVirtualDirectory destination, string destFilename)
		{
			return this.provider.Move(this, destination, destFilename);
		}

		public IVirtualFile MoveTo(string destDirVirtualPath)
		{
			return MoveTo(destDirVirtualPath, this.Name);
		}

		public IVirtualFile MoveTo(string destDirVirtualPath, string destFilaname)
		{
			var destination = provider.GetDirectory(destDirVirtualPath);
			return MoveTo(destination, destFilaname);
		}

		public IVirtualPathProvider VirtualPathProvider
		{
			get { return this.provider; }
		}

		public IVirtualDirectory Directory
		{
			get { return this.provider.GetDirectory(provider.GetParentPath(this.path)); }
		}

		public string Name
		{
			get { return Path.GetFileName(this.path); }
		}

		public string VirtualPath
		{
			get { return this.path; }
		}

		public string RealPath
		{
			get { return this.path; }
		}

		public bool IsDirectory
		{
			get { return false ; }
		}

		public DateTime LastModified
		{
			get { return this.lastModified; }
		}

		public void Delete()
		{
			this.provider.DeleteFile(this.path);
		}
	}
}


text:
package org.pentaho.gis.shapefiles;

import org.pentaho.di.core.row.RowMetaInterface;

/*
 * Created on 30-jun-2004
 *
 * @author Matt
 *
 */

public interface ShapeInterface {
  public int getType();

  public void setDbfData( Object[] row );
  public Object[] getDbfData();

  public void setDbfMeta( RowMetaInterface rowMeta );
  public RowMetaInterface getDbfMeta();
}


text:
using System;

namespace Azure.Messaging.EventGrid.SystemEvents
{
    /// <summary> Schema of the Data property of an EventGridEvent for an Microsoft.Storage.BlobInventoryPolicyCompleted event. </summary>
    public partial class StorageBlobInventoryPolicyCompletedEventData
    {
        /// <summary> Initializes a new instance of StorageBlobInventoryPolicyCompletedEventData. </summary>
        internal StorageBlobInventoryPolicyCompletedEventData()
        {
        }

        /// <summary> Initializes a new instance of StorageBlobInventoryPolicyCompletedEventData. </summary>
        /// <param name="scheduleDateTime"> The time at which inventory policy was scheduled. </param>
        /// <param name="accountName"> The account name for which inventory policy is registered. </param>
        /// <param name="ruleName"> The rule name for inventory policy. </param>
        /// <param name="policyRunStatus"> The status of inventory run, it can be Succeeded/PartiallySucceeded/Failed. </param>
        /// <param name="policyRunStatusMessage"> The status message for inventory run. </param>
        /// <param name="policyRunId"> The policy run id for inventory run. </param>
        /// <param name="manifestBlobUrl"> The blob URL for manifest file for inventory run. </param>
        internal StorageBlobInventoryPolicyCompletedEventData(DateTimeOffset? scheduleDateTime, string accountName, string ruleName, string policyRunStatus, string policyRunStatusMessage, string policyRunId, string manifestBlobUrl)
        {
            ScheduleDateTime = scheduleDateTime;
            AccountName = accountName;
            RuleName = ruleName;
            PolicyRunStatus = policyRunStatus;
            PolicyRunStatusMessage = policyRunStatusMessage;
            PolicyRunId = policyRunId;
            ManifestBlobUrl = manifestBlobUrl;
        }

        /// <summary> The time at which inventory policy was scheduled. </summary>
        public DateTimeOffset? ScheduleDateTime { get; }
        /// <summary> The account name for which inventory policy is registered. </summary>
        public string AccountName { get; }
        /// <summary> The rule name for inventory policy. </summary>
        public string RuleName { get; }
        /// <summary> The status of inventory run, it can be Succeeded/PartiallySucceeded/Failed. </summary>
        public string PolicyRunStatus { get; }
        /// <summary> The status message for inventory run. </summary>
        public string PolicyRunStatusMessage { get; }
        /// <summary> The policy run id for inventory run. </summary>
        public string PolicyRunId { get; }
        /// <summary> The blob URL for manifest file for inventory run. </summary>
        public string ManifestBlobUrl { get; }
    }
}


text:
<?php namespace Impl\Repo;

use Order;
use User;
use Kind;
use Category;
use Unit;
use Purpose;
use ShipsList;
use ShipsNew;
use Impl\Repo\Order\EloquentOrder;
use Impl\Repo\ShipsList\EloquentShipsList;
use Impl\Repo\ShipsNew\EloquentShipsNew;
use Impl\Repo\User\EloquentUser;
use Impl\Repo\Unit\EloquentUnit;
use Impl\Repo\Kind\EloquentKind;
use Impl\Repo\Category\EloquentCategory;
use Impl\Repo\Purpose\EloquentPurpose;
use Illuminate\Support\ServiceProvider;

class RepoServiceProvider extends ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $app = $this->app;

        $app->bind('Impl\Repo\Order\OrderInterface', function($app)
        {
            return  new EloquentOrder(
                new Order
            );
        });

        $app->bind('Impl\Repo\User\UserInterface', function($app)
        {
            return new EloquentUser(
                new User
            );
        });

        $app->bind('Impl\Repo\Unit\UnitInterface', function($app)
        {
            return new EloquentUnit(
                new Unit
            );
        });
        $app->bind('Impl\Repo\Kind\KindInterface', function($app)
        {
            return new EloquentKind(
                new Kind
            );
        });
        $app->bind('Impl\Repo\Category\CategoryInterface', function($app)
        {
            return new EloquentCategory(
                new Category
            );
        });
        $app->bind('Impl\Repo\Purpose\PurposeInterface', function($app)
        {
            return new EloquentPurpose(
                new Purpose
            );
        });
        $app->bind('Impl\Repo\ShipsList\ShipsListInterface', function($app)
        {
            return new EloquentShipsList(
                new ShipsList
            );
        });
        $app->bind('Impl\Repo\ShipsNew\ShipsNewInterface', function($app)
        {
            return new EloquentShipsNew(
                new ShipsNew
            );
        });
    }

}


text:
package com.mobgen.halo.android.content.sync;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Pair;

import com.mobgen.halo.android.content.models.HaloSyncLog;
import com.mobgen.halo.android.framework.common.utils.AssertionUtils;
import com.mobgen.halo.android.framework.toolbox.data.HaloResultV2;
import com.mobgen.halo.android.framework.toolbox.data.HaloStatus;

/**
 * @hide Helper to do the synchronization process.
 */
public final class ModuleSyncHelper {

    /**
     * The status for the log of halo.
     */
    private static final String BUNDLE_STATUS = "halo_status";
    /**
     * The synchronization log for halo.
     */
    private static final String BUNDLE_SYNC_LOG = "halo_sync_log";

    /**
     * The private constructor for the helper.
     */
    private ModuleSyncHelper() {
        //Private constructor to avoid instances for this helper.
    }

    /**
     * Creates a bundle given the log of the sync.
     *
     * @param synchronizationResult The synchronization result.
     * @return The bundle created.
     */
    public static Bundle bundleizeSync(HaloResultV2<HaloSyncLog> synchronizationResult) {
        AssertionUtils.notNull(synchronizationResult, "synchronizationResult");
        Bundle bundle = new Bundle();
        bundle.putParcelable(BUNDLE_STATUS, synchronizationResult.status());
        bundle.putParcelable(BUNDLE_SYNC_LOG, synchronizationResult.data());
        return bundle;
    }

    /**
     * Changes the bundle into the status and the sync log.
     *
     * @param bundle The bundle.
     * @return The pair of status and sync log.
     */
    @NonNull
    public static Pair<HaloStatus, HaloSyncLog> debundleizeSync(@NonNull Bundle bundle) {
        AssertionUtils.notNull(bundle, "bundle");
        HaloStatus status = bundle.getParcelable(BUNDLE_STATUS);
        HaloSyncLog syncLog = bundle.getParcelable(BUNDLE_SYNC_LOG);
        return new Pair<>(status, syncLog);
    }
}


text:
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/object/blank'

module ActionView
  # = Active Model Helpers
  module Helpers
    module ActiveModelHelper
    end

    module ActiveModelInstanceTag
      def object
        @active_model_object ||= begin
          object = super
          object.respond_to?(:to_model) ? object.to_model : object
        end
      end

      %w(content_tag to_date_select_tag to_datetime_select_tag to_time_select_tag).each do |meth|
        module_eval "def #{meth}(*) error_wrapping(super) end", __FILE__, __LINE__
      end

      def tag(type, options, *)
        tag_generate_errors?(options) ? error_wrapping(super) : super
      end

      def error_wrapping(html_tag)
        if object_has_errors?
          Base.field_error_proc.call(html_tag, self)
        else
          html_tag
        end
      end

      def error_message
        object.errors[@method_name]
      end

      private

      def object_has_errors?
        object.respond_to?(:errors) && object.errors.respond_to?(:full_messages) && error_message.any?
      end

      def tag_generate_errors?(options)
        options['type'] != 'hidden'
      end
    end
  end
end


text:
HaTeX is a Haskell library that implements the *LaTeX syntax*, plus some abstractions on top.

Check a list of usage examples in the [Examples](https://github.com/Daniel-Diaz/HaTeX/tree/master/Examples) directory
of the repository in GitHub.
A good starting point is [simple.hs](https://github.com/Daniel-Diaz/HaTeX/blob/master/Examples/simple.hs).
Run any example script executing the ``main`` function.

## Installation notes

To install `HaTeX`, use [cabal-install](http://hackage.haskell.org/package/cabal-install)
or [stack](http://docs.haskellstack.org/en/stable/README).

To install with cabal, run:

    $ cabal update
    $ cabal install HaTeX

This will download and install the latest official release (recommended).
If you want to try a newer version, use _git_ to clone the code contained
in this repository.

    $ git clone https://github.com/Daniel-Diaz/HaTeX.git
    $ cd HaTeX
    $ cabal install

However, this is not recommended as it may include some bugs or oddities due to in-development features.
Note that this package follows the [_Package Versioning Policy_](http://www.haskell.org/haskellwiki/Package_versioning_policy),
so it is unlikely to suffer from API breakages if you follow it too when importing the library (assuming
you are using the version in Hackage).

## Current HaTeX versions

[![HaTeX on Hackage](https://img.shields.io/hackage/v/HaTeX.svg)](https://hackage.haskell.org/package/HaTeX)

[![HaTeX on Stackage](http://stackage.org/package/HaTeX/badge/lts)](http://stackage.org/lts/package/HaTeX)

[![HaTeX on Stackage Nightly](http://stackage.org/package/HaTeX/badge/nightly)](http://stackage.org/nightly/package/HaTeX)

## HaTeX User's Guide

The HaTeX User's Guide lives [here](https://github.com/Daniel-Diaz/hatex-guide)... and is also done in Haskell!
It is free source and anybody can contribute to it. Doing so, you will help current and future users!

A downloadable version (not necessarily the latest version, but most likely)
can be found [here](http://daniel-diaz.github.com/projects/hatex/hatex-guide.pdf).
To be sure that you are reading the last version, go to the github repository of the guide and follow instructions
to build it. It is fairly easy.

Please note that the user's guide needs to be updated (contributions are more than welcome!).

## Community and Contributions

There are many ways to get involved in the HaTeX project. Use the most comfortable way for you.

* Fork the [GitHub repository](https://github.com/Daniel-Diaz/HaTeX) and make your own contributions.
* Report bugs or make suggestions opening a ticket in the [Issue Tracker](https://github.com/Daniel-Diaz/HaTeX/issues).
* Help us to improve and extend our [hatex-guide](https://github.com/Daniel-Diaz/hatex-guide).

## TODO list

* Add more examples.
* Add more documentation.
* BibTeX support.

## Related projects

* [haskintex](http://daniel-diaz.github.io/projects/haskintex): Tool to use Haskell (and, additionaly, the HaTeX library)
within a LaTeX file.
* [TeX-my-math](https://github.com/leftaroundabout/Symbolic-math-HaTeX): Experimental library to ease the production
of mathematical expressions using HaTeX.

## Travis automatic build

For every code push to the GitHub repository, an automatic build checks that the library compiles with several
versions of GHC (check [.travis.yml](https://github.com/Daniel-Diaz/HaTeX/blob/master/.travis.yml) for the complete list of versions)
and that all tests pass. This label indicates the result of the last automatic build.

[![Build Status](https://travis-ci.org/Daniel-Diaz/HaTeX.png?branch=master)](https://travis-ci.org/Daniel-Diaz/HaTeX)

Currently, automatic builds are only running under Linux.


text:
package v17_06_1

import (
	"bytes"
	"encoding/json"
	"fmt"

	specs "github.com/opencontainers/runtime-spec/specs-go"
)

type linuxSyscalls []linuxSyscall

type linuxSyscall struct {
	specs.LinuxSyscall
}

func (ls *linuxSyscall) UnmarshalJSON(b []byte) error {
	var t struct {
		specs.LinuxSyscall
		Name *string `json:"name,omitempty"`
	}
	if err := json.Unmarshal(b, &t); err != nil {
		return err
	}
	ls.LinuxSyscall = t.LinuxSyscall
	if t.Name != nil {
		if ls.LinuxSyscall.Names != nil {
			return fmt.Errorf("found incompatible 'name' and 'names' fields")
		}
		ls.LinuxSyscall.Names = []string{*t.Name}
		t.Name = nil
	}
	return nil
}

// TODO: figure out how to omitempty when pointer is nil
type memorySwappiness struct {
	V *uint64 `json:",omitempty"`
}

func (m memorySwappiness) String() string {
	if m.V == nil {
		return "<nil>"
	}
	return fmt.Sprintf("%d", *m.V)
}

var null = []byte("null")

func (m *memorySwappiness) MarshalJSON() ([]byte, error) {
	if m.V == nil {
		return null, nil
	}
	return []byte(fmt.Sprintf("%d", *m.V)), nil
}

func (m *memorySwappiness) UnmarshalJSON(b []byte) error {
	if bytes.Compare(b, null) == 0 {
		return nil
	}

	var n uint64
	var i int64
	err := json.Unmarshal(b, &i)
	switch err.(type) {
	case nil:
		n = uint64(i)
	case *json.UnmarshalTypeError:
		// The only valid reason for accepting a uint64 that does not fit into an int64
		// is for erroneous -1 values being converted to uint64.
		// Nevertheless, try unmarshaling it and error out if it's not a number at all.
		if err := json.Unmarshal(b, &n); err != nil {
			return err
		}
	default:
		return err
	}
	if n >= 0 && n <= 100 {
		m.V = &n
	} else {
		m.V = nil
	}
	return nil
}

type linuxCapabilities struct {
	V *specs.LinuxCapabilities
}

func (l *linuxCapabilities) MarshalJSON() ([]byte, error) {
	return json.Marshal(l.V)
}

func (l *linuxCapabilities) UnmarshalJSON(b []byte) error {
	if bytes.Compare(b, null) == 0 {
		return nil
	}
	var s specs.LinuxCapabilities
	err := json.Unmarshal(b, &s)
	switch err.(type) {
	case nil:
		l.V = &s
	case *json.UnmarshalTypeError:
		var caps []string
		err = json.Unmarshal(b, &caps)
		if err != nil {
			return err
		}
		// TODO: copy caps or not copy caps?
		l.V = &specs.LinuxCapabilities{
			Bounding:    caps,
			Effective:   caps,
			Inheritable: caps,
			Permitted:   caps,
			Ambient:     nil,
		}
	}
	return err
}


text:
package basic.singleton;

/**
 * Created by Linuxea on 17-11-25.
 */

public class Main {

	public static void main(String[] args) {
		ControllerA controllerA = new ControllerA();
		ControllerA controllerA1 = new ControllerA();
		System.out.println(controllerA == controllerA1);
		// instance can not access static field
		System.out.println(ControllerA.getServiceA() == ControllerA.getServiceA());
	}
}


text:
#include "third_party/blink/renderer/core/layout/hit_test_location.h"

#include "third_party/blink/renderer/platform/geometry/float_rounded_rect.h"

namespace blink {

HitTestLocation::HitTestLocation()
    : is_rect_based_(false), is_rectilinear_(true) {}

HitTestLocation::HitTestLocation(const gfx::Point& point)
    : HitTestLocation(PhysicalOffset(point)) {}

HitTestLocation::HitTestLocation(const PhysicalOffset& point)
    : point_(point),
      bounding_box_(RectForPoint(point)),
      transformed_point_(point),
      transformed_rect_(gfx::RectF(bounding_box_)),
      is_rect_based_(false),
      is_rectilinear_(true) {}

HitTestLocation::HitTestLocation(const gfx::PointF& point)
    : point_(PhysicalOffset::FromPointFFloor(point)),
      bounding_box_(RectForPoint(point_)),
      transformed_point_(point),
      transformed_rect_(gfx::RectF(bounding_box_)),
      is_rect_based_(false),
      is_rectilinear_(true) {}

HitTestLocation::HitTestLocation(const gfx::PointF& point,
                                 const PhysicalRect& bounding_box)
    : point_(PhysicalOffset::FromPointFFloor(point)),
      bounding_box_(bounding_box),
      transformed_point_(point),
      transformed_rect_(gfx::RectF(bounding_box)),
      is_rect_based_(false),
      is_rectilinear_(true) {}

HitTestLocation::HitTestLocation(const DoublePoint& point)
    : HitTestLocation(gfx::PointF(point)) {}

HitTestLocation::HitTestLocation(const gfx::PointF& point,
                                 const gfx::QuadF& quad)
    : transformed_point_(point), transformed_rect_(quad), is_rect_based_(true) {
  point_ = PhysicalOffset::FromPointFFloor(point);
  bounding_box_ = PhysicalRect::EnclosingRect(quad.BoundingBox());
  is_rectilinear_ = quad.IsRectilinear();
}

HitTestLocation::HitTestLocation(const PhysicalRect& rect)
    : point_(rect.Center()),
      bounding_box_(rect),
      transformed_point_(point_),
      is_rect_based_(true),
      is_rectilinear_(true) {
  transformed_rect_ = gfx::QuadF(gfx::RectF(bounding_box_));
}

HitTestLocation::HitTestLocation(const HitTestLocation& other,
                                 const PhysicalOffset& offset)
    : point_(other.point_),
      bounding_box_(other.bounding_box_),
      transformed_point_(other.transformed_point_),
      transformed_rect_(other.transformed_rect_),
      is_rect_based_(other.is_rect_based_),
      is_rectilinear_(other.is_rectilinear_) {
  Move(offset);
}

HitTestLocation::HitTestLocation(const HitTestLocation& other,
                                 wtf_size_t fragment_index)
    : point_(other.point_),
      bounding_box_(other.bounding_box_),
      transformed_point_(other.transformed_point_),
      transformed_rect_(other.transformed_rect_),
      fragment_index_(fragment_index),
      is_rect_based_(other.is_rect_based_),
      is_rectilinear_(other.is_rectilinear_) {}

HitTestLocation::HitTestLocation(const HitTestLocation& other) = default;

HitTestLocation& HitTestLocation::operator=(const HitTestLocation& other) =
    default;

void HitTestLocation::Move(const PhysicalOffset& offset) {
  point_ += offset;
  bounding_box_.Move(offset);
  transformed_point_ += gfx::Vector2dF(offset);
  transformed_rect_ += gfx::Vector2dF(offset);
}

bool HitTestLocation::Intersects(const PhysicalRect& rect) const {
  // FIXME: When the hit test is not rect based we should use
  // rect.contains(m_point).
  // That does change some corner case tests though.

  // First check if rect even intersects our bounding box.
  if (!rect.Intersects(bounding_box_))
    return false;

  // If the transformed rect is rectilinear the bounding box intersection was
  // accurate.
  if (is_rectilinear_)
    return true;

  // If rect fully contains our bounding box, we are also sure of an
  // intersection.
  if (rect.Contains(bounding_box_))
    return true;

  // Otherwise we need to do a slower quad based intersection test.
  return transformed_rect_.IntersectsRect(gfx::RectF(rect));
}

bool HitTestLocation::Intersects(const gfx::RectF& rect) const {
  if (is_rect_based_)
    return transformed_rect_.IntersectsRect(rect);
  return rect.InclusiveContains(transformed_point_);
}

bool HitTestLocation::Intersects(const FloatRoundedRect& rect) const {
  return rect.IntersectsQuad(transformed_rect_);
}

bool HitTestLocation::Intersects(const gfx::QuadF& quad) const {
  // TODO(chrishtr): if the quads are not rectilinear, calling Intersects
  // has false positives.
  if (is_rect_based_)
    return Intersects(quad.BoundingBox());
  return quad.Contains(gfx::PointF(point_));
}

bool HitTestLocation::ContainsPoint(const gfx::PointF& point) const {
  return transformed_rect_.Contains(point);
}

}  // namespace blink


text:
using MVCForum.Domain.Interfaces.API;

namespace MVCForum.API
{
    public class MVCForumAPI : IMVCForumAPI
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public MVCForumAPI(IMemberAPI memberAPI, IPostAPI postAPI, ITopicAPI topicAPI, ICategoryAPI categoryAPI)
        {
            Member = memberAPI;
            Post = postAPI;
            Topic = topicAPI;
            Category = categoryAPI;
        }

        public IMemberAPI Member { get; set; }
        public IPostAPI Post { get; set; }
        public ITopicAPI Topic { get; set; }
        public ICategoryAPI Category { get; set; }
    }
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

require_once(dirname(dirname(dirname(__FILE__))).'/lib.php');   // module library
require_once(dirname(dirname(__FILE__)).'/edit_form.php');    // parent class definition

/**
 * Class for editing "Number of errors" grading strategy forms.
 *
 * @uses moodleform
 */
class workshop_edit_numerrors_strategy_form extends workshop_edit_strategy_form {

    /**
     * Define the elements to be displayed at the form
     *
     * Called by the parent::definition()
     *
     * @return void
     */
    protected function definition_inner(&$mform) {

        $plugindefaults     = get_config('workshopform_numerrors');
        $nodimensions       = $this->_customdata['nodimensions'];       // number of currently filled dimensions
        $norepeats          = $this->_customdata['norepeats'];          // number of dimensions to display
        $descriptionopts    = $this->_customdata['descriptionopts'];    // wysiwyg fields options
        $current            = $this->_customdata['current'];            // current data to be set

        $mform->addElement('hidden', 'norepeats', $norepeats);
        $mform->setType('norepeats', PARAM_INT);
        // value not to be overridden by submitted value
        $mform->setConstants(array('norepeats' => $norepeats));

        for ($i = 0; $i < $norepeats; $i++) {
            $mform->addElement('header', 'dimension'.$i, get_string('dimensionnumber', 'workshopform_numerrors', $i+1));
            $mform->addElement('hidden', 'dimensionid__idx_'.$i);   // the id in workshop_forms
            $mform->setType('dimensionid__idx_'.$i, PARAM_INT);
            $mform->addElement('editor', 'description__idx_'.$i.'_editor',
                    get_string('dimensiondescription', 'workshopform_numerrors'), '', $descriptionopts);
            $mform->addElement('text', 'grade0__idx_'.$i, get_string('grade0', 'workshopform_numerrors'), array('size'=>'15'));
            $mform->setDefault('grade0__idx_'.$i, $plugindefaults->grade0);
            $mform->setType('grade0__idx_'.$i, PARAM_TEXT);
            $mform->addElement('text', 'grade1__idx_'.$i, get_string('grade1', 'workshopform_numerrors'), array('size'=>'15'));
            $mform->setDefault('grade1__idx_'.$i, $plugindefaults->grade1);
            $mform->setType('grade1__idx_'.$i, PARAM_TEXT);
            $mform->addElement('select', 'weight__idx_'.$i,
                    get_string('dimensionweight', 'workshopform_numerrors'), workshop::available_dimension_weights_list());
            $mform->setDefault('weight__idx_'.$i, 1);
        }

        $mform->addElement('header', 'mappingheader', get_string('grademapping', 'workshopform_numerrors'));
        $mform->addElement('static', 'mappinginfo', get_string('maperror', 'workshopform_numerrors'),
                                                            get_string('mapgrade', 'workshopform_numerrors'));

        // get the total weight of all items == maximum weighted number of errors
        $totalweight = 0;
        for ($i = 0; $i < $norepeats; $i++) {
            if (!empty($current->{'weight__idx_'.$i})) {
                $totalweight += $current->{'weight__idx_'.$i};
            }
        }
        $totalweight = max($totalweight, $nodimensions);

        $percents = array();
        $percents[''] = '';
        for ($i = 100; $i >= 0; $i--) {
            $percents[$i] = get_string('percents', 'workshopform_numerrors', $i);
        }
        $mform->addElement('static', 'mappingzero', 0, get_string('percents', 'workshopform_numerrors', 100));
        for ($i = 1; $i <= $totalweight; $i++) {
            $selects = array();
            $selects[] = $mform->createElement('select', 'map__idx_'.$i, $i, $percents);
            $selects[] = $mform->createElement('static', 'mapdefault__idx_'.$i, '',
                                        get_string('percents', 'workshopform_numerrors', floor(100 - $i * 100 / $totalweight)));
            $mform->addGroup($selects, 'grademapping'.$i, $i, array(' '), false);
            $mform->setDefault('map__idx_'.$i, '');
        }

        $mform->registerNoSubmitButton('noadddims');
        $mform->addElement('submit', 'noadddims', get_string('addmoredimensions', 'workshopform_numerrors',
                workshop_numerrors_strategy::ADDDIMS));
        $mform->closeHeaderBefore('noadddims');
        $this->set_data($current);

    }

}


text:
import {Injectable} from '@angular/core';
import {NgbDateStruct} from '../ngb-date-struct';
import {NgbDateNativeAdapter} from './ngb-date-native-adapter';

/**
 * NgbDateAdapter implementation that allows using native javascript UTC date as a user date model.
 * Same as NgbDateNativeAdapter, but uses UTC dates.
 *
 * @since 3.2.0
 */
@Injectable()
export class NgbDateNativeUTCAdapter extends NgbDateNativeAdapter {
  protected _fromNativeDate(date: Date): NgbDateStruct {
    return {year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate()};
  }

  protected _toNativeDate(date: NgbDateStruct): Date {
    const jsDate = new Date(Date.UTC(date.year, date.month - 1, date.day));
    // avoid 30 -> 1930 conversion
    jsDate.setUTCFullYear(date.year);
    return jsDate;
  }
}


text:
package de.hbrs.aspgen.api.parser;

import java.io.File;

import de.hbrs.aspgen.api.ast.AspectJUnit;

public interface AspectJParser {
    AspectJUnit parse(final String source);
    AspectJUnit parse(final File file);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/color_white"
    android:orientation="vertical">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/head_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/dk_bg_gray_round_rectangle"
        android:padding="@dimen/border_padding">

        <EditText
            android:id="@+id/edt_select_position"
            android:layout_width="0dp"
            android:layout_height="@dimen/edt_height"
            android:background="@drawable/dk_bg_round_edt"
            android:hint="@string/position_address"
            android:paddingLeft="6dp"
            android:singleLine="true"
            android:textColor="@color/color_bold_text_black"
            android:textCursorDrawable="@drawable/dk_bg_edt_hint"
            android:textSize="@dimen/edt_text_size"
            android:textColorHint="@color/color_bold_text_hint"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_position_list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>


text:
<?php

namespace OpenDominion\Http\Controllers\Dominion;

use OpenDominion\Calculators\Dominion\BuildingCalculator;
use OpenDominion\Calculators\Dominion\LandCalculator;
use OpenDominion\Calculators\Dominion\PopulationCalculator;
use OpenDominion\Calculators\Dominion\ProductionCalculator;
use OpenDominion\Helpers\BuildingHelper;
use OpenDominion\Helpers\LandHelper;
use OpenDominion\Services\DominionQueueService;

class AdvisorsController extends AbstractDominionController
{
    public function getAdvisors()
    {
        return redirect()->route('dominion.advisors.production');
    }

    public function getAdvisorsProduction()
    {
        $populationCalculator = app(PopulationCalculator::class);
        $productionCalculator = app(ProductionCalculator::class);

        return view('pages.dominion.advisors.production', compact(
            'populationCalculator',
            'productionCalculator'
        ));
    }

    public function getAdvisorsMilitary()
    {
        return view('pages.dominion.advisors.military');
    }

    public function getAdvisorsLand()
    {
        $landHelper = app(LandHelper::class);
        $landCalculator = app(LandCalculator::class);
        $dominionQueueService = app(DominionQueueService::class);

        return view('pages.dominion.advisors.land', compact(
            'landHelper',
            'landCalculator',
            'dominionQueueService'
        ));
    }

    public function getAdvisorsConstruction()
    {
        $buildingHelper = app(BuildingHelper::class);
        $buildingCalculator = app(BuildingCalculator::class);
        $landCalculator = app(LandCalculator::class);
        $dominionQueueService = app(DominionQueueService::class);

        return view('pages.dominion.advisors.construction', compact(
            'buildingHelper',
            'buildingCalculator',
            'landCalculator',
            'dominionQueueService'
        ));
    }
}


text:
List *list = nullptr;

void destroy_data(void *data)
{
    free(data);
}

TEST(ListTest, ListInit)
{

    list = (List *)malloc(sizeof(List));
    EXPECT_NE(nullptr, list);

    list_init(list, nullptr);
    EXPECT_EQ(0, list_size(list));
    EXPECT_EQ(nullptr, list_head(list));

    list_init(list, destroy_data);
    EXPECT_EQ(0, list_size(list));
    EXPECT_EQ(nullptr, list_head(list));
}

TEST(ListTest, InsetItem)
{
    char *bytes = (char *)malloc(100);
    for ( int i = 0 ; i < 100 ; ++i ) {
        bytes[i] = i;
    }

    int list_old_length = list_size(list);

    int ret = list_insert_next(list, nullptr, (void *)bytes);

    EXPECT_EQ(0, ret);
    EXPECT_EQ(list_old_length + 1, list_size(list));
}

TEST(ListTest, RemoveItem)
{
    char *bytes = nullptr;

    int list_old_length = list_size(list);
    int ret = list_remove_next(list, nullptr, (void**)&bytes);

    EXPECT_EQ(0, ret);
    EXPECT_EQ(list_old_length - 1, list_size(list));

    for ( int i = 0 ; i < 100 ; ++i ) {
        EXPECT_EQ(i, bytes[i]);
    }

    free(bytes);
}

TEST(ListTest, DestroyList)
{
    list_destroy(list);

    EXPECT_EQ(0, list_size(list));
}

int main(int argc, char *argv[])
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
This file explains the gmtools mod, not the gmtools API.

# Usage
Usage of the mod is very similar to the gmtools' API. Open the console and have fun!

**Note: all paths must be wrapped in double quotes (")**, otherwise errors will arise.

### ```gmad_create inputFolder, outputGMA```
Description:
- Creates a *.gma* file based on the inputFolder.

Parameters:
- inputFolder (required): the path to the mod you want to create
- outputGMA (optional): the path to the *.gma*, **note**: the *.gma* extenesion will be added by gmad if it isn't there

Returns:
- string: whatever gmad returns

Example:
```gmad_create "C:\Users\andrew\Desktop\mod" "C:\Users\andrew\Desktop\mod.gma"```

### ```gmad_extract inputGMA outputFolder```
Description:
- Extracts the inputGMA.

Parameters:
- inputGMA (required): the path to the *.gma* you want to create
- outputFolder (optional): the path where the *.gma* will be extracted

Returns:
- string: whatever gmad returns

Example:
```gmad_extract "C:\Users\andrew\Desktop\mod.gma" "C:\Users\andrew\Desktop\mod"```

### ```gmpublish_list```
Description:
- Lists all the mods you have uploaded to the Garry's Mod Workshop.

Parameters:
- none

Returns:
- string: whatever gmpublish returns

Example:
```gmpublish_list```


text:
function fahrenheit_to_celsius(F)
    C = 0

    # Your code goes here: calculate the temperature in Celsius,
    # store in a variable (we called it C), and return it.

    return C
end


text:
from setuptools import setup

from django_arakoon_cache import __VERSION__ as VERSION

setup(
    name='django-arakoon-cache',
    version=VERSION,
    description='Arakoon cache backend for Django.',
    long_description=open('README.rst').read(),
    author='Mohab Usama',
    author_email='mohab.usama@gmail.com',
    url='https://github.com/mohabusama/django-arakoon-cache',
    packages=['django_arakoon_cache'],
    install_requires=['arakoon'],
    license=open('LICENSE').read(),
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)


text:
"""
Support for Xiaomi Yeelight Wifi color bulb.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.yeelight/
"""
import logging
import colorsys

import voluptuous as vol

from homeassistant.util.color import (
    color_temperature_mired_to_kelvin as mired_to_kelvin,
    color_temperature_kelvin_to_mired as kelvin_to_mired,
    color_temperature_to_rgb)
from homeassistant.const import CONF_DEVICES, CONF_NAME
from homeassistant.components.light import (
    ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_TRANSITION, ATTR_COLOR_TEMP,
    ATTR_FLASH, FLASH_SHORT, FLASH_LONG,
    SUPPORT_BRIGHTNESS, SUPPORT_RGB_COLOR, SUPPORT_TRANSITION,
    SUPPORT_COLOR_TEMP, SUPPORT_FLASH,
    Light, PLATFORM_SCHEMA)
import homeassistant.helpers.config_validation as cv

REQUIREMENTS = ['yeelight==0.2.1']

_LOGGER = logging.getLogger(__name__)

CONF_TRANSITION = "transition"
DEFAULT_TRANSITION = 350

CONF_SAVE_ON_CHANGE = "save_on_change"
CONF_MODE_MUSIC = "use_music_mode"

DOMAIN = 'yeelight'

DEVICE_SCHEMA = vol.Schema({
    vol.Optional(CONF_NAME): cv.string,
    vol.Optional(CONF_TRANSITION, default=DEFAULT_TRANSITION): cv.positive_int,
    vol.Optional(CONF_MODE_MUSIC, default=False): cv.boolean,
    vol.Optional(CONF_SAVE_ON_CHANGE, default=True): cv.boolean,
})

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {vol.Optional(CONF_DEVICES, default={}): {cv.string: DEVICE_SCHEMA}, })

SUPPORT_YEELIGHT_RGB = (SUPPORT_RGB_COLOR |
                        SUPPORT_COLOR_TEMP)

SUPPORT_YEELIGHT = (SUPPORT_BRIGHTNESS |
                    SUPPORT_TRANSITION |
                    SUPPORT_FLASH)

def _cmd(func):
    """A wrapper to catch exceptions from the bulb."""
    def _wrap(self, *args, **kwargs):
        import yeelight
        try:
            _LOGGER.debug("Calling %s with %s %s", func, args, kwargs)
            return func(self, *args, **kwargs)
        except yeelight.BulbException as ex:
            _LOGGER.error("Error when calling %s: %s", func, ex)

    return _wrap

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Yeelight bulbs."""
    lights = []
    if discovery_info is not None:
        _LOGGER.debug("Adding autodetected %s", discovery_info['hostname'])

        # not using hostname, as it seems to vary.
        name = "yeelight_%s_%s" % (discovery_info["device_type"],
                                   discovery_info["properties"]["mac"])
        device = {'name': name, 'ipaddr': discovery_info['host']}

        lights.append(YeelightLight(device, DEVICE_SCHEMA({})))
    else:
        for ipaddr, device_config in config[CONF_DEVICES].items():
            _LOGGER.debug("Adding configured %s", device_config[CONF_NAME])

            device = {'name': device_config[CONF_NAME], 'ipaddr': ipaddr}
            lights.append(YeelightLight(device, device_config))

    add_devices(lights, True)  # true to request an update before adding.

class YeelightLight(Light):
    """Representation of a Yeelight light."""

    def __init__(self, device, config):
        """Initialize the light."""
        self.config = config
        self._name = device['name']
        self._ipaddr = device['ipaddr']

        self._supported_features = SUPPORT_YEELIGHT
        self._available = False
        self._bulb_device = None

        self._brightness = None
        self._color_temp = None
        self._is_on = None
        self._rgb = None

    @property
    def available(self) -> bool:
        """Return if bulb is available."""
        return self._available

    @property
    def supported_features(self) -> int:
        """Flag supported features."""
        return self._supported_features

    @property
    def unique_id(self) -> str:
        """Return the ID of this light."""
        return "{}.{}".format(self.__class__, self._ipaddr)

    @property
    def color_temp(self) -> int:
        """Return the color temperature."""
        return self._color_temp

    @property
    def name(self) -> str:
        """Return the name of the device if any."""
        return self._name

    @property
    def is_on(self) -> bool:
        """Return true if device is on."""
        return self._is_on

    @property
    def brightness(self) -> int:
        """Return the brightness of this light between 1..255."""
        return self._brightness

    def _get_rgb_from_properties(self):
        rgb = self._properties.get("rgb", None)
        color_mode = self._properties.get("color_mode", None)
        if not rgb or not color_mode:
            return rgb

        color_mode = int(color_mode)
        if color_mode == 2:  # color temperature
            return color_temperature_to_rgb(self.color_temp)
        if color_mode == 3:  # hsv
            hue = self._properties.get("hue")
            sat = self._properties.get("sat")
            val = self._properties.get("bright")
            return colorsys.hsv_to_rgb(hue, sat, val)

        rgb = int(rgb)
        blue = rgb & 0xff
        green = (rgb >> 8) & 0xff
        red = (rgb >> 16) & 0xff

        return red, green, blue

    @property
    def rgb_color(self) -> tuple:
        """Return the color property."""
        return self._rgb

    @property
    def _properties(self) -> dict:
        return self._bulb.last_properties

    @property
    def _bulb(self) -> object:
        import yeelight
        if self._bulb_device is None:
            try:
                self._bulb_device = yeelight.Bulb(self._ipaddr)
                self._bulb_device.get_properties()  # force init for type

                btype = self._bulb_device.bulb_type
                if btype == yeelight.BulbType.Color:
                    self._supported_features |= SUPPORT_YEELIGHT_RGB
                self._available = True
            except yeelight.BulbException as ex:
                self._available = False
                _LOGGER.error("Failed to connect to bulb %s, %s: %s",
                              self._ipaddr, self._name, ex)

        return self._bulb_device

    def set_music_mode(self, mode) -> None:
        """Set the music mode on or off."""
        if mode:
            self._bulb.start_music()
        else:
            self._bulb.stop_music()

    def update(self) -> None:
        """Update properties from the bulb."""
        import yeelight
        try:
            self._bulb.get_properties()

            self._is_on = self._properties.get("power") == "on"

            bright = self._properties.get("bright", None)
            if bright:
                self._brightness = 255 * (int(bright) / 100)

            temp_in_k = self._properties.get("ct", None)
            if temp_in_k:
                self._color_temp = kelvin_to_mired(int(temp_in_k))

            self._rgb = self._get_rgb_from_properties()

            self._available = True
        except yeelight.BulbException as ex:
            if self._available:  # just inform once
                _LOGGER.error("Unable to update bulb status: %s", ex)
            self._available = False

    @_cmd
    def set_brightness(self, brightness, duration) -> None:
        """Set bulb brightness."""
        if brightness:
            _LOGGER.debug("Setting brightness: %s", brightness)
            self._bulb.set_brightness(brightness / 255 * 100,
                                      duration=duration)

    @_cmd
    def set_rgb(self, rgb, duration) -> None:
        """Set bulb's color."""
        if rgb and self.supported_features & SUPPORT_RGB_COLOR:
            _LOGGER.debug("Setting RGB: %s", rgb)
            self._bulb.set_rgb(rgb[0], rgb[1], rgb[2], duration=duration)

    @_cmd
    def set_colortemp(self, colortemp, duration) -> None:
        """Set bulb's color temperature."""
        if colortemp and self.supported_features & SUPPORT_COLOR_TEMP:
            temp_in_k = mired_to_kelvin(colortemp)
            _LOGGER.debug("Setting color temp: %s K", temp_in_k)

            self._bulb.set_color_temp(temp_in_k, duration=duration)

    @_cmd
    def set_default(self) -> None:
        """Set current options as default."""
        self._bulb.set_default()

    @_cmd
    def set_flash(self, flash) -> None:
        """Activate flash."""
        if flash:
            from yeelight import RGBTransition, SleepTransition, Flow
            if self._bulb.last_properties["color_mode"] != 1:
                _LOGGER.error("Flash supported currently only in RGB mode.")
                return

            transition = self.config[CONF_TRANSITION]
            if flash == FLASH_LONG:
                count = 1
                duration = transition * 5
            if flash == FLASH_SHORT:
                count = 1
                duration = transition * 2

            red, green, blue = self.rgb_color

            transitions = list()
            transitions.append(
                RGBTransition(255, 0, 0, brightness=10, duration=duration))
            transitions.append(SleepTransition(
                duration=transition))
            transitions.append(
                RGBTransition(red, green, blue, brightness=self.brightness,
                              duration=duration))

            flow = Flow(count=count, transitions=transitions)
            self._bulb.start_flow(flow)

    def turn_on(self, **kwargs) -> None:
        """Turn the bulb on."""
        brightness = kwargs.get(ATTR_BRIGHTNESS)
        colortemp = kwargs.get(ATTR_COLOR_TEMP)
        rgb = kwargs.get(ATTR_RGB_COLOR)
        flash = kwargs.get(ATTR_FLASH)

        duration = self.config[CONF_TRANSITION]  # in ms
        if ATTR_TRANSITION in kwargs:  # passed kwarg overrides config
            duration = kwargs.get(ATTR_TRANSITION) * 1000  # kwarg in s

        self._bulb.turn_on(duration=duration)

        if self.config[CONF_MODE_MUSIC] and not self._bulb.music_mode:
            self.set_music_mode(self.config[CONF_MODE_MUSIC])

        # values checked for none in methods
        self.set_rgb(rgb, duration)
        self.set_colortemp(colortemp, duration)
        self.set_brightness(brightness, duration)
        self.set_flash(flash)

        # save the current state if we had a manual change.
        if self.config[CONF_SAVE_ON_CHANGE]:
            if brightness or colortemp or rgb:
                self.set_default()

    def turn_off(self, **kwargs) -> None:
        """Turn off."""
        self._bulb.turn_off()


text:
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Event, Emitter } from 'vs/base/common/event';
import { ExtHostTelemetryShape } from 'vs/workbench/api/common/extHost.protocol';
import { TelemetryLevel } from 'vs/platform/telemetry/common/telemetry';
import type { TelemetryConfiguration } from 'vscode';

export class ExtHostTelemetry implements ExtHostTelemetryShape {
	private readonly _onDidChangeTelemetryEnabled = new Emitter<boolean>();
	readonly onDidChangeTelemetryEnabled: Event<boolean> = this._onDidChangeTelemetryEnabled.event;

	private readonly _onDidChangeTelemetryConfiguration = new Emitter<TelemetryConfiguration>();
	readonly onDidChangeTelemetryConfiguration: Event<TelemetryConfiguration> = this._onDidChangeTelemetryConfiguration.event;

	private _productConfig: { usage: boolean; error: boolean } = { usage: true, error: true };
	private _level: TelemetryLevel = TelemetryLevel.NONE;
	private _oldTelemetryEnablement: boolean | undefined;

	getTelemetryConfiguration(): boolean {
		return this._level === TelemetryLevel.USAGE;
	}

	getTelemetryDetails(): TelemetryConfiguration {
		return {
			isCrashEnabled: this._level >= TelemetryLevel.CRASH,
			isErrorsEnabled: this._productConfig.error ? this._level >= TelemetryLevel.ERROR : false,
			isUsageEnabled: this._productConfig.usage ? this._level >= TelemetryLevel.USAGE : false
		};
	}

	$initializeTelemetryLevel(level: TelemetryLevel, productConfig?: { usage: boolean; error: boolean }): void {
		this._level = level;
		this._productConfig = productConfig || { usage: true, error: true };
	}

	$onDidChangeTelemetryLevel(level: TelemetryLevel): void {
		this._oldTelemetryEnablement = this.getTelemetryConfiguration();
		this._level = level;
		if (this._oldTelemetryEnablement !== this.getTelemetryConfiguration()) {
			this._onDidChangeTelemetryEnabled.fire(this.getTelemetryConfiguration());
		}
		this._onDidChangeTelemetryConfiguration.fire(this.getTelemetryDetails());
	}
}

export const IExtHostTelemetry = createDecorator<IExtHostTelemetry>('IExtHostTelemetry');
export interface IExtHostTelemetry extends ExtHostTelemetry, ExtHostTelemetryShape { }


text:
<?php
namespace OSTD\Autoloader;

class Autoloader{
	protected $_baseDir = null;

	public function __construct(){
		$this->_baseDir = getcwd();
	}

	public function loadClass($className){
		$fileName = $this->_baseDir . '/' . str_replace('\\', '/', $className) . '.php';

		if(is_file($fileName)){
			require_once($fileName);
		}
	}

	public function register(){
		spl_autoload_register(array($this, 'loadClass'));
	}
}


text:
<ExampleDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <View>Examples/CreateRadarChart/RadarChartCustomizationExampleView.xaml</View>
  <ViewModel>Examples.CreateRadarChart.RadarChartCustomizationExampleViewModel</ViewModel>
  <ImagePath>/SciChart.Examples;component/Resources/Images/ExampleImages/demoCandlestickAndLines.png</ImagePath>
  <IconPath>IconPolar</IconPath>
  <ToolTipDescription>Radar Chart.</ToolTipDescription>
  <Description>
    Demonstrates how to create a customization Radar Chart. A radar chart is a graphical method of displaying multivariate data in the form of a two-dimensional chart of three or more quantitative variables represented on axes starting from the same point. The relative position and angle of the axes is typically uninformative.

    [i][b]Tips![/i][/b]
    [i]You can configurate AxisLength and Angle properties in RadarYAxis. But before you should set to false AutoAxisLength or AutoAxisAngleCalculation properties in SciChartRadarSurface.[/i]

    [i]For customizate axis label you should use label provider on axis [/i]

    [b]Documentation Links[/b]
    Coming soon.
  </Description>
  <CodeFiles>
    <string>Resources/ExampleSourceFiles/CreateRadarChart/RadarChartCustomizationExampleView.xaml.txt</string>
    <string>Resources/ExampleSourceFiles/CreateRadarChart/RadarChartCustomizationExampleView.xaml.cs.txt</string>
    <string>Resources/ExampleSourceFiles/CreateRadarChart/RadarChartCustomizationExampleViewModel.cs.txt</string>
    <string>Resources/ExampleSourceFiles/CreateRadarChart/RadarChartCustomizationLabelProviders.cs.txt</string>
  </CodeFiles>
  <Features>
  </Features>
</ExampleDefinition>


text:
@extends('layouts.default')
@section('content')

Password Recovery

{{ $errors->first('email') }}

{{ $errors->first('password') }}

{{ $errors->first('password_confirmation') }}

{{ $errors->first('token') }}

{{ $errors->first('error') }}

							<form class="center-block" action="{{ action('RemindersController@postReset') }}" method="POST">

								    Email address
								    {{Form::email('email',Input::old('email'), array(
								    						'class' => "form-control",
								    						'placeholder' => "youremail@example.com"
								    					) )}}

								    New Password
								    <input type="password" class="form-control" id="password" name="password">

								    New Password Again
								    <input type="password" class="form-control" id="password_confirmation" name="password_confirmation">

									Auth Token
								    {{ Form::text('token', $token,
								     array('class' => "form-control") ) }}

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

									{{ link_to('auth/login', 'Back to login page', array('class' => ' btn btn-link'), null) }}

							</form>

@stop


text:
layout: post
date: '2016-02-03'
title: "COCKTAIL DRESSES Sherri Hill 9601 Short Homecoming Dress"
category: COCKTAIL DRESSES
tags: [COCKTAIL DRESSES]
---
### COCKTAIL DRESSES Sherri Hill 9601 Short Homecoming Dress
Just **$409.99**
###

Sherri Hill 9601 Short Homecoming Dress.

Available in sizes 0-18.

Buy it: [https://www.eudances.com/en/cocktail-dresses/1357-sherri-hill-9601-short-homecoming-dress.html](https://www.eudances.com/en/cocktail-dresses/1357-sherri-hill-9601-short-homecoming-dress.html)


text:
var Send = require("./send.js");
var Validar = require("./validate.js");

var errorModal = require("../views/error.eco");
var errorModalHTML = document.getElementById('errorModal')

var successModal = require("../views/success.eco");
var successModalHTML = document.getElementById('successModal')

function init(){
	animateScroll();
	navColapse();
	startDatepicker();
	sameInpustValues()
	Validar();
	sendInformation()
}

// Init Date Pickers
function startDatepicker(){
  $('.datepicker').pickadate();
}

// Animate Scroll
function animateScroll() {
  $('.nav a, #btn-header').click(function(){
    //Toggle Class
    $(".active").removeClass("active");
    $(this).closest('li').addClass("active");
    var theClass = $(this).attr("class");
    $('.'+theClass).parent('li').addClass('active');
    //Animate
    $('html, body').stop().animate({
        scrollTop: $( $(this).attr('href') ).offset().top - 100
    }, 400);
    return false;
  });
  $('.scrollTop a').scrollTop();
}

// Function to collapse nav on mobile
function navColapse(){
	$('.navbar-collapse a').click(function(){
    	$(".navbar-collapse").collapse('hide');
	});
}

// inputs dates equal values
function sameInpustValues(){
	$('.in').change(function() {
		$('.in').val(this.value)
	});
	$('.out').change(function() {
		$('.out').val(this.value)
	});
}

// Send information using send.js
function sendInformation(){
	$('#send-request').click(function(){
		var values = getvalues();
		if(validateValues()){
			successSend()
			Send(values);
		}
	})
}

// Get values of request
function getvalues(){
	var checkin = $('#checkin').val();
	var checkout = $('#checkout').val();
	var name = $('#name').val();
	var email = $('#email').val();
	var commet = $('#commet').val();
	var guests = $('#guests').val();

	var mensaje = {
		checkin: checkin,
		checkout: checkout,
		name: name,
		email: email,
		commet: commet,
		guests: guests
	};
	return mensaje
}

function validateValues(){
	var name = document.getElementById('name');
	var email = document.getElementById('email');
	var guests = document.getElementById('guests');

	var mensaje = {};

	if (hasClass(name, "valid")) {
		if (hasClass(email, "valid")) {
			if (hasClass(guests, "valid")) {
				return true
			} else {
				mensaje = { text:"The guests field is required" }
				errorModalHTML.innerHTML = errorModal(mensaje);
				$('#errorModal').modal('show');
				guests.focus();
				return false
			}
		} else {
			mensaje = { text:"The email field is required" }
			errorModalHTML.innerHTML = errorModal(mensaje);
			$('#errorModal').modal('show');
			email.focus();
			return false
		}
	}else{
		mensaje = { text:"The name field is required" }
		errorModalHTML.innerHTML = errorModal(mensaje);
		$('#errorModal').modal('show');
		name.focus();
		return false
	}
}

function successSend(){

	var mensaje = { text:"We have received your information !! \n We will contact you to provide more information." }
	successModalHTML.innerHTML = successModal(mensaje);
	$('#successModal').modal('show');

	$('#checkin').val("");
	$('#checkout').val("");
	$('#name').val("");
	$('#email').val("");
	$('#commet').val("");
	$('#guests').val("");
}

function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

module.exports = init;


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Package exception</title>
<meta name="date" content="2016-05-25">
<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

Next

Frames

No Frames

All Classes

Uses of Package
exception

No usage of exception

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
function readFile(s) {
	if(localStorage.getItem("FILE:" + s) != null && localStorage.getItem("FILE:" + s) != undefined && localStorage.getItem("FILE:" + s) != "undefined") {
	return localStorage.getItem("FILE:" + s);
	}
	else
	{
		return "";
	}

}
function writeFile(s,s2) {
	return localStorage.setItem("FILE:" + s,s2);
}


text:
var route = require('koa-route');
var service = global.inject_service("pessoa.service");

var PessoaController = {
    index: function *(next){
        this.body = yield service.list();
    },
    create: function *(next){
        var data = this.request.body;
        this.body = yield service.save(data);
    },
    show: function *(id){
        this.body = yield service.get(id);
    },
    update: function *(id){
        var data = this.request.body;
        this.body = yield service.update(id,data);
    },
    delete : function *(id){
        this.body = yield service.delete(id);
    },
    sortear : function *(){
        this.body = yield service.sortear();
    }
};

module.exports.install = function (app){
    app.use(route.get('/v1/pessoas', PessoaController.index));
    app.use(route.get('/v1/pessoas/sortear', PessoaController.sortear));
    app.use(route.get('/v1/pessoas/:id', PessoaController.show));
    app.use(route.post('/v1/pessoas', PessoaController.create));
    app.use(route.post('/v1/pessoas/:id', PessoaController.update));
    app.use(route.delete('/v1/pessoas/:id', PessoaController.delete));
};