text:
package org.apache.falcon.resource;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Entity list used for marshalling / unmarshalling with REST calls.
 */
@XmlRootElement(name = "dependents")
@XmlAccessorType(XmlAccessType.FIELD)
@edu.umd.cs.findbugs.annotations.SuppressWarnings({"EI_EXPOSE_REP", "EI_EXPOSE_REP2"})
public class InstanceDependencyResult extends APIResult {

    @XmlElement(name = "dependencies")
    private SchedulableEntityInstance[] dependencies;

    //For JAXB
    private InstanceDependencyResult() {
        super();
    }

    public InstanceDependencyResult(Status status, String message) {
        super(status, message);
    }

    public SchedulableEntityInstance[] getDependencies() {
        return dependencies;
    }

    public void setDependencies(SchedulableEntityInstance[] dependencies) {
        this.dependencies = dependencies;
    }

    @Override
    public Object[] getCollection() {
        return getDependencies();
    }

    @Override
    public void setCollection(Object[] items) {
        if (items == null) {
            setDependencies(new SchedulableEntityInstance[0]);
        } else {
            SchedulableEntityInstance[] newInstances = new SchedulableEntityInstance[items.length];
            for (int index = 0; index < items.length; index++) {
                newInstances[index] = (SchedulableEntityInstance)items[index];
            }
            setDependencies(newInstances);
        }
    }

    @Override
    public String toString() {
        StringBuilder buffer = new StringBuilder();
        if (dependencies != null) {
            for (SchedulableEntityInstance element : dependencies) {
                buffer.append(element.toString());
                buffer.append("\n");
            }
        }
        return buffer.toString();
    }

}


text:
try {
  // Prints: true
  console.log(await kuzzle.ms.setnx('foo', 'bar'));

  // Prints: false
  console.log(await kuzzle.ms.setnx('foo', 'qux'));

  // Prints: bar
  console.log(await kuzzle.ms.get('foo'));
} catch (error) {
  console.error(error.message);
}

redpajama_set_name: RedPajamaGithub


text:
/* Includes ------------------------------------------------------------------*/
#include "BUSApp.h"			/*!< Bus application parameters */
#include "../../MBALIBRARY/MBALib.h"		/*!< Access to MBA instance */
#include "../../PHDLLAYER/BUSAPI/BUSAPI.h" 	/*!< Main API of this file */
#include "../../TOOLS/MemoryManagement.h" 	/*!< Definition of memory functions */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/

THREAD_ID ThreadIDBUSReadProcess[BUS_INSTANCES];  /*!< Thread IDs */
THREAD_ID ThreadIDBUSWriteProcess[BUS_INSTANCES];  /*!< Thread IDs */

/**
 * @brief A mail queue for each bus thread is created. This mailbox are used to
 * receive data from MBA process or other bus threads
 */
MAIL_QUEUE_ID QueueIDBusQueue[BUS_INSTANCES];

#if BUS_INSTANCES > 0
/**
 * @brief BusQueue_1 is the queue for the interface 0. See @ref InstanceID.
 */
DEFINE_MAIL_QUEUE (BusQueue_1, BUS_QUEUE_SIZE, TransProtFrame);
#endif
#if BUS_INSTANCES > 1
/**
 * @brief BusQueue_2 is the queue for the interface 1. See @ref InstanceID.
 */
DEFINE_MAIL_QUEUE (BusQueue_2, BUS_QUEUE_SIZE, TransProtFrame);
#endif
#if BUS_INSTANCES > 2
/**
 * @brief BusQueue_2 is the queue for the interface 1. See @ref InstanceID.
 */
DEFINE_MAIL_QUEUE (BusQueue_3, BUS_QUEUE_SIZE, TransProtFrame);
#endif

/**
 * @brief Queues of MBA Instances. Usually only one Queue.
 */
extern MAIL_QUEUE_ID QueueIDMBAQueue;

/**
 * @brief A mutex is needed to get access to the MBA Queue. This Queue is shared
 *				by all available bus interfaces
 */
DEFINE_MUTEX(MBAMutex);
MUTEX_ID MidMBAMutex;              /*!< Mutex ID */

/**
 * @brief Thread argument. The BUS ID is used by each bus thread to point to the
 *				correct bus functions. Other arguments may be added in the future.
 */
int32_t InstanceID[BUS_INSTANCES] =
{
 BUS_ID_1,
 BUS_ID_2
#if BUS_INSTANCES > 2
 , BUS_ID_3
#endif
 };

/* Private function prototypes -----------------------------------------------*/
OS_THREAD_TYPE BUSReadProcess (OS_THREAD_ARG argument);	 /*!< Bus thread function */
OS_THREAD_TYPE BUSWriteProcess (OS_THREAD_ARG argument); /*!< Bus thread function */

/**
 * @brief Thread definition. There are as many instances as available bus interfaces
 */
DEFINE_THREAD(BUSReadProcess, osPriorityNormal, BUS_INSTANCES, BUS_STACKSIZE);
DEFINE_THREAD(BUSWriteProcess, osPriorityNormal, BUS_INSTANCES, BUS_STACKSIZE);

/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Initializes BUS App process
  * @details Mail queues, threads and all elements needed for tasks initialization.
  * @retval @ref BusInstanceRet
  */
int32_t InitBUSProcess(void)
{
  int32_t ret = INSTANCE_OK;
  int32_t FuncRet;

  /* Create Bus buffers */
#if BUS_INSTANCES > 0
  CreateMailQueue(FuncRet, QueueIDBusQueue[BUS_ID_1],MAIL_QUEUE_REF(BusQueue_1), NULL);
  if(!FuncRet)
  {
	  ret = BUFFER_ERROR; // Mail Queue object not created
  }
#endif
#if BUS_INSTANCES > 1

  CreateMailQueue(FuncRet, QueueIDBusQueue[BUS_ID_2] ,MAIL_QUEUE_REF(BusQueue_2), NULL);
  if(!FuncRet)
  {
	  ret = BUFFER_ERROR; // Mail Queue object not created
  }
#endif
#if BUS_INSTANCES > 2
  CreateMailQueue(FuncRet, QueueIDBusQueue[BUS_ID_3], MAIL_QUEUE_REF(BusQueue_3), NULL);
  if(!QueueIDBusQueue[BUS_ID_3])
  {
	ret = BUFFER_ERROR; // Mail Queue object not created
  }
#endif

  /* Create synchronization tools */
  CreateMutex(MidMBAMutex, MUTEX_REF(MBAMutex));
  if (!MidMBAMutex)
  {
      ret = SYNC_TOOL_ERROR; // Mutex object not created
  }

  return ret;
}

/**
  * @brief   Creates a new thread form an external module.
  * @param[in] 	Thread ID
  */
void LaunchBUSInstance(uint8_t BusInstanceID)
{
  uint32_t FuncRet;
  CreateThread (FuncRet, ThreadIDBUSReadProcess[BusInstanceID],THREAD_REF(BUSReadProcess), &(InstanceID[BusInstanceID]));
  if(!FuncRet)
  {
	  /* Handle Erro */
  }
}
/**
  * @brief   Bus task instance.
  * @details This task must be called for each available bus interface. It is the
  *	     responsible of the initialization and configuration of the physical bus
  *	     interface. Furthermore, data transfer are transmitted /
  *	     received to / from the MBA instance and the linked Bus.
  * @param[in] 	argument Bus identification
  */
OS_THREAD_TYPE BUSReadProcess (OS_THREAD_ARG argument)
{
  uint8_t *BusBuffer; 	/* Temporal buffer to save data from/to linked bus */
  uint32_t FrameSize, FuncRet;	/* Saves size of the received/transmitted frames */
  TransProtFrame *TxFrame = NULL;  /* Transfer protocol buffers to transfer data */
  OSRetValue	RetMutex;

  /* Get BUS Identification */
  int32_t BUSId = *((int32_t *)argument);

  /* Initialize BUS functions, buffer and variables */
  BusInstances[BUSId].Init();

  /* Configure Bus HW interface to start the communication */
  if(BusInstances[BUSId].Configuration(1,0) < 0)
  {
      BusInstances[BUSId].DeInit();
      ForceBusInterfaceStop(BUSId);
      TransferProtocolUpdateInterfaceState(BUSId);
      ForceStopThread(FuncRet, ThreadIDBUSReadProcess[BUSId]);
  }
  else
  {
    /* Once the Interface is enabled, launch the read process */
    CreateThread (FuncRet, ThreadIDBUSWriteProcess[BUSId],THREAD_REF(BUSWriteProcess),&(InstanceID[BUSId]));
    if(!FuncRet)
    {
  	/* handle Error */
    }
  }

  while (1)
  {
    /* Check data from Bus */
    if(BusInstances[BUSId].DataAvailable() > 0)
    {
      /* Alloc memory for temporal buffer */
      FrameSize = BusInstances[BUSId].SizeDataAvailable();
      BusBuffer = (uint8_t*) MemAlloc(FrameSize);

      if(BusBuffer != NULL)
      {
        /* Read data in from the bus */
        BusInstances[BUSId].Read(BusBuffer, FrameSize);

        /* Put data into mailbox */
        MailAlloc(TxFrame, QueueIDMBAQueue, 0);        // Allocate memory
        if(TxFrame)
        {
          /* Cast data from bus into transfer protocol frame */
          TransferProtocolCast(TxFrame, BusBuffer, FrameSize, BUSId,
          TransferProtocolGetInterfaceType(BUSId) | FROM_BUFFER);

          /* Check is the resource is available */
          RetMutex = MutexWait(MidMBAMutex);
          switch(RetMutex)
          {
            case OS_OK:
            /* Put data into MBA buffer */
            MailPut(QueueIDMBAQueue, TxFrame);
            MutexRelease(MidMBAMutex);
            break;
            case OS_TIMEOUT:
            break;
            case OS_ERROR:
            break;
            default:
            break;
          }
        }
      }

      if(BusBuffer != NULL)
      {
        /* Free allocated data */
        MemFree(BusBuffer);
        BusBuffer = NULL;
      }
    }
  }
}
/**
  * @brief  	Bus task instance.
  * @details	This task must be called for each available bus interface. It is the
  *		        responsible of the initialization and configuration of the physical bus
  *		        interface. Furthermore, data transfer are transmitted /
  *		        received to / from the MBA instance and the linked Bus.
  * @param[in] 	argument Bus identification
  */
OS_THREAD_TYPE BUSWriteProcess (OS_THREAD_ARG argument)
{
  uint8_t *BusBuffer; 	/* Temporal buffer to save data from/to linked bus */
  uint32_t FrameSize;	/* Saves size of the received/transmitted frames */

  TransProtFrame *RxFrame = NULL; /* Transfer protocol buffers to transfer data
				    to/from the MBA instante */
  OSGlobalRet  RetMail;

  /* Get BUS Identification */
  int32_t BUSId = *((int32_t *)argument);

  /* If this thread is enabled, it means that this interface is initializated
   * for continuous communication, therefore this interface is set ACTIVE
   */
  SetBusInstanceState(BUSId, BUS_ACTIVE);
  TransferProtocolUpdateInterfaceState(BUSId);

  while (1)
  {

    /* if there is data in the mailbox, read it */
    MailGet(RetMail, QueueIDBusQueue[BUSId]);
    if (RetMail.RetValue == OS_OK)
    {
      RxFrame = RetMail.Data;
      FrameSize = GetFrameSizeP(RxFrame);

      /* Allocate memory for busbuffer */
      BusBuffer = (uint8_t*) MemAlloc(FrameSize);

      if(BusBuffer != NULL)
      {
        /* Cast from transfer protocol to buffer format */
        FrameSize = TransferProtocolCast(RxFrame, BusBuffer, FrameSize, BUSId,
        TransferProtocolGetInterfaceType(BUSId) | TO_BUFFER);

        /* Add new frame into Bus buffer to send it */
        BusInstances[BUSId].Write(BusBuffer, FrameSize);

        /* Free allocated data */
        MailFree(QueueIDBusQueue[BUSId], RxFrame);

        if(BusBuffer != NULL)
        {
          /* Free allocated data */
          MemFree(BusBuffer);
          BusBuffer = NULL;
        }
      }
    }
  }
}
/**
  *@}
  */
