text:
package com.intellij.codeInsight.intention.impl;

import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.ShowIntentionsPass;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.intention.EmptyIntentionAction;
import com.intellij.codeInsight.intention.HighPriorityAction;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInsight.intention.impl.config.IntentionActionWrapper;
import com.intellij.codeInsight.intention.impl.config.IntentionManagerSettings;
import com.intellij.codeInspection.ex.QuickFixWrapper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Iconable;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.util.PsiUtilBase;
import gnu.trove.THashSet;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.*;

/**
* @author cdr
*/
class IntentionListStep implements ListPopupStep<IntentionActionWithTextCaching>, SpeedSearchFilter<IntentionActionWithTextCaching> {
  private final Set<IntentionActionWithTextCaching> myCachedIntentions = new THashSet<IntentionActionWithTextCaching>(ACTION_TEXT_AND_CLASS_EQUALS);
  private final Set<IntentionActionWithTextCaching> myCachedErrorFixes = new THashSet<IntentionActionWithTextCaching>(ACTION_TEXT_AND_CLASS_EQUALS);
  private final Set<IntentionActionWithTextCaching> myCachedInspectionFixes = new THashSet<IntentionActionWithTextCaching>(ACTION_TEXT_AND_CLASS_EQUALS);
  private final Set<IntentionActionWithTextCaching> myCachedGutters = new THashSet<IntentionActionWithTextCaching>(ACTION_TEXT_AND_CLASS_EQUALS);
  private final IntentionManagerSettings mySettings;
  @Nullable
  private final IntentionHintComponent myIntentionHintComponent;
  private final Editor myEditor;
  private final PsiFile myFile;
  private final Project myProject;
  private static final TObjectHashingStrategy<IntentionActionWithTextCaching> ACTION_TEXT_AND_CLASS_EQUALS = new TObjectHashingStrategy<IntentionActionWithTextCaching>() {
    public int computeHashCode(final IntentionActionWithTextCaching object) {
      return object.getText().hashCode();
    }

    public boolean equals(final IntentionActionWithTextCaching o1, final IntentionActionWithTextCaching o2) {
      return o1.getAction().getClass() == o2.getAction().getClass() && o1.getText().equals(o2.getText());
    }
  };
  private Runnable myFinalRunnable;

  IntentionListStep(@Nullable IntentionHintComponent intentionHintComponent,
                    @NotNull ShowIntentionsPass.IntentionsInfo intentions,
                    @NotNull Editor editor,
                    @NotNull PsiFile file,
                    @NotNull Project project) {
    myIntentionHintComponent = intentionHintComponent;
    myEditor = editor;
    myFile = file;
    myProject = project;
    mySettings = IntentionManagerSettings.getInstance();
    updateActions(intentions);
  }

  //true if something changed
  boolean updateActions(@NotNull ShowIntentionsPass.IntentionsInfo intentions) {
    boolean result = wrapActionsTo(intentions.errorFixesToShow, myCachedErrorFixes);
    result &= wrapActionsTo(intentions.inspectionFixesToShow, myCachedInspectionFixes);
    result &= wrapActionsTo(intentions.intentionsToShow, myCachedIntentions);
    result &= wrapActionsTo(intentions.guttersToShow, myCachedGutters);
    return !result;
  }

  private boolean wrapActionsTo(@NotNull List<HighlightInfo.IntentionActionDescriptor> newDescriptors,
                                @NotNull Set<IntentionActionWithTextCaching> cachedActions) {
    final int caretOffset = myEditor.getCaretModel().getOffset();
    final int fileOffset = caretOffset > 0 && caretOffset == myFile.getTextLength() ? caretOffset - 1 : caretOffset;
    PsiElement element;
    final PsiElement hostElement;
    if (myFile instanceof PsiCompiledElement) {
      hostElement = element = myFile;

    }
    else if (PsiDocumentManager.getInstance(myProject).isUncommited(myEditor.getDocument())) {
      //???
      FileViewProvider viewProvider = myFile.getViewProvider();
      hostElement = element = viewProvider.findElementAt(fileOffset, viewProvider.getBaseLanguage());
    }
    else {
      hostElement = myFile.getViewProvider().findElementAt(fileOffset, myFile.getLanguage());
      element = InjectedLanguageUtil.findElementAtNoCommit(myFile, fileOffset);
    }
    PsiFile injectedFile;
    Editor injectedEditor;
    if (element == null || element == hostElement) {
      injectedFile = myFile;
      injectedEditor = myEditor;
    }
    else {
      injectedFile = element.getContainingFile();
      injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(myEditor, injectedFile);
    }

    boolean result = true;
    for (Iterator<IntentionActionWithTextCaching> iterator = cachedActions.iterator(); iterator.hasNext();) {
      IntentionActionWithTextCaching cachedAction = iterator.next();
      IntentionAction action = cachedAction.getAction();
      if (!ShowIntentionActionsHandler.availableFor(myFile, myEditor, action)
        && (hostElement == element || element != null && !ShowIntentionActionsHandler.availableFor(injectedFile, injectedEditor, action))) {
        iterator.remove();
        result = false;
      }
    }

    Set<IntentionActionWithTextCaching> wrappedNew = new THashSet<IntentionActionWithTextCaching>(newDescriptors.size(), ACTION_TEXT_AND_CLASS_EQUALS);
    for (HighlightInfo.IntentionActionDescriptor descriptor : newDescriptors) {
      final IntentionAction action = descriptor.getAction();
      if (element != null && element != hostElement && ShowIntentionActionsHandler.availableFor(injectedFile, injectedEditor, action)) {
        IntentionActionWithTextCaching cachedAction = wrapAction(descriptor, element, injectedFile, injectedEditor);
        wrappedNew.add(cachedAction);
        result &= !cachedActions.add(cachedAction);
      }
      else if (hostElement != null && ShowIntentionActionsHandler.availableFor(myFile, myEditor, action)) {
        IntentionActionWithTextCaching cachedAction = wrapAction(descriptor, hostElement, myFile, myEditor);
        wrappedNew.add(cachedAction);
        result &= !cachedActions.add(cachedAction);
      }
    }
    for (Iterator<IntentionActionWithTextCaching> iterator = cachedActions.iterator(); iterator.hasNext();) {
      IntentionActionWithTextCaching cachedAction = iterator.next();
      if (!wrappedNew.contains(cachedAction)) {
        // action disappeared
        iterator.remove();
        result = false;
      }
    }
    return result;
  }

  IntentionActionWithTextCaching wrapAction(@NotNull HighlightInfo.IntentionActionDescriptor descriptor,
                                            @NotNull PsiElement element,
                                            @NotNull PsiFile containingFile,
                                            @NotNull Editor containingEditor) {
    IntentionActionWithTextCaching cachedAction = new IntentionActionWithTextCaching(descriptor);
    final List<IntentionAction> options = descriptor.getOptions(element);
    if (options == null) return cachedAction;
    for (IntentionAction option : options) {
      if (!option.isAvailable(myProject, containingEditor, containingFile)) {
        // if option is not applicable in injected fragment, check in host file context
        if (containingEditor == myEditor || !option.isAvailable(myProject, myEditor, myFile)) {
          continue;
        }
      }
      IntentionActionWithTextCaching textCaching = new IntentionActionWithTextCaching(option);
      boolean isErrorFix = myCachedErrorFixes.contains(textCaching);
      if (isErrorFix) {
        cachedAction.addErrorFix(option);
      }
      boolean isInspectionFix = myCachedInspectionFixes.contains(textCaching);
      if (isInspectionFix) {
        cachedAction.addInspectionFix(option);
      }
      else {
        cachedAction.addIntention(option);
      }
    }
    return cachedAction;
  }

  public String getTitle() {
    return null;
  }

  public boolean isSelectable(final IntentionActionWithTextCaching action) {
    return true;
  }

  public PopupStep onChosen(final IntentionActionWithTextCaching action, final boolean finalChoice) {
    if (finalChoice && !(action.getAction() instanceof EmptyIntentionAction)) {
      applyAction(action);
      return FINAL_CHOICE;
    }

    if (hasSubstep(action)) {
      return getSubStep(action, action.getToolName());
    }

    return FINAL_CHOICE;
  }

  public Runnable getFinalRunnable() {
    return myFinalRunnable;
  }

