text:
"""python_instance.py: Python Instance for running python functions
"""
import base64
import os
import signal
import time
try:
  import Queue as queue
except:
  import queue
import threading
import sys
import re
import pulsar
import contextimpl
import Function_pb2
import log
import util
import InstanceCommunication_pb2

from functools import partial
from collections import namedtuple
from threading import Timer
from function_stats import Stats

Log = log.Log
# Equivalent of the InstanceConfig in Java
InstanceConfig = namedtuple('InstanceConfig', 'instance_id function_id function_version function_details max_buffered_tuples')
# This is the message that the consumers put on the queue for the function thread to process
InternalMessage = namedtuple('InternalMessage', 'message topic serde consumer')
InternalQuitMessage = namedtuple('InternalQuitMessage', 'quit')
DEFAULT_SERIALIZER = "serde.IdentitySerDe"

PY3 = sys.version_info[0] >= 3

def base64ify(bytes_or_str):
    if PY3 and isinstance(bytes_or_str, str):
        input_bytes = bytes_or_str.encode('utf8')
    else:
        input_bytes = bytes_or_str

    output_bytes = base64.urlsafe_b64encode(input_bytes)
    if PY3:
        return output_bytes.decode('ascii')
    else:
        return output_bytes

class PythonInstance(object):
  def __init__(self, instance_id, function_id, function_version, function_details, max_buffered_tuples,
               expected_healthcheck_interval, user_code, pulsar_client, secrets_provider, cluster_name):
    self.instance_config = InstanceConfig(instance_id, function_id, function_version, function_details, max_buffered_tuples)
    self.user_code = user_code
    self.queue = queue.Queue(max_buffered_tuples)
    self.log_topic_handler = None
    if function_details.logTopic is not None and function_details.logTopic != "":
      self.log_topic_handler = log.LogTopicHandler(str(function_details.logTopic), pulsar_client)
    self.pulsar_client = pulsar_client
    self.input_serdes = {}
    self.consumers = {}
    self.output_serde = None
    self.function_class = None
    self.function_purefunction = None
    self.producer = None
    self.execution_thread = None
    self.atmost_once = self.instance_config.function_details.processingGuarantees == Function_pb2.ProcessingGuarantees.Value('ATMOST_ONCE')
    self.atleast_once = self.instance_config.function_details.processingGuarantees == Function_pb2.ProcessingGuarantees.Value('ATLEAST_ONCE')
    self.auto_ack = self.instance_config.function_details.autoAck
    self.contextimpl = None
    self.last_health_check_ts = time.time()
    self.timeout_ms = function_details.source.timeoutMs if function_details.source.timeoutMs > 0 else None
    self.expected_healthcheck_interval = expected_healthcheck_interval
    self.secrets_provider = secrets_provider
    self.metrics_labels = [function_details.tenant,
                           "%s/%s" % (function_details.tenant, function_details.namespace),
                           "%s/%s/%s" % (function_details.tenant, function_details.namespace, function_details.name),
                           instance_id, cluster_name]
    self.stats = Stats(self.metrics_labels)

  def health_check(self):
    self.last_health_check_ts = time.time()
    health_check_result = InstanceCommunication_pb2.HealthCheckResult()
    health_check_result.success = True
    return health_check_result

  def process_spawner_health_check_timer(self):
    if time.time() - self.last_health_check_ts > self.expected_healthcheck_interval * 3:
      Log.critical("Haven't received health check from spawner in a while. Stopping instance...")
      os.kill(os.getpid(), signal.SIGKILL)
      sys.exit(1)

    Timer(self.expected_healthcheck_interval, self.process_spawner_health_check_timer).start()

  def run(self):
    # Setup consumers and input deserializers
    mode = pulsar._pulsar.ConsumerType.Shared
    if self.instance_config.function_details.source.subscriptionType == Function_pb2.SubscriptionType.Value("FAILOVER"):
      mode = pulsar._pulsar.ConsumerType.Failover

    subscription_name = str(self.instance_config.function_details.tenant) + "/" + \
                        str(self.instance_config.function_details.namespace) + "/" + \
                        str(self.instance_config.function_details.name)
    for topic, serde in self.instance_config.function_details.source.topicsToSerDeClassName.items():
      if not serde:
        serde_kclass = util.import_class(os.path.dirname(self.user_code), DEFAULT_SERIALIZER)
      else:
        serde_kclass = util.import_class(os.path.dirname(self.user_code), serde)
      self.input_serdes[topic] = serde_kclass()
      Log.debug("Setting up consumer for topic %s with subname %s" % (topic, subscription_name))
      self.consumers[topic] = self.pulsar_client.subscribe(
        str(topic), subscription_name,
        consumer_type=mode,
        message_listener=partial(self.message_listener, self.input_serdes[topic]),
        unacked_messages_timeout_ms=int(self.timeout_ms) if self.timeout_ms else None
      )

    for topic, consumer_conf in self.instance_config.function_details.source.inputSpecs.items():
      if not consumer_conf.serdeClassName:
        serde_kclass = util.import_class(os.path.dirname(self.user_code), DEFAULT_SERIALIZER)
      else:
        serde_kclass = util.import_class(os.path.dirname(self.user_code), consumer_conf.serdeClassName)
      self.input_serdes[topic] = serde_kclass()
      Log.debug("Setting up consumer for topic %s with subname %s" % (topic, subscription_name))
      if consumer_conf.isRegexPattern:
        self.consumers[topic] = self.pulsar_client.subscribe(
          re.compile(str(topic)), subscription_name,
          consumer_type=mode,
          message_listener=partial(self.message_listener, self.input_serdes[topic]),
          unacked_messages_timeout_ms=int(self.timeout_ms) if self.timeout_ms else None
        )
      else:
        self.consumers[topic] = self.pulsar_client.subscribe(
          str(topic), subscription_name,
          consumer_type=mode,
          message_listener=partial(self.message_listener, self.input_serdes[topic]),
          unacked_messages_timeout_ms=int(self.timeout_ms) if self.timeout_ms else None
        )

    function_kclass = util.import_class(os.path.dirname(self.user_code), self.instance_config.function_details.className)
    if function_kclass is None:
      Log.critical("Could not import User Function Module %s" % self.instance_config.function_details.className)
      raise NameError("Could not import User Function Module %s" % self.instance_config.function_details.className)
    try:
      self.function_class = function_kclass()
    except:
      self.function_purefunction = function_kclass

    self.contextimpl = contextimpl.ContextImpl(self.instance_config, Log, self.pulsar_client,
                                               self.user_code, self.consumers,
                                               self.secrets_provider, self.metrics_labels)
    # Now launch a thread that does execution
    self.execution_thread = threading.Thread(target=self.actual_execution)
    self.execution_thread.start()

    # start proccess spawner health check timer
    self.last_health_check_ts = time.time()
    if self.expected_healthcheck_interval > 0:
      Timer(self.expected_healthcheck_interval, self.process_spawner_health_check_timer).start()

  def actual_execution(self):
    Log.debug("Started Thread for executing the function")

    while True:
      try:
        msg = self.queue.get(True)
        if isinstance(msg, InternalQuitMessage):
          break
        Log.debug("Got a message from topic %s" % msg.topic)
        # deserialize message
        input_object = msg.serde.deserialize(msg.message.data())
        # set current message in context
        self.contextimpl.set_current_message_context(msg.message.message_id(), msg.topic)
        output_object = None
        self.saved_log_handler = None
        if self.log_topic_handler is not None:
          self.saved_log_handler = log.remove_all_handlers()
          log.add_handler(self.log_topic_handler)
        successfully_executed = False
        try:
          # get user function start time for statistic calculation
          self.stats.set_last_invocation(time.time())

          # start timer for process time
          self.stats.process_time_start()
          if self.function_class is not None:
            output_object = self.function_class.process(input_object, self.contextimpl)
          else:
            output_object = self.function_purefunction.process(input_object)
          successfully_executed = True

          # stop timer for process time
          self.stats.process_time_end()
        except Exception as e:
          Log.exception("Exception while executing user method")
          self.stats.incr_total_user_exceptions()

        if self.log_topic_handler is not None:
          log.remove_all_handlers()
          log.add_handler(self.saved_log_handler)
        if successfully_executed:
          self.process_result(output_object, msg)
          self.stats.incr_total_processed_successfully()

      except Exception as e:
        Log.error("Uncaught exception in Python instance: %s" % e);
        self.stats.incr_total_sys_exceptions()

  def done_producing(self, consumer, orig_message, result, sent_message):
    if result == pulsar.Result.Ok and self.auto_ack and self.atleast_once:
      consumer.acknowledge(orig_message)

  def process_result(self, output, msg):
    if output is not None and self.instance_config.function_details.sink.topic != None and \
            len(self.instance_config.function_details.sink.topic) > 0:
      if self.output_serde is None:
        self.setup_output_serde()
      if self.producer is None:
        self.setup_producer()

      # serialize function output
      output_bytes = self.output_serde.serialize(output)

      if output_bytes is not None:
        props = {"__pfn_input_topic__" : str(msg.topic), "__pfn_input_msg_id__" : base64ify(msg.message.message_id().serialize())}
        self.producer.send_async(output_bytes, partial(self.done_producing, msg.consumer, msg.message), properties=props)
    elif self.auto_ack and self.atleast_once:
      msg.consumer.acknowledge(msg.message)

  def setup_output_serde(self):
    if self.instance_config.function_details.sink.serDeClassName != None and \
            len(self.instance_config.function_details.sink.serDeClassName) > 0:
      serde_kclass = util.import_class(os.path.dirname(self.user_code), self.instance_config.function_details.sink.serDeClassName)
      self.output_serde = serde_kclass()
    else:
      global DEFAULT_SERIALIZER
      serde_kclass = util.import_class(os.path.dirname(self.user_code), DEFAULT_SERIALIZER)
      self.output_serde = serde_kclass()

  def setup_producer(self):
    if self.instance_config.function_details.sink.topic != None and \
            len(self.instance_config.function_details.sink.topic) > 0:
      Log.debug("Setting up producer for topic %s" % self.instance_config.function_details.sink.topic)
      self.producer = self.pulsar_client.create_producer(
        str(self.instance_config.function_details.sink.topic),
        block_if_queue_full=True,
        batching_enabled=True,
        batching_max_publish_delay_ms=1,
        max_pending_messages=100000)

  def message_listener(self, serde, consumer, message):
    # increment number of received records from source
    self.stats.incr_total_received()
    item = InternalMessage(message, consumer.topic(), serde, consumer)
    self.queue.put(item, True)
    if self.atmost_once and self.auto_ack:
      consumer.acknowledge(message)

  def get_and_reset_metrics(self):
    # First get any user metrics
    metrics = self.get_metrics()
    self.reset_metrics()
    return metrics

  def reset_metrics(self):
    self.stats.reset()
    self.contextimpl.reset_metrics()

  def get_metrics(self):

    total_received =  self.stats.get_total_received()
    total_processed_successfully = self.stats.get_total_processed_successfully()
    total_user_exceptions = self.stats.get_total_user_exceptions()
    total_sys_exceptions = self.stats.get_total_sys_exceptions()
    avg_process_latency_ms = self.stats.get_avg_process_latency()
    last_invocation = self.stats.get_last_invocation()

    total_received_1min = self.stats.get_total_received_1min()
    total_processed_successfully_1min = self.stats.get_total_processed_successfully_1min()
    total_user_exceptions_1min = self.stats.get_total_user_exceptions_1min()
    total_sys_exceptions_1min = self.stats.get_total_sys_exceptions_1min()
    avg_process_latency_ms_1min = self.stats.get_avg_process_latency_1min()

    metrics_data = InstanceCommunication_pb2.MetricsData()
    # total metrics
    metrics_data.receivedTotal = int(total_received) if sys.version_info.major >= 3 else long(total_received)
    metrics_data.processedSuccessfullyTotal = int(total_processed_successfully) if sys.version_info.major >= 3 else long(total_processed_successfully)
    metrics_data.systemExceptionsTotal = int(total_sys_exceptions) if sys.version_info.major >= 3 else long(total_sys_exceptions)
    metrics_data.userExceptionsTotal = int(total_user_exceptions) if sys.version_info.major >= 3 else long(total_user_exceptions)
    metrics_data.avgProcessLatency = avg_process_latency_ms
    metrics_data.lastInvocation = int(last_invocation) if sys.version_info.major >= 3 else long(last_invocation)
    # 1min metrics
    metrics_data.receivedTotal_1min = int(total_received_1min) if sys.version_info.major >= 3 else long(total_received_1min)
    metrics_data.processedSuccessfullyTotal_1min = int(
      total_processed_successfully_1min) if sys.version_info.major >= 3 else long(total_processed_successfully_1min)
    metrics_data.systemExceptionsTotal_1min = int(total_sys_exceptions_1min) if sys.version_info.major >= 3 else long(
      total_sys_exceptions_1min)
    metrics_data.userExceptionsTotal_1min = int(total_user_exceptions_1min) if sys.version_info.major >= 3 else long(
      total_user_exceptions_1min)
    metrics_data.avgProcessLatency_1min = avg_process_latency_ms_1min

    # get any user metrics
    user_metrics = self.contextimpl.get_metrics()
    for metric_name, value in user_metrics.items():
      metrics_data.userMetrics[metric_name] = value

    return metrics_data

  def add_system_metrics(self, metric_name, value, metrics):
    metrics.metrics[metric_name].count = value
    metrics.metrics[metric_name].sum = value
    metrics.metrics[metric_name].min = 0
    metrics.metrics[metric_name].max = value

  def get_function_status(self):
    status = InstanceCommunication_pb2.FunctionStatus()
    status.running = True

    total_received = self.stats.get_total_received()
    total_processed_successfully = self.stats.get_total_processed_successfully()
    total_user_exceptions = self.stats.get_total_user_exceptions()
    total_sys_exceptions = self.stats.get_total_sys_exceptions()
    avg_process_latency_ms = self.stats.get_avg_process_latency()
    last_invocation = self.stats.get_last_invocation()

    status.numReceived = int(total_received) if sys.version_info.major >= 3 else long(total_received)
    status.numSuccessfullyProcessed = int(total_processed_successfully) if sys.version_info.major >= 3 else long(total_processed_successfully)
    status.numUserExceptions = int(total_user_exceptions) if sys.version_info.major >= 3 else long(total_user_exceptions)
    status.instanceId = self.instance_config.instance_id
    for ex, tm in self.stats.latest_user_exception:
      to_add = status.latestUserExceptions.add()
      to_add.exceptionString = ex
      to_add.msSinceEpoch = tm
    status.numSystemExceptions = int(total_sys_exceptions) if sys.version_info.major >= 3 else long(total_sys_exceptions)
    for ex, tm in self.stats.latest_sys_exception:
      to_add = status.latestSystemExceptions.add()
      to_add.exceptionString = ex
      to_add.msSinceEpoch = tm
    status.averageLatency = avg_process_latency_ms
    status.lastInvocationTime = int(last_invocation) if sys.version_info.major >= 3 else long(last_invocation)
    return status

  def join(self):
    self.queue.put(InternalQuitMessage(True), True)
    self.execution_thread.join()