/**
  *@}
  */


text:
import { WinterWarning16 } from "../../";

export = WinterWarning16;


text:
.playlistsNav {
  display: flex;
  flex-flow: column;
  width: 200px;
  border-right: 1px solid var(--border-color);
  background-color: var(--sidebar-bg);
  max-height: 100%;
  overflow: hidden;
  position: relative;
}

.playlistsNav__header {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
}

.actions {
  align-items: stretch;
}

.action {
  background: transparent;
  border: none;
  color: var(--text);
  width: 33px;
  padding-top: 10px;
  padding-bottom: 10px;
  text-align: center;

  :global .fa {
    margin-right: 0;
  }

  &:hover {
    background: rgba(0 0 0 0.05);
  }
}

.playlistsNav__title {
  padding: 0 12px;
  margin: 10px 0;
  font-size: 11px;
  font-weight: bold;
  flex: 1;
}

.playlistsNav__body {
  flex: 1 1 auto;
  overflow: auto;
}

.item__link {
  font-size: 1rem;
  display: block;
  color: inherit;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  cursor: pointer;
  padding: 8px 12px;
  text-decoration: none;
  border-style: solid;
  border-color: transparent;
  border-width: 1px 0;

  &:hover {
    background-color: var(--sidebar-item-active-bg);
    color: var(--text);
  }

  &:global(.isActive) {
    z-index: 10;
    border-style: solid;
    border-color: var(--border-color);
    border-width: 1px 0;
    background-color: var(--sidebar-item-active-bg);
    color: var(--main-color);
  }
}

.item__input {
  font-size: 1rem;
  display: block;
  width: 100%;
  background-color: var(--sidebar-item-active-bg);
  color: var(--main-color);
  padding: 8px 12px;
  outline: none;
  border-style: solid;
  border-color: var(--border-color);
  border-width: 1px 0;
}


text:
.. title:: Introduction

.. include:: ../../README.rst


text:
import boto3
import json

import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

dynamo = boto3.resource('dynamodb')

def lambda_handler(event, context):
  logger.info(event)
  key = event['Id']
  table = dynamo.Table('MortgageQuotes')
  record = table.get_item(Key={'Id': key }, ConsistentRead=True)
  if 'Item' in record:
    return {'Quotes' : record['Item']['Quotes'] }
  else:
    logger.info("No aggregate for key %s" % key)
    return {'Quotes' : [] }


text:
package org.wso2.am.integration.tests.token;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.bean.*;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.am.integration.test.utils.clients.APIStoreRestClient;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;

import javax.ws.rs.core.Response;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static org.testng.Assert.*;

public class TokenAPITestCase extends APIMIntegrationBaseTest {

    private APIPublisherRestClient apiPublisher;
    private APIStoreRestClient apiStore;
    private ServerConfigurationManager serverConfigurationManager;

    private static final Log log = LogFactory.getLog(TokenAPITestCase.class);

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init();
        /*
          If test run in external distributed deployment you need to copy following resources accordingly.
          configFiles/hostobjecttest/api-manager.xml
          configFiles/tokenTest/log4j.properties
          To tests issue mentioned in https://wso2.org/jira/browse/APIMANAGER-2065 please run this test against
          WSo2 Load balancer fronted 2 gateways 2 key manager setup with WSClient mode. Please refer resource api-manager.xml file.
        */

        String publisherURLHttp = publisherUrls.getWebAppURLHttp();
        String storeURLHttp = storeUrls.getWebAppURLHttp();
        serverConfigurationManager = new ServerConfigurationManager(gatewayContext);
        serverConfigurationManager.applyConfigurationWithoutRestart(new File(getAMResourceLocation()
                + File.separator +
                "configFiles/tokenTest/" +
                "api-manager.xml"));
        serverConfigurationManager.applyConfiguration(new File(getAMResourceLocation()
                + File.separator +
                "configFiles/tokenTest/" +
                "log4j.properties"));

        apiPublisher = new APIPublisherRestClient(publisherURLHttp);
        apiStore = new APIStoreRestClient(storeURLHttp);

        apiPublisher.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());
        apiStore.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());

    }

    @Test(groups = {"wso2.am"}, description = "Token API Test other")
    public void testTokenAPITestCase() throws Exception {

        String APIName = "TokenTestAPI";
        String APIContext = "tokenTestAPI";
        String tags = "youtube, token, media";
        String url = "http://gdata.youtube.com/feeds/api/standardfeeds";
        String description = "This is test API create by API manager integration test";
        String providerName = "admin";
        String APIVersion = "1.0.0";

        APIRequest apiRequest = new APIRequest(APIName, APIContext, new URL(url));
        apiRequest.setTags(tags);
        apiRequest.setDescription(description);
        apiRequest.setVersion(APIVersion);
        apiRequest.setSandbox(url);
        apiPublisher.addAPI(apiRequest);
        APILifeCycleStateRequest updateRequest =
                new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED);
        apiPublisher.changeAPILifeCycleStatus(updateRequest);

        // Create application
        apiStore.addApplication("TokenTestAPI-Application", "Gold", "", "this-is-test");
        SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName,
                storeContext.getContextTenant()
                        .getContextUser()
                        .getUserName()
        );
        subscriptionRequest.setTier("Gold");
        subscriptionRequest.setApplicationName("TokenTestAPI-Application");
        apiStore.subscribe(subscriptionRequest);

        //Generate sandbox Token and invoke with that
        APPKeyRequestGenerator generateAppKeyRequestSandBox =
                new APPKeyRequestGenerator("TokenTestAPI-Application");
        generateAppKeyRequestSandBox.setKeyType("SANDBOX");
        String responseStringSandBox =
                apiStore.generateApplicationKey(generateAppKeyRequestSandBox).getData();
        JSONObject responseSandBOX = new JSONObject(responseStringSandBox);
        String SANDbOXAccessToken =
                responseSandBOX.getJSONObject("data").getJSONObject("key").get("accessToken")
                        .toString();
        Map<String, String> requestHeadersSandBox = new HashMap<String, String>();
        requestHeadersSandBox.put("Authorization", "Bearer " + SANDbOXAccessToken);
        HttpResponse youTubeResponseSandBox = HttpRequestUtil
                .doGet(gatewayUrls.getWebAppURLNhttp() + "tokenTestAPI/1.0.0/most_popular",
                        requestHeadersSandBox);
        log.info("Response " + youTubeResponseSandBox);
        // assertEquals(youTubeResponseSandBox.getResponseCode(), 200, "Response code mismatched");

        //Generate production token and invoke with that
        APPKeyRequestGenerator generateAppKeyRequest =
                new APPKeyRequestGenerator("TokenTestAPI-Application");
        String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
        JSONObject response = new JSONObject(responseString);
        /*Response would be like -
         {"validityTime":"360000","consumerKey":"Ow2cGYBf3xlAPpG3Q51W_3qnoega",
        "accessToken":"qo3oNebQaF16C6qw1a56aZn2nwEa","enableRegenarate":true,"accessallowdomains":"ALL","
        consumerSecret":"ctHfsc1jFR7ovUgZ0oeHK8i9F9oa"}*/

        String accessToken =
                response.getJSONObject("data").getJSONObject("key").get("accessToken").toString();
        String consumerKey =
                response.getJSONObject("data").getJSONObject("key").getString("consumerKey");
        String consumerSecret =
                response.getJSONObject("data").getJSONObject("key").getString("consumerSecret");
        //Obtain user access token
        Thread.sleep(2000);
        String requestBody = "grant_type=password&username=admin&password=admin&scope=PRODUCTION";
        URL tokenEndpointURL = new URL(gatewayUrls.getWebAppURLNhttp() + "token");
        JSONObject accessTokenGenerationResponse = new JSONObject(
                apiStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody,
                        tokenEndpointURL).getData()
        );
        /*Response would be like -
        {"token_type":"bearer","expires_in":3600,"refresh_token":"736b6b5354e4cf24f217718b2f3f72b",
        "access_token":"e06f12e3d6b1367d8471b093162f6729"}
         */
        String userAccessToken = accessTokenGenerationResponse.getString("access_token");
        String refreshToken = accessTokenGenerationResponse.getString("refresh_token");
        log.info(refreshToken);
        Map<String, String> requestHeaders = new HashMap<String, String>();
        //Check User Access Token
        requestHeaders.put("Authorization", "Bearer " + userAccessToken);
        Thread.sleep(2000);
        HttpResponse youTubeResponse = HttpRequestUtil
                .doGet(gatewayUrls.getWebAppURLNhttp() + "tokenTestAPI/1.0.0/most_popular", requestHeaders);
        //check JWT headers here
        assertEquals(youTubeResponse.getResponseCode(), Response.Status.OK.getStatusCode(),
                "Response code mismatched");
        assertTrue(youTubeResponse.getData().contains("<feed"), "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<category"),
                "Response data mismatched");
        assertTrue(youTubeResponse.getData().contains("<entry>"),
                "Response data mismatched");

        //Check Application Access Token
        requestHeaders.clear();
        requestHeaders.put("Authorization", "Bearer " + accessToken);
        HttpResponse youTubeResponseWithApplicationToken = HttpRequestUtil
                .doGet(gatewayUrls.getWebAppURLNhttp() + "tokenTestAPI/1.0.0/most_popular", requestHeaders);
        assertEquals(youTubeResponseWithApplicationToken.getResponseCode(), Response.Status.OK.getStatusCode(),
                "Response code mismatched");
        assertTrue(youTubeResponseWithApplicationToken.getData().contains("<feed"),
                "Response data mismatched");
        assertTrue(youTubeResponseWithApplicationToken.getData().contains("<category"),
                "Response data mismatched");
        assertTrue(youTubeResponseWithApplicationToken.getData().contains("<entry>"),
                "Response data mismatched");

        //Invoke Https end point
        HttpResponse youTubeResponseWithApplicationTokenHttps = HttpRequestUtil
                .doGet(gatewayUrls.getWebAppURLNhttp() + "tokenTestAPI/1.0.0/most_popular", requestHeaders);
        log.info("Response " + youTubeResponseWithApplicationTokenHttps);
        assertEquals(youTubeResponseWithApplicationTokenHttps.getResponseCode(), 200, "Response code mismatched");

        HttpResponse errorResponse = null;
        for (int i = 0; i < 40; i++) {
            errorResponse = HttpRequestUtil
                    .doGet(gatewayUrls.getWebAppURLNhttp() + "tokenTestAPI/1.0.0/most_popular",
                            requestHeaders);
        }

        assert errorResponse != null;
        assertEquals(errorResponse.getResponseCode(), 503,
                "Response code mismatched while token API test case");
        Thread.sleep(60000);
        errorResponse = HttpRequestUtil
                .doGet(gatewayUrls.getWebAppURLNhttp() + "tokenTestAPI/1.0.0/most_popular", requestHeaders);
        log.info("Error response " + errorResponse);

        apiPublisher.revokeAccessToken(accessToken, consumerKey, providerName);
        requestHeaders.clear();
        requestHeaders.put("Authorization", "Bearer " + "this-is-incorrect-token");
        errorResponse = HttpRequestUtil
                .doGet(gatewayUrls.getWebAppURLNhttp() + "tokenTestAPI/1.0.0/most_popular", requestHeaders);
        assertEquals(errorResponse.getResponseCode(), 401,
                "Response code mismatched while token API test case");
        //TODO handle this in automation core level
        try {
            StringBuilder soapRequest = new StringBuilder(
                    "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
            soapRequest.append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
            soapRequest
                    .append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>");
            soapRequest
                    .append("<GetMyName xmlns=\"http://tempuri.org/\"><name>Sam</name></GetMyName>");
            soapRequest.append("</soap:Body></soap:Envelope>");
            errorResponse = HttpRequestUtil
                    .doPost(new URL(gatewayUrls.getWebAppURLNhttp() + "tokenTestAPI/1.0.0/most_popular"),
                            soapRequest.toString(), requestHeaders);
            log.info("Error Response " + errorResponse);
        } catch (Exception e) {
            //handle error
        }
        assertEquals(errorResponse.getResponseCode(), 401, "Response code mismatched while token API test case");

    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {
        apiStore.removeApplication("TokenTestAPI-Application");
        super.cleanup();
        serverConfigurationManager.restoreToLastConfiguration();
    }
}