  private void applyAction(final IntentionActionWithTextCaching cachedAction) {
    myFinalRunnable = new Runnable() {
      public void run() {
        HintManager.getInstance().hideAllHints();
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          public void run() {
            if (myProject.isDisposed()) return;
            PsiDocumentManager.getInstance(myProject).commitAllDocuments();
            final PsiFile file = PsiUtilBase.getPsiFileInEditor(myEditor, myProject);
            if (file == null) {
              return;
            }

            ShowIntentionActionsHandler.chooseActionAndInvoke(file, myEditor, cachedAction.getAction(), cachedAction.getText());
          }
        });
      }
    };
  }

  IntentionListStep getSubStep(final IntentionActionWithTextCaching action, final String title) {
    ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo();
    for (final IntentionAction optionIntention : action.getOptionIntentions()) {
      intentions.intentionsToShow.add(new HighlightInfo.IntentionActionDescriptor(optionIntention, getIcon(optionIntention)));
    }
    for (final IntentionAction optionFix : action.getOptionErrorFixes()) {
      intentions.errorFixesToShow.add(new HighlightInfo.IntentionActionDescriptor(optionFix, getIcon(optionFix)));
    }
    for (final IntentionAction optionFix : action.getOptionInspectionFixes()) {
      intentions.inspectionFixesToShow.add(new HighlightInfo.IntentionActionDescriptor(optionFix, getIcon(optionFix)));
    }

    return new IntentionListStep(myIntentionHintComponent, intentions,myEditor, myFile, myProject){
      public String getTitle() {
        return title;
      }
    };
  }

  private static Icon getIcon(IntentionAction optionIntention) {
    return optionIntention instanceof Iconable ? ((Iconable)optionIntention).getIcon(0) : null;
  }

  public boolean hasSubstep(final IntentionActionWithTextCaching action) {
    return action.getOptionIntentions().size() + action.getOptionErrorFixes().size() > 0;
  }

  @NotNull
  public List<IntentionActionWithTextCaching> getValues() {
    List<IntentionActionWithTextCaching> result = new ArrayList<IntentionActionWithTextCaching>(myCachedErrorFixes);
    result.addAll(myCachedInspectionFixes);
    result.addAll(myCachedIntentions);
    result.addAll(myCachedGutters);
    Collections.sort(result, new Comparator<IntentionActionWithTextCaching>() {
      public int compare(final IntentionActionWithTextCaching o1, final IntentionActionWithTextCaching o2) {
        int weight1 = getWeight(o1);
        int weight2 = getWeight(o2);
        if (weight1 != weight2) {
          return weight2 - weight1;
        }
        return Comparing.compare(o1.getText(), o2.getText());
      }
    });
    return result;
  }

  private int getWeight(IntentionActionWithTextCaching action) {
    IntentionAction a = action.getAction();
    int group = getGroup(action);
    if (a instanceof IntentionActionWrapper) {
      a = ((IntentionActionWrapper)a).getDelegate();
    }
    if (a instanceof HighPriorityAction) {
      return group + 3;
    }
    else if (a instanceof LowPriorityAction) {
      return group - 3;
    }
    else {
      return group;
    }
  }

  private int getGroup(IntentionActionWithTextCaching action) {
    if (myCachedErrorFixes.contains(action)) {
      return 20;
    }
    else if (myCachedInspectionFixes.contains(action)) {
      return 10;
    }
    else if (action.getAction() instanceof EmptyIntentionAction) {
      return -10;
    }
    else {
      return 0;
    }
  }

  @NotNull
  public String getTextFor(final IntentionActionWithTextCaching action) {
    return action.getAction().getText();
  }

  public Icon getIconFor(final IntentionActionWithTextCaching value) {
    if (value.getIcon() != null) {
      return value.getIcon();
    }

    final IntentionAction action = value.getAction();

    Object iconable = action;
    //custom icon
    if (action instanceof QuickFixWrapper) {
      iconable = ((QuickFixWrapper)action).getFix();
    } else if (action instanceof IntentionActionWrapper) {
      iconable = ((IntentionActionWrapper)action).getDelegate();
    }

    if (iconable instanceof Iconable) {
      final Icon icon = ((Iconable)iconable).getIcon(0);
      if (icon != null) {
        return icon;
      }
    }

    if (mySettings.isShowLightBulb(action)) {
      return myCachedErrorFixes.contains(value) ? IntentionHintComponent.ourQuickFixIcon
             : myCachedInspectionFixes.contains(value) ? IntentionHintComponent.ourBulbIcon :
               IntentionHintComponent.ourIntentionIcon;
    }
    else {
      return myCachedErrorFixes.contains(value) ? IntentionHintComponent.ourQuickFixOffIcon : IntentionHintComponent.ourIntentionOffIcon;
    }
  }

  public void canceled() {
    if (myIntentionHintComponent != null) {
      myIntentionHintComponent.canceled(this);
    }
  }

  public int getDefaultOptionIndex() { return 0; }
  public ListSeparator getSeparatorAbove(final IntentionActionWithTextCaching value) {
    List<IntentionActionWithTextCaching> values = getValues();
    int index = values.indexOf(value);
    if (index <= 0) return null;
    IntentionActionWithTextCaching prev = values.get(index - 1);

    if (getGroup(value) != getGroup(prev)) {
      return new ListSeparator();
    }
    return null;
  }
  public boolean isMnemonicsNavigationEnabled() { return false; }
  public MnemonicNavigationFilter<IntentionActionWithTextCaching> getMnemonicNavigationFilter() { return null; }
  public boolean isSpeedSearchEnabled() { return true; }
  public boolean isAutoSelectionEnabled() { return false; }
  public SpeedSearchFilter<IntentionActionWithTextCaching> getSpeedSearchFilter() { return this; }

  //speed search filter
  public boolean canBeHidden(final IntentionActionWithTextCaching value) { return true;}
  public String getIndexedString(final IntentionActionWithTextCaching value) { return getTextFor(value);}
}


text:
/*global app:false */
'use strict';

app.controller('UserLoginCtrl', ['$rootScope', '$scope', '$routeParams', '$location',
	function($rootScope, $scope, $routeParams, $location) {

}]);

app.controller('UserSignUpCtrl', ['$rootScope', '$scope', '$routeParams', '$location',
	function($rootScope, $scope, $routeParams, $location) {

}]);

app.service('UserService', ['$http', function ($http) {
	return {
		removeAccount: function() {
			$http({ method: 'DELETE', url: '/account' })
				.success(function () {
					window.location = '/';
				}).error(function (data) {
					console.log('Error occured', data);
				});
		}
	};
}]);

app.factory('accRemovalModal', ['vModal', function (vModal) {
  return vModal({
    controller: 'ConfirmAccRemovalCtrl',
    controllerAs: 'ctrl',
    templateUrl: '/views/confirm-acc-removal.html'
  });
}]);

app.controller('ConfirmAccRemovalCtrl', ['accRemovalModal', 'UserService', function (accRemovalModal, UserService) {
  this.close = accRemovalModal.deactivate;

  this.removeAccount = function() {
  	UserService.removeAccount();
  };
}]);

app.controller('UserProfileCtrl', ['$rootScope', '$scope', '$routeParams', 'accRemovalModal',
	function($rootScope, $scope, $routeParams, modal) {
		$scope.pswChange = {};

		$scope.deactivateAccount = function() {
			modal.activate();
		};
}]);

app.controller('UserForgetPswCtrl', ['$rootScope', '$scope', '$routeParams', '$location',
	function($rootScope, $scope, $routeParams, $location) {

}]);

app.controller('UserResetPswCtrl', ['$rootScope', '$scope', '$routeParams', '$location',
	function($rootScope, $scope, $routeParams, $location) {

}]);

redpajama_set_name: RedPajamaGithub


text:
#include "pch.h"
#include "ScriptsLoader.h"
#include "XmlHttpRequest.h"

using namespace HologramJS::API;
using namespace HologramJS::Utilities;
using namespace concurrency;
using namespace std;

bool XmlHttpRequest::UseFileSystem = false;
wstring XmlHttpRequest::BaseUrl = L"";
wstring XmlHttpRequest::BasePath = L"";
JsValueRef XmlHttpRequest::m_createXHRFunction = JS_INVALID_REFERENCE;
JsValueRef XmlHttpRequest::m_getResponseFunction = JS_INVALID_REFERENCE;
JsValueRef XmlHttpRequest::m_getResponseTextFunction = JS_INVALID_REFERENCE;
JsValueRef XmlHttpRequest::m_sendXHRFunction = JS_INVALID_REFERENCE;

XmlHttpRequest::XmlHttpRequest()
{
}

bool
XmlHttpRequest::Initialize()
{
	RETURN_IF_FALSE(ScriptHostUtilities::ProjectFunction(L"create", L"xhr", createXHR, nullptr, &m_createXHRFunction));
	RETURN_IF_FALSE(ScriptHostUtilities::ProjectFunction(L"send", L"xhr", sendXHR, nullptr, &m_sendXHRFunction));
	RETURN_IF_FALSE(ScriptHostUtilities::ProjectFunction(L"getResponse", L"xhr", getResponse, nullptr, &m_getResponseFunction));
	RETURN_IF_FALSE(ScriptHostUtilities::ProjectFunction(L"getResponseText", L"xhr", getResponseText, nullptr, &m_getResponseTextFunction));

	return true;
}

_Use_decl_annotations_
JsValueRef
CHAKRA_CALLBACK
XmlHttpRequest::createXHR(
	JsValueRef callee,
	bool isConstructCall,
	JsValueRef *arguments,
	unsigned short argumentCount,
	PVOID callbackData
)
{
	ExternalObject* externalObject = new ExternalObject();
	RETURN_INVALID_REF_IF_FALSE(externalObject->Initialize(new XmlHttpRequest()));
	return ScriptResourceTracker::ObjectToDirectExternal(externalObject);
}

_Use_decl_annotations_
JsValueRef
CHAKRA_CALLBACK
XmlHttpRequest::sendXHR(
	JsValueRef callee,
	bool isConstructCall,
	JsValueRef *arguments,
	unsigned short argumentCount,
	PVOID callbackData
)
{
	RETURN_INVALID_REF_IF_FALSE(argumentCount == 5);
	auto xhr = ScriptResourceTracker::ExternalToObject<XmlHttpRequest>(arguments[1]);
	RETURN_INVALID_REF_IF_NULL(xhr);

	wstring method;
	RETURN_INVALID_REF_IF_FALSE(ScriptHostUtilities::GetString(arguments[2], method));

	wstring uri;
	RETURN_INVALID_REF_IF_FALSE(ScriptHostUtilities::GetString(arguments[3], uri));

	wstring type;
	RETURN_INVALID_REF_IF_FALSE(ScriptHostUtilities::GetString(arguments[4], type));

	xhr->SendRequest(method, uri, type);

	return JS_INVALID_REFERENCE;
}

_Use_decl_annotations_
JsValueRef
CHAKRA_CALLBACK
XmlHttpRequest::getResponseText(
	JsValueRef callee,
	bool isConstructCall,
	JsValueRef *arguments,
	unsigned short argumentCount,
	PVOID callbackData
)
{
	RETURN_INVALID_REF_IF_FALSE(argumentCount == 2);
	auto xhr = ScriptResourceTracker::ExternalToObject<XmlHttpRequest>(arguments[1]);
	RETURN_INVALID_REF_IF_NULL(xhr);

	RETURN_INVALID_REF_IF_FALSE(xhr->IsTextResponse());

	JsValueRef returnValue;
	RETURN_INVALID_REF_IF_JS_ERROR(JsPointerToString(xhr->m_responseText.c_str(), xhr->m_responseText.length(), &returnValue));

	return returnValue;

	/*

	if (xhr != null)
	{
	if (xhr.responseType == "blob" || xhr.responseType == "arraybuffer")
	{
	return XHRResourceTracker.CreateExternalArray(xhr.response);
	}
	}

	return JavaScriptValue.Invalid;
	*/
	return JS_INVALID_REFERENCE;
}

_Use_decl_annotations_
JsValueRef
CHAKRA_CALLBACK
XmlHttpRequest::getResponse(
	JsValueRef callee,
	bool isConstructCall,
	JsValueRef *arguments,
	unsigned short argumentCount,
	PVOID callbackData
)
{
	RETURN_INVALID_REF_IF_FALSE(argumentCount == 2);
	auto xhr = ScriptResourceTracker::ExternalToObject<XmlHttpRequest>(arguments[1]);
	RETURN_INVALID_REF_IF_NULL(xhr);

	RETURN_INVALID_REF_IF_TRUE(xhr->IsTextResponse());

	Microsoft::WRL::ComPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess;
	RETURN_INVALID_REF_IF_FAILED(reinterpret_cast<IInspectable*>(xhr->m_response)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess)));

	byte* responseNativeBuffer;
	RETURN_INVALID_REF_IF_FAILED(bufferByteAccess->Buffer(&responseNativeBuffer));

	JsValueRef returnArray;
	void* responesExternalBuffer;
	RETURN_INVALID_REF_IF_JS_ERROR(ScriptResourceTracker::CreateAndTrackExternalBuffer(xhr->m_responseLength, &responesExternalBuffer, &returnArray));

	CopyMemory(responesExternalBuffer, responseNativeBuffer, xhr->m_responseLength);

	return returnArray;
}