text:
/****************************************************************************/
/**
*
* @file xuartlite_intr.c
*
* This file contains interrupt-related functions for the UART Lite component
* (XUartLite).
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver   Who  Date     Changes
* ----- ---- -------- -----------------------------------------------
* 1.00a ecm  08/31/01 First release
* 1.00b jhl  02/21/02 Repartitioned the driver for smaller files
* 1.02a rpm  02/14/07 Added check for outstanding transmission before
*			calling the send callback (avoids extraneous
*			callback invocations)
* 2.00a ktn  10/20/09 Updated to use HAL Processor APIs. The macros have been
*		      renamed to remove _m from the name.
* </pre>
*
*****************************************************************************/

/***************************** Include Files ********************************/

#include "xuartlite.h"
#include "xuartlite_i.h"
#include "xil_io.h"

/************************** Constant Definitions ****************************/

/**************************** Type Definitions ******************************/

/***************** Macros (Inline Functions) Definitions ********************/

/************************** Function Prototypes *****************************/

static void ReceiveDataHandler(XUartLite *InstancePtr);
static void SendDataHandler(XUartLite *InstancePtr);

/************************** Variable Definitions ****************************/

typedef void (*Handler)(XUartLite *InstancePtr);

/****************************************************************************/
/**
*
* This function sets the handler that will be called when an event (interrupt)
* occurs in the driver. The purpose of the handler is to allow application
* specific processing to be performed.
*
* @param	InstancePtr is a pointer to the XUartLite instance.
* @param	FuncPtr is the pointer to the callback function.
* @param	CallBackRef is the upper layer callback reference passed back
*		when the callback function is invoked.
*
* @return	None.
*
* @note		There is no assert on the CallBackRef since the driver doesn't
*		know what it is (nor should it)
*
*****************************************************************************/
void XUartLite_SetRecvHandler(XUartLite *InstancePtr,
				XUartLite_Handler FuncPtr, void *CallBackRef)
{
	/*
	 * Assert validates the input arguments
	 * CallBackRef not checked, no way to know what is valid
	 */
	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(FuncPtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	InstancePtr->RecvHandler = FuncPtr;
	InstancePtr->RecvCallBackRef = CallBackRef;
}

/****************************************************************************/
/**
*
* This function sets the handler that will be called when an event (interrupt)
* occurs in the driver. The purpose of the handler is to allow application
* specific processing to be performed.
*
* @param	InstancePtr is a pointer to the XUartLite instance .
* @param	FuncPtr is the pointer to the callback function.
* @param	CallBackRef is the upper layer callback reference passed back
*		when the callback function is invoked.
*
* @return 	None.
*
* @note		There is no assert on the CallBackRef since the driver doesn't
*		know what it is (nor should it)
*
*****************************************************************************/
void XUartLite_SetSendHandler(XUartLite *InstancePtr,
				XUartLite_Handler FuncPtr, void *CallBackRef)
{
	/*
	 * Assert validates the input arguments
	 * CallBackRef not checked, no way to know what is valid
	 */
	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(FuncPtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	InstancePtr->SendHandler = FuncPtr;
	InstancePtr->SendCallBackRef = CallBackRef;
}

/****************************************************************************/
/**
*
* This function is the interrupt handler for the UART lite driver.
* It must be connected to an interrupt system by the user such that it is
* called when an interrupt for any UART lite occurs. This function
* does not save or restore the processor context such that the user must
* ensure this occurs.
*
* @param	InstancePtr contains a pointer to the instance of the UART that
*		the interrupt is for.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
void XUartLite_InterruptHandler(XUartLite *InstancePtr)
{
	u32 IsrStatus;

	Xil_AssertVoid(InstancePtr != NULL);

	/*
	 * Read the status register to determine which, coulb be both
	 * interrupt is active
	 */
	IsrStatus = XUartLite_ReadReg(InstancePtr->RegBaseAddress,
					XUL_STATUS_REG_OFFSET);

	if ((IsrStatus & (XUL_SR_RX_FIFO_FULL |
		XUL_SR_RX_FIFO_VALID_DATA)) != 0) {
		ReceiveDataHandler(InstancePtr);
	}

	if (((IsrStatus & XUL_SR_TX_FIFO_EMPTY) != 0) &&
		(InstancePtr->SendBuffer.RequestedBytes > 0)) {
		SendDataHandler(InstancePtr);
	}
}

/****************************************************************************/
/**
*
* This function handles the interrupt when data is received, either a single
* byte when FIFOs are not enabled, or multiple bytes with the FIFO.
*
* @param	InstancePtr is a pointer to the XUartLite instance.
*
* @return	None.
*
* @note		None.
*
*****************************************************************************/
static void ReceiveDataHandler(XUartLite *InstancePtr)
{
	/*
	 * If there are bytes still to be received in the specified buffer
	 * go ahead and receive them
	 */
	if (InstancePtr->ReceiveBuffer.RemainingBytes != 0) {
		XUartLite_ReceiveBuffer(InstancePtr);
	}

	/*
	 * If the last byte of a message was received then call the application
	 * handler, this code should not use an else from the previous check of
	 * the number of bytes to receive because the call to receive the buffer
	 * updates the bytes to receive
	 */
	if (InstancePtr->ReceiveBuffer.RemainingBytes == 0) {
		InstancePtr->RecvHandler(InstancePtr->RecvCallBackRef,
		InstancePtr->ReceiveBuffer.RequestedBytes -
		InstancePtr->ReceiveBuffer.RemainingBytes);
	}

	/*
	 * Update the receive stats to reflect the receive interrupt
	 */
	InstancePtr->Stats.ReceiveInterrupts++;
}

/****************************************************************************/
/**
*
* This function handles the interrupt when data has been sent, the transmit
* FIFO is empty (transmitter holding register).
*
* @param	InstancePtr is a pointer to the XUartLite instance .
*
* @return	None.
*
* @note		None.
*
*****************************************************************************/
static void SendDataHandler(XUartLite *InstancePtr)
{
	/*
	 * If there are not bytes to be sent from the specified buffer,
	 * call the callback function
	 */
	if (InstancePtr->SendBuffer.RemainingBytes == 0) {
		int SaveReq;

		/*
		 * Save and zero the requested bytes since transmission
		 * is complete
		 */
		SaveReq = InstancePtr->SendBuffer.RequestedBytes;
		InstancePtr->SendBuffer.RequestedBytes = 0;

		/*
		 * Call the application handler to indicate
		 * the data has been sent
		 */
		InstancePtr->SendHandler(InstancePtr->SendCallBackRef, SaveReq);
	}
	/*
	 * Otherwise there is still more data to send in the specified buffer
	 * so go ahead and send it
	 */
	else {
		XUartLite_SendBuffer(InstancePtr);
	}

	/*
	 * Update the transmit stats to reflect the transmit interrupt
	 */
	InstancePtr->Stats.TransmitInterrupts++;
}

/*****************************************************************************/
/**
*
* This function disables the UART interrupt. After calling this function,
* data may still be received by the UART but no interrupt will be generated
* since the hardware device has no way to disable the receiver.
*
* @param	InstancePtr is a pointer to the XUartLite instance.
*
* @return	None.
*
* @note		None.
*
*****************************************************************************/
void XUartLite_DisableInterrupt(XUartLite *InstancePtr)
{
	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Write to the control register to disable the interrupts, the only
	 * other bits in this register are the FIFO reset bits such that
	 * writing them to zero will not affect them.
	 */
	XUartLite_WriteReg(InstancePtr->RegBaseAddress,
				XUL_CONTROL_REG_OFFSET, 0);
}

/*****************************************************************************/
/**
*
* This function enables the UART interrupt such that an interrupt will occur
* when data is received or data has been transmitted. The device contains
* 16 byte receive and transmit FIFOs such that an interrupt is generated
* anytime there is data in the receive FIFO and when the transmit FIFO
* transitions from not empty to empty.
*
* @param	InstancePtr is a pointer to the XUartLite instance.
*
* @return	None.
*
* @note		None.
*
*****************************************************************************/
void XUartLite_EnableInterrupt(XUartLite *InstancePtr)
{
	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Write to the control register to enable the interrupts, the only
	 * other bits in this register are the FIFO reset bits such that
	 * writing them to zero will not affect them.
	 */
	XUartLite_WriteReg(InstancePtr->RegBaseAddress,
				XUL_CONTROL_REG_OFFSET, XUL_CR_ENABLE_INTR);
}

redpajama_set_name: RedPajamaGithub


text:
from functools import partial
from urlparse import urlparse

from django import http
from django.conf import settings
from django.db import IntegrityError
from django.shortcuts import get_object_or_404, redirect
from django.contrib import auth
from django.template import Context, loader
from django.utils.datastructures import SortedDict
from django.views.decorators.cache import never_cache
from django.utils.decorators import method_decorator
from django.utils.encoding import smart_str
from django.utils.http import base36_to_int
from django.contrib.auth.tokens import default_token_generator

import commonware.log
import jingo
from radagast.wizard import Wizard
from ratelimit.decorators import ratelimit
from tower import ugettext as _, ugettext_lazy as _lazy
from session_csrf import anonymous_csrf, anonymous_csrf_exempt
from mobility.decorators import mobile_template
import waffle

from access.middleware import ACLMiddleware
import amo
from amo import messages
from amo.decorators import (json_view, login_required, permission_required,
                            write, post_required)
from amo.forms import AbuseForm
from amo.urlresolvers import reverse
from amo.utils import send_mail
from abuse.models import send_abuse_report
from addons.models import Addon
from addons.views import BaseFilter
from addons.decorators import addon_view_factory, can_be_purchased
from access import acl
from bandwagon.models import Collection
from stats.models import Contribution
from users.models import UserNotification
import users.notifications as notifications

from .models import UserProfile
from .signals import logged_out
from . import forms
from .utils import EmailResetCode, UnsubscribeCode
import tasks

log = commonware.log.getLogger('z.users')
addon_view = addon_view_factory(qs=Addon.objects.valid)

@login_required(redirect=False)
@json_view
def ajax(request):
    """Query for a user matching a given email."""
    email = request.GET.get('q', '').strip()
    u = get_object_or_404(UserProfile, email=email)
    return dict(id=u.id, name=u.name)

def confirm(request, user_id, token):
    user = get_object_or_404(UserProfile, id=user_id)

    if not user.confirmationcode:
        return http.HttpResponseRedirect(reverse('users.login'))

    if user.confirmationcode != token:
        log.info(u"Account confirmation failed for user (%s)", user)
        messages.error(request, _('Invalid confirmation code!'))
        return http.HttpResponseRedirect(reverse('users.login'))

    user.confirmationcode = ''
    user.save()
    messages.success(request, _('Successfully verified!'))
    log.info(u"Account confirmed for user (%s)", user)
    return http.HttpResponseRedirect(reverse('users.login'))

def confirm_resend(request, user_id):
    user = get_object_or_404(UserProfile, id=user_id)

    if not user.confirmationcode:
        return http.HttpResponseRedirect(reverse('users.login'))

    # Potential for flood here if someone requests a confirmationcode and then
    # re-requests confirmations.  We may need to track requests in the future.
    log.info(u"Account confirm re-requested for user (%s)", user)

    user.email_confirmation_code()

    msg = _(u'An email has been sent to your address {0} to confirm '
             'your account. Before you can log in, you have to activate '
             'your account by clicking on the link provided in this '
             'email.').format(user.email)
    messages.info(request, _('Confirmation Email Sent'), msg)

    return http.HttpResponseRedirect(reverse('users.login'))

@login_required
def delete(request):
    amouser = request.amo_user
    if request.method == 'POST':
        form = forms.UserDeleteForm(request.POST, request=request)
        if form.is_valid():
            messages.success(request, _('Profile Deleted'))
            amouser.anonymize()
            logout(request)
            form = None
            return http.HttpResponseRedirect(reverse('users.login'))
    else:
        form = forms.UserDeleteForm()

    return jingo.render(request, 'users/delete.html',
                        {'form': form, 'amouser': amouser})

@login_required
def delete_photo(request):
    u = request.amo_user

    if request.method == 'POST':
        u.picture_type = ''
        u.save()
        log.debug(u"User (%s) deleted photo" % u)
        tasks.delete_photo.delay(u.picture_path)
        messages.success(request, _('Photo Deleted'))
        return http.HttpResponseRedirect(reverse('users.edit') +
                                         '#user-profile')

    return jingo.render(request, 'users/delete_photo.html', dict(user=u))

@write
@login_required
def edit(request):
    # Don't use request.amo_user since it has too much caching.
    amouser = UserProfile.objects.get(pk=request.user.id)
    if request.method == 'POST':
        # ModelForm alters the instance you pass in.  We need to keep a copy
        # around in case we need to use it below (to email the user)
        original_email = amouser.email
        form = forms.UserEditForm(request.POST, request.FILES, request=request,
                                  instance=amouser)
        if form.is_valid():
            messages.success(request, _('Profile Updated'))
            if amouser.email != original_email:
                l = {'user': amouser,
                     'mail1': original_email,
                     'mail2': amouser.email}
                log.info(u"User (%(user)s) has requested email change from"
                          "(%(mail1)s) to (%(mail2)s)" % l)
                messages.info(request, _('Email Confirmation Sent'),
                    _(u'An email has been sent to {0} to confirm your new '
                       'email address. For the change to take effect, you '
                       'need to click on the link provided in this email. '
                       'Until then, you can keep logging in with your '
                       'current email address.').format(amouser.email))

                domain = settings.DOMAIN
                token, hash = EmailResetCode.create(amouser.id, amouser.email)
                url = "%s%s" % (settings.SITE_URL,
                                reverse('users.emailchange', args=[amouser.id,
                                                                token, hash]))
                t = loader.get_template('users/email/emailchange.ltxt')
                c = {'domain': domain, 'url': url, }
                send_mail(_(("Please confirm your email address "
                             "change at %s") % domain),
                    t.render(Context(c)), None, [amouser.email],
                    use_blacklist=False)

                # Reset the original email back.  We aren't changing their
                # address until they confirm the new one
                amouser.email = original_email
            form.save()
            return http.HttpResponseRedirect(reverse('users.edit'))
        else:

            messages.error(request, _('Errors Found'),
                                    _('There were errors in the changes '
                                      'you made. Please correct them and '
                                      'resubmit.'))
    else:
        form = forms.UserEditForm(instance=amouser)

    return jingo.render(request, 'users/edit.html',
                        {'form': form, 'amouser': amouser})

@write
@login_required
@permission_required('Admin', 'EditAnyUser')
def admin_edit(request, user_id):
    amouser = get_object_or_404(UserProfile, pk=user_id)

    if request.method == 'POST':
        form = forms.AdminUserEditForm(request.POST, request.FILES,
                                       request=request, instance=amouser)
        if form.is_valid():
            form.save()
            messages.success(request, _('Profile Updated'))
            return http.HttpResponseRedirect(reverse('zadmin.index'))
    else:
        form = forms.AdminUserEditForm(instance=amouser)
    return jingo.render(request, 'users/edit.html',
                        {'form': form, 'amouser': amouser})

def emailchange(request, user_id, token, hash):
    user = get_object_or_404(UserProfile, id=user_id)

    try:
        _uid, newemail = EmailResetCode.parse(token, hash)
    except ValueError:
        return http.HttpResponse(status=400)

    if _uid != user.id:
        # I'm calling this a warning because invalid hashes up to this point
        # could be any number of things, but this is a targeted attack from
        # one user account to another
        log.warning((u"[Tampering] Valid email reset code for UID (%s) "
                     "attempted to change email address for user (%s)")
                                                        % (_uid, user))
        return http.HttpResponse(status=400)

    user.email = newemail
    user.save()

    l = {'user': user, 'newemail': newemail}
    log.info(u"User (%(user)s) confirmed new email address (%(newemail)s)" % l)
    messages.success(request, _('Your email address was changed successfully'),
            _(u'From now on, please use {0} to log in.').format(newemail))

    return http.HttpResponseRedirect(reverse('users.edit'))

def _clean_next_url(request):
    gets = request.GET.copy()
    url = gets['to']

    if not url:
        url = settings.LOGIN_REDIRECT_URL

    # We want to not redirect outside of AMO via login/logout (also see
    # "domain" below)
    if '://' in url:
        url = '/'

    # TODO(davedash): This is a remora-ism, let's remove this after remora and
    # since all zamboni 'to' parameters will begin with '/'.
    if url and not url.startswith('/'):
        url = '/' + url

    gets['to'] = url

    domain = gets.get('domain', None)
    if domain in settings.VALID_LOGIN_REDIRECTS.keys():
        gets['to'] = "%s%s" % (settings.VALID_LOGIN_REDIRECTS[domain], url)

    request.GET = gets
    return request

@anonymous_csrf
@post_required
@ratelimit(block=True, rate=settings.LOGIN_RATELIMIT_ALL_USERS)
def browserid_login(request):
    if waffle.switch_is_active('browserid-login'):
        logout(request)
        user = auth.authenticate(assertion=request.POST['assertion'],
                                 host=request.POST['audience'])
        if user is not None:
            profile = UserProfile.objects.get(user=user)
            if profile.needs_tougher_password:
                return http.HttpResponse("", status=400)
            auth.login(request, user)
            return http.HttpResponse(status=200)
    return http.HttpResponse(status=401)

@addon_view
@can_be_purchased
@anonymous_csrf
@ratelimit(block=True, rate=settings.LOGIN_RATELIMIT_ALL_USERS)
def paypal_start(request, addon=None):
    download = urlparse(request.GET.get('realurl', '')).path
    data = {'addon': addon, 'is_ajax': request.is_ajax(), 'download': download}

    if request.user.is_authenticated():
        return jingo.render(request, 'addons/paypal_start.html', data)

    return _login(request, data=data, template='addons/paypal_start.html',
                  dont_redirect=True)

@anonymous_csrf
@mobile_template('users/{mobile/}login_modal.html')
@ratelimit(block=True, rate=settings.LOGIN_RATELIMIT_ALL_USERS)
def login_modal(request, template=None):
    return _login(request, template=template)

@anonymous_csrf
@mobile_template('users/{mobile/}login.html')
@ratelimit(block=True, rate=settings.LOGIN_RATELIMIT_ALL_USERS)
def login(request, template=None):
    return _login(request, template=template)

def _login(request, template=None, data=None, dont_redirect=False):
    data = data or {}
    # In case we need it later.  See below.
    get_copy = request.GET.copy()

    logout(request)

    if 'to' in request.GET:
        request = _clean_next_url(request)

    limited = getattr(request, 'limited', 'recaptcha_shown' in request.POST)
    user = None
    if 'username' in request.POST:
        try:
            # We are doing all this before we try and validate the form.
            user = UserProfile.objects.get(email=request.POST['username'])
            limited = ((user.failed_login_attempts >=
                        settings.LOGIN_RATELIMIT_USER) or limited)
            user.log_login_attempt(request, False)
        except UserProfile.DoesNotExist:
            pass

    partial_form = partial(forms.AuthenticationForm, use_recaptcha=limited)
    r = auth.views.login(request, template_name=template,
                         redirect_field_name='to',
                         authentication_form=partial_form,
                         extra_context=data)

    if isinstance(r, http.HttpResponseRedirect):
        # Django's auth.views.login has security checks to prevent someone from
        # redirecting to another domain.  Since we want to allow this in
        # certain cases, we have to make a new response object here to replace
        # the above.

        if 'domain' in request.GET:
            request.GET = get_copy
            request = _clean_next_url(request)
            r = http.HttpResponseRedirect(request.GET['to'])

        # Succsesful log in according to django.  Now we do our checks.  I do
        # the checks here instead of the form's clean() because I want to use
        # the messages framework and it's not available in the request there.
        user = request.user.get_profile()

        if user.deleted:
            logout(request)
            log.warning(u'Attempt to log in with deleted account (%s)' % user)
            messages.error(request, _('Wrong email address or password!'))
            data.update({'form': partial_form()})
            return jingo.render(request, template, data)

        if user.confirmationcode:
            logout(request)
            log.info(u'Attempt to log in with unconfirmed account (%s)' % user)
            msg1 = _(u'A link to activate your user account was sent by email '
                      'to your address {0}. You have to click it before you '
                      'can log in.').format(user.email)
            url = "%s%s" % (settings.SITE_URL,
                            reverse('users.confirm.resend', args=[user.id]))
            msg2 = _('If you did not receive the confirmation email, make '
                      'sure your email service did not mark it as "junk '
                      'mail" or "spam". If you need to, you can have us '
                      'resend the confirmation message '
                      'to your email address mentioned above.') % url
            messages.error(request, _('Activation Email Sent'),  msg1)
            messages.info(request, _('Having Trouble?'), msg2,
                          title_safe=True)
            data.update({'form': partial_form()})
            return jingo.render(request, template, data)

        rememberme = request.POST.get('rememberme', None)
        if rememberme:
            request.session.set_expiry(settings.SESSION_COOKIE_AGE)
            log.debug((u'User (%s) logged in successfully with '
                                        '"remember me" set') % user)
        else:
            user.log_login_attempt(request, True)

        if dont_redirect:
            # We're recalling the middleware to re-initialize amo_user
            ACLMiddleware().process_request(request)
            r = jingo.render(request, template, data)

    return r

def logout(request):
    # Not using get_profile() becuase user could be anonymous
    user = request.user
    if not user.is_anonymous():
        log.debug(u"User (%s) logged out" % user)

    auth.logout(request)

    if 'to' in request.GET:
        request = _clean_next_url(request)

    next = request.GET.get('to') or settings.LOGOUT_REDIRECT_URL
    response = http.HttpResponseRedirect(next)
    # Fire logged out signal so we can be decoupled from cake.
    logged_out.send(None, request=request, response=response)
    return response

def profile(request, user_id):
    user = get_object_or_404(UserProfile, id=user_id)

    # Get user's own and favorite collections, if they allowed that.
    if user.display_collections:
        own_coll = (Collection.objects.listed().filter(author=user)
                    .order_by('-created'))[:10]
    else:
        own_coll = []
    if user.display_collections_fav:
        fav_coll = (Collection.objects.listed().filter(following__user=user)
                    .order_by('-following__created'))[:10]
    else:
        fav_coll = []

    edit_any_user = acl.action_allowed(request, 'Admin', 'EditAnyUser')
    own_profile = (request.user.is_authenticated() and
                   request.amo_user.id == user.id)

    if user.is_developer:
        addons = amo.utils.paginate(request,
            user.addons_listed.order_by('-weekly_downloads'))
    else:
        addons = []

    def get_addons(reviews):
        if not reviews:
            return
        qs = Addon.objects.filter(id__in=set(r.addon_id for r in reviews))
        addons = dict((addon.id, addon) for addon in qs)
        for review in reviews:
            review.addon = addons.get(review.addon_id)
    reviews = user.reviews.transform(get_addons)

    data = {'profile': user, 'own_coll': own_coll, 'reviews': reviews,
            'fav_coll': fav_coll, 'edit_any_user': edit_any_user,
            'addons': addons, 'own_profile': own_profile}
    if not own_profile:
        data['abuse_form'] = AbuseForm(request=request)

    return jingo.render(request, 'users/profile.html', data)

@anonymous_csrf
def register(request):
    if request.user.is_authenticated():
        messages.info(request, _("You are already logged in to an account."))
        form = None
    elif request.method == 'POST':

        form = forms.UserRegisterForm(request.POST)

        if form.is_valid():
            try:
                u = form.save(commit=False)
                u.set_password(form.cleaned_data['password'])
                u.generate_confirmationcode()
                u.save()
                u.create_django_user()
                log.info(u"Registered new account for user (%s)", u)

                u.email_confirmation_code()

                msg = _('Congratulations! Your user account was successfully '
                        'created.')
                messages.success(request, msg)

                msg = _(u'An email has been sent to your address {0} to '
                         'confirm your account. Before you can log in, you '
                         'have to activate your account by clicking on the '
                         'link provided in this email.').format(u.email)
                messages.info(request, _('Confirmation Email Sent'), msg)
            except IntegrityError, e:
                # I was unable to reproduce this, but I suspect it happens
                # when they POST twice quickly and the slaves don't have the
                # new info yet (total guess).  Anyway, I'm assuming the
                # first one worked properly, so this is still a success
                # case to tne end user so we just log it...
                log.error("Failed to register new user (%s): %s" % (u, e))

            return http.HttpResponseRedirect(reverse('users.login'))

        else:
            messages.error(request, _('There are errors in this form'),
                            _('Please correct them and resubmit.'))
    else:
        form = forms.UserRegisterForm()
    return jingo.render(request, 'users/register.html', {'form': form, })

@anonymous_csrf_exempt
def report_abuse(request, user_id):
    user = get_object_or_404(UserProfile, pk=user_id)
    form = AbuseForm(request.POST or None, request=request)
    if request.method == "POST" and form.is_valid():
        send_abuse_report(request, user, form.cleaned_data['text'])
        messages.success(request, _('User reported.'))
    else:
        return jingo.render(request, 'users/report_abuse_full.html',
                            {'profile': user, 'abuse_form': form, })
    return redirect(reverse('users.profile', args=[user.pk]))

@never_cache
def password_reset_confirm(request, uidb36=None, token=None):
    """
    Pulled from django contrib so that we can add user into the form
    so then we can show relevant messages about the user.
    """
    assert uidb36 is not None and token is not None
    user = None
    try:
        uid_int = base36_to_int(uidb36)
        user = UserProfile.objects.get(id=uid_int)
    except (ValueError, UserProfile.DoesNotExist):
        pass

    if user is not None and default_token_generator.check_token(user, token):
        validlink = True
        if request.method == 'POST':
            form = forms.SetPasswordForm(user, request.POST)
            if form.is_valid():
                form.save()
                return redirect(reverse('django.contrib.auth.'
                                        'views.password_reset_complete'))
        else:
            form = forms.SetPasswordForm(user)
    else:
        validlink = False
        form = None

    return jingo.render(request, 'users/pwreset_confirm.html',
                        {'form': form, 'validlink': validlink})

@never_cache
def unsubscribe(request, hash=None, token=None, perm_setting=None):
    """
    Pulled from django contrib so that we can add user into the form
    so then we can show relevant messages about the user.
    """
    assert hash is not None and token is not None
    user = None

    try:
        email = UnsubscribeCode.parse(token, hash)
        user = UserProfile.objects.get(email=email)
    except (ValueError, UserProfile.DoesNotExist):
        pass

    perm_settings = []
    if user is not None:
        unsubscribed = True
        if not perm_setting:
            # TODO: make this work. nothing currently links to it, though.
            perm_settings = [l for l in notifications.NOTIFICATIONS
                             if not l.mandatory]
        else:
            perm_setting = notifications.NOTIFICATIONS_BY_SHORT[perm_setting]
            UserNotification.update_or_create(update={'enabled': False},
                    user=user, notification_id=perm_setting.id)
            perm_settings = [perm_setting]
    else:
        unsubscribed = False

    return jingo.render(request, 'users/unsubscribe.html',
            {'unsubscribed': unsubscribed, 'perm_settings': perm_settings})

class ContributionsFilter(BaseFilter):
    opts = (('date', _lazy(u'Purchase Date')),
            ('price', _lazy(u'Price')),
            ('name', _lazy(u'Name')))

    def filter(self, field):
        qs = self.base_queryset
        if field == 'date':
            return qs.order_by('-created')
        elif field == 'price':
            return qs.order_by('amount')
        elif field == 'name':
            return qs.order_by('addon__name')

@login_required
def purchases(request, addon_id=None):
    """A list of purchases that a user has made through the marketplace."""
    if not waffle.switch_is_active('marketplace'):
        raise http.Http404

    # TODO(ashort): this is where we'll need to get cunning about refunds.
    cs = Contribution.objects.filter(user=request.amo_user,
                                     type=amo.CONTRIB_PURCHASE)
    if addon_id:
        cs = cs.filter(addon=addon_id)

    filter = ContributionsFilter(request, cs, key='sort', default='date')
    purchases = amo.utils.paginate(request, filter.qs)

    if addon_id and not purchases.object_list:
        # User has requested a receipt for an addon they don't have.
        raise http.Http404
    return jingo.render(request, 'users/purchases.html',
                        {'purchases': purchases, 'filter': filter,
                         'url_base': reverse('users.purchases'),
                         'single': bool(addon_id)})

# Start of the Support wizard all of these are accessed through the
# SupportWizard below.
def plain(request, contribution, wizard):
    # Simple view that just shows a template matching the step.
    tpl = wizard.tpl('%s.html' % wizard.step)
    return wizard.render(request, tpl, {'addon': contribution.addon,
                                        'contribution': contribution})

def support_author(request, contribution, wizard):
    addon = contribution.addon
    form = forms.ContactForm(request.POST)
    if request.method == 'POST':
        if form.is_valid():
            template = jingo.render_to_string(request,
                                wizard.tpl('emails/support-request.txt'),
                                context={'contribution': contribution,
                                         'addon': addon, 'form': form,
                                         'user': request.amo_user})
            log.info('Support request to dev. by user: %s for addon: %s' %
                     (request.amo_user.pk, addon.pk))
            # L10n: %s is the addon name.
            send_mail(_(u'New Support Request for %s' % addon.name),
                      template, request.amo_user.email,
                      [smart_str(addon.support_email)])
            return redirect(reverse('users.support',
                                    args=[contribution.pk, 'author-sent']))

    return wizard.render(request, wizard.tpl('author.html'),
                         {'addon': addon, 'form': form})

def support_mozilla(request, contribution, wizard):
    addon = contribution.addon
    form = forms.ContactForm(request.POST)
    if request.method == 'POST':
        if form.is_valid():
            template = jingo.render_to_string(request,
                                wizard.tpl('emails/support-request.txt'),
                                context={'addon': addon, 'form': form,
                                         'contribution': contribution,
                                         'user': request.amo_user})
            log.info('Support request to mozilla by user: %s for addon: %s' %
                     (request.amo_user.pk, addon.pk))
            # L10n: %s is the addon name.
            send_mail(_(u'New Support Request for %s' % addon.name),
                      template, request.amo_user.email, [settings.FLIGTAR])
            return redirect(reverse('users.support',
                                    args=[contribution.pk, 'mozilla-sent']))

    return wizard.render(request, wizard.tpl('mozilla.html'),
                         {'addon': addon, 'form': form})

def refund_request(request, contribution, wizard):
    addon = contribution.addon
    form = forms.RemoveForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            return redirect(reverse('users.support',
                                    args=[contribution.pk, 'reason']))

    return wizard.render(request, wizard.tpl('request.html'),
                         {'addon': addon, 'form': form,
                          'contribution': contribution})

def refund_reason(request, contribution, wizard):
    addon = contribution.addon
    if not 'request' in wizard.get_progress():
        return redirect(reverse('users.support',
                                args=[contribution.pk, 'request']))

    form = forms.ContactForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            # if under 30 minutes, refund
            # TODO(ashort): add in the logic for under 30 minutes.
            template = jingo.render_to_string(request,
                                wizard.tpl('emails/refund-request.txt'),
                                context={'addon': addon, 'form': form,
                                         'user': request.amo_user,
                                         'contribution': contribution})
            log.info('Refund request sent by user: %s for addon: %s' %
                     (request.amo_user.pk, addon.pk))
            # L10n: %s is the addon name.
            send_mail(_(u'New Refund Request for %s' % addon.name),
                      template, request.amo_user.email,
                      [smart_str(addon.support_email)])
            return redirect(reverse('users.support',
                                    args=[contribution.pk, 'refund-sent']))

    return wizard.render(request, wizard.tpl('refund.html'),
                         {'contribut': addon, 'form': form})

class SupportWizard(Wizard):
    title = _lazy('Support')
    steps = SortedDict((('start', plain),
                ('site', plain),
                ('resources', plain),
                ('mozilla', support_mozilla),
                ('mozilla-sent', plain),
                ('author', support_author),
                ('author-sent', plain),
                ('request', refund_request),
                ('reason', refund_reason),
                ('refund-sent', plain)))

    def tpl(self, x):
        return 'users/support/%s' % x

    @property
    def wrapper(self):
        return self.tpl('wrapper.html')

    @method_decorator(login_required)
    def dispatch(self, request, contribution_id, step='', *args, **kw):
        contribution = get_object_or_404(Contribution, pk=contribution_id)
        if contribution.user.pk != request.amo_user.pk:
            raise http.Http404
        args = [contribution] + list(args)
        return super(SupportWizard, self).dispatch(request, step, *args, **kw)


text:
require 'spec_helper'

RSpec.describe Clarification::SearchResponse do

  it "should initialize with a raw response body from the api and a concept object"

end


text:
from typing import (
    Any,
    List
)

class Error(Exception):
    pass

class EmptyListError(Error):
    def __init__(self, message: str, files: List[Any]) -> None:
        self.message = message
        self.files = files

class CancelledByUserError(Error):
    def __init__(self, message: str) -> None:
        self.message = message


text:
layout: loop
title: Feature availability Loop
description: Feature availability loop lists feature availabilities.
sidebar: loop
lang: en
subnav: loop_feature_availability
uses_global_argument: true
returns_global_outputs: { countable : true, timestampable : true, versionable : false }
type: "feature-availability"
arguments :
    - {name: "id", description: "A single or a list of feature availability ids.", example: "id=\"2\", id=\"1,4,7\""}
    - {name: "feature", description: "A single or a list of feature ids.", example: "id=\"2\", id=\"1,4,7\""}
    - {name: "exclude", description: "A single or a list of feature availability ids to exclude.", example: "exclude=\"456,123\""}
    - {name: "lang", description: "A lang id", example: "lang=\"1\""}
    - {
            name: "order", description: "A list of values", example: "order=\"alpha_reverse\"", default: "manual",
            expected_values: [
                {name: "alpha",             description: "alphabetical order on title"},
                {name: "alpha_reverse",     description: "reverse alphabetical order on title"},
                {name: "manual",            description: ""},
                {name: "manual_reverse",    description: ""}
            ]
          }

outputs :
    - {name: "$ID", description: "the feature availability id"}
    - {name: "$IS_TRANSLATED", description: "check if the feature_availability is translated"}
    - {name: "$FEATURE_ID", description: "The ID ot the related feature"}
    - {name: "$LOCALE", description: "The locale used for this research"}
    - {name: "$TITLE", description: "the feature availability title"}
    - {name: "$CHAPO", description: "the feature availability chapo"}
    - {name: "$DESCRIPTION", description: "the feature availability description"}
    - {name: "$POSTSCRIPTUM", description: "the feature availability postscriptum"}
    - {name: "$POSITION", description: "the feature availability position"}
---


text:
import url from 'url';
import fs from 'fs';

import parser from 'swagger-parser';

import ConfigureRouter from './ConfigureRouter';
import PrunePaths from './PrunePaths';

export default function(config) {
  if (!config.swaggerFile) {
    throw new Error('Config is missing `swaggerFile` parameter');
  }

  if (config.ignorePaths && config.mockRoutes) {
    throw new Error('Cannot specify both ignorePaths and mockPaths in config');
  }

  let basePath;
  let router;

  let parserPromise = new Promise((resolve) => {
    parser.dereference(config.swaggerFile, function(err, api) {
      if (err) throw err;

      init(api);
      resolve();
    });
  });

  if (config.watch) {
    fs.watchFile(config.swaggerFile, function() {
      parser.dereference(config.swaggerFile, function(err, api) {
        if (err) throw err;

        init(api);
      });
    });
  }

  function init(api) {
    if (config.ignorePaths) {
      api.paths = PrunePaths(api.paths, config.ignorePaths);
    } else if (config.mockPaths) {
      api.paths = PrunePaths(api.paths, config.mockPaths, true);
    }

    basePath = api.basePath || '';
    router = ConfigureRouter(api.paths);
  }

  return function(req, res, next) {
    parserPromise.then(() => {
      const method = req.method.toLowerCase();

      let path = url.parse(req.url).pathname;
      path = path.replace(basePath + '/', '');
      if (path.charAt(0) !== '/') {
        path = '/' + path;
      }

      const matchingRoute = router.match('/' + method + path);

      if (!matchingRoute) return next();

      if (process.env.debug) {
        console.log('Request: %s %s', req.method, path);
      }

      try {
        const response = matchingRoute.fn();
        res.setHeader('Content-Type', 'application/json');
        res.write(response !== null ? JSON.stringify(response) : '');
      } catch(e) {
        res.statusCode = 500;
        res.write(JSON.stringify({message: e.message}, null, 4));
      }

      res.end();
    });
  };
};


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:divider="@drawable/divider"
              android:dividerPadding="8dp"
              android:orientation="horizontal"
              android:showDividers="middle">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:maxLines="2"
        android:text="Posts\n66"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:maxLines="2"
        android:text="Views\n12K"/>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:maxLines="2"
        android:text="Links\n12K"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:maxLines="2"
        android:text="Participants\n12K"/>

</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>tableiw</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
    <link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
    <link rel="prev" href="tableimix.html" title="tableimix" />
    <link rel="next" href="tablekt.html" title="tablekt" />

          tableiw

          Prev
          Orchestra Opcodes and Operators
           Next

          tableiw

tableiw —
      Change the contents of existing function tables.

Description

      This opcode operates on existing function tables, changing their contents. tableiw is used when all inputs are init time variables or constants and you only want to run it at the initialization of the instrument. The valid combinations of variable types are shown by the first letter of the variable names.

Syntax

tableiw isig, indx, ifn [, ixmode] [, ixoff] [, iwgmode]

Initialization

      isig -- Input value to write to the table.

      indx -- Index into table, either a positive number range matching the table length (ixmode = 0) or a 0 to 1 range (ixmode not equal to 0)

      ifn -- Table number. Must be >= 1. Floats are rounded down to an integer. If a table number does not point to a valid table, or the table has not yet been loaded (GEN01) then an error will result and the instrument will be de-activated.

      ixmode (optional, default=0) -- index mode.

            0 = indx and ixoff ranges match the length of the table.

            not equal to 0 = indx and ixoff have a 0 to 1 range.

      ixoff (optional, default=0) -- index offset.

             0 = Total index is controlled directly by indx, i.e. the indexing starts from the start of the table.

             Not equal to 0 = Start indexing from somewhere else in the table. Value must be positive and less than the table length (ixmode = 0) or less than 1 (ixmode not equal to  0).

      iwgmode (optional, default=0) -- Wrap and guard point mode.

             0 = Limit mode.

             1 = Wrap mode.

             2 = Guardpoint mode.

Performance

Limit mode (0)

        Limit the total index (indx + ixoff) to between 0 and the guard point. For a table of length 5, this means that locations 0 to 3 and location 4 (the guard point) can be written. A negative total index writes to location 0.

Wrap mode (1)

        Wrap total index value into locations 0 to E, where E is either one less than the table length or the factor of 2 number which is one less than the table length. For example, wrap into a 0 to 3 range - so that total index 6 writes to location 2.

Guardpoint mode (2)

        The guardpoint is written at the same time as location 0 is written - with the same value.

        This facilitates writing to tables which are intended to be read with interpolation for producing smooth cyclic waveforms. In addition, before it is used, the total index is incremented by half the range between one location and the next, before being rounded down to the integer address of a table location.

        Normally (iwgmode = 0 or 1) for a table of length 5 - which has locations 0 to 3 as the main table and location 4 as the guard point, a total index in the range of 0 to 0.999 will write to location 0. ("0.999" means just less than 1.0.) 1.0 to 1.999 will write to location 1 etc. A similar pattern holds for all total indexes 0 to 4.999 (igwmode = 0) or to 3.999 (igwmode = 1). igwmode = 0 enables locations 0 to 4 to be written - with the guardpoint (4) being written with a potentially different value from location 0.

        With a table of length 5 and the iwgmode = 2, then when the total index is in the range 0 to 0.499, it will write to locations 0 and 4. Range 0.5 to 1.499 will write to location 1 etc. 3.5 to 4.0 will also write to locations 0 and 4.

        This way, the writing operation most closely approximates the results of interpolated reading. Guard point mode should only be used with tables that have a guardpoint.

        Guardpoint mode is accomplished by adding 0.5 to the total index, rounding to the next lowest integer, wrapping it modulo the factor of two which is one less than the table length, writing the table (locations 0 to 3 in our example) and then writing to the guard point if index = 0.

Examples

      Here is an example of the tableiw opcode. It uses the file tableiw.csd.

            Example 935. Example of the tableiw opcode.

See the sections Real-time Audio and Command Line Flags for more information on using command line flags.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-odac     ;;;realtime audio out
;-iadc    ;;;uncomment -iadc if realtime audio input is needed too
; For Non-realtime ouput leave only the line below:
; -o tableiw.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

seed 0	;generate new values every time the instr is played

instr 1

ifn = p4
isize = p5
ithresh = 0.5

itemp ftgen ifn, 0, isize, 21, 2

iwrite_value = 0
i_index = 0

loop_start:
    iread_value tablei i_index, ifn

    if iread_value > ithresh then
         iwrite_value = 1
    else
         iwrite_value = -1
    endif
tableiw iwrite_value, i_index, ifn
loop_lt i_index, 1, isize, loop_start
    turnoff

endin

instr 2

ifn = p4
isize = ftlen(ifn)
prints "Index\tValue\n"

i_index = 0
loop_start:
    ivalue tablei i_index, ifn
    prints "%d:\t%f\n", i_index, ivalue

  loop_lt i_index, 1, isize, loop_start		;read table 1 with our index

aout oscili .5, 100, ifn			;use table to play the polypulse
     outs   aout, aout

endin
</CsInstruments>
<CsScore>
i 1 0 1 100 16
i 2 0 2 100
e
</CsScore>
</CsoundSynthesizer>

See Also

      tablew,
      tablewkt

 More information on this opcode: http://www.csoundjournal.com/issue12/genInstruments.html  , written by Jacob Joaquin

Credits

            Author: Robin Whittle

            Australia

            May 1997

New in version 3.47

Updated August 2002, thanks go to Abram Hindle for pointing out the correct syntax.

          Prev

            Up

           Next

          tableimix

            Home

           tablekt


text:
@implementation NSImage (KBImage)

- (NSImage *)kb_imageTintedWithColor:(NSColor *)tint {
  if (!tint) return [self copy];

  CIFilter *colorGenerator = [CIFilter filterWithName:@"CIConstantColorGenerator"];
  CIColor *color = [[CIColor alloc] initWithColor:tint];

  [colorGenerator setValue:color forKey:kCIInputColorKey];

  CIFilter *colorFilter = [CIFilter filterWithName:@"CIColorControls"];

  [colorFilter setValue:[colorGenerator valueForKey:kCIOutputImageKey] forKey:kCIInputImageKey];
  [colorFilter setValue:[NSNumber numberWithFloat:3.0] forKey:kCIInputSaturationKey];
  [colorFilter setValue:[NSNumber numberWithFloat:0.35] forKey:kCIInputBrightnessKey];
  [colorFilter setValue:[NSNumber numberWithFloat:1.0] forKey:kCIInputContrastKey];

  CIFilter *monochromeFilter = [CIFilter filterWithName:@"CIColorMonochrome"];
  CIImage *baseImage = [CIImage imageWithData:[self TIFFRepresentation]];

  [monochromeFilter setValue:baseImage forKey:kCIInputImageKey];
  [monochromeFilter setValue:[CIColor colorWithRed:0.75 green:0.75 blue:0.75] forKey:kCIInputColorKey];
  [monochromeFilter setValue:[NSNumber numberWithFloat:1.0] forKey:kCIInputIntensityKey];

  CIFilter *compositingFilter = [CIFilter filterWithName:@"CIMultiplyCompositing"];

  [compositingFilter setValue:[colorFilter valueForKey:kCIOutputImageKey] forKey:kCIInputImageKey];
  [compositingFilter setValue:[monochromeFilter valueForKey:kCIOutputImageKey] forKey:kCIInputBackgroundImageKey];

  CIImage *outputImage = [compositingFilter valueForKey:kCIOutputImageKey];

  CGRect extend = [outputImage extent];
  CGSize size = self.size;
  NSImage *tintedImage = [[NSImage alloc] initWithSize: size];

  [tintedImage lockFocus];
  {
    CGContextRef contextRef = [[NSGraphicsContext currentContext] graphicsPort];
    CIContext *ciContext = [CIContext contextWithCGContext:contextRef options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:kCIContextUseSoftwareRenderer]];
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    [ciContext drawImage:outputImage inRect:rect fromRect:extend];
  }
  [tintedImage unlockFocus];

  return tintedImage;
}