text:
package lv.emes.libraries.patches.android_compat;

import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

/**
 * An utility class containing Java 8 standard util methods
 * that are not supported on older Android versions we need to support currently.
 *
Static methods:
 *

 *
computeIfAbsent

 *

 *
 * @author eMeS
 * @version 1.0.
 * @since 2.2.3.
 */
public final class JavaUtilCompatibility {

    private JavaUtilCompatibility() {
    }

    public static <K,V>  V computeIfAbsent(Map<K, V> map, K key,
                                           Function<? super K, ? extends V> mappingFunction) {
        Objects.requireNonNull(mappingFunction);
        V v;
        if ((v = map.get(key)) == null) {
            V newValue;
            if ((newValue = mappingFunction.apply(key)) != null) {
                map.put(key, newValue);
                return newValue;
            }
        }

        return v;
    }
}


text:
function repeat(string, times) {
  var result = "";
  for (var i = 0; i < times; i++)
    result += string;
  return result;
}

function TextCell(text) {
  this.text = text.split("\n");
}
TextCell.prototype.minWidth = function() {
  return this.text.reduce(function(width, line) {
    return Math.max(width, line.length);
  }, 0);
};
TextCell.prototype.minHeight = function() {
  return this.text.length;
};
TextCell.prototype.draw = function(width, height) {
  var result = [];
  for (var i = 0; i < height; i++) {
    var line = this.text[i] || "";
    result.push(line + repeat(" ", width - line.length));
  }
  return result;
};
//eloquentJS code end

function StretchCell(inner, width, height) {
  this.inner = inner;
  this.width = width;
  this.height = height;
}
StretchCell.prototype.minWidth = function() {
  return Math.max(this.inner.minWidth(), this.width);
};
StretchCell.prototype.minHeight = function() {
  return Math.max(this.inner.minHeight(), this.height);
};
StretchCell.prototype.draw = function(width, height) {
  return this.inner.draw(Math.max(this.minWidth(), width), Math.max(this.minHeight(), height));
};

var sc = new StretchCell(new TextCell("abc"), 1, 2);
console.log(sc.minWidth());
// → 3
console.log(sc.minHeight());
// → 2
console.log(sc.draw(3, 2));
// → ["abc", "   "]


text:
export * from "./shadowGenerator";
export * from "./cascadedShadowGenerator";
export * from "./shadowGeneratorSceneComponent";


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".TermsActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/HeyVolo.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/main.backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:fitsSystemWindows="true"
                android:src="@drawable/terms"
                app:layout_collapseMode="parallax"
                />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/HeyVolo.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_scrolling" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end" />

</android.support.design.widget.CoordinatorLayout>


text:
"use strict";
let conventionalChangelog = require('conventional-changelog');

let options = {
  preset: 'angular'
};

if(require.main === module) {
  let context, gitOpts;

  if (process.argv[2]) {
    context = {};
    gitOpts = {};
    context.previousTag = process.argv[2];
    gitOpts.from = process.argv[2];
  }

  if (process.argv[3]) {
    context.currentTag = process.argv[3];
  }

  showChangelog(context, gitOpts);
}