void
XmlHttpRequest::SendRequest(
	const std::wstring& method,
	const std::wstring& uri,
	const std::wstring type
)
{
	m_method = method;
	m_url = uri;
	m_state = RequestState::OPENED;
	m_responseType = type;

	if (m_url.empty() || (_wcsicmp(m_method.c_str(), L"get") != 0))
	{
		return;
	}

	if ((_wcsnicmp(m_url.c_str(), L"http://", wcslen(L"http://")) == 0)
		|| (_wcsnicmp(m_url.c_str(), L"https://", wcslen(L"https://")) == 0)
		|| !UseFileSystem)
	{
		DownloadAsync();
	}
	else
	{
		ReadFromPackageAsync();
	}
}

task<void>
XmlHttpRequest::ReadFromPackageAsync()
{
	wstring completePath = BasePath + m_url;
	auto mainPathElements = HologramJS::ScriptsLoader::SplitPath(completePath);

	if (mainPathElements.size() == 0)
	{
		return;
	}

	auto fileName = mainPathElements.front();
	mainPathElements.erase(mainPathElements.begin());

	if (IsTextResponse())
	{
		auto responsePlatformString = await HologramJS::ScriptsLoader::ReadTextFromFile(
			Windows::ApplicationModel::Package::Current->InstalledLocation,
			mainPathElements,
			fileName);
		m_responseText = responsePlatformString->Data();
		m_responseType.assign(L"text");
	}
	else // arraybuffer or blob
	{
		m_response = await HologramJS::ScriptsLoader::ReadBinaryFromFile(
			Windows::ApplicationModel::Package::Current->InstalledLocation,
			mainPathElements,
			fileName);

		m_responseLength = m_response->Length;
	}

	m_state = RequestState::DONE;
	m_status = 200;
	m_statusText = L"OK";

	FireStateChanged();
}

task<void>
XmlHttpRequest::DownloadAsync()
{
	Windows::Foundation::Uri^ uri;

	if ((_wcsnicmp(m_url.c_str(), L"http://", wcslen(L"http://")) == 0)
		|| (_wcsnicmp(m_url.c_str(), L"https://", wcslen(L"https://")) == 0))
	{
		uri = ref new Windows::Foundation::Uri(Platform::StringReference(m_url.c_str()));
	}
	else
	{
		wstring completeUrl = BaseUrl + m_url;
		uri = ref new Windows::Foundation::Uri( Platform::StringReference(completeUrl.c_str()));
	}

	Windows::Web::Http::HttpClient^ httpClient = ref new  Windows::Web::Http::HttpClient();

	if (_wcsicmp(m_method.c_str(), L"get") == 0)
	{
		auto responseMessage = await httpClient->GetAsync(uri);
		if (responseMessage->IsSuccessStatusCode)
		{
			if (IsTextResponse())
			{
				auto responseText= await responseMessage->Content->ReadAsStringAsync();
				m_responseText.assign(responseText->Data());
			}
			else
			{
				m_response = await responseMessage->Content->ReadAsBufferAsync();
				m_responseLength = m_response->Length;
			}

			m_status = 200;
			m_statusText = L"OK";
		}
		else
		{
			m_status = static_cast<int>(responseMessage->StatusCode);
			m_statusText.assign(responseMessage->ReasonPhrase->Data());
		}
	}

	m_state = RequestState::DONE;

	FireStateChanged();

	return;
}

void
XmlHttpRequest::FireStateChanged()
{
	if (HasCallback())
	{
		vector<JsValueRef> parameters(5);
		JsValueRef* typeParam = &parameters[0];
		EXIT_IF_JS_ERROR(JsPointerToString(L"change", wcslen(L"change"), typeParam));

		JsValueRef* stateParam = &parameters[1];
		EXIT_IF_JS_ERROR(JsIntToNumber(static_cast<int>(m_state), stateParam));

		JsValueRef* statusParam = &parameters[2];
		EXIT_IF_JS_ERROR(JsIntToNumber(static_cast<int>(m_status), statusParam));

		JsValueRef* statusTextParam = &parameters[3];
		EXIT_IF_JS_ERROR(JsPointerToString(m_statusText.c_str(), m_statusText.length(), statusTextParam));

		JsValueRef* responesTypeParam = &parameters[4];
		EXIT_IF_JS_ERROR(JsPointerToString(m_responseType.c_str(), m_responseType.length(), responesTypeParam));

		(void)InvokeCallback(parameters);
	}
}


text:
from __future__ import unicode_literals

import json
from uuid import uuid4

import pytest
from babeldjango.templatetags.babel import currencyfmt
from django.contrib.auth.models import AnonymousUser
from django.core import signing
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from mock import MagicMock, Mock
from prices import Price
from satchless.item import InsufficientStock

from saleor.cart import CartStatus, forms, utils
from saleor.cart.context_processors import cart_counter
from saleor.cart.models import Cart, ProductGroup
from saleor.cart.views import update
from saleor.discount.models import Sale
from saleor.product.models import Category

@pytest.fixture()
def cart_request_factory(rf, monkeypatch):
    def create_request(user=None, token=None):
        request = rf.get('/')
        if user is None:
            request.user = AnonymousUser()
        else:
            request.user = user
        request.discounts = Sale.objects.all()
        monkeypatch.setattr(request, 'get_signed_cookie',
                            Mock(return_value=token))
        return request
    return create_request

@pytest.fixture()
def opened_anonymous_cart(db):
    return Cart.objects.get_or_create(user=None, status=CartStatus.OPEN)[0]

@pytest.fixture()
def cancelled_anonymous_cart(db):
    return Cart.objects.get_or_create(user=None, status=CartStatus.CANCELED)[0]

@pytest.fixture()
def opened_user_cart(customer_user):
    return Cart.objects.get_or_create(
        user=customer_user, status=CartStatus.OPEN)[0]

@pytest.fixture()
def cancelled_user_cart(customer_user):
    return Cart.objects.get_or_create(
        user=customer_user, status=CartStatus.CANCELED)[0]

@pytest.fixture()
def local_currency(monkeypatch):
    def side_effect(price, currency):
        return price
    monkeypatch.setattr('saleor.cart.views.to_local_currency', side_effect)

def test_get_or_create_anonymous_cart_from_token(
        opened_anonymous_cart, cancelled_anonymous_cart, opened_user_cart,
        cancelled_user_cart):
    queryset = Cart.objects.all()
    carts = list(queryset)
    cart = utils.get_or_create_anonymous_cart_from_token(
        opened_anonymous_cart.token)
    assert Cart.objects.all().count() == 4
    assert cart == opened_anonymous_cart

    # test against getting closed carts
    cart = utils.get_or_create_anonymous_cart_from_token(
        cancelled_anonymous_cart.token)
    assert Cart.objects.all().count() == 5
    assert cart not in carts
    assert cart.user is None
    assert cart.status == CartStatus.OPEN
    cart.delete()

    # test against new token
    cart = utils.get_or_create_anonymous_cart_from_token(uuid4())
    assert Cart.objects.all().count() == 5
    assert cart not in carts
    assert cart.user is None
    assert cart.status == CartStatus.OPEN
    cart.delete()

    # test against getting cart assigned to user
    cart = utils.get_or_create_anonymous_cart_from_token(opened_user_cart.token)
    assert Cart.objects.all().count() == 5
    assert cart not in carts
    assert cart.user is None
    assert cart.status == CartStatus.OPEN
    cart.delete()

def test_get_or_create_user_cart(
        customer_user, opened_anonymous_cart, cancelled_anonymous_cart,
        opened_user_cart, cancelled_user_cart, admin_user):
    cart = utils.get_or_create_user_cart(customer_user)
    assert Cart.objects.all().count() == 4
    assert cart == opened_user_cart

    # test against getting closed carts
    Cart.objects.create(user=admin_user, status=CartStatus.CANCELED)
    queryset = Cart.objects.all()
    carts = list(queryset)
    cart = utils.get_or_create_user_cart(admin_user)
    assert Cart.objects.all().count() == 6
    assert cart not in carts
    assert cart.user is admin_user
    assert cart.status == CartStatus.OPEN
    cart.delete()

def test_get_anonymous_cart_from_token(
        opened_anonymous_cart, cancelled_anonymous_cart, opened_user_cart,
        cancelled_user_cart):
    cart = utils.get_anonymous_cart_from_token(opened_anonymous_cart.token)
    assert Cart.objects.all().count() == 4
    assert cart == opened_anonymous_cart

    # test against getting closed carts
    cart = utils.get_anonymous_cart_from_token(cancelled_anonymous_cart.token)
    assert Cart.objects.all().count() == 4
    assert cart is None

    # test against new token
    cart = utils.get_anonymous_cart_from_token(uuid4())
    assert Cart.objects.all().count() == 4
    assert cart is None

    # test against getting cart assigned to user
    cart = utils.get_anonymous_cart_from_token(opened_user_cart.token)
    assert Cart.objects.all().count() == 4
    assert cart is None

def test_get_user_cart(
        opened_anonymous_cart, cancelled_anonymous_cart, opened_user_cart,
        cancelled_user_cart, admin_user, customer_user):
    cart = utils.get_user_cart(customer_user)
    assert Cart.objects.all().count() == 4
    assert cart == opened_user_cart

    # test against getting closed carts
    Cart.objects.create(user=admin_user, status=CartStatus.CANCELED)
    queryset = Cart.objects.all()
    carts = list(queryset)
    cart = utils.get_user_cart(admin_user)
    assert Cart.objects.all().count() == 5
    assert cart is None

def test_get_or_create_cart_from_request(cart_request_factory, monkeypatch,
                                         customer_user):
    token = uuid4()
    queryset = Cart.objects.all()
    request = cart_request_factory(user=customer_user, token=token)
    user_cart = Cart(user=customer_user)
    anonymous_cart = Cart()
    mock_get_for_user = Mock(return_value=user_cart)
    mock_get_for_anonymous = Mock(return_value=anonymous_cart)
    monkeypatch.setattr('saleor.cart.utils.get_or_create_user_cart',
                        mock_get_for_user)
    monkeypatch.setattr(
        'saleor.cart.utils.get_or_create_anonymous_cart_from_token',
        mock_get_for_anonymous)
    returned_cart = utils.get_or_create_cart_from_request(request, queryset)
    mock_get_for_user.assert_called_once_with(customer_user, queryset)
    assert returned_cart == user_cart

    request = cart_request_factory(user=None, token=token)
    returned_cart = utils.get_or_create_cart_from_request(request, queryset)
    mock_get_for_anonymous.assert_called_once_with(token, queryset)
    assert returned_cart == anonymous_cart