@end


text:
class AddIdPrincipalToProduct < ActiveRecord::Migration[5.1]
  def change
    add_column :products, :idprincipal, :boolean, default:false
  end
end


text:
package org.apache.geode.internal.cache.wan;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.geode.cache.Cache;
import org.apache.geode.distributed.Locator;
import org.apache.geode.distributed.internal.InternalLocator;
import org.apache.geode.internal.admin.remote.DistributionLocatorId;

public class MyDistributedSystemListener implements DistributedSystemListener {

  public int addCount;
  public int removeCount;
  Cache cache;

  public MyDistributedSystemListener() {}

  /**
   * Please note that dynamic addition of the sender id to region is not yet available.
   */
  public void addedDistributedSystem(int remoteDsId) {
    addCount++;
    List<Locator> locatorsConfigured = Locator.getLocators();
    Locator locator = locatorsConfigured.get(0);
    Map<Integer, Set<DistributionLocatorId>> allSiteMetaData =
        ((InternalLocator) locator).getlocatorMembershipListener().getAllLocatorsInfo();
    System.out.println("Added : allSiteMetaData : " + allSiteMetaData);
  }

  public void removedDistributedSystem(int remoteDsId) {
    removeCount++;
    List<Locator> locatorsConfigured = Locator.getLocators();
    Locator locator = locatorsConfigured.get(0);
    Map<Integer, Set<DistributionLocatorId>> allSiteMetaData =
        ((InternalLocator) locator).getlocatorMembershipListener().getAllLocatorsInfo();
    System.out.println("Removed : allSiteMetaData : " + allSiteMetaData);
  }