function showChangelog(context, gitOpts) {
  conventionalChangelog(options, context, gitOpts).pipe(process.stdout);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>2473 Potzneusiedl, Austria</formatted_address>
  <address_component>
   <long_name>Potzneusiedl</long_name>
   <short_name>Potzneusiedl</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Potzneusiedl</long_name>
   <short_name>Gemeinde Potzneusiedl</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Neusiedl am See District</long_name>
   <short_name>Neusiedl am See District</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Burgenland</long_name>
   <short_name>Burgenland</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>2473</long_name>
   <short_name>2473</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>48.0448614</lat>
    <lng>16.9481245</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>48.0388864</lat>
     <lng>16.9378170</lng>
    </southwest>
    <northeast>
     <lat>48.0478301</lat>
     <lng>16.9605300</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>48.0388864</lat>
     <lng>16.9378170</lng>
    </southwest>
    <northeast>
     <lat>48.0478301</lat>
     <lng>16.9605300</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJQ0bq1rhgbEcR4BLmLVeXAAQ</place_id>
 </result>
</GeocodeResponse>


text:
#include <cstdio>
#include <cassert>
#include <climits>

#include <iostream>
#include <unordered_map>
#include <vector>

#include <mkl.h>

#include "SpMP/mm_io.h"
#include "SpMP/Utils.hpp"
#include "SpMP/LevelSchedule.hpp"
#include "SpMP/synk/barrier.hpp"

#include "knob.h"
#include "CSR_Interface.h"
#include "TriSolve.hpp"
#include "SpGEMM.hpp"
#include "ILU.hpp"
#include "IChol.hpp"
#include "BFSBipartite.h"

using namespace std;
using namespace SpMP;

struct ReorderingInfo {
    int *row_perm, *row_inverse_perm;
    int row_perm_len;
    int *col_perm, *col_inverse_perm;
    int col_perm_len;

    bool cost_benefit_analysis_done;

    ReorderingInfo() :
        row_perm(NULL), row_inverse_perm(NULL), row_perm_len(0),
        col_perm(NULL), col_inverse_perm(NULL), col_perm_len(0),
        cost_benefit_analysis_done(false)
    { }
};

static double bw_threshold_to_reorder = 45*1e9;
    // based on the result in endeavor, needs to be autotuned later

void SetBandwidthThresholdToReorder(double bw)
{
    bw_threshold_to_reorder = bw;
}

// set this true to see important decisions on matrix reordering
static bool LOG_REORDERING = false;
// set this true to see if we're doing transposes which is not cheap.
// we'd like to avoid transpose as much as possible if matrix
// is symmetric or a transposed version of the matrix is already
// available in the application context
static bool LOG_TRANSPOSE = false;

void SetLogLevel(int level)
{
    if (level > 0)
    {
        LOG_REORDERING = true;
        LOG_TRANSPOSE = true;
    }
    else
    {
        LOG_REORDERING = false;
        LOG_TRANSPOSE = false;
    }
}

static double spmp_spmv_time = 0;
static double spmp_trsv_time = 0;

static double knob_spmv_time = 0;
static double knob_trsv_time = 0;

double GetSpMPSpMVTime()
{
    return spmp_spmv_time;
}

void ResetSpMPSpMVTime()
{
    spmp_spmv_time = 0;
}

double GetSpMPTriangularSolveTime()
{
    return spmp_trsv_time;
}

void ResetSpMPTriangularSolveTime()
{
    spmp_trsv_time = 0;
}

double GetKnobSpMVTime()
{
    return knob_spmv_time;
}

void ResetKnobSpMVTime()
{
    knob_spmv_time = 0;
}

double GetKnobTriangularSolveTime()
{
    return knob_trsv_time;
}

void ResetKnobTriangularSolveTime()
{
    knob_trsv_time = 0;
}

// Julia variables' scope is function-wise at AST level, even though in the source
// level, it may appears to have nested scopes. Our Julia compiler creates matrix
// knobs for array variables at the entry of a function, and deleted all
// of them at each exit of the function.
// Also, the Julia compiler creates function knobs for library function call sites at
// the entry of the function, associates it with the related matrix knobs, and
// delete all of them at each exit of the function.

/**************************** Definition of knobs *****************************/

// A matrix knob stores the information shared by all the functions refering to this matrix.
// Function-specific info like a level schedule should be put into a function knob.
struct MatrixKnob {
    bool         constant_valued;     // The matrix is a constant in value(and thus of course constant in structure).
    bool         constant_structured; // A matrix might be changed, and thus its version updated, but its structure might stay the same
    bool         is_symmetric;
    bool         is_structure_symmetric; // is_symmetric implies is_structure_symmetric
    bool         is_structure_only;   // true if structure of matrix is only used
    bool         is_single_def; // The matrix is defined only once.

    MatrixKnob  *derivatives[DERIVATIVE_TYPE_COUNT];
    bool         is_structure_derivatives[DERIVATIVE_TYPE_COUNT];

    MatrixKnob() :
        schedule(NULL), dss_handle(NULL), A(NULL), numrows(0), numcols(0), colptr(NULL), rowval(NULL), nzval(NULL)
    {
        for (int i = 0; i < DERIVATIVE_TYPE_COUNT; i++) {
            derivatives[i] = NULL;
            is_structure_derivatives[i] = false;
        }
    }

    ~MatrixKnob()
    {
        // Delete only the data owned by this matrix knob.
        // ISSUE: it seems that the fields in one matrix knob may be shared
        // by other matrix knobs. And deleting the fields causing segementation
        // fault when deleting the other matrix knobs.
        // TODO: maybe each knob should know which fields it owns, and which it
        // shares and does not own? Then each knob can safely releases the owned
        // fields. But we do not need this functionality for now.
        // if (schedule != NULL) delete schedule;
        // if (A != NULL) DeleteOptimizedRepresentation(this)
    }

    // auxiliary data structure
    LevelSchedule     *schedule;
    _MKL_DSS_HANDLE_t dss_handle;

    // The following fields shouldn't be passed to Julia because it has no idea
    // of their format.
    CSR        * A; // CSC used in Julia is often not be the best performing format. We want to decouple from it by having a shadow copy of the Julia CSC matrix in more optimized representation. For now, we fix it as CSR in SpMP. Later, we need to make it something like union so that we can change the matrix representation depending on the context

    ReorderingInfo reordering_info;

    // These are copied from Julia CSC matrix
    int numrows;
    int numcols;
    int *colptr;
    int *rowval;
    double *nzval;
};

unordered_map<int *, MatrixKnob *> mknob_map; // rowval -> mknob map

// This is the base class of all function knobs
struct FunctionKnob {
    // knobs for the result and matrix arguments of the function, and maybe others
    // like consumers of the function. Each function knob may define this
    // vector in its own way.
    std::vector<MatrixKnob *> mknobs;

    bool is_reordering_decision_maker;
    ReorderingInfo reordering_info;

    FunctionKnob() : is_reordering_decision_maker(false) { }
    ~FunctionKnob()
    {
        // This does not affect the knobs themselves.
        mknobs.clear();
    }
};

/**************************** Usage of knobs *****************************/
// TODO: pass parameters (constant_structured, etc.) to NewMatrixKnob
MatrixKnob* NewMatrixKnob(
    bool constant_valued = false, bool constant_structured = false, bool is_symmetric = false,
    bool is_structure_symmetric = false, bool is_structure_only = false,
    bool is_single_def = false)
{
    // The matrix knob is for a matrix that is constant either in value or
    // structure. Otherwise, it is not useful for now, although in future, we
    // might want to consider slowly changing matrices.

    assert(!constant_valued || constant_structured);
    assert(!is_symmetric || is_structure_symmetric);

    MatrixKnob* m = new MatrixKnob();

    m->constant_valued = constant_valued;
    m->constant_structured = constant_structured;
    m->is_symmetric = is_symmetric;
    m->is_structure_symmetric = is_structure_symmetric;
    m->is_structure_only = is_structure_only;
    m->is_single_def = is_single_def;

    return m;
}

void FillMatrixInfoOnce(MatrixKnob* mknob, int numrows, int numcols, int *colptr, int *rowval, double *nzval)
{
    if (mknob->numrows == 0) {
        // The matrix knob does not have the matrix info yet
        mknob->numrows = numrows;
        mknob->numcols = numcols;
        mknob->colptr = colptr;
        mknob->rowval = rowval;
        mknob->nzval = nzval;
        if (rowval) mknob_map[rowval] = mknob;
    }
}

void DeleteMatrixKnob(MatrixKnob* mknob)
{
    if (mknob != NULL)
    {
        mknob_map.erase(mknob->rowval);
        delete mknob;
    }
}

static bool CheckMatrixKnobConsistency(MatrixKnob *m)
{
    if (m->constant_valued) {
        assert(m->constant_structured);
        if (!m->constant_structured) {
            return false;
        }
    }
    if (m->is_symmetric) {
        assert(m->is_structure_symmetric);
        if (!m->is_structure_symmetric) {
            return false;
        }
    }

    return true;
}

void SetConstantValued(MatrixKnob* mknob)
{
    mknob->constant_valued = true;
    mknob->constant_structured = true;
}

bool IsConstantValued(MatrixKnob* mknob)
{
    return mknob->constant_valued;
}

void SetConstantStructured(MatrixKnob* mknob)
{
    mknob->constant_structured = true;
}

bool IsConstantStructured(MatrixKnob* mknob)
{
    return mknob->constant_structured;
}

void SetValueSymmetric(MatrixKnob *mknob)
{
    mknob->is_symmetric = true;
    mknob->is_structure_symmetric = true;
}

bool IsValueSymmetric(MatrixKnob *mknob)
{
    return mknob->is_symmetric;
}

void SetStructureSymmetric(MatrixKnob *mknob)
{
    mknob->is_structure_symmetric = true;
}

bool IsStructureSymmetric(MatrixKnob *mknob)
{
    return mknob->is_structure_symmetric;
}

void SetStructureOnly(MatrixKnob *mknob)
{
    mknob->is_structure_only = true;
}

bool IsStructureOnly(MatrixKnob *mknob)
{
    return mknob->is_structure_only;
}

void SetMatrix(MatrixKnob* mknob, void* A)
{
    mknob->A = (CSR*) A;
}

void* GetMatrix(MatrixKnob* mknob)
{
    return mknob->A;
}

void SetDssHandle(MatrixKnob* mknob, void* dss_handle)
{
    mknob->dss_handle = dss_handle;
}

void* GetDssHandle(MatrixKnob* mknob)
{
    return mknob->dss_handle;
}

static void DeleteOptimizedRepresentation(MatrixKnob *m)
{
    if (m->A) {
        FREE(m->A->rowptr);
        FREE(m->A->colidx);
        FREE(m->A->values);
        delete m->A;
        m->A = NULL;
    }
}

/**
 * nzval can be NULL, which means we're creating an optimized representation only for structure
 * of the matrix
 */
static void CreateOptimizedRepresentation(
    MatrixKnob *m, int numrows, int numcols, int *colptr, int *rowval, double *nzval)
{
    if (m->A) return;

    // if something is not constant, it's a waste of time to create an optimized representation
    if ((!m->is_structure_only || !m->constant_structured) && !m->constant_valued) {
        fprintf(stderr, "Warning: creating an optimized representation when not needed\n");
        return;
    }
    if (m->is_structure_only && nzval != NULL) {
        fprintf(stderr, "Warning: pass nzval as NULL when we only care about structure\n");
    }

    // If transpose is already available, just us it.
    MatrixKnob *knobTranspose = m->derivatives[DERIVATIVE_TYPE_TRANSPOSE];
    if (knobTranspose && (m->is_structure_only || !m->is_structure_derivatives[DERIVATIVE_TYPE_TRANSPOSE])) {
        if (knobTranspose->numrows != 0) {
            // knobTranspose has been filled with the info of the transposed matrix
            m->A = new CSR(numrows, numcols, knobTranspose->colptr, knobTranspose->rowval, knobTranspose->nzval);
            return;
        }
    }

    // Simply copying CSC to CSR will create a transposed version of original matrix
    CSR *AT = new CSR(numcols, numrows, colptr, rowval, nzval);

    // When compiler tells you matrix must be symmetric, we skip checking symmetry
    bool needTranspose = false;
    if (m->is_structure_only && !m->is_structure_symmetric) {
        needTranspose = !AT->isSymmetric(false);
    }
    if (!m->is_structure_only && !m->is_symmetric) {
        needTranspose = !AT->isSymmetric(true);
    }

    if (needTranspose) {
        double t = omp_get_wtime();
        m->A = AT->transpose();
        if (LOG_TRANSPOSE) {
            t = omp_get_wtime() - t;
            printf("Transposing a matrix takes %g (%g gbps)\n", t, (double)AT->getNnz()*12*2/t/1e9);
        }

#ifndef NDEBUG
        AT->make0BasedIndexing();
        CSR *tempA = AT->transpose();
        tempA->make1BasedIndexing();
        AT->make1BasedIndexing();

        //m->A->print();
        //tempA->print();

        assert(m->A->equals(*tempA, true));
        delete tempA;
#endif

        MatrixKnob *knobTranspose = NewMatrixKnob(m->constant_valued,
                                                  m->constant_structured,
                                                  m->is_symmetric,
                                                  m->is_structure_symmetric,
                                                  m->is_structure_only,
                                                  m->is_single_def);
        FillMatrixInfoOnce(knobTranspose, AT->m, AT->n, AT->rowptr, AT->colidx, AT->values);
        m->derivatives[DERIVATIVE_TYPE_TRANSPOSE] = knobTranspose;
        m->is_structure_derivatives[DERIVATIVE_TYPE_TRANSPOSE] = m->is_structure_only;
        knobTranspose->derivatives[DERIVATIVE_TYPE_TRANSPOSE] = m;
        knobTranspose->is_structure_derivatives[DERIVATIVE_TYPE_TRANSPOSE] = m->is_structure_only;
        knobTranspose->A = AT;
        assert(CheckMatrixKnobConsistency(knobTranspose));
    }
    else {
        m->A = AT;

        // in case the compiler was not able to prove the following facts
        m->is_structure_symmetric = true;
        if (!m->is_structure_only) {
            // in case the compiler was not able to prove the following facts
            m->is_symmetric = true;
        }
    }
}

void SetDerivative(MatrixKnob *mknob, DerivativeType type, MatrixKnob *derivative)
{
    assert(type >= 0 && type < DERIVATIVE_TYPE_COUNT);
    if (DERIVATIVE_TYPE_TRANSPOSE == type || DERIVATIVE_TYPE_SYMMETRIC == type) {
        // no need to set transpose or symmetric version of A if A is symmetric
        assert(!mknob->is_symmetric);
        assert(!mknob->is_structure_only || !mknob->is_structure_symmetric);
    }
    if (mknob->derivatives[type] && !mknob->is_structure_derivatives[type]) {
        fprintf(stderr, "Warning: mknob->derivative[%d] is already set.\n", type);
        return;
    }
    else {
        mknob->derivatives[type] = derivative;
        mknob->is_structure_derivatives[type] = false;
    }

    if (DERIVATIVE_TYPE_TRANSPOSE == type &&
            (!derivative->derivatives[type] || derivative->is_structure_derivatives[type])) {
        derivative->derivatives[type] = mknob;
        derivative->is_structure_derivatives[type] = false;
    }
    if ((DERIVATIVE_TYPE_LOWER_TRIANGULAR == type || DERIVATIVE_TYPE_UPPER_TRIANGULAR == type) &&
            (!derivative->derivatives[DERIVATIVE_TYPE_SYMMETRIC] || derivative->is_structure_derivatives[DERIVATIVE_TYPE_SYMMETRIC])) {
        derivative->derivatives[DERIVATIVE_TYPE_SYMMETRIC] = mknob;
        derivative->is_structure_derivatives[type] = false;
    }
}

MatrixKnob* GetDerivative(MatrixKnob* mknob, DerivativeType type)
{
    assert(type >= 0 && type < DERIVATIVE_TYPE_COUNT);
    return mknob->is_structure_derivatives[type] ? NULL : mknob->derivatives[type];
}

void SetStructureDerivative(MatrixKnob *mknob, DerivativeType type, MatrixKnob *derivative)
{
    assert(type >= 0 && type < DERIVATIVE_TYPE_COUNT);
    if (DERIVATIVE_TYPE_TRANSPOSE == type || DERIVATIVE_TYPE_SYMMETRIC == type) {
        // no need to set transpose or symmetric version of A if A is symmetric
        assert(!mknob->is_structure_symmetric);
    }
    if (mknob->derivatives[type]) {
        // we can overwrite structure derivative with value derivative,
        // but not vicex versa
        fprintf(stderr, "Warning: mknob->derivative[%d] is already set.\n", type);
        return;
    }
    else {
        mknob->derivatives[type] = derivative;
        mknob->is_structure_derivatives[type] = true;
    }

    if (DERIVATIVE_TYPE_TRANSPOSE == type && !derivative->derivatives[type]) {
        derivative->derivatives[type] = mknob;
        derivative->is_structure_derivatives[type] = true;
    }
    if ((DERIVATIVE_TYPE_LOWER_TRIANGULAR == type || DERIVATIVE_TYPE_UPPER_TRIANGULAR == type) && !derivative->derivatives[DERIVATIVE_TYPE_SYMMETRIC]) {
        derivative->derivatives[DERIVATIVE_TYPE_SYMMETRIC] = mknob;
        derivative->is_structure_derivatives[DERIVATIVE_TYPE_SYMMETRIC] = true;
    }
}

MatrixKnob *GetStructureDerivative(MatrixKnob *mknob, DerivativeType type)
{
    assert(type >= 0 && type < DERIVATIVE_TYPE_COUNT);
    return mknob->derivatives[type];
}

void PropagateMatrixInfo(MatrixKnob* to_mknob, MatrixKnob* from_mknob)
{
    assert(to_mknob != NULL);
    assert(from_mknob != NULL);

    // Call to this function is due an assignment matrixA = matrixB. Thus
    // the destination matrix is not constant-valued. But both should be
    // at least constant-structured, otherwise, they are useless.
    // The destination matrix can be a single-def, though, which means it
    // is statically defined only by this source matrix, not anywhere else. In
    // this situation, we can safely let the two matrices share all their
    // information.
    assert(to_mknob->constant_structured && !to_mknob->constant_valued);
    assert(from_mknob->constant_structured || from_mknob->constant_valued);

    // Since the destination matrix is only constant-structured, we can only
    // copy the information that are determined only by structures, unless the
    // destination matrix is a single-def.

    // QUESTION: Schedule and dss_handle should depend only on structure, not value, right?
    if (from_mknob->schedule && !to_mknob->schedule)
        to_mknob->schedule   = from_mknob->schedule;
    if (from_mknob->dss_handle && !to_mknob->dss_handle)
        to_mknob->dss_handle = from_mknob->dss_handle;

    if (to_mknob->is_single_def) {
        to_mknob->A       = from_mknob->A;
        to_mknob->numrows = from_mknob->numrows;
        to_mknob->numcols = from_mknob->numcols;
        to_mknob->colptr  = from_mknob->colptr;
        to_mknob->rowval  = from_mknob->rowval;
        to_mknob->nzval   = from_mknob->nzval;
    }
    // How about derivatives?
    // Jongsoo: please see what to do here to be complete.
}

void AddMatrixKnob(FunctionKnob* fknob, MatrixKnob* mknob)
{
    assert(fknob != NULL);
    assert(mknob != NULL);
    fknob->mknobs.push_back(mknob);
}

MatrixKnob* GetMatrixKnob(FunctionKnob* fknob, int i)
{
    return fknob->mknobs[i];
}

FunctionKnob* NewFunctionKnob()
{
    return new FunctionKnob;
}

void DeleteFunctionKnob(FunctionKnob* fknob)
{
    if (fknob != NULL) delete fknob;
}

static double getWidthAfterPermutation(const CSR *A, const int *col_perm)
{
    int base = A->getBase();
    const int *rowptr = A->rowptr - base;
    const int *colidx = A->colidx - base;
    col_perm -= base;

    unsigned long long total_width = 0;

#pragma omp parallel reduction(+:total_width)
    {
        int iBegin, iEnd;
        getLoadBalancedPartition(&iBegin, &iEnd, rowptr + base, A->m);
        iBegin += base;
        iEnd += base;

        for (int i = iBegin; i < iEnd; ++i) {
            if (rowptr[i] == rowptr[i + 1]) continue;

            int min_row = INT_MAX, max_row = INT_MIN;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
                int c = col_perm[colidx[j]];
                min_row = min(c, min_row);
                max_row = max(c, max_row);
            }

            int width = max_row - min_row;
            total_width += width;
        }
    } // omp parallel

    return (double)total_width/A->m;
}