def test_get_cart_from_request(monkeypatch, customer_user,
                               cart_request_factory):
    queryset = Cart.objects.all()
    token = uuid4()
    request = cart_request_factory(user=customer_user, token=token)
    user_cart = Cart(user=customer_user)
    mock_get_for_user = Mock(return_value=user_cart)
    monkeypatch.setattr('saleor.cart.utils.get_user_cart',
                        mock_get_for_user)
    returned_cart = utils.get_cart_from_request(request, queryset)
    mock_get_for_user.assert_called_once_with(customer_user, queryset)
    assert returned_cart == user_cart

    assert list(returned_cart.discounts) == list(request.discounts)

    mock_get_for_user = Mock(return_value=None)
    monkeypatch.setattr('saleor.cart.utils.get_user_cart',
                        mock_get_for_user)
    returned_cart = utils.get_cart_from_request(request, queryset)
    mock_get_for_user.assert_called_once_with(customer_user, queryset)
    assert not Cart.objects.filter(token=returned_cart.token).exists()

    anonymous_cart = Cart()
    mock_get_for_anonymous = Mock(return_value=anonymous_cart)
    monkeypatch.setattr(
        'saleor.cart.utils.get_anonymous_cart_from_token',
        mock_get_for_anonymous)
    request = cart_request_factory(user=None, token=token)
    returned_cart = utils.get_cart_from_request(request, queryset)
    mock_get_for_user.assert_called_once_with(customer_user, queryset)
    assert returned_cart == anonymous_cart

    mock_get_for_anonymous = Mock(return_value=None)
    monkeypatch.setattr(
        'saleor.cart.utils.get_anonymous_cart_from_token',
        mock_get_for_anonymous)
    returned_cart = utils.get_cart_from_request(request, queryset)
    assert not Cart.objects.filter(token=returned_cart.token).exists()

def test_find_and_assign_anonymous_cart(
        opened_anonymous_cart, customer_user, client):
    cart_token = opened_anonymous_cart.token
    # Anonymous user has a cart with token stored in cookie
    value = signing.get_cookie_signer(salt=utils.COOKIE_NAME).sign(cart_token)
    client.cookies[utils.COOKIE_NAME] = value
    # Anonymous logs in
    response = client.post(
        reverse('account_login'),
        {'username': customer_user.email, 'password': 'password'}, follow=True)
    assert response.context['user'] == customer_user
    # User should have only one cart, the same as he had previously in
    # anonymous session
    authenticated_user_carts = customer_user.carts.filter(
        status=CartStatus.OPEN)
    assert authenticated_user_carts.count() == 1
    assert authenticated_user_carts[0].token == cart_token

def test_login_without_a_cart(customer_user, client):
    assert utils.COOKIE_NAME not in client.cookies
    response = client.post(
        reverse('account_login'),
        {'username': customer_user.email, 'password': 'password'}, follow=True)
    assert response.context['user'] == customer_user
    authenticated_user_carts = customer_user.carts.filter(
        status=CartStatus.OPEN)
    assert authenticated_user_carts.count() == 0

def test_login_with_incorrect_cookie_token(customer_user, client):
    value = signing.get_cookie_signer(salt=utils.COOKIE_NAME).sign('incorrect')
    client.cookies[utils.COOKIE_NAME] = value
    response = client.post(
        reverse('account_login'),
        {'username': customer_user.email, 'password': 'password'}, follow=True)
    assert response.context['user'] == customer_user
    authenticated_user_carts = customer_user.carts.filter(
        status=CartStatus.OPEN)
    assert authenticated_user_carts.count() == 0

def test_find_and_assign_anonymous_cart_and_close_opened(
        customer_user, opened_user_cart, opened_anonymous_cart,
        cart_request_factory):
    token = opened_anonymous_cart.token
    token_user = opened_user_cart.token
    request = cart_request_factory(user=customer_user, token=token)
    mock_view = lambda request: Mock(delete_cookie=lambda name: None)
    utils.find_and_assign_anonymous_cart()(mock_view)(request)
    token_cart = Cart.objects.filter(token=token).first()
    user_cart = Cart.objects.filter(token=token_user).first()
    assert token_cart.user.pk == customer_user.pk
    assert token_cart.status == CartStatus.OPEN
    assert user_cart.status == CartStatus.CANCELED

def test_adding_without_checking(cart, product_in_stock):
    variant = product_in_stock.variants.get()
    cart.add(variant, 1000, check_quantity=False)
    assert len(cart) == 1

def test_adding_zero_quantity(cart, product_in_stock):
    variant = product_in_stock.variants.get()
    cart.add(variant, 0)
    assert len(cart) == 0

def test_adding_same_variant(cart, product_in_stock):
    variant = product_in_stock.variants.get()
    cart.add(variant, 1)
    cart.add(variant, 2)
    price_total = 10 * 3
    assert len(cart) == 1
    assert cart.count() == {'total_quantity': 3}
    assert cart.get_total().gross == price_total

def test_replacing_same_variant(cart, product_in_stock):
    variant = product_in_stock.variants.get()
    cart.add(variant, 1, replace=True)
    cart.add(variant, 2, replace=True)
    assert len(cart) == 1
    assert cart.count() == {'total_quantity': 2}

def test_adding_invalid_quantity(cart, product_in_stock):
    variant = product_in_stock.variants.get()
    with pytest.raises(ValueError):
        cart.add(variant, -1)

@pytest.mark.parametrize('create_line_data, get_line_data, lines_equal', [
    (None, None, True),
    ({'gift-wrap': True}, None, False),
    ({'gift-wrap': True}, {'gift-wrap': True}, True)
])
def test_getting_line(create_line_data, get_line_data, lines_equal,
                      cart, product_in_stock):
    variant = product_in_stock.variants.get()
    assert cart.get_line(variant) is None
    line = cart.create_line(variant, 1, create_line_data)
    fetched_line = cart.get_line(variant, data=get_line_data)
    lines_are_equal = fetched_line == line
    assert lines_equal is lines_are_equal

def test_change_status(cart):
    with pytest.raises(ValueError):
        cart.change_status('spanish inquisition')

    cart.change_status(CartStatus.OPEN)
    assert cart.status == CartStatus.OPEN
    cart.change_status(CartStatus.CANCELED)
    assert cart.status == CartStatus.CANCELED

def test_shipping_detection(cart, product_in_stock):
    variant = product_in_stock.variants.get()
    assert not cart.is_shipping_required()
    cart.add(variant, 1, replace=True)
    assert cart.is_shipping_required()

def test_cart_counter(monkeypatch):
    monkeypatch.setattr('saleor.cart.context_processors.get_cart_from_request',
                        Mock(return_value=Mock(quantity=4)))
    ret = cart_counter(Mock())
    assert ret == {'cart_counter': 4}

def test_get_product_variants_and_prices():
    variant = Mock(product_id=1, id=1)
    cart = MagicMock(spec=Cart)
    cart.lines.all.return_value = [
        Mock(quantity=1, variant=variant,
             get_price_per_item=Mock(return_value=10))]
    variants = list(utils.get_product_variants_and_prices(cart, variant))
    assert variants == [(variant, 10)]

def test_contains_unavailable_variants():
    missing_variant = Mock(
        check_quantity=Mock(side_effect=InsufficientStock('')))
    cart = MagicMock()
    cart.lines.all.return_value = [Mock(variant=missing_variant)]
    assert utils.contains_unavailable_variants(cart)

    variant = Mock(check_quantity=Mock())
    cart.lines.all.return_value = [Mock(variant=variant)]
    assert not utils.contains_unavailable_variants(cart)

def test_remove_unavailable_variants(cart, product_in_stock):
    variant = product_in_stock.variants.get()
    cart.add(variant, 1)
    variant.stock.update(quantity=0)
    utils.remove_unavailable_variants(cart)
    assert len(cart) == 0

def test_check_product_availability_and_warn(
        monkeypatch, cart, product_in_stock):
    variant = product_in_stock.variants.get()
    cart.add(variant, 1)
    monkeypatch.setattr('django.contrib.messages.warning',
                        Mock(warning=Mock()))
    monkeypatch.setattr('saleor.cart.utils.contains_unavailable_variants',
                        Mock(return_value=False))

    utils.check_product_availability_and_warn(MagicMock(), cart)
    assert len(cart) == 1

    monkeypatch.setattr('saleor.cart.utils.contains_unavailable_variants',
                        Mock(return_value=True))
    monkeypatch.setattr('saleor.cart.utils.remove_unavailable_variants',
                        lambda c: c.add(variant, 0, replace=True))

    utils.check_product_availability_and_warn(MagicMock(), cart)
    assert len(cart) == 0

def test_add_to_cart_form():
    cart_lines = []
    cart = Mock(add=lambda variant, quantity: cart_lines.append(variant),
                get_line=Mock(return_value=Mock(quantity=1)))
    data = {'quantity': 1}
    form = forms.AddToCartForm(data=data, cart=cart, product=Mock())

    product_variant = Mock(check_quantity=Mock(return_value=None))
    form.get_variant = Mock(return_value=product_variant)

    assert form.is_valid()
    form.save()
    assert cart_lines == [product_variant]

    with pytest.raises(NotImplementedError):
        data = {'quantity': 1}
        form = forms.AddToCartForm(data=data, cart=cart, product=Mock())
        form.is_valid()
    data = {}

    form = forms.AddToCartForm(data=data, cart=cart, product=Mock())
    assert not form.is_valid()

def test_form_when_variant_does_not_exist():
    cart_lines = []
    cart = Mock(add=lambda variant, quantity: cart_lines.append(Mock()),
                get_line=Mock(return_value=Mock(quantity=1)))

    form = forms.AddToCartForm(data={'quantity': 1}, cart=cart, product=Mock())
    form.get_variant = Mock(side_effect=ObjectDoesNotExist)
    assert not form.is_valid()

def test_add_to_cart_form_when_empty_stock():
    cart_lines = []
    cart = Mock(add=lambda variant, quantity: cart_lines.append(Mock()),
                get_line=Mock(return_value=Mock(quantity=1)))

    form = forms.AddToCartForm(data={'quantity': 1}, cart=cart, product=Mock())
    exception_mock = InsufficientStock(
        Mock(get_stock_quantity=Mock(return_value=1)))
    product_variant = Mock(check_quantity=Mock(side_effect=exception_mock))
    form.get_variant = Mock(return_value=product_variant)
    assert not form.is_valid()

def test_add_to_cart_form_when_insufficient_stock():
    cart_lines = []
    cart = Mock(add=lambda variant, quantity: cart_lines.append(variant),
                get_line=Mock(return_value=Mock(quantity=1)))

    form = forms.AddToCartForm(data={'quantity': 1}, cart=cart, product=Mock())
    exception_mock = InsufficientStock(
        Mock(get_stock_quantity=Mock(return_value=4)))
    product_variant = Mock(check_quantity=Mock(side_effect=exception_mock))
    form.get_variant = Mock(return_value=product_variant)
    assert not form.is_valid()

def test_replace_cart_line_form(cart, product_in_stock):
    variant = product_in_stock.variants.get()
    initial_quantity = 1
    replaced_quantity = 4

    cart.add(variant, initial_quantity)
    data = {'quantity': replaced_quantity}
    form = forms.ReplaceCartLineForm(data=data, cart=cart, variant=variant)
    assert form.is_valid()
    form.save()
    assert cart.quantity == replaced_quantity