  public int getAddCount() {
    return addCount;
  }

  public int getRemoveCount() {
    return removeCount;
  }

}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOrdersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');//姓名
            $table->string('stu_num');//学号
            $table->string('phone_num');//手机号
            $table->string('location');//外勤地址
            $table->boolean('if_errands');//是否外勤
            $table->string('description');//问题描述
            $table->boolean('if_completed');//是否完成
            $table->boolean('if_allocated');//是否已经指派
            $table->date('appointment_date');//预约日期
            $table->time('start_time');//预约时间段起点
            $table->time('end_time');//预约时间段终点
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('orders');
    }
}


text:
export { default as after } from './after.js';
export { default as ary } from './ary.js';
export { default as before } from './before.js';
export { default as bind } from './bind.js';
export { default as bindKey } from './bindKey.js';
export { default as curry } from './curry.js';
export { default as curryRight } from './curryRight.js';
export { default as debounce } from './debounce.js';
export { default as defer } from './defer.js';
export { default as delay } from './delay.js';
export { default as flip } from './flip.js';
export { default as memoize } from './memoize.js';
export { default as negate } from './negate.js';
export { default as once } from './once.js';
export { default as overArgs } from './overArgs.js';
export { default as partial } from './partial.js';
export { default as partialRight } from './partialRight.js';
export { default as rearg } from './rearg.js';
export { default as rest } from './rest.js';
export { default as spread } from './spread.js';
export { default as throttle } from './throttle.js';
export { default as unary } from './unary.js';
export { default as wrap } from './wrap.js';
export { default as default } from './function.default';