template<class T>
T *getTempVector(int l)
{
    static T *temp_vector = NULL;
    static int temp_vector_len = -1;

    if (!temp_vector) {
        temp_vector = (T *)malloc(sizeof(T)*l);
        temp_vector_len = l;
    }
    else if (l > temp_vector_len) {
        temp_vector = (T *)realloc(temp_vector, sizeof(T)*l);
        temp_vector_len = l;
    }

    return temp_vector;
}

template<class T>
void reorderVectorWithInversePermInplace_(T *v, const int *inversePerm, int len)
{
    T *temp = getTempVector<T>(len);

    if (inversePerm) {
#pragma omp parallel for
        for (int i = 0; i < len; ++i) {
            assert(inversePerm[i] >= 0 && inversePerm[i] < len);
            temp[i] = v[inversePerm[i]];
        }
#pragma omp parallel for
        for (int i = 0; i < len; ++i) {
            v[i] = temp[i];
        }
    }
}

void reorderVectorWithInversePermInplace(double *v, const int *inversePerm, int len)
{
    reorderVectorWithInversePermInplace_(v, inversePerm, len);
}

void multiplyWithVector(
  double *w,
  double alpha, const CSR *A, const double *x,
  double beta, const double *y,
  double gamma,
  const double *z);

void multiplyWithVector(
  double _Complex *w,
  double alpha, const CSR *A, const double _Complex *x,
  double beta, const double _Complex *y,
  double gamma,
  const double _Complex *z);

template<class T> // T: vector type
void SpMV_(
    int m, int n,
    T *w,
    double alpha,
    int *A_colptr, int *A_rowval, double *A_nzval,
    T *x,
    double beta,
    T *y,
    double gamma,
    T *z,
    FunctionKnob *fknob)
{
    knob_spmv_time -= omp_get_wtime();

    assert(fknob);
    MatrixKnob *mknob = GetMatrixKnob(fknob, 0);
    assert(mknob);
    assert(mknob->constant_valued);

    CreateOptimizedRepresentation(
        mknob, m, n, A_colptr, A_rowval,
        mknob->is_structure_only ? NULL : A_nzval);

    assert(mknob->A);

    double current_spmv_time = -omp_get_wtime();
    if (w == x) {
        T *temp_vector = getTempVector<T>(n);

#pragma omp parallel for
        for (int i = 0; i < n; ++i) {
            temp_vector[i] = x[i];
        }

        multiplyWithVector(w, alpha, mknob->A, temp_vector, beta, y, gamma, z);
    }
    else {
        multiplyWithVector(w, alpha, mknob->A, x, beta, y, gamma, z);
    }
    current_spmv_time += omp_get_wtime();
    spmp_spmv_time += current_spmv_time;

    if (fknob->is_reordering_decision_maker &&
            !fknob->reordering_info.cost_benefit_analysis_done &&
            fknob->reordering_info.row_inverse_perm == NULL) {

        fknob->reordering_info.cost_benefit_analysis_done = true;

        double bw = ((mknob->A->values ? 12. : 4.)*mknob->A->getNnz() + 8.*(mknob->A->m + mknob->A->n))/current_spmv_time;
        if (LOG_REORDERING) {
            printf("SpMV: reordering decision maker. BW measured is %g gbps\n", bw/1e9);
        }

        if (bw < bw_threshold_to_reorder) {
            double old_width_time = -omp_get_wtime();
            double old_w = m != n ? 1 : mknob->A->getAverageWidth(true);
                // don't compute width for rectangular matrices because it's ill-defined
            old_width_time += omp_get_wtime();

            fknob->reordering_info.row_inverse_perm = MALLOC(int, m);
            fknob->reordering_info.col_perm = MALLOC(int, n);

            if (LOG_REORDERING) {
                printf("SpMV: permute matrix and input vector\n");
            }

            if (m != n) {
                CSR AT(n, m, A_colptr, A_rowval, A_nzval);

                fknob->reordering_info.row_perm = MALLOC(int, m);
                fknob->reordering_info.col_inverse_perm = MALLOC(int, n);

                double t = omp_get_wtime();
                bfsBipartite(
                    *mknob->A, AT,
                    fknob->reordering_info.row_perm,
                    fknob->reordering_info.row_inverse_perm,
                    fknob->reordering_info.col_perm,
                    fknob->reordering_info.col_inverse_perm);
                if (LOG_REORDERING) {
                    t = omp_get_wtime() - t;
                    printf("SpMV: matrix is rectangular. bfsBipartite takes %g (%g gbps)\n", t, ((double)mknob->A->getNnz()*4 + m*4*8)/t/1e9);
                }
            }
            else {
                double t = omp_get_wtime();
                mknob->A->getBFSPermutation(
                    fknob->reordering_info.col_perm,
                    fknob->reordering_info.row_inverse_perm);
                fknob->reordering_info.row_perm = fknob->reordering_info.col_perm;
                fknob->reordering_info.col_inverse_perm = fknob->reordering_info.row_inverse_perm;
                t = omp_get_wtime() - t;
                if (LOG_REORDERING) {
                    printf("SpMV: matrix is square. bfs takes %g (%g gbps)\n", t, ((double)mknob->A->getNnz()*4 + m*6*8)/t/1e9);
                }
            }

            double new_width_time = -omp_get_wtime();
            double new_w = m != n ? 0 : getWidthAfterPermutation(mknob->A, fknob->reordering_info.col_perm);
                // don't compute width for rectangular matrices because it's ill-defined
            new_width_time += omp_get_wtime();
            if (LOG_REORDERING) {
                printf("SpMV: old_width = %g, new_width = %g, old_width takes %g sec new_width takes %g sec\n", old_w, new_w, old_width_time, new_width_time);
            }

            if (new_w/old_w < 1.2) {
                double t = omp_get_wtime();
                mknob->A = mknob->A->permute(
                    fknob->reordering_info.col_perm,
                    fknob->reordering_info.row_inverse_perm);

                fknob->reordering_info.row_perm_len = m;
                fknob->reordering_info.col_perm_len = n;

                mknob->reordering_info = fknob->reordering_info;

                reorderVectorWithInversePermInplace_<T>(
                    x, fknob->reordering_info.col_inverse_perm, n);
                if (y && y != x)
                    reorderVectorWithInversePermInplace_<T>(
                        y, fknob->reordering_info.row_inverse_perm, m);
                if (z && z != x && z != y)
                    reorderVectorWithInversePermInplace_<T>(
                        z, fknob->reordering_info.row_inverse_perm, m);
                if (w != x && w != y && w != z)
                    reorderVectorWithInversePermInplace_<T>(
                        w, fknob->reordering_info.row_inverse_perm, m);

                if (LOG_REORDERING) {
                    t = omp_get_wtime() - t;

                    printf("SpMV: row_perm=%p row_inverse_perm=%p col_perm=%p col_inverse_perm=%p\n", fknob->reordering_info.row_perm, fknob->reordering_info.row_inverse_perm, fknob->reordering_info.col_perm, fknob->reordering_info.col_inverse_perm);
                    printf("SpMV: permutation takes %g (%g gbps)\n", t, ((double)mknob->A->getNnz()*2*12 + m*6*8)/t/1e9);
                }
            }
            else {
                if (fknob->reordering_info.row_perm != fknob->reordering_info.col_perm)
                    FREE(fknob->reordering_info.row_perm);
                fknob->reordering_info.row_perm = NULL;
                if (fknob->reordering_info.col_inverse_perm != fknob->reordering_info.row_inverse_perm)
                    FREE(fknob->reordering_info.col_inverse_perm);
                fknob->reordering_info.col_inverse_perm = NULL;
                FREE(fknob->reordering_info.col_perm);
                FREE(fknob->reordering_info.row_inverse_perm);
            }
        }
    }

    knob_spmv_time += omp_get_wtime();
}

void SpMV(
    int m, int n,
    double *w,
    double alpha,
    int *A_colptr, int *A_rowval, double *A_nzval,
    double *x,
    double beta,
    double *y,
    double gamma,
    double *z,
    FunctionKnob *fknob)
{
    return SpMV_<double>(m, n, w, alpha, A_colptr, A_rowval, A_nzval, x, beta, y, gamma, z, fknob);
}

void SpMVComplex(
    int m, int n,
    double _Complex *w,
    double alpha,
    int *A_colptr, int *A_rowval, double *A_nzval,
    double _Complex *x,
    double beta,
    double _Complex *y,
    double gamma,
    double _Complex *z,
    FunctionKnob *fknob)
{
    return SpMV_<double _Complex>(m, n, w, alpha, A_colptr, A_rowval, A_nzval, x, beta, y, gamma, z, fknob);
}