def test_replace_cartline_form_when_insufficient_stock(
        monkeypatch, cart, product_in_stock):
    variant = product_in_stock.variants.get()
    initial_quantity = 1
    replaced_quantity = 4

    cart.add(variant, initial_quantity)
    exception_mock = InsufficientStock(
        Mock(get_stock_quantity=Mock(return_value=2)))
    monkeypatch.setattr('saleor.product.models.ProductVariant.check_quantity',
                        Mock(side_effect=exception_mock))
    data = {'quantity': replaced_quantity}
    form = forms.ReplaceCartLineForm(data=data, cart=cart, variant=variant)
    assert not form.is_valid()
    with pytest.raises(KeyError):
        form.save()
    assert cart.quantity == initial_quantity

def test_view_empty_cart(client, request_cart):
    response = client.get('/cart/')
    assert response.status_code == 200

def test_view_cart(client, sale, product_in_stock, request_cart):
    variant = product_in_stock.variants.get()
    request_cart.add(variant, 1)
    response = client.get('/cart/')
    response_cart_line = response.context[0]['cart_lines'][0]
    cart_line = request_cart.lines.first()
    assert not response_cart_line['get_total'] == cart_line.get_total()
    assert response.status_code == 200

def test_view_update_cart_quantity(client, local_currency, product_in_stock, request_cart):
    variant = product_in_stock.variants.get()
    request_cart.add(variant, 1)
    response = client.post(
        '/cart/update/%s/' % (variant.pk,),
        {'quantity': 3},
        HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    assert response.status_code == 200
    assert request_cart.quantity == 3

def test_view_invalid_update_cart(client, product_in_stock, request_cart):
    variant = product_in_stock.variants.get()
    request_cart.add(variant, 1)
    response = client.post(
        '/cart/update/%s/' % (variant.pk,),
        {},
        HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    resp_decoded = json.loads(response.content.decode('utf-8'))
    assert response.status_code == 400
    assert 'error' in resp_decoded.keys()
    assert request_cart.quantity == 1

def test_cart_page_without_openexchagerates(
        client, product_in_stock, request_cart, settings):
    settings.OPENEXCHANGERATES_API_KEY = None
    variant = product_in_stock.variants.get()
    request_cart.add(variant, 1)
    response = client.get('/cart/')
    context = response.context
    assert context['local_cart_total'] is None

def test_cart_page_with_openexchagerates(
        client, monkeypatch, product_in_stock, request_cart, settings):
    settings.DEFAULT_COUNTRY = 'PL'
    settings.OPENEXCHANGERATES_API_KEY = 'fake-key'
    variant = product_in_stock.variants.get()
    request_cart.add(variant, 1)
    response = client.get('/cart/')
    context = response.context
    assert context['local_cart_total'] is None
    monkeypatch.setattr(
        'django_prices_openexchangerates.models.get_rates',
        lambda c: {'PLN': Mock(rate=2)})
    response = client.get('/cart/')
    context = response.context
    assert context['local_cart_total'].currency == 'PLN'

def test_cart_summary_page(client, product_in_stock, request_cart):
    variant = product_in_stock.variants.get()
    request_cart.add(variant, 1)
    response = client.get('/cart/summary/')
    assert response.status_code == 200
    content = response.context
    assert content['quantity'] == request_cart.quantity
    cart_total = request_cart.get_total()
    assert content['total'] == currencyfmt(
        cart_total.gross, cart_total.currency)
    assert len(content['lines']) == 1
    cart_line = content['lines'][0]
    assert cart_line['variant'] == variant.name
    assert cart_line['quantity'] == 1

def test_cart_summary_page_empty_cart(client, request_cart):
    response = client.get('/cart/summary/')
    assert response.status_code == 200
    data = response.context
    assert data['quantity'] == 0

def test_total_with_discount(client, sale, request_cart, product_in_stock):
    sales = Sale.objects.all()
    variant = product_in_stock.variants.get()
    request_cart.add(variant, 1)
    line = request_cart.lines.first()
    assert line.get_total(discounts=sales) == Price(currency="USD", net=5)

def test_product_group():
    group = ProductGroup([Mock(is_shipping_required=Mock(return_value=False)),
                          Mock(is_shipping_required=Mock(return_value=False))])
    assert not group.is_shipping_required()
    group = ProductGroup([Mock(is_shipping_required=Mock(return_value=True)),
                          Mock(is_shipping_required=Mock(return_value=False))])
    assert group.is_shipping_required()

def test_cart_queryset(customer_user):
    saved_cart = Cart.objects.create(status=CartStatus.SAVED)
    waiting_cart = Cart.objects.create(status=CartStatus.WAITING_FOR_PAYMENT)
    checkout_cart = Cart.objects.create(status=CartStatus.CHECKOUT)
    canceled_cart = Cart.objects.create(status=CartStatus.CANCELED)

    anonymous_carts = Cart.objects.anonymous()
    assert anonymous_carts.filter(pk=saved_cart.pk).exists()

    saved = Cart.objects.saved()
    assert saved.filter(pk=saved_cart.pk).exists()

    waiting_for_payment = Cart.objects.waiting_for_payment()
    assert waiting_for_payment.filter(pk=waiting_cart.pk).exists()

    checkout = Cart.objects.checkout()
    assert checkout.filter(pk=checkout_cart.pk).exists()

    canceled = Cart.objects.canceled()
    assert canceled.filter(pk=canceled_cart.pk).exists()

def test_get_user_open_cart(customer_user, opened_user_cart):

    assert Cart.get_user_open_cart(customer_user) == opened_user_cart

    cart = Cart.objects.create(user=customer_user)

    assert Cart.get_user_open_cart(customer_user) == cart
    assert Cart.objects.get(pk=opened_user_cart.pk).status == CartStatus.CANCELED

def test_cart_repr():
    cart = Cart()

    assert repr(cart) == 'Cart(quantity=0)'

    cart.quantity = 1

    assert repr(cart) == 'Cart(quantity=1)'

def test_cart_get_total_empty(db):
    cart = Cart.objects.create()

    with pytest.raises(AttributeError):
        cart.get_total()

def test_cart_change_user(customer_user):
    cart1 = Cart.objects.create()

    cart1.change_user(customer_user)
    cart2 = Cart.objects.create()

    cart2.change_user(customer_user)

    old_cart = Cart.objects.get(pk=cart1.pk)

    assert old_cart.user == customer_user
    assert old_cart.status == CartStatus.CANCELED

def test_cart_line_repr(product_in_stock, request_cart_with_item):
    variant = product_in_stock.variants.get()
    line = request_cart_with_item.lines.first()
    assert repr(line) == 'CartLine(variant=%r, quantity=%r, data=%r)' % (
        variant, line.quantity, line.data)

def test_cart_line_state(product_in_stock, request_cart_with_item):
    variant = product_in_stock.variants.get()
    line = request_cart_with_item.lines.first()

    assert line.__getstate__() == (variant, line.quantity, line.data)

    line.__setstate__((variant, 2, line.data))

    assert line.quantity == 2

def test_get_category_variants_and_prices(default_category, product_in_stock,
                                          request_cart_with_item):
    variant = product_in_stock.variants.get()
    top_category = Category.objects.create(name='foo', slug='bar')
    product_in_stock.categories.add(top_category)
    default_category.parent = top_category
    default_category.save()
    result = list(utils.get_category_variants_and_prices(request_cart_with_item,
                                                         top_category))
    assert result[0][0] == variant

def test_update_view_must_be_ajax(customer_user, rf):
    request = rf.post('/')
    request.user = customer_user
    request.discounts = None
    result = update(request, 1)
    assert result.status_code == 302

def test_get_or_create_db_cart(customer_user, db, rf):
    def view(request, cart, *args, **kwargs):
        return HttpResponse()

    decorated_view = utils.get_or_create_db_cart()(view)
    assert Cart.objects.filter(user=customer_user).count() == 0
    request = rf.get('/')
    request.user = customer_user
    decorated_view(request)
    assert Cart.objects.filter(user=customer_user).count() == 1

    request.user = AnonymousUser()
    decorated_view(request)
    assert Cart.objects.filter(user__isnull=True).count() == 1


text:
#include "K2Pch.h"
#include "K2Configs.h"
#include "AssetManager.h"
#include "Command.h"
#include "ConsoleVariable.h"
#include "K2Asset.h"
#include "PathLib.h"
#include "Texture.h"
#include "PathLib.h"
#include "ZipArchive.h"
#include "math/euler.h"
#include "XMLFile.h"
#include "XMLElement.h"

namespace Demi
{
    void DiK2Configs::Init()
    {
#if DEMI_PLATFORM == DEMI_PLATFORM_WIN32
        LoadConfig("ConfigWin32.xml");
#elif DEMI_PLATFORM == DEMI_PLATFORM_OSX
        LoadConfig("ConfigOSX.xml");
#else
        LoadConfig("ConfigiOS.xml");
#endif

        DiString resPath;
        if (DiBase::CommandMgr->GetConsoleVar("k2_resource_path"))
        {
            resPath = DiBase::CommandMgr->GetConsoleVar("k2_resource_path")->GetString();
        }

        DiString texPath;
        if (DiBase::CommandMgr->GetConsoleVar("k2_texture_path"))
        {
            texPath = DiBase::CommandMgr->GetConsoleVar("k2_texture_path")->GetString();
        }

        // if zip
        if (resPath.CheckFileExtension("zip") || resPath.CheckFileExtension("s2z"))
            SetK2ResourcePack(resPath, texPath);

        // register the asset type
        DiAssetManager::GetInstance().RegisterAssetType(DiK2ModelAsset::TYPE, "", [](const DiString& name){
            return make_shared<DiK2ModelAsset>(name);
        });

        // register the manual loader
        DiAssetManager::GetInstance().RegisterManualLoader(DiTexture::TYPE, [&](const DiString& name){
            auto ret = DiK2Configs::GetTexture(name);
            return ret;
        });
    }

    void DiK2Configs::Shutdown()
    {
        DiAssetManager::GetInstance().UnregisterAssetType(DiK2ModelAsset::TYPE);

#ifdef _K2_RECORD_USED_RESOURCE
        DumpUsedRes();
#endif
    }

    DiString DiK2Configs::GetK2MediaPath(const DiString& relativePath, bool texture)
    {
        auto var = DiBase::CommandMgr->GetConsoleVar(texture ? "k2_texture_path" : "k2_resource_path");
        if (!var)
        {
            DI_WARNING("Invalid k2 media path!");
            return DiString::BLANK;
        }

        if (!RESOURCE_PACK)
        {
            DiString baseFolder = var->GetString();

#if DEMI_PLATFORM == DEMI_PLATFORM_IOS
            baseFolder = DiPathLib::GetApplicationPath() + baseFolder;
#endif
            baseFolder += "/";
            baseFolder += relativePath;
            return baseFolder;
        }
        else
        {
            return relativePath;
        }
    }

    DiDataStreamPtr DiK2Configs::GetDataStream(const DiString& relPath, K2ResourceType type)
    {
#ifdef _K2_RECORD_USED_RESOURCE
        sUsedResources.insert(relPath);
#endif

        DiString full = GetK2MediaPath(relPath, type == K2_RES_TEXTURE);

        if (RESOURCE_PACK)
        {
            DiDataStreamPtr data = RESOURCE_PACK->Open(full);
            return data;
        }
        else
        {
            // now we just simply using OS's file system
            FILE* fp = fopen(full.c_str(), type == K2_RES_XML ? "r" : "rb");
            if (!fp)
            {
                DI_WARNING("Cannot open the file: %s", full.c_str());
                return nullptr;
            }
            DiDataStreamPtr data(DI_NEW DiFileHandleDataStream(fp));
            return data;
        }
    }

    DiTexturePtr DiK2Configs::GetSpecialTexture(const DiString& name)
    {
        static DiMap<DiString, DefaultTextureType> sMap;
        if(sMap.empty())
        {
            sMap["$black"] = DEFAULT_BLACK;
            sMap["$white"] = DEFAULT_WHITE;
            sMap["$flat"]  = DEFAULT_FLAT;
        }
        auto i = sMap.find(name);
        if(i != sMap.end())
        {
            return DiTexture::GetDefaultTexture(i->second);
        }
        return DiTexture::GetDefaultTexture();
    }

    DiTexturePtr DiK2Configs::GetTexture(const DiString& relPath)
    {
        DiString baseName = relPath.ExtractFileName();
        if (baseName.empty() || baseName[0] == '$')
            return DiK2Configs::GetSpecialTexture(baseName);

        DiTexturePtr ret = DiAssetManager::GetInstance().FindAsset<DiTexture>(relPath);
        if (ret)
            return ret;

        bool needprefix = !TEXTURE_PACK_PREFIX_FOLDER.empty();
        if(DiString::StartsWith(relPath, TEXTURE_PACK_PREFIX_FOLDER))
        {
            needprefix = false;
        }

        DiString full = GetK2MediaPath(relPath, true);
        if(full.empty())
        {
            DI_WARNING("Empty texture file!, using default texture instead");
            return DiTexture::GetDefaultTexture();
        }

#if 0
        if (TEXTURE_PACK && full[0] != '\\' && full[0] != '/')
        {
            full = "/"+full;
        }
#endif

        DiString tgaExt = ".tga";
#if DEMI_PLATFORM == DEMI_PLATFORM_IOS
        DiString compExt = ".pvr";
#else
        DiString compExt = ".dds";
#endif

        DiString tgaFile = full + tgaExt;
        DiString ddsFile = full + compExt;
        bool useTga = false;

        if (TEXTURE_PACK)
        {
            DiDataStreamPtr data;

            /// TODO read the descriptor file
            if(needprefix)
            {
                tgaFile = DiK2Configs::TEXTURE_PACK_PREFIX_FOLDER + tgaFile;
                ddsFile = DiK2Configs::TEXTURE_PACK_PREFIX_FOLDER + ddsFile;
            }

            if (TEXTURE_PACK->HasFile(ddsFile))
                data = TEXTURE_PACK->Open(ddsFile);
            else
            {
                data = TEXTURE_PACK->Open(tgaFile);
                useTga = true;
            }

            if (!data)
            {
                DI_WARNING("Cannot open the texture file: %s, using default texture", ddsFile.c_str());
                return DiTexture::GetDefaultTexture();
            }

#ifdef _K2_RECORD_USED_RESOURCE
            sUsedResources.insert(relPath + (useTga ? tgaExt : compExt));
#endif
            ret = DiAssetManager::GetInstance().CreateOrReplaceAsset<DiTexture>(relPath);
            ret->Load(data);
            return ret;
        }
        else
        {
            FILE* fp = nullptr;

            // try dds
            fp = fopen(ddsFile.c_str(), "rb");

            // try tga
            if (!fp)
            {
                fp = fopen(tgaFile.c_str(), "rb");
                useTga = true;
            }

            if (!fp)
            {
                DI_WARNING("Cannot open the texture file: %s, using default texture", ddsFile.c_str());
                return DiTexture::GetDefaultTexture();
            }

#ifdef _K2_RECORD_USED_RESOURCE
            sUsedResources.insert(relPath + (useTga ? tgaExt : compExt));
#endif
            DiDataStreamPtr texData(DI_NEW DiFileHandleDataStream(relPath, fp));

            ret = DiAssetManager::GetInstance().CreateOrReplaceAsset<DiTexture>(relPath);
            ret->Load(texData);
            return ret;
        }
    }

    DiQuat DiK2Configs::ConvertAngles(const DiVec3& eulerrot)
    {
        DiQuat q;
        DiVec3 euler(DiDegree(eulerrot.x).valueRadians(),
            DiDegree(eulerrot.y).valueRadians(), DiDegree(eulerrot.z).valueRadians());
        DiEuler::ToQuat(q, euler, DiEuler::YXZ);
        return q;
    }

    bool DiK2Configs::K2ArchiveExists(const DiString& relPath, bool texture)
    {
        if (RESOURCE_PACK)
        {
            if (texture && TEXTURE_PACK)
                return TEXTURE_PACK->HasFile(relPath);
            else
                return RESOURCE_PACK->HasFile(relPath);
        }
        else
        {
            DiString full = GetK2MediaPath(relPath, texture);
            return DiPathLib::FileExisted(full);
        }
    }

    DiString DiK2Configs::GetShader(const DiString& shader)
    {
        static DiStrHash<DiString> table;
        if (table.empty())
        {
            table["mesh_color_cliff"] = CLIFF_SHADER;
            table["meshc_color_water5"] = WATER_SHADER;
        }

        auto i = table.find(shader);
        if (i != table.end())
            return i->second;
        else
            return MESH_SHADER;
    }

    void DiK2Configs::SetK2ResourcePack(const DiString& resPack, const DiString& texturePack)
    {
        DiTimer timer;

        DiK2Configs::RESOURCE_PACK = DI_NEW DiZipArchive(resPack);
        DiK2Configs::TEXTURE_PACK = DI_NEW DiZipArchive(texturePack);

        CommandMgr->RegisterString("k2_resource_path", resPack, 0);
        CommandMgr->RegisterString("k2_texture_path", texturePack, 0);

        DiK2Configs::RESOURCE_PACK->Load();
        DiK2Configs::TEXTURE_PACK->Load();

        DiK2Configs::TEXTURE_PACK_PREFIX_FOLDER = DetectTexturePackDesc();

        double loadingTime = timer.GetElapse();
        DI_LOG("Zip files loading time: %f", loadingTime);
    }

    void DiK2Configs::SetK2ResourcePack(const DiString& resPack)
    {
        DiTimer timer;

        DiK2Configs::RESOURCE_PACK = DI_NEW DiZipArchive(resPack);
        DiK2Configs::TEXTURE_PACK = RESOURCE_PACK;

        CommandMgr->RegisterString("k2_resource_path", resPack, 0);
        CommandMgr->RegisterString("k2_texture_path", resPack, 0);

        DiK2Configs::RESOURCE_PACK->Load();

        double loadingTime = timer.GetElapse();
        DI_LOG("Zip files loading time: %f", loadingTime);
    }

    void DiK2Configs::ReleaseK2Packs()
    {
        SAFE_DELETE(DiK2Configs::RESOURCE_PACK);
        SAFE_DELETE(DiK2Configs::TEXTURE_PACK);
    }

#ifdef _K2_RECORD_USED_RESOURCE
    DiSet<DiString> DiK2Configs::sUsedResources;

    void DiK2Configs::DumpUsedRes()
    {
        DiString path = DiPathLib::GetApplicationPath();
        path += "used_k2_res.txt";

        FILE* fp = fopen(path.c_str(), "w+");
        for (auto i = sUsedResources.begin(); i != sUsedResources.end(); ++i)
        {
            fprintf(fp, "%s\n", i->c_str());
        }
        fclose(fp);
    }
#endif

    void DiK2Configs::LoadConfig(const DiString& config)
    {
        auto file = DiAssetManager::GetInstance().OpenArchive(config, true);
        if (!file)
        {
            DI_WARNING("Failed to load the config: %s", config.c_str());
            return;
        }

        shared_ptr<DiXMLFile> xmlfile(new DiXMLFile());
        xmlfile->Load(file->GetAsString());
        DiXMLElement node = xmlfile->GetRoot();
        DiXMLElement child = node.GetChild();
        while (child)
        {
            DiString name = child.GetName();
            if (name == "Property")
            {
                DiString key = child.GetAttribute("key");
                DiString val = child.GetAttribute("value");
                CommandMgr->RegisterString(key, val, 0);
            }

            child = child.GetNext();
        }
    }

    DiString DiK2Configs::DetectTexturePackDesc()
    {
        DiString ret;
        if (TEXTURE_PACK)
        {
            if (TEXTURE_PACK->HasFile("descriptor"))
            {
                return "00000000/";
            }
        }
        return ret;
    }

    DiString DiK2Configs::TEXTURE_PACK_PREFIX_FOLDER;

    DiZipArchive* DiK2Configs::TEXTURE_PACK  = nullptr;
    DiZipArchive* DiK2Configs::RESOURCE_PACK = nullptr;

    DiString DiK2Configs::MESH_SHADER    = "k2_color";
    DiString DiK2Configs::CLIFF_SHADER   = "k2_cliff";
    DiString DiK2Configs::TERRAIN_SHADER = "k2_terrain";
    DiString DiK2Configs::WATER_SHADER   = "k2_water";
}


text:
"""
Helper methods and support classes for `ARP` implementation.

Revision Info
=============
* $LastChangedBy: mandke $
* $LastChangedDate: 2011-09-27 22:15:57 -0500 (Tue, 27 Sep 2011) $
* $LastChangedRevision: 5167 $

:author: Ketan Mandke <kmandke@mail.utexas.edu>

:copyright:
    Copyright 2009 The University of Texas at Austin

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

:var ARP_VERBOSE:
    Constant enumeration to control verbose thresholds in this file.

    Setting the verbose level of a `ARP` above this threshold will cause the
    corresponding output in this file to be written (or logged).

:var ARP_OPCODE_REQUEST:
    Enumeration for operation code corresponding to ARP request.

:var ARP_OPCODE_REPLY:
    Enumeration for operation code corresponding to ARP reply.
"""
__docformat__ = "restructuredtext en"

from SimPy.Simulation import hold
from wins.protocol.mac import MAC
from wins.packet import Packet, ANNO

from scapy.all import ARP as ARPpacket

ARP_VERBOSE = 45
ARP_OPCODE_REQUEST = 1
ARP_OPCODE_REPLY   = 2

class ARPRequest(ARPpacket):
    name = "ARP Request"
    def __init__(self, *args, **kwargs):
        """Contructor; initialize 'op' parameter to `ARP_OPCODE_REQUEST`."""
        ARPpacket.__init__(self, *args, **kwargs)
        self.op = ARP_OPCODE_REQUEST

class ARPReply(ARPpacket):
    name = "ARP Reply"
    def __init__(self, *args, **kwargs):
        """Contructor; initialize 'op' parameter to `ARP_OPCODE_REPLY`."""
        ARPpacket.__init__(self, *args, **kwargs)
        self.op = ARP_OPCODE_REPLY

def isarprequest(p):
    """Is packet an ARP request?"""
    arp, isreq = None, False
    if isinstance(p, Packet):
        if p.haslayer(ARPpacket): arp = p[ARPpacket]
        elif p.haslayer(ARPRequest): arp = p[ARPRequest]
    if arp:
        isreq = (arp.op == ARP_OPCODE_REQUEST)
    return isreq

def isarpreply(p):
    """Is packet an ARP reply?"""
    arp, isrep = None, False
    if isinstance(p, Packet):
        if p.haslayer(ARPpacket): arp = p[ARPpacket]
        elif p.haslayer(ARPReply): arp = p[ARPReply]
    if arp:
        isrep = (arp.op == ARP_OPCODE_REPLY)
    return isrep

def get_arprequest(p):
    """Extract ARP request from packet `p`.

    :return: ARP Request message or `None` if no matching layer found.
    """
    arp = None
    if isarprequest(p):
        if p.haslayer(ARPpacket): arp = p[ARPpacket]
        elif p.haslayer(ARPRequest): arp = p[ARPRequest]
        else: raise RuntimeError, \
                "[ARP]: get_arprequest() failed to find matching layer!"
    return arp

def get_arpreply(p):
    """Extract ARP reply from packet `p`.

    :return: ARP Reply message or `None` if no matching layer found.
    """
    arp = None
    if isarpreply(p):
        if p.haslayer(ARPpacket): arp = p[ARPpacket]
        elif p.haslayer(ARPReply): arp = p[ARPReply]
        else: raise RuntimeError, \
                "[ARP]: get_arpreply() failed to find matching layer!"
    return arp


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;

namespace Oxide
{
    /// <summary>
    /// Represents a data file than can store and recall plain text
    /// </summary>
    public class Datafile
    {
        private string text;
        private bool changed;
        private string filename;

        public Datafile(string name)
        {
            filename = Main.GetPath("data/" + name + ".txt");
            Reload();
        }

        /// <summary>
        /// Lists all partialname*.txt files in the ./data/ folder
        /// </summary>
        public static string[] List(string partialname)
        {
            // Iterate all physical plugins
            var files1 = Directory.GetFiles(Main.GetPath("data/"), partialname + "*.txt").Select(f => Path.GetFileNameWithoutExtension(f));

            return files1.ToArray();
        }

        /// <summary>
        /// Removes a fullname.txt file from the ./data/ folder
        /// </summary>
        public static bool Remove(string fullname)
        {
            // Iterate all physical plugins
            string fname = Main.GetPath("data/" + fullname + ".txt");
            if (!File.Exists(fname))
                return false;

            try
            {
                File.Delete(fname);
                return true;
            }
            catch (IOException deleteError)
            {
                return false;
            }
        }

        /// <summary>
        /// Reloads this datafile
        /// </summary>
        public void Reload()
        {
            if (File.Exists(filename))
                text = File.ReadAllText(filename);
            else
                text = "";
        }

        /// <summary>
        /// Gets the plaintext stored in this datafile
        /// </summary>
        /// <returns></returns>
        public string GetText()
        {
            return text;
        }

        /// <summary>
        /// Sets the plaintext stored in this datafile
        /// </summary>
        /// <param name="txt"></param>
        public void SetText(string txt)
        {
            text = txt;
            changed = true;
        }

        /// <summary>
        /// Saves this datafile if changes have been made
        /// </summary>
        public void Save()
        {
            if (!changed) return;
            changed = false;
            File.WriteAllText(filename, text);
        }
    }
}


text:
package com.ilivoo.common.socket.serializing.serializers.definition;

import com.ilivoo.common.socket.serializing.SerializerRegistration;
import com.ilivoo.common.socket.serializing.serializers.FieldSerializer;
import com.ilivoo.common.socket.serializing.serializers.FieldSerializer.SavedField;

public class SerializerDefinition {
    private short id;

    private String name;

    private PropertyDefinition[] properties;

    public static SerializerDefinition valueOf(SerializerRegistration registration){
	SerializerDefinition definition = new SerializerDefinition();
	definition.id = registration.getId();
	definition.name = registration.getType().getName();
	PropertyDefinition[] prop = null;
	if(registration.getSerializer() instanceof FieldSerializer){
	    SavedField[] sfs = FieldSerializer.getFieldForType(registration.getType());
	    prop = new PropertyDefinition[sfs.length];
	    for(int i = 0; i < sfs.length; i++){
		prop[i] = PropertyDefinition.valueOf(sfs[i].field);
	    }
	}
	definition.properties = prop;
	return definition;
    }

    public short getId() {
        return id;
    }

    public void setId(short id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public PropertyDefinition[] getProperties() {
        return properties;
    }

    public void setProperties(PropertyDefinition[] properties) {
        this.properties = properties;
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

[name]

			Class for loading [page:AnimationClip AnimationClips] in JSON format.
			This uses the [page:FileLoader] internally for loading files.

Example

		// instantiate a loader
		var loader = new THREE.AnimationLoader();

		// load a resource
		loader.load(
			// resource URL
			'animations/animation.js',

			// onLoad callback
			function ( animations ) {
				// animations is an array of AnimationClips
			},

			// onProgress callback
			function ( xhr ) {
				console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
			},

			// onError callback
			function ( err ) {
				console.log( 'An error happened' );
			}
		);

Constructor

[name]( [param:LoadingManager manager] )

		[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].

		Creates a new [name].

Properties

[property:LoadingManager manager]

			The [page:LoadingManager loadingManager]  the loader is using. Default is [page:DefaultLoadingManager].

Methods

[method:null load]( [param:String url], [param:Function onLoad], [param:Function onProgress], [param:Function onError] )

		[page:String url] — the path or URL to the file. This can also be a
			[link:https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs Data URI].

		[page:Function onLoad] — Will be called when load completes. The argument will be the loaded [page:Animation animation].

		[page:Function onProgress] — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total] and .[page:Integer loaded] bytes.

		[page:Function onError] — Will be called if load errors.

		Begin loading from url and pass the loaded animation to onLoad.

[method:null parse]( [param:JSON json], [param:Function onLoad] )

		[page:JSON json] — required

		[page:Function onLoad] — Will be called when parsing completes.

		Parse the JSON object and pass the result to onLoad. Individual clips in the object will
		be parsed with [page:AnimationClip.parse].

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]


text:
package reactor.core.publisher;

import java.util.Arrays;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Scannable;
import reactor.test.StepVerifier;
import reactor.test.publisher.FluxOperatorTest;
import reactor.test.subscriber.AssertSubscriber;

import static org.assertj.core.api.Assertions.assertThat;

public class FluxMaterializeTest
		extends FluxOperatorTest<String, Signal<String>> {

	@Override
	@SuppressWarnings("unchecked")
	protected List<Scenario<String, Signal<String>>> scenarios_operatorSuccess() {
		return Arrays.asList(
				scenario(Flux::materialize)
						.receive(s -> assertThat(s).isEqualTo(Signal.next(item(0))),
								s -> assertThat(s).isEqualTo(Signal.next(item(1))),
								s -> assertThat(s).isEqualTo(Signal.next(item(2))),
								s -> assertThat(s).isEqualTo(Signal.complete()))
						.verifier(step -> step.expectNext(Signal.next(item(0)))
						                      .expectNext(Signal.next(item(1)))
						                      .consumeSubscriptionWith(s -> {
							                      if(s instanceof FluxMaterialize.MaterializeSubscriber) {
								                      FluxMaterialize.MaterializeSubscriber m =
										                      (FluxMaterialize.MaterializeSubscriber) s;

								                      m.peek();
								                      m.poll();
								                      m.size();
							                      }
						                      })
						                      .expectNext(Signal.next(item(2)))
						                      .thenRequest(1)
						                      .expectNext(Signal.complete())
						                      .consumeSubscriptionWith(s -> {
							                      if(s instanceof FluxMaterialize.MaterializeSubscriber){
								                      FluxMaterialize.MaterializeSubscriber m =
										                      (FluxMaterialize.MaterializeSubscriber)s;

								                      m.peek();
								                      m.poll();
								                      m.size();

								                      try{
									                      m.offer(null);
									                      Assert.fail();
								                      }
								                      catch (UnsupportedOperationException u){
									                      //ignore
								                      }

								                      try{
									                      m.iterator();
									                      Assert.fail();
								                      }
								                      catch (UnsupportedOperationException u){
									                      //ignore
								                      }
							                      }
						                      })
						                      .verifyComplete())
		);
	}

	@Override
	protected List<Scenario<String, Signal<String>>> scenarios_errorFromUpstreamFailure() {
		return Arrays.asList(
				scenario(Flux::materialize)
						.verifier(step -> {
							Hooks.onErrorDropped(c -> assertThat(c).hasMessage("dropped"));
							Hooks.onNextDropped(c -> assertThat(c).isEqualTo("dropped"));
							step.assertNext(s -> assertThat(s
									.getThrowable()).hasMessage("test"))
							    .verifyComplete();
						})
		);
	}

	@Test
	public void completeOnlyBackpressured() {
		AssertSubscriber<Signal<Integer>> ts = AssertSubscriber.create(0L);

		Flux.<Integer>empty().materialize()
		                     .subscribe(ts);

		ts.assertNoValues()
		  .assertNoError()
		  .assertNotComplete();

		ts.request(1);

		ts.assertValues(Signal.complete())
		  .assertNoError()
		  .assertComplete();
	}

	@Test
	public void errorOnlyBackpressured() {
		AssertSubscriber<Signal<Integer>> ts = AssertSubscriber.create(0L);

		RuntimeException ex = new RuntimeException();

		Flux.<Integer>error(ex).materialize()
		                       .subscribe(ts);

		ts.assertNoValues()
		  .assertNoError()
		  .assertNotComplete();

		ts.request(1);

		ts.assertValues(Signal.error(ex))
		  .assertNoError()
		  .assertComplete();
	}

	@Test
	public void materialize() {
		StepVerifier.create(Flux.just("Three", "Two", "One")
		                        .materialize())
		            .expectNextMatches(s -> s.isOnNext() && "Three".equals(s.get()))
		            .expectNextMatches(s -> s.isOnNext() && "Two".equals(s.get()))
		            .expectNextMatches(s -> s.isOnNext() && "One".equals(s.get()))
		            .expectNextMatches(Signal::isOnComplete)
		            .verifyComplete();
	}

	@Test
	public void materialize2() {
		StepVerifier.create(Flux.just("Three", "Two")
		                        .concatWith(Flux.error(new RuntimeException("test")))
		                        .materialize())
		            .expectNextMatches(s -> s.isOnNext() && "Three".equals(s.get()))
		            .expectNextMatches(s -> s.isOnNext() && "Two".equals(s.get()))
		            .expectNextMatches(s -> s.isOnError() && s.getThrowable() != null
				            && "test".equals(s.getThrowable().getMessage()))
		            .verifyComplete();
	}

    @Test
    public void scanSubscriber() {
        CoreSubscriber<Signal<String>> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
        FluxMaterialize.MaterializeSubscriber<String> test = new FluxMaterialize.MaterializeSubscriber<String>(actual);
        Subscription parent = Operators.emptySubscription();
        test.onSubscribe(parent);

        assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
        assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
        test.requested = 35;
        assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(35);
        assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(0); // RS: TODO non-zero size

        assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
        test.terminalSignal = Signal.error(new IllegalStateException("boom"));
        assertThat(test.scan(Scannable.Attr.ERROR)).hasMessage("boom");
        assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();

        assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
        test.cancel();
        assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
    }
}


text:
var TestRunner = require("../../test-runner.js"),
    test = new TestRunner();

describe("regions/width tests", function(){

  before(function(onDone) {
    test.init(onDone);
  });

  after(function() {
    test.shutdown();
  });

  it("correct.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/correct.vtt", "regions/width/correct.json", onDone);
  });

  it("incorrect-delimiter.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/incorrect-delimiter.vtt", "regions/width/bad-width.json", onDone);
  });

  it("letter-in-value.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/letter-in-value.vtt", "regions/width/bad-width.json", onDone);
  });

  it("negative-percent.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/negative-percent.vtt", "regions/width/bad-width.json", onDone);
  });

  it("no-percentage.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/no-percentage.vtt", "regions/width/bad-width.json", onDone);
  });

  it("percent-over.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/percent-over.vtt", "regions/width/bad-width.json", onDone);
  });

  it("percentage-at-front.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/percentage-at-front.vtt", "regions/width/bad-width.json", onDone);
  });

  it("space-after-delimiter.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/space-after-delimiter.vtt", "regions/width/bad-width.json", onDone);
  });

  it("space-before-delimiter.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/space-before-delimiter.vtt", "regions/width/bad-width.json", onDone);
  });

  it("two-periods.vtt", function(onDone){
    test.jsonEqualParsing("regions/width/two-periods.vtt", "regions/width/bad-width.json", onDone);
  });

});