text:
{-# LANGUAGE OverloadedStrings #-}

module Cric.PackagesSpec (
  test
  ) where

import Test.Hspec
import SpecHelpers

import Cric
import Cric.Packages

test :: Spec
test = do
  describe "getPackageManager" $ do
    it "detects RPM" $ do
      let sshMock = mockCommand "which rpm" (0, "/bin/rpm") defaultSshMock
      result <- testCricWith sshMock getPackageManager
      result `shouldBe` RPM

    it "detects Yum" $ do
      let sshMock = mockCommand "which yum" (0, "/bin/yum") defaultSshMock
      result <- testCricWith sshMock getPackageManager
      result `shouldBe` Yum

    it "detects APT" $ do
      let sshMock = mockCommand "which apt-get" (0, "/bin/apt-get") defaultSshMock
      result <- testCricWith sshMock getPackageManager
      result `shouldBe` APT

    it "returns UnknownPackageManager if it can't find anything" $ do
      result <- testCric getPackageManager
      result `shouldBe` UnknownPackageManager

  describe "installPackage" $ do
    it "uses the package manager found" $ do
      let mock = mockCommand "which apt-get"   (0, "/bin/apt-get")
               . mockCommand "apt-get install" (0, "apt-get called")
               $ defaultSshMock
      result <- testCricWith mock $ installPackage ("haskell-platform" :: String)
      result `shouldBe` Right "apt-get called"

    context "when it can't find a package manager" $ do
      it "returns a NoPackageManagerFound error" $ do
        result <- testCric $ installPackage ("haskell-platform" :: String)
        result `shouldBe` Left NoPackageManagerFound

    context "when the installation fails" $ do
      it "returns an error" $ do
        let mock = mockCommand "which rpm" (0, "/bin/rpm")
                 . mockCommand "rpm -i"    (1, "installation failed")
                 $ defaultSshMock

        result <- testCricWith mock $ installPackage ("haskell-platform" :: String)
        result `shouldBe`
          Left (UnknownPkgManagerError $ Failure 1 "installation failed" "")

  describe "removePackage" $ do
    it "uses the package manager found" $ do
      let mock = mockCommand "which apt-get"  (0, "/bin/apt-get")
               . mockCommand "apt-get remove" (0, "apt-get called")
               $ defaultSshMock
      result <- testCricWith mock $ removePackage ("haskell-platform" :: String)
      result `shouldBe` Right "apt-get called"

    context "when it can't find a package manager" $ do
      it "returns a NoPackageManagerFound error" $ do
        result <- testCric $ removePackage ("haskell-platform" :: String)
        result `shouldBe` Left NoPackageManagerFound

    context "when the removal fails" $ do
      it "returns an error" $ do
        let mock = mockCommand "which rpm" (0, "/bin/rpm")
                 . mockCommand "rpm -e"    (1, "removal failed")
                 $ defaultSshMock

        result <- testCricWith mock $ removePackage ("haskell-platform" :: String)
        result `shouldBe`
          Left (UnknownPkgManagerError $ Failure 1 "removal failed" "")


text:
.class Lo/Kg$iF;
.super Lo/Kg$ˋ;
.source ""

# interfaces
.implements Ljava/util/SortedSet;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lo/Kg;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "iF"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<E:Ljava/lang/Object;>Lo/Kg$\u02cb<TE;>;Ljava/util/SortedSet<TE;>;"
    }