static void TriangularSolve_(
    int L_numrows, int L_numcols, int* L_colptr, int* L_rowval, double* L_nzval,
    double *y, double *b, FunctionKnob* fknob,
    void (*solveFunction)(CSR&, double *, const double *, const LevelSchedule&),
    void (*solveFunctionWithReorderedMatrix)(CSR&, double *, const double *, const LevelSchedule&))
{
    knob_trsv_time -= omp_get_wtime();

    CSR* L = NULL;
    bool needToDeleteL = false;

    LevelSchedule* schedule = NULL;
    bool needToDeleteSchedule = false;

    MatrixKnob *m = NULL;

    if (fknob) {
        assert(fknob->mknobs.size() == 1);
        m = fknob->mknobs[0]; // This is the matrix knob for L or U
        assert(m != NULL);

        if ((m->schedule || m->derivatives[DERIVATIVE_TYPE_SYMMETRIC] && m->derivatives[DERIVATIVE_TYPE_SYMMETRIC]->schedule) && m->constant_structured) {
            // matrix has constant structure so reuse already available schedule
            if (m->schedule) schedule = m->schedule;
            else {
                schedule = m->derivatives[DERIVATIVE_TYPE_SYMMETRIC]->schedule;
                m->schedule = schedule;
            }
        } else if (m->constant_structured) {
            // if schedule is not available construct it
            if (m->constant_valued) {
                // if it's constant valued, also save a shadow optimized representation
                CreateOptimizedRepresentation(m, L_numrows, L_numcols, L_colptr, L_rowval, L_nzval);
                L = m->A;
            }

            MatrixKnob *symKnob = m->derivatives[DERIVATIVE_TYPE_SYMMETRIC];
            if (symKnob && (symKnob->A || symKnob->colptr)) {
                // if structurally symmetric version of this matrix is available use it for
                // constructing schedule
                CreateOptimizedRepresentation(symKnob, L_numrows, L_numcols, symKnob->colptr, symKnob->rowval, NULL);
                schedule = new LevelSchedule;
                double t = omp_get_wtime();
                schedule->constructTaskGraph(*symKnob->A);
                if (LOG_REORDERING) {
                    t = omp_get_wtime() - t;
                    printf("TriangularSolve: constructTaskGraph takes %g (%g gbps)\n", t, (double)symKnob->A->getNnz()*4/t/1e9);
                }
                m->derivatives[DERIVATIVE_TYPE_SYMMETRIC]->schedule = schedule;
                m->schedule = schedule;
            } else if (m->A) {
                // if structurally symmetric version is not available, we have to construct it
                schedule = new LevelSchedule;

                int *symRowPtr = NULL, *symColIdx = NULL, *symDiagPtr = NULL, *symExtPtr = NULL;
                double t = omp_get_wtime();
                // ISSUE: if L is lower part of A, and A is symmetric, then it
                // seems to be assumed that A's matrix info has already been
                // filled into A's knob. This assumption does not always hold.
                bool wasSymmetric = getSymmetricNnzPattern(
                    m->A, &symRowPtr, &symDiagPtr, &symExtPtr, &symColIdx);
                if (LOG_REORDERING) {
                    t = omp_get_wtime() - t;
                    printf("TriangularSolve: matrix is not structurally symmetric. getSymmetricNnzPattern takes %g (%g gbps)\n", t, (double)m->A->getNnz()*4*2/t/1e9);
                }

                t = omp_get_wtime();
                if (wasSymmetric) {
                    FREE(symRowPtr);
                    FREE(symColIdx);
                    FREE(symDiagPtr);
                    FREE(symExtPtr);

                    schedule->constructTaskGraph(*m->A);
                } else {
                    schedule->constructTaskGraph(
                       m->A->m,
                       symRowPtr, symDiagPtr, symExtPtr, symColIdx,
                       PrefixSumCostFunction(symRowPtr));

                    if (!symKnob) {
                        symKnob = NewMatrixKnob(m->constant_valued,
                                                m->constant_structured,
                                                m->is_symmetric,
                                                m->is_structure_symmetric,
                                                true /* is_structure_only */,
                                                m->is_single_def
                        );
                        FillMatrixInfoOnce(symKnob, m->A->m, m->A->n, NULL, NULL, NULL);
                        m->derivatives[DERIVATIVE_TYPE_SYMMETRIC] = symKnob;
                        m->is_structure_derivatives[DERIVATIVE_TYPE_SYMMETRIC] = true;
                    }
                    symKnob->A = new CSR(m->A->m, m->A->n, symRowPtr, symColIdx, NULL);
                    symKnob->schedule = schedule;

                    FREE(symDiagPtr);
                    FREE(symExtPtr);
                }

                if (LOG_REORDERING) {
                    t = omp_get_wtime() - t;
                    printf("TriangularSolve: constructTaskGraph takes %g (%g gbps)\n", t, (double)m->A->getNnz()*4/t/1e9);
                }

                m->schedule = schedule;
            }
        } // constant_structured
    } // fknob != NULL

    if (!schedule && !L) {
        CSR *LT = new CSR(L_numrows, L_numcols, L_colptr, L_rowval, L_nzval);
        needToDeleteL = true;

        schedule = new LevelSchedule;
        needToDeleteSchedule = true;

        double t = omp_get_wtime();

        int *symRowPtr = NULL, *symColIdx = NULL, *symDiagPtr = NULL, *symExtPtr = NULL;
        bool wasSymmetric = getSymmetricNnzPattern(
            LT, &symRowPtr, &symDiagPtr, &symExtPtr, &symColIdx);

        if (LOG_REORDERING) {
            t = omp_get_wtime() - t;
            printf("TriangularSolve: matrix is not structurally symmetric. getSymmetricNnzPattern takes %g (%g gbps)\n", t, (double)LT->getNnz()*4*2/t/1e9);
        }

        if (wasSymmetric) {
            FREE(symRowPtr);
            FREE(symColIdx);

            L = LT;
            t = omp_get_wtime();
            schedule->constructTaskGraph(*L);
            if (LOG_REORDERING) {
                t = omp_get_wtime() - t;
                printf("TriangularSolve: constructTaskGraph takes %g (%g gbps)\n", t, (double)L->getNnz()*4/t/1e9);
            }

            if (m && m->constant_structured) {
                m->schedule = schedule;
                needToDeleteSchedule = false;
            }
        }
        else {
            t = omp_get_wtime();
            schedule->constructTaskGraph(
               LT->m,
               symRowPtr, symDiagPtr, symExtPtr, symColIdx,
               PrefixSumCostFunction(symRowPtr));
            if (LOG_REORDERING) {
                t = omp_get_wtime() - t;
                printf("TriangularSolve: constructTaskGraph takes %g (%g gbps)\n", t, (double)LT->getNnz()*4/t/1e9);
            }

            t = omp_get_wtime();
            L = LT->transpose();
            delete LT;

            if (LOG_TRANSPOSE) {
                t = omp_get_wtime() - t;
                printf("Transposing a matrix takes %g (%g gbps)\n", t, (double)LT->getNnz()*12*2/t/1e9);
            }

            if (m && m->constant_structured) {
                MatrixKnob *symKnob = m->derivatives[DERIVATIVE_TYPE_SYMMETRIC];
                if (!symKnob) {
                    symKnob = NewMatrixKnob(m->constant_valued,
                                            m->constant_structured,
                                            m->is_symmetric,
                                            m->is_structure_symmetric,
                                            true /* is_structure_only */,
                                            m->is_single_def
                                            );
                    FillMatrixInfoOnce(symKnob, m->A->m, m->A->n, NULL, NULL, NULL);
                    m->derivatives[DERIVATIVE_TYPE_SYMMETRIC] = symKnob;
                    m->is_structure_derivatives[DERIVATIVE_TYPE_SYMMETRIC] = true;
                }
                symKnob->A = new CSR(m->A->m, m->A->n, symRowPtr, symColIdx, NULL);
                symKnob->schedule = schedule;
                m->schedule = schedule;
                needToDeleteSchedule = false;
            } else {
                FREE(symRowPtr);
                FREE(symColIdx);
            }
        }

        FREE(symDiagPtr);
        FREE(symExtPtr);
    } else if (!L) {
        if (m->constant_valued) {
            CreateOptimizedRepresentation(m, L_numrows, L_numcols, L_colptr, L_rowval, L_nzval);
            L = m->A;
        } else if (m->is_symmetric) {
            L = new CSR(L_numrows, L_numcols, L_colptr, L_rowval, L_nzval);
            needToDeleteL = true;
        } else {
            CSR *LT = new CSR(L_numrows, L_numcols, L_colptr, L_rowval, L_nzval);
            double t = omp_get_wtime();
            L = LT->transpose();
            delete LT;

            if (LOG_TRANSPOSE) {
                t = omp_get_wtime() - t;
                printf("Transposing a matrix takes %g (%g gbps)\n", t, (double)LT->getNnz()*12*2/t/1e9);
            }

            needToDeleteL = true;
        }
    }

    if (m && m->schedule && m->A) {
        fknob->reordering_info.col_perm = m->schedule->origToThreadContPerm;
        fknob->reordering_info.row_perm = m->schedule->origToThreadContPerm;
        fknob->reordering_info.row_inverse_perm = m->schedule->threadContToOrigPerm;
        fknob->reordering_info.col_inverse_perm = m->schedule->threadContToOrigPerm;
        fknob->reordering_info.row_perm_len = m->A->m;
        fknob->reordering_info.col_perm_len = m->A->n;
        assert(m->A->m == m->A->n);

        if (m->reordering_info.row_perm != fknob->reordering_info.row_perm &&
                !fknob->reordering_info.cost_benefit_analysis_done &&
                fknob->is_reordering_decision_maker) {

            fknob->reordering_info.cost_benefit_analysis_done = true;

            double t = omp_get_wtime();

            m->A->constructDiagPtr();
            m->A = m->A->permute(
                fknob->reordering_info.col_perm,
                fknob->reordering_info.row_inverse_perm);

            m->reordering_info = fknob->reordering_info;

            double *temp_vector = getTempVector<double>(L->m);

            reorderVectorWithInversePermInplace(
                b, fknob->reordering_info.col_inverse_perm, L->m);

            if (LOG_REORDERING) {
                t = omp_get_wtime() - t;

                printf("TriangularSolve triSolve is reordering decision maker. Permute matrix and input vector\n");
                printf("TriangularSolve: row_perm=%p row_inverse_perm=%p col_perm=%p col_inverse_perm=%p\n", fknob->reordering_info.row_perm, fknob->reordering_info.row_inverse_perm, fknob->reordering_info.col_perm, fknob->reordering_info.col_inverse_perm);
                printf("TriangularSolve: permutation takes %g (%g gbps)\n", t, ((double)m->A->getNnz()*2*12 + m->A->m*2*8)/t/1e9);
            }

            L = m->A;
        }
    }

    assert(L != NULL);
    assert(schedule != NULL);

    spmp_trsv_time -= omp_get_wtime();
    if (fknob->reordering_info.row_inverse_perm == m->reordering_info.row_inverse_perm) {
        (*solveFunctionWithReorderedMatrix)(*L, y, b, *schedule);
    }
    else {
        assert(m->reordering_info.row_inverse_perm == NULL);
        (*solveFunction)(*L, y, b, *schedule);
    }
    spmp_trsv_time += omp_get_wtime();

    if (needToDeleteSchedule) {
        delete schedule;
    }
    if (needToDeleteL) {
        delete L;
    }

    knob_spmv_time += omp_get_wtime();
}

void ForwardTriangularSolve(
    int numrows, int numcols, int* colptr, int* rowval, double* nzval,
    double *y, double *b, FunctionKnob* fknob)
{
    TriangularSolve_(
        numrows, numcols, colptr, rowval, nzval, y, b, fknob,
        &forwardSolve,
        &forwardSolveWithReorderedMatrix);
}

void BackwardTriangularSolve(
    int numrows, int numcols, int* colptr, int* rowval, double* nzval,
    double *y, double *b, FunctionKnob* fknob)
{
    TriangularSolve_(
        numrows, numcols, colptr, rowval, nzval, y, b, fknob,
        &backwardSolve,
        &backwardSolveWithReorderedMatrix);
}

static bool reuse_inspection                = true;
static bool collective_structure_prediction = true;

void SetReuseInspection(bool reuse)
{
    reuse_inspection = reuse;
}

void SetCollectiveStructurePrediction(bool collective)
{
    collective_structure_prediction = collective;
}