text:
@interface Config : NSObject {
  NSUserDefaults *_defaults;
}

+ (nonnull Config *)sharedInstance;

@property (nonatomic, nullable, strong) NSURL *nightscoutURL;
@property (nonatomic, nullable, strong) NSString *nightscoutAPISecret;
@property (nonatomic, nullable, strong) NSSet *autoConnectIds;
@property (nonatomic, assign) BOOL uploadEnabled;
@property (nonatomic, assign) BOOL fetchCGMEnabled;

@end


text:
package org.opensaml.xml.signature.impl;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.security.Init;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.signature.XMLSignature;
import org.opensaml.xml.Configuration;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.Marshaller;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.security.SecurityHelper;
import org.opensaml.xml.signature.ContentReference;
import org.opensaml.xml.signature.KeyInfo;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.util.XMLHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * A marshaller for {@link org.opensaml.xml.signature.Signature} objects. This marshaller is really a no-op class. All
 * the creation of the signature DOM elements is handled by {@link org.opensaml.xml.signature.Signer} when it signs the
 * object.
 */
public class SignatureMarshaller implements Marshaller {

    /** Class logger. */
    private final Logger log = LoggerFactory.getLogger(SignatureMarshaller.class);

    /** Constructor. */
    public SignatureMarshaller() {
        if (!Init.isInitialized()) {
            log.debug("Initializing XML security library");
            Init.init();
        }
    }