.end annotation

# direct methods
.method constructor <init>(Ljava/util/SortedSet;Lo/Bl;)V
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Ljava/util/SortedSet<TE;>;Lo/Bl<-TE;>;)V"
        }
    .end annotation

    .line 833
    invoke-direct {p0, p1, p2}, Lo/Kg$ˋ;-><init>(Ljava/util/Set;Lo/Bl;)V

    .line 834
    return-void
.end method

# virtual methods
.method public comparator()Ljava/util/Comparator;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()Ljava/util/Comparator<-TE;>;"
        }
    .end annotation

    .line 838
    iget-object v0, p0, Lo/Kg$iF;->ˊ:Ljava/util/Collection;

    check-cast v0, Ljava/util/SortedSet;

    invoke-interface {v0}, Ljava/util/SortedSet;->comparator()Ljava/util/Comparator;

    move-result-object v0

    return-object v0
.end method

.method public first()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TE;"
        }
    .end annotation

    .line 859
    invoke-virtual {p0}, Lo/Kg$iF;->iterator()Ljava/util/Iterator;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method public headSet(Ljava/lang/Object;)Ljava/util/SortedSet;
    .locals 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TE;)Ljava/util/SortedSet<TE;>;"
        }
    .end annotation

    .line 849
    new-instance v0, Lo/Kg$iF;

    iget-object v1, p0, Lo/Kg$iF;->ˊ:Ljava/util/Collection;

    check-cast v1, Ljava/util/SortedSet;

    invoke-interface {v1, p1}, Ljava/util/SortedSet;->headSet(Ljava/lang/Object;)Ljava/util/SortedSet;

    move-result-object v1

    iget-object v2, p0, Lo/Kg$iF;->ˋ:Lo/Bl;

    invoke-direct {v0, v1, v2}, Lo/Kg$iF;-><init>(Ljava/util/SortedSet;Lo/Bl;)V

    return-object v0