void *CholFact(
    int m, int n, int *colptr, int *rowval, double *nzval,
    FunctionKnob *fknob)
{
    assert(fknob);

    MatrixKnob *mknob_A = fknob->mknobs[0];
    assert(mknob_A);
    assert(mknob_A->constant_structured);

    if (!mknob_A->dss_handle) {
        MKL_INT opt = MKL_DSS_DEFAULTS;
        MKL_INT error = dss_create(mknob_A->dss_handle, opt);
        if (error != MKL_DSS_SUCCESS) {
            fprintf(stderr, "dss_create returned error code %d\n", error);
        }

        opt = MKL_DSS_NON_SYMMETRIC;
        int nnz = colptr[n] - 1;
        error = dss_define_structure(mknob_A->dss_handle, opt, colptr, m, m, rowval, nnz);
        if (error != MKL_DSS_SUCCESS) {
            fprintf(stderr, "dss_define_structure returned error code %d\n", error);
        }

        opt = MKL_DSS_AUTO_ORDER;
        error = dss_reorder(mknob_A->dss_handle, opt, NULL);
        if (error != MKL_DSS_SUCCESS) {
            fprintf(stderr, "dss_reorder returned error code %d\n", error);
        }
    }

    MKL_INT opt = MKL_DSS_DEFAULTS;
    MKL_INT error = dss_factor_real(mknob_A->dss_handle, opt, nzval);
    if (error != MKL_DSS_SUCCESS) {
        fprintf(stderr, "dss_factor_real returned error code %d\n", error);
    }

    void *ret= mknob_A->dss_handle;
    if (!reuse_inspection || !collective_structure_prediction) {
        mknob_A->dss_handle = NULL;
    }
    return ret;
}

void CholFactInverseDivide(
    void *factor, double *y, double *b, FunctionKnob *fknob)
{
    assert(factor);
    _MKL_DSS_HANDLE_t dss_handle = (_MKL_DSS_HANDLE_t)factor;

    MKL_INT opt = MKL_DSS_DEFAULTS;
    int nrhs = 1;
    MKL_INT error = dss_solve_real(dss_handle, opt, b, nrhs, y);
    if (error != MKL_DSS_SUCCESS) {
        fprintf(stderr, "dss_solve_real returned error code %d\n", error);
    }
}

// C = A*D*B
// A is m*k matrix
// B is k*n matrix
// C is m*n matrix
void ADB(
    int m, int n, int k,
    int **C_colptr, int **C_rowval, double **C_nzval,
    int *A_colptr, int *A_rowval, double *A_nzval,
    int *B_colptr, int *B_rowval, double *B_nzval,
    const double *d,
    FunctionKnob *fknob)
{
    MatrixKnob *mknob_C = GetMatrixKnob(fknob, 0);
    MatrixKnob *mknob_A = GetMatrixKnob(fknob, 1);
    MatrixKnob *mknob_D = GetMatrixKnob(fknob, 2);
    MatrixKnob *mknob_B = GetMatrixKnob(fknob, 3);

    // By simply casting CSC as CSR, we get transposes of A and B.
    // Computing B'*D*A' gives (A*D*B)', so simply casting back the result
    // back as CSC will give the desired result, A*D*B.
    CSR *AT = new CSR(k, m, A_colptr, A_rowval, A_nzval);
    CSR *BT = new CSR(n, k, B_colptr, B_rowval, B_nzval);

    if (!mknob_C->A) {
        if (*C_colptr) {
            assert(*C_rowval);
            assert(*C_nzval);

            // Use memory passed from Julia, meaning
            // Julia uses in-place interface.
            mknob_C->A = new CSR(n, m, *C_colptr, *C_rowval, *C_nzval);
            inspectADB(mknob_C->A, BT, AT);
        }
        else {
            assert(!*C_rowval);
            assert(!*C_nzval);

            // Create memory inside
            mknob_C->A = inspectADB(BT, AT);
        }
    }

    adb(mknob_C->A, BT, AT, d);

    if (*C_colptr) {
        assert(*C_colptr == mknob_C->A->rowptr);
        assert(*C_rowval == mknob_C->A->colidx);
        assert(*C_nzval == mknob_C->A->values);
    }
    else {
        assert(!*C_rowval);
        assert(!*C_nzval);

        *C_colptr = mknob_C->A->rowptr;
        *C_rowval = mknob_C->A->colidx;
        *C_nzval = mknob_C->A->values;
    }

    if (!reuse_inspection || !collective_structure_prediction) {
        mknob_C->A = NULL;
    }
}

void ILU(
    int m, int n,
    int *A_colptr, int *A_rowval, double *A_nzval,
    double *LU_nzval,
    FunctionKnob *fknob)
{
    CSR *A = new CSR(m, n, A_colptr, A_rowval, A_nzval);
    LevelSchedule *schedule = new LevelSchedule;
    schedule->constructTaskGraph(*A);
    ilu0(LU_nzval, *A, *schedule);
    delete schedule;
    delete A;
}

void IChol(
    int m, int n,
    int *A_colptr, int *A_rowval, double *A_nzval,
    double *L_nzval,
    FunctionKnob *fknob)
{
    CSR *A = new CSR(m, n, A_colptr, A_rowval, A_nzval);
    LevelSchedule *schedule = new LevelSchedule;
    schedule->constructTaskGraph(*A);
    ichol0(*A, L_nzval, *schedule);
    delete schedule;
    delete A;
}

void SpSquareWithEps(
    int m, int n,
    int **C_colptr, int **C_rowval, double **C_nzval,
    int *A_colptr, int *A_rowval, double *A_nzval,
    double eps,
    FunctionKnob *fknob)
{
    CSR AT(n, m, A_colptr, A_rowval, A_nzval);

    CSR *A;
    if (fknob && fknob->mknobs[0] && fknob->mknobs[0]->is_symmetric) {
        A = &AT;
    }
    else {
        double t = omp_get_wtime();

        A = AT.transpose();

        if (LOG_TRANSPOSE) {
            t = omp_get_wtime() - t;
            printf("Transposing a matrix takes %g (%g gbps)\n", t, (double)AT.getNnz()*12*2/t/1e9);
        }
    }

    CSR *C = SpGEMMWithEps(A, &AT, eps);

    if (A != &AT) {
        delete A;
    }

    *C_colptr = C->rowptr;
    *C_rowval = C->colidx;
    *C_nzval = C->values;
}

void SpAdd(
    int m, int n,
    int **C_colptr, int **C_rowval, double **C_nzval,
    double alpha,
    int *A_colptr, int *A_rowval, double *A_nzval,
    double beta,
    int *B_colptr, int *B_rowval, double *B_nzval,
    FunctionKnob *fknob)
{
    CSR AT(n, m, A_colptr, A_rowval, A_nzval);
    CSR BT(n, m, B_colptr, B_rowval, B_nzval);
    // It doesn't matter if we do matrix addition in CSR or CSC
    CSR *C = SpAdd(alpha, &AT, beta, &BT);

    *C_colptr = C->rowptr;
    *C_rowval = C->colidx;
    *C_nzval = C->values;
}

double Trace(int n, int *A_colptr, int *A_rowval, double *A_nzval)
{
    double trace = 0;
#pragma omp parallel for reduction(+:trace)
    for (int i = 0; i < n; ++i) {
        for (int j = A_colptr[i] - 1; j < A_colptr[i + 1] - 1; ++j) {
            if (A_rowval[j] - 1 == i) {
                trace += A_nzval[j];
            }
        }
    }
    return trace;
}

void SetReorderingDecisionMaker(FunctionKnob *fknob, int perm_restriction)
{
    // TODO: see how to make use of the restriction parameter.
    fknob->is_reordering_decision_maker = true;
}

int *GetRowReorderingVector(FunctionKnob *fknob, int *len)
{
    *len = fknob->reordering_info.row_perm_len;
    return fknob->reordering_info.row_perm;
}

int *GetRowInverseReorderingVector(FunctionKnob *fknob, int *len)
{
    *len = fknob->reordering_info.row_perm_len;
    return fknob->reordering_info.row_inverse_perm;
}

int *GetColReorderingVector(FunctionKnob *fknob, int *len)
{
    *len = fknob->reordering_info.col_perm_len;
    return fknob->reordering_info.col_perm;
}

int *GetColInverseReorderingVector(FunctionKnob *fknob, int *len)
{
    *len = fknob->reordering_info.col_perm_len;
    return fknob->reordering_info.col_inverse_perm;
}

void ReorderMatrixInplace(int numRows, int numCols, int *colptr, int *rowval, double *nzval,
                 int *perm, int *inversePerm)
{
    assert(perm);
    assert(inversePerm);

    CSR AT(numCols, numRows, colptr, rowval, nzval);
    CSR newAT(AT);

    newAT.permuteRowptr(&AT, inversePerm);
    newAT.permuteMain(&AT, perm, inversePerm);

    if (LOG_REORDERING) {
        printf("CSR_ReorderMatrix: perm=%p inversePerm=%p\n", perm, inversePerm);
    }

    auto itr = mknob_map.find(rowval);
    if (itr != mknob_map.end()) {
        if (LOG_REORDERING) {
            printf("CSR_ReorderMatrix: a related matrix knob found. Set its reordering information\n");
        }

        itr->second->reordering_info.row_perm = perm;
        itr->second->reordering_info.col_perm = perm;
        itr->second->reordering_info.col_inverse_perm = inversePerm;
        itr->second->reordering_info.row_inverse_perm = inversePerm;
        itr->second->reordering_info.row_perm_len = numRows;
        itr->second->reordering_info.col_perm_len = numCols;

        if (itr->second->A) {
            if (LOG_REORDERING) {
                printf("CSR_ReorderMatrix: an optimized matrix representation found. Update it.\n");
            }

            itr->second->A = NULL;
            CreateOptimizedRepresentation(
                itr->second, numRows, numCols, colptr, rowval, nzval);
        }
    }
}

void ReorderMatrix(int numRows, int numCols, int *colptr, int *rowval, double *nzval, int *colptr_out, int *rowval_out, double *nzval_out,
                 int *perm, int *inversePerm)
{
    // The original and the result array space must be different
    assert(colptr != colptr_out);
    assert(rowval != rowval_out);
    assert(nzval != nzval_out);

    assert(perm);
    assert(inversePerm);

    CSR AT(numCols, numRows, colptr, rowval, nzval);
    CSR newAT(numCols, numRows, colptr_out, rowval_out, nzval_out);

    AT.permuteRowptr(&newAT, inversePerm);
    AT.permuteMain(&newAT, perm, inversePerm);

    if (LOG_REORDERING) {
        printf("CSR_ReorderMatrix: perm=%p inversePerm=%p\n", perm, inversePerm);
    }

    auto itr = mknob_map.find(rowval);
    if (itr != mknob_map.end()) {
        if (LOG_REORDERING) {
            printf("CSR_ReorderMatrix: a related matrix knob found. Set its reordering information\n");
        }

        itr->second->reordering_info.row_perm = perm;
        itr->second->reordering_info.col_perm = perm;
        itr->second->reordering_info.col_inverse_perm = inversePerm;
        itr->second->reordering_info.row_inverse_perm = inversePerm;
        itr->second->reordering_info.row_perm_len = numRows;
        itr->second->reordering_info.col_perm_len = numCols;

        mknob_map[rowval_out] = itr->second;

        itr->second->colptr = colptr_out;
        itr->second->rowval = rowval_out;
        itr->second->nzval = nzval_out;

        if (itr->second->A) {
            if (LOG_REORDERING) {
                printf("CSR_ReorderMatrix: an optimized matrix representation found. Update it.\n");
            }

            itr->second->A = NULL;
            CreateOptimizedRepresentation(
                itr->second, numRows, numCols, colptr_out, rowval_out, nzval_out);
        }
    }
}