    /** {@inheritDoc} */
    public Element marshall(XMLObject xmlObject) throws MarshallingException {
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            return marshall(xmlObject, document);
        } catch (ParserConfigurationException e) {
            throw new MarshallingException("Unable to create Document to place marshalled elements in", e);
        }
    }

    /** {@inheritDoc} */
    public Element marshall(XMLObject xmlObject, Element parentElement) throws MarshallingException {
        Element signatureElement = createSignatureElement((SignatureImpl) xmlObject, parentElement.getOwnerDocument());
        XMLHelper.appendChildElement(parentElement, signatureElement);
        return signatureElement;
    }

    /** {@inheritDoc} */
    public Element marshall(XMLObject xmlObject, Document document) throws MarshallingException {
        Element signatureElement = createSignatureElement((SignatureImpl) xmlObject, document);

        Element documentRoot = document.getDocumentElement();
        if (documentRoot != null) {
            document.replaceChild(signatureElement, documentRoot);
        } else {
            document.appendChild(signatureElement);
        }

        return signatureElement;
    }

    /**
     * Creates the signature elements but does not compute the signatuer.
     *
     * @param signature the XMLObject to be signed
     * @param document the owning document
     *
     * @return the Signature element
     *
     * @throws MarshallingException thrown if the signature can not be constructed
     */
    private Element createSignatureElement(Signature signature, Document document) throws MarshallingException {
        log.debug("Starting to marshall {}", signature.getElementQName());

        try {
            log.debug("Creating XMLSignature object");
            XMLSignature dsig = null;
            if (signature.getHMACOutputLength() != null && SecurityHelper.isHMAC(signature.getSignatureAlgorithm())) {
                dsig = new XMLSignature(document, "", signature.getSignatureAlgorithm(), signature
                        .getHMACOutputLength(), signature.getCanonicalizationAlgorithm());
            } else {
                dsig = new XMLSignature(document, "", signature.getSignatureAlgorithm(), signature
                        .getCanonicalizationAlgorithm());
            }

            log.debug("Adding content to XMLSignature.");
            for (ContentReference contentReference : signature.getContentReferences()) {
                contentReference.createReference(dsig);
            }

            log.debug("Creating Signature DOM element");
            Element signatureElement = dsig.getElement();

            if (signature.getKeyInfo() != null) {
                Marshaller keyInfoMarshaller = Configuration.getMarshallerFactory().getMarshaller(
                        KeyInfo.DEFAULT_ELEMENT_NAME);
                keyInfoMarshaller.marshall(signature.getKeyInfo(), signatureElement);
            }

            ((SignatureImpl) signature).setXMLSignature(dsig);
            signature.setDOM(signatureElement);
            signature.releaseParentDOM(true);
            return signatureElement;

        } catch (XMLSecurityException e) {
            log.error("Unable to construct signature Element " + signature.getElementQName(), e);
            throw new MarshallingException("Unable to construct signature Element " + signature.getElementQName(), e);
        }
    }

}