.end method

.method public last()Ljava/lang/Object;
    .locals 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TE;"
        }
    .end annotation

    .line 864
    iget-object v0, p0, Lo/Kg$iF;->ˊ:Ljava/util/Collection;

    check-cast v0, Ljava/util/SortedSet;

    move-object v1, v0

    .line 866
    :goto_0
    invoke-interface {v1}, Ljava/util/SortedSet;->last()Ljava/lang/Object;

    move-result-object v2

    .line 867
    iget-object v0, p0, Lo/Kg$iF;->ˋ:Lo/Bl;

    invoke-interface {v0, v2}, Lo/Bl;->ˊ(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 868
    return-object v2

    .line 870
    :cond_0
    invoke-interface {v1, v2}, Ljava/util/SortedSet;->headSet(Ljava/lang/Object;)Ljava/util/SortedSet;

    move-result-object v1

    .line 871
    goto :goto_0
.end method

.method public subSet(Ljava/lang/Object;Ljava/lang/Object;)Ljava/util/SortedSet;
    .locals 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TE;TE;)Ljava/util/SortedSet<TE;>;"
        }
    .end annotation

    .line 843
    new-instance v0, Lo/Kg$iF;

    iget-object v1, p0, Lo/Kg$iF;->ˊ:Ljava/util/Collection;

    check-cast v1, Ljava/util/SortedSet;

    invoke-interface {v1, p1, p2}, Ljava/util/SortedSet;->subSet(Ljava/lang/Object;Ljava/lang/Object;)Ljava/util/SortedSet;

    move-result-object v1

    iget-object v2, p0, Lo/Kg$iF;->ˋ:Lo/Bl;

    invoke-direct {v0, v1, v2}, Lo/Kg$iF;-><init>(Ljava/util/SortedSet;Lo/Bl;)V

    return-object v0
.end method

.method public tailSet(Ljava/lang/Object;)Ljava/util/SortedSet;
    .locals 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TE;)Ljava/util/SortedSet<TE;>;"
        }
    .end annotation

    .line 854
    new-instance v0, Lo/Kg$iF;

    iget-object v1, p0, Lo/Kg$iF;->ˊ:Ljava/util/Collection;

    check-cast v1, Ljava/util/SortedSet;

    invoke-interface {v1, p1}, Ljava/util/SortedSet;->tailSet(Ljava/lang/Object;)Ljava/util/SortedSet;

    move-result-object v1

    iget-object v2, p0, Lo/Kg$iF;->ˋ:Lo/Bl;

    invoke-direct {v0, v1, v2}, Lo/Kg$iF;-><init>(Ljava/util/SortedSet;Lo/Bl;)V

    return-object v0
.end method