/* vim: set tabstop=8 softtabstop=4 sw=4 expandtab: */


text:
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import           Control.Concurrent.Async
import           Control.Monad
import           Database.MySQL.Base
import           System.Environment
import           System.IO.Streams        (fold)
import  qualified Data.ByteString as B

main :: IO ()
main = do
    args <- getArgs
    case args of [threadNum] -> go (read threadNum)
                 _ -> putStrLn "No thread number provided."

go :: Int -> IO ()
go n = void . flip mapConcurrently [1..n] $ \ _ -> do
    c <- connect defaultConnectInfo { ciUser = "testMySQLHaskell"
                                    , ciDatabase = "testMySQLHaskell"
                                    }

    stmt <- prepareStmt c "SELECT * FROM employees"
    (fs, is) <- queryStmt c stmt []
    (rowCount :: Int) <- fold (\s _ -> s+1) 0 is
    putStr "field name: "
    forM_ fs $ \ f -> B.putStr (columnName f) >> B.putStr ", "
    putStr "\n"
    putStr "numbers of rows: "
    print rowCount


text:
@class LDMItem, LDMQueryFilter, LDMDataGridStyle;

@interface LDKDataGridCollectionViewCell : LDKEditDetailCollectionViewCell <LDKNewDataGridViewDelegate>

@property (nonatomic, strong) LDMItem *dataGridDef;
@property (nonatomic, strong) LDMDataGridStyle *dataGridStyle;
@property (nonatomic, strong) LDMQueryFilter *filter;
@property (nonatomic, strong) LDMQueryFilter *search;
@property (unsafe_unretained, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet LDKNewDataGridView *dataGridView;
@property (nonatomic, strong) NSString *functionId;

@end


text:
/**
 * @author sunag / http://www.sunag.com.br/
 */

import { TempNode } from '../core/TempNode.js';
import { FloatNode } from '../inputs/FloatNode.js';
import { ExpressionNode } from '../core/ExpressionNode.js';
import { TextureCubeUVNode } from './TextureCubeUVNode.js';
import { ReflectNode } from '../accessors/ReflectNode.js';
import { NormalNode } from '../accessors/NormalNode.js';
import { ColorSpaceNode } from '../utils/ColorSpaceNode.js';
import { BlinnExponentToRoughnessNode } from '../bsdfs/BlinnExponentToRoughnessNode.js';

function TextureCubeNode( value, textureSize ) {

	TempNode.call( this, 'v4' );

	this.value = value;
	this.textureSize = textureSize || new FloatNode( 1024 );

	this.radianceCache = { uv: new TextureCubeUVNode(
		new ReflectNode( ReflectNode.VECTOR ),
		this.textureSize,
		new BlinnExponentToRoughnessNode()
	) };

	this.irradianceCache = { uv: new TextureCubeUVNode(
		new NormalNode( NormalNode.WORLD ),
		this.textureSize,
		new FloatNode( 1 ).setReadonly( true )
	) };

}

TextureCubeNode.prototype = Object.create( TempNode.prototype );
TextureCubeNode.prototype.constructor = TextureCubeNode;
TextureCubeNode.prototype.nodeType = "TextureCube";

TextureCubeNode.prototype.generateTextureCubeUV = function ( builder, cache ) {

	var uv_10 = cache.uv.build( builder ) + '.uv_10',
		uv_20 = cache.uv.build( builder ) + '.uv_20',
		t = cache.uv.build( builder ) + '.t';

	var color10 = 'texture2D( ' + this.value.build( builder, 'sampler2D' ) + ', ' + uv_10 + ' )',
		color20 = 'texture2D( ' + this.value.build( builder, 'sampler2D' ) + ', ' + uv_20 + ' )';

	// add a custom context for fix incompatibility with the core
	// include ColorSpace function only for vertex shader (in fragment shader color space functions is added automatically by core)
	// this should be removed in the future
	// context.include =: is used to include or not functions if used FunctionNode
	// context.ignoreCache =: not create temp variables nodeT0..9 to optimize the code
	var context = { include: builder.isShader( 'vertex' ), ignoreCache: true };
	var outputType = this.getType( builder );

	builder.addContext( context );

	cache.colorSpace10 = cache.colorSpace10 || new ColorSpaceNode( new ExpressionNode( '', outputType ) );
	cache.colorSpace10.fromDecoding( builder.getTextureEncodingFromMap( this.value.value ) );
	cache.colorSpace10.input.parse( color10 );

	color10 = cache.colorSpace10.build( builder, outputType );

	cache.colorSpace20 = cache.colorSpace20 || new ColorSpaceNode( new ExpressionNode( '', outputType ) );
	cache.colorSpace20.fromDecoding( builder.getTextureEncodingFromMap( this.value.value ) );
	cache.colorSpace20.input.parse( color20 );

	color20 = cache.colorSpace20.build( builder, outputType );

	// end custom context

	builder.removeContext();

	return 'mix( ' + color10 + ', ' + color20 + ', ' + t + ' ).rgb';

};

TextureCubeNode.prototype.generate = function ( builder, output ) {

	if ( builder.isShader( 'fragment' ) ) {

		var radiance = this.generateTextureCubeUV( builder, this.radianceCache );
		var irradiance = this.generateTextureCubeUV( builder, this.irradianceCache );

		builder.context.extra.irradiance = irradiance;

		return builder.format( 'vec4( ' + radiance + ', 1.0 )', this.getType( builder ), output );

	} else {

		console.warn( "THREE.TextureCubeNode is not compatible with " + builder.shader + " shader." );

		return builder.format( 'vec4( 0.0 )', this.getType( builder ), output );

	}

};

TextureCubeNode.prototype.toJSON = function ( meta ) {

	var data = this.getJSONNode( meta );

	if ( ! data ) {

		data = this.createJSONNode( meta );

		data.value = this.value.toJSON( meta ).uuid;

	}

	return data;

};

export { TextureCubeNode };


text:
require File.expand_path('../../../spec_helper', __FILE__)

module Pod
  describe Specification::Set::Statistics do

    #-------------------------------------------------------------------------#

    describe "In general" do
      before do
        @source = Source.new(fixture('spec-repos/master'))
        @set    = @source.search_by_name('JSONKit').first
        @stats  = Spec::Set::Statistics.new
      end

      it "returns the creation date of Pod" do
        @stats.creation_date(@set).should == Time.parse('2011-09-12 10:49:04 +0200')
      end

      it "returns the creation date of more Pods" do
        sets = [@set, @source.search_by_name('libPusher').first ]
        expected = {
          "JSONKit"=> Time.parse('2011-09-12 10:49:04 +0200'),
          "libPusher"=> Time.parse('2012-02-01 17:05:58 +0100'),
        }
        @stats.creation_dates(sets).should == expected
      end

      it "returns the GitHub watchers of a Pod" do
        repo_data = { 'watchers' => 2771 }
        GitHub.expects(:repo).with('https://github.com/johnezang/JSONKit.git').returns(repo_data)
        @stats.github_watchers(@set).should == 2771
      end

      it "returns the GitHub forks of a Pod" do
        repo_data = { 'forks' => 423 }
        GitHub.expects(:repo).with('https://github.com/johnezang/JSONKit.git').returns(repo_data)
        @stats.github_forks(@set).should == 423
      end

      it "returns the time of the last push from GitHub" do
        repo_data = { 'pushed_at' => "2012-07-12T17:36:21Z" }
        GitHub.expects(:repo).with('https://github.com/johnezang/JSONKit.git').returns(repo_data)
        @stats.github_pushed_at(@set).should == Time.parse("2012-07-12T17:36:21Z")
      end

      it "returns nil for GitHub based methods if the Pod is not hosted by GitHub" do
        @set.specification.source = { :git => 'example.com/repo.git' }
        @stats.github_watchers(@set).should  == nil
        @stats.github_forks(@set).should     == nil
        @stats.github_pushed_at(@set).should == nil
      end
    end

    #-------------------------------------------------------------------------#

    describe "Cache" do
      before do
        @source = Source.new(fixture('spec-repos/master'))
        @set    = @source.search_by_name('JSONKit').first
        @stats  = Spec::Set::Statistics.new
      end

      it "defaults the cache expiration to 3 days" do
        @stats.cache_expiration.should == 60 * 60 * 24 * 3
      end

      it "uses an in memory cache" do
        repo_data = { 'watchers' => 2771 }
        GitHub.expects(:repo).with('https://github.com/johnezang/JSONKit.git').returns(repo_data)
        @stats.github_watchers(@set).should == 2771
        GitHub.expects(:repo).never
        @stats.github_watchers(@set).should == 2771
      end

      extend SpecHelper::TemporaryDirectory

      before do
        @cache_hash = { 'JSONKit' => {
          :gh_watchers => 2771,
          :gh_forks    => 423,
          :pushed_at   => "2012-07-12T17:36:21Z",
          :gh_date     => Time.now
        }}
        @cache_file = temporary_directory + 'cache_file.yaml'
        File.open(@cache_file, 'w') { |f| f.write(YAML.dump(@cache_hash)) }
        @stats.cache_file = @cache_file
      end

      it "uses a cache file, if provided" do
        GitHub.expects(:repo).never
        @stats.github_watchers(@set).should == 2771
      end

      it "saves the cache after computing the creation date of a set" do
        @stats.creation_date(@set)
        cache_hash = YAML.load(@cache_file.read)
        cache_hash['JSONKit'][:creation_date].should == Time.parse('2011-09-12 10:49:04 +0200')
      end

      it "saves the cache after computing the creation date of many sets" do
        sets = [@set, @source.search_by_name('libPusher').first ]
        @stats.creation_dates(sets)
        cache_hash = YAML.load(@cache_file.read)
        cache_hash['JSONKit'][:creation_date].should == Time.parse('2011-09-12 10:49:04 +0200')
        cache_hash['libPusher'][:creation_date].should == Time.parse('2012-02-01 17:05:58 +0100')
      end

      it "saves the cache only one time cache after computing the creation date of many sets" do
        @stats.expects(:save_cache).once
        sets = [@set, @source.search_by_name('libPusher').first ]
        @stats.creation_dates(sets)
      end

      it "uses the cache of GitHub values if still valid" do
        GitHub.expects(:repo).never
        @stats.github_watchers(@set).should  == 2771
        @stats.github_forks(@set).should     == 423
        @stats.github_pushed_at(@set).should == Time.parse("2012-07-12T17:36:21Z")
      end

      before do
        @repo_fixture = { 'watchers' => 2771, 'forks' => 423, 'pushed_at' => "2012-07-12T17:36:21Z" }
        File.open(@cache_file, 'w') { |f| f.write(YAML.dump({ 'JSONKit' => {}})) }
        GitHub.expects(:repo).with('https://github.com/johnezang/JSONKit.git').returns(@repo_fixture)
      end

      it "saves the cache after retrieving GitHub information" do
        @stats.github_watchers(@set)
        saved_cache = YAML.load(@cache_file.read)
        saved_cache['JSONKit'][:gh_date] = nil
        @cache_hash['JSONKit'][:gh_date] = nil
        saved_cache.should == @cache_hash
      end

      it "updates the GitHub cache if not valid" do
        @cache_hash['JSONKit'][:gh_date] = (Time.now - 60 * 60 * 24 * 5)
        @stats.github_forks(@set).should == 423
      end

      it "stores in the cache time of the last access to the GitHub API" do
        @stats.github_watchers(@set)
        saved_cache = YAML.load(@cache_file.read)
        time_delta = (Time.now - saved_cache['JSONKit'][:gh_date])
        time_delta.should < 60
      end
    end

    #-------------------------------------------------------------------------#

  end
end