text:
package org.osjava.jardiff;
import java.util.HashMap;
import java.util.Map;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * A reusable class which uses the ASM to build up ClassInfo about a
 * java class file.
 *
 * @author Antony Riley
 */
public class ClassInfoVisitor extends ClassVisitor
{
    /**
     * The class file version.
     */
    private int version;

    /**
     * The access flags for the class.
     */

    private int access;

    /**
     * The internal name of the class.
     */
    private String name;

    /**
     * The signature of the class
     */
    private String signature;

    /**
     * The internal name of the superclass.
     */
    private String supername;

    /**
     * An array of internal names of interfaces implemented by this class.
     */
    private String[] interfaces;

    /**
     * A map of method signature to a MethodInfo describing the method.
     */
    private Map<String, MethodInfo> methodMap;

    /**
     * A map of field signature to a FieldInfo describing the field.
     */
    private Map<String, FieldInfo> fieldMap;

    public ClassInfoVisitor() {
        super(Opcodes.ASM5);
    }

    /**
     * Reset this ClassInfoVisitor so that it can be used to visit another
     * class.
     */
    public void reset() {
        methodMap = new HashMap<String, MethodInfo>();
        fieldMap = new HashMap<String, FieldInfo>();
    }

    /**
     * The the classInfo this ClassInfoVisitor has built up about a class
     */
    public ClassInfo getClassInfo() {
        return new ClassInfo(version, access, name, signature, supername,
                             interfaces, methodMap, fieldMap);
    }

    /**
     * Receive notification of information about a class from ASM.
     *
     * @param version the class file version number.
     * @param access the access flags for the class.
     * @param name the internal name of the class.
     * @param signature the signature of the class.
     * @param supername the internal name of the super class.
     * @param interfaces the internal names of interfaces implemented.
     */
    public void visit(int version, int access, String name, String signature,
                      String supername, String[] interfaces) {
        this.version = version;
        this.access = access;
        this.name = name;
        this.signature = signature;
        this.supername = supername;
        this.interfaces = interfaces;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc,
                                     String signature, String[] exceptions) {
        methodMap.put(name + desc, new MethodInfo(access, name, desc,
                                                  signature, exceptions));
        return null;
    }

    @Override
    public FieldVisitor visitField(int access, String name, String desc,
                                   String signature, Object value) {
        fieldMap.put(name,
                     new FieldInfo(access, name, desc, signature, value));
        return null;
    }
}


text:
(function( app, tplPath ) {

	app.directive( 'timetable', [ 'timetableService', '$translate', function( timetableService, $translate ) {

		return {
			restrict: 'A',
			templateUrl: tplPath + 'timetable.tpl.html',
			scope: {},
			link: link
		};

		function link( scope ) {

			scope.days = [];
			scope.isOpen = null;
			var timetable = {};

			timetableService.getTimetable().then(
				function( data ) {
					timetable = data;
					scope.days = timetableService.getDays();
					scope.isOpen = isNowOpen();
				}
			);

			function isNowOpen() {
				var today = new Date(),
				currDayStr = timetableService.getDayString( today.getDay() );
				return timetableService.isCurrTimeInRange( timetable[ currDayStr ] );
			}

			scope.getMorningTime = function( day ) {
				var morning = timetable[ day ].morning || '';
				return morning.from && morning.to ? morning.from + ' - ' + morning.to : '';
			}

			scope.getAfternoonTime = function( day ) {
				var afternoon = timetable[ day ].afternoon || '';
				return afternoon.from && afternoon.to ? afternoon.from + ' - ' + afternoon.to : '';
			}

			scope.isCurrentWeekDay = function( day ) {
				return timetableService.isCurrentWeekDay( day );
			}
		}

	}]);

})( window.adpdl.module,
	window.adpdl.paths.tplPath );