text:
First, please do a search in [open issues](https://github.com/sjova/vscode-sass-format/issues) to see if the issue or feature request has already been filed. Use this [query](https://github.com/sjova/vscode-sass-format/issues?q=is%3Aopen+is%3Aissue+label%3Afeature-request+sort%3Areactions-%2B1-desc) to search for the most popular feature requests.

If you find your issue already exists, make relevant comments and add your [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). Use a reaction in place of a "+1" comment.

👍 - upvote

👎 - downvote

If you cannot find an existing issue that describes your bug or feature, submit an issue using the guidelines below.

## Writing Good Bug Reports and Feature Requests

File a single issue per problem and feature request.

* Do not enumerate multiple bugs or feature requests in the same issue.
* Do not add your issue as a comment to an existing issue unless it's for the identical input. Many issues look similar, but have different causes.

The more information you can provide, the more likely someone will be successful reproducing the issue and finding a fix.

Please include the following with each issue.

* Version of operating system
* Version of VS Code
* Version of Sass Formatter extension
* List of extensions that you have installed.

> **Tip:** You can easily add the list of extensions by creating the issue using `Report Issues` from VS Code's Help menu.

* Reproducible steps (1... 2... 3...) and what you expected versus what you actually saw.
* Images, animations, or a link to a video.
* A code snippet that demonstrates the issue or a link to a code repository we can easily pull down onto our machine to recreate the issue.

> **Note:** Because we need to copy and paste the code snippet, including a code snippet as a media file (i.e. .gif) is not sufficient.

* Errors in the Dev Tools Console (Help | Toggle Developer Tools)

Please remember to do the following:

* Search the issue repository to see if there exists a duplicate.
* Recreate the issue after disabling all extensions (see the [docs for how to do this](https://code.visualstudio.com/docs/editor/extension-gallery#_disable-an-extension)). If you find the issue is caused by an extension you have installed please file an issue on the extension respectively.
* Simplify your code around the issue so we can better isolate the problem.

Don't feel bad if we can't reproduce the issue and ask for more information!


text:
from __future__ import print_function

import logging
import os

def setup_logging():
    # Set log level of the messages to show.

    level_name = os.environ.get("BUCK_WRAPPER_LOG_LEVEL", "INFO")
    level_name_to_level = {
        "CRITICAL": logging.CRITICAL,
        "ERROR": logging.ERROR,
        "WARNING": logging.WARNING,
        "INFO": logging.INFO,
        "DEBUG": logging.DEBUG,
        "NOTSET": logging.NOTSET,
    }
    level = level_name_to_level.get(level_name.upper(), logging.INFO)
    if level == logging.INFO:
        format_string = "%(message)s"
    else:
        format_string = (
            "%(asctime)s [%(levelname)s][%(filename)s:%(lineno)d] %(message)s"
        )
    logging.basicConfig(level=level, format=format_string)


text:
var http = require('http'),
    director = require('director'),
    urllib = require('url'),
    util = require('util'),
    querystring = require('querystring'),
    request = require('request'),
    async = require('async'),
    moment = require('moment'),
    winston = require('winston'),
    Sentry = require('winston-sentry'),
    creds = require('./creds.js'),
    static = require('node-static');
var file = new(static.Server)('.');
var argv = require('yargs')
    .usage('start a Parse.ly API shim on a specified port.\nUsage: $0')
    .example('$0 -p 8080', 'start the server on port 8080')
    .describe('p', 'port')
    .default('p', '8080')
    .argv
console.log(util.inspect(creds,false,2,true));
var host = 'localhost',
    port = argv.p,
    API_KEY = creds.API_KEY,
    API_SECRET = creds.API_SECRET,
    SENTRY_DSN = creds.SENTRY_DSN;

var baseUrl = "http://api.parsely.com/v2";

// Set up logging
var logger = new winston.Logger({
    transports: [ new winston.transports.Console({timestamp: true})]
});
// Only use sentry if we have a proper DSN.
if (creds.SENTRY_DSN!='not-configured') {
  winston.add(
    new Sentry({
          level: 'warn',
          dsn: SENTRY_DSN,
          patchGlobal: true,
        })
  )
}

function getSecret(apikey) {
  return API_SECRET;
}

function combine(obj1, obj2) {
  var obj3 =  {};
  for (var i in obj1) {obj3[i] = obj1[i]};
  for (var i in obj2) {obj3[i] = obj2[i]};
  return obj3;
}

// TODO having a function here for each second level URL value
// [posts, sections, tags, authors] might be an anti-pattern.
function analyticsPosts() {
  var query = urllib.parse(this.req.url,true).query;
  ParselyHandler('/analytics/posts',this, query);
}

function analyticsSections() {
  var query = urllib.parse(this.req.url,true).query;
  ParselyHandler('/analytics/sections',this, query);
}

function analyticsTags() {
  var query = urllib.parse(this.req.url,true).query;
  ParselyHandler('/analytics/tags',this, query);
}

function analyticsAuthors() {
  var query = urllib.parse(this.req.url,true).query;
  ParselyHandler('/analytics/authors',this, query);
}

function sharesPosts() {
  var query = urllib.parse(this.req.url,true).query;
  ParselyHandler('/shares/posts',this, query);
}

function analyticsAuthorDetail(that, author) {
  author = author.replace('-','%20');
  var endpoint = '/analytics/author/' + author + '/detail';
  var query = urllib.parse(this.req.url,true).query;
  ParselyHandler(endpoint,this, query);
}

// Pass API call from web client along to parsely API server.
function ParselyHandler(endpoint,that, query) {
  extract = getCredsAndjQuery(query);
  // Combine full credentails and remaining query parameters
  var qs =  combine(extract.creds,query);
  // Assemble URI for API request.
  var apiUrl = baseUrl + endpoint
  var options = { url: apiUrl, qs: qs};
  logger.info('request options: ' + util.inspect(options,false,2,true));
  qstring = querystring.stringify(qs);
  logger.info('API URL: ' + apiUrl + '?' + qstring);
  request(options,function(err, apiResponse, body) {
    browserApiCallback(err,apiResponse,body,that.res,extract.jQuery);
  });
}

function authorDaily(that, author) {
  logger.info('author Daily ' + author);
  var query = urllib.parse(that.req.url,true).query;
  extract = getCredsAndjQuery(query);
  author = author.replace('-','%20');

  function HandleAsyncResults(err, results) {
    // Send results to browser
    jQueryCallback = extract.jQuery.callback
                     + '([' + JSON.stringify(results) + '])';
    that.res.writeHead(200, {'Content-Type': 'application/json' });
    that.res.end(jQueryCallback);
  }

  // MAGIC MUMBER: days for which to calculate aggregate hits.
  // Calculate array of dates in YYYY-MM-DD format.
  numberOfDays = 10;
  tasks = [];
  var now = moment();
  for (i = 0; i < numberOfDays; i++) {
    day = now.format('YYYY-MM-DD');
    now.subtract('days',1);
    tasks.push(buildAPICall(extract.creds, baseUrl, day, author));
  }
  logger.info('daysInPeriod', util.inspect(tasks,false,2,true));
  async.parallel(tasks,HandleAsyncResults);
}

// Returns a function which fits the async.parallel pattern:
// a function which takes one argument, which is a callback.
// the return function executes this callback as its final action.
function buildAPICall(creds, baseUrl, date, author) {
  return function(callback) {
    var url = baseUrl + '/analytics/author/' + author + '/detail';
    // MAGIC NUMBER: number of posts to consider for daily totals: 20.
    params = { apikey: creds.apikey, secret: creds.secret,
               period_start: date, period_end: date, limit: 20};
    // TODO watch out!  deal with blank jQuery object on
    // those calls for the aggregate points.
    var options = {url: url, qs: params};
    logger.info('request options: ' + util.inspect(options,false,2,true));
    qstring = querystring.stringify(params);
    logger.info('API URL: ' + url + '?' + qstring);
    request(options, function( err, apiResponse, body) {
      aggregateApiCallback(err, apiResponse, body, date, callback);
    });
  }
}

function aggregateApiCallback(err, apiResponse, body, date, callback) {
  if (err) {
     logger.info('AGGREGATE API REQUEST ERROR');
     // TODO handle error
  } else if (apiResponse.statusCode == 200 ) {
    if (body.code > 200) {
      logger.info('AGGREGATE API RESPONSE NOT OK');
     // TODO handle error
    } else {
     // TODO handle OK
      logger.info('AGGREGATE API RESPONSE OK');
      data = JSON.parse(body);
      //logger.info(util.inspect(data, false, 2, true));
      //logger.info(util.inspect(data[0], false, 2, true));
      // Sum up _hits from each element
      totalHits = 0;
      for (i in data.data) {
        //logger.info(util.inspect(data.data[i], false, 2, true));
        totalHits += data.data[i]._hits;
      }
      result = {date: date, hits: totalHits};
      callback(err, result)
    }
  } else {
    logger.info('AGGREGATE API RESPONSE ERROR');
    clientResponse.end(body);
    logger.info(body);
  }
}

// return results to requestor (browser).
function browserApiCallback(err, apiResponse, body, clientResponse, jQuery) {
  if (err) {
     logger.info('API REQUEST ERROR');
     clientResponse.writeHead(500, {'Content-Type': 'text/plain' });
     clientResponse.end('Error');
  } else if (apiResponse.statusCode == 200 ) {
    if (body.code > 200) {
      logger.info('API RESPONSE NOT OK');
      clientResponse.writeHead(body.code, {'Content-Type': 'text/plain' });
      clientResponse.end();
    } else {
      logger.info('API RESPONSE OK');
      clientResponse.writeHead(200, {'Content-Type': 'application/json' });
      jQueryCallback = jQuery.callback + '([' + body + '])';
      clientResponse.end(jQueryCallback);
      data = JSON.parse(body);
      logger.info(util.inspect(data, false, 2, true));
    }
  } else {
    logger.info('API RESPONSE ERROR');
    clientResponse.end(body);
    logger.info(body);
  }
}

function getCreds(apikey) {
  // Lookup secret by apikey in config/default.json
  var creds = {
    apikey: apikey,
    secret: getSecret(apikey)
  }
  return creds;
}

function getCredsAndjQuery(query) {
  // Clean off jQuery callback stuff
  // Don't want to pass that to parsely API.
  var jQuery =  {
    callback: query.callback,
    _: query._
  }
  delete query.callback;
  delete query._;

  // Lookup secret by apikey in config/default.json
  var creds = {
    apikey: query.apikey,
    secret: getSecret(query.apikey)
  }

  // Remove credentials from query object
  delete query.apikey;
  delete query.secret; //placeholder secret sent by client
  return {creds: creds, jQuery: jQuery};
}

function staticServe() {
  file.serve(this.req, this.res);
}

function fail(that) {
  logger.error('test error from author dashboard. everything is OK.');
}

// define a routing table.
var router = new director.http.Router({
  '/v2': {
    '/analytics': {
      '/posts': {
        get: analyticsPosts
      },
      '/sections': {
        get: analyticsSections
      },
      '/tags': {
        get: analyticsTags
      },
      '/authors': {
        get: analyticsAuthors
      },
      // author is for the detail section
      '/author': {
        '/:author': {
          '/detail' : {
            get: function(author) {
              analyticsAuthorDetail(this,author);
            }
          }
        }
      },
    },
    '/shares': {
      '/posts': {
        get: sharesPosts
      }
    }
  },
  '/v3': {
    '/aggregates' : {
      '/author' : {
        '/:author' : {
          '/daily' : {
            get : function (author) {
               logger.info('/v3/aggregates/author/' + author + '/daily');
               authorDaily(this, author);
              }
          }
        }
      }
    },
    '/fail' :{
      get : fail
    }
  }
});

// Create HTTP server
var serv = http.createServer(function (req, res) {
  logger.info('HTTP request: req.method:  '+ req.method);
  logger.info('HTTP request: req.url:  '+ req.url);
  logger.info('HTTP request: req.body: '+ req.body);
  var path = urllib.parse(req.url,true).pathname;
  logger.info('HTTP request: path: '+ path);
  req.addListener('end', function () {
    router.dispatch(req, res, function(err) {
      if (err) {
        res.writeHead(404);
        res.end()
      }
    });
  }).resume();
});

// Serve static files.
// For everything that's doesnt match the routing table.
router.get(/.*/, staticServe);

serv.listen(port,host);
logger.info('Server running at http://'+host+':'+port);


text:
namespace blink {

void HeapAllocator::backingFree(void* address) {
  if (!address)
    return;

  ThreadState* state = ThreadState::current();
  if (state->sweepForbidden())
    return;
  ASSERT(!state->isInGC());

  // Don't promptly free large objects because their page is never reused.
  // Don't free backings allocated on other threads.
  BasePage* page = pageFromObject(address);
  if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
    return;

  HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
  ASSERT(header->checkHeader());
  NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
  state->promptlyFreed(header->gcInfoIndex());
  arena->promptlyFreeObject(header);
}

void HeapAllocator::freeVectorBacking(void* address) {
  backingFree(address);
}

void HeapAllocator::freeInlineVectorBacking(void* address) {
  backingFree(address);
}

void HeapAllocator::freeHashTableBacking(void* address) {
  backingFree(address);
}

bool HeapAllocator::backingExpand(void* address, size_t newSize) {
  if (!address)
    return false;

  ThreadState* state = ThreadState::current();
  if (state->sweepForbidden())
    return false;
  ASSERT(!state->isInGC());
  ASSERT(state->isAllocationAllowed());
  DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap());

  // FIXME: Support expand for large objects.
  // Don't expand backings allocated on other threads.
  BasePage* page = pageFromObject(address);
  if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
    return false;

  HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
  ASSERT(header->checkHeader());
  NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
  bool succeed = arena->expandObject(header, newSize);
  if (succeed)
    state->allocationPointAdjusted(arena->arenaIndex());
  return succeed;
}

bool HeapAllocator::expandVectorBacking(void* address, size_t newSize) {
  return backingExpand(address, newSize);
}

bool HeapAllocator::expandInlineVectorBacking(void* address, size_t newSize) {
  return backingExpand(address, newSize);
}

bool HeapAllocator::expandHashTableBacking(void* address, size_t newSize) {
  return backingExpand(address, newSize);
}

bool HeapAllocator::backingShrink(void* address,
                                  size_t quantizedCurrentSize,
                                  size_t quantizedShrunkSize) {
  if (!address || quantizedShrunkSize == quantizedCurrentSize)
    return true;

  ASSERT(quantizedShrunkSize < quantizedCurrentSize);

  ThreadState* state = ThreadState::current();
  if (state->sweepForbidden())
    return false;
  ASSERT(!state->isInGC());
  ASSERT(state->isAllocationAllowed());
  DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap());

  // FIXME: Support shrink for large objects.
  // Don't shrink backings allocated on other threads.
  BasePage* page = pageFromObject(address);
  if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
    return false;

  HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
  ASSERT(header->checkHeader());
  NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
  // We shrink the object only if the shrinking will make a non-small
  // prompt-free block.
  // FIXME: Optimize the threshold size.
  if (quantizedCurrentSize <=
          quantizedShrunkSize + sizeof(HeapObjectHeader) + sizeof(void*) * 32 &&
      !arena->isObjectAllocatedAtAllocationPoint(header))
    return true;

  bool succeededAtAllocationPoint =
      arena->shrinkObject(header, quantizedShrunkSize);
  if (succeededAtAllocationPoint)
    state->allocationPointAdjusted(arena->arenaIndex());
  return true;
}

bool HeapAllocator::shrinkVectorBacking(void* address,
                                        size_t quantizedCurrentSize,
                                        size_t quantizedShrunkSize) {
  return backingShrink(address, quantizedCurrentSize, quantizedShrunkSize);
}

bool HeapAllocator::shrinkInlineVectorBacking(void* address,
                                              size_t quantizedCurrentSize,
                                              size_t quantizedShrunkSize) {
  return backingShrink(address, quantizedCurrentSize, quantizedShrunkSize);
}

}  // namespace blink


text:
ES5Harness.registerTest({

    id: "15.4.4.14-9-a-1",

    path: "TestCases/chapter15/15.4/15.4.4/15.4.4.14/15.4.4.14-9-a-1.js",

    description: "Array.prototype.indexOf - test that added properties of step 2 are visible here",

    test: function testcase() {

        var arr = { };

        Object.defineProperty(arr, "length", {
            get: function () {
                arr[2] = "length";
                return 3;
            },
            configurable: true
        });

        return 2 === Array.prototype.indexOf.call(arr, "length");
    },

    precondition: function prereq() {
        return fnExists(Array.prototype.indexOf) && fnExists(Object.defineProperty);
    }

});


text: scp *version.txt happybrackets@happybrackets.net:happybrackets.net/downloads/