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

<title>All Classes</title>
<meta name="date" content="2015-10-02">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Blog

BlogCrawler

BlogCrawlerTest

Category

CategoryCrawler

CategoryCrawlerTest

CategoryModel

Controller

Crawler

CSDNBlogDownloader

GUI

IndexCrawler

IndexCrawlerTest

Model

Parser

UrlModel

User

UserModel

Util


text:
#include "CCActionInstant.h"
#include "CCNode.h"
#include "CCSprite.h"
#include "CCScriptSupport.h"

namespace cocos2d {
	//
	// InstantAction
	//
	CCActionInstant::CCActionInstant()
	{}

	CCObject * CCActionInstant::copyWithZone(cocos2d::CCZone *pZone)
	{
		CCZone *pNewZone = NULL;
		CCActionInstant *pRet = NULL;
		if (pZone && pZone->m_pCopyObject)
		{
			pRet = (CCActionInstant*)(pZone->m_pCopyObject);
		}
		else
		{
			pRet = new CCActionInstant();
			pZone = pNewZone = new CCZone(pRet);
		}
		CCFiniteTimeAction::copyWithZone(pZone);
		CC_SAFE_DELETE(pNewZone);
		return pRet;
	}
	bool CCActionInstant::isDone()
	{
		return true;
	}
	void CCActionInstant::step(ccTime dt)
	{
        CC_UNUSED_PARAM(dt);
		update(1);
	}
	void CCActionInstant::update(ccTime time)
	{
        CC_UNUSED_PARAM(time);
		// ignore
	}
	CCFiniteTimeAction * CCActionInstant::reverse()
	{
		return (CCFiniteTimeAction*)(copy()->autorelease());
	}

	//
	// Show
	//
	CCShow* CCShow::action()
	{
		CCShow* pRet = new CCShow();
		pRet->autorelease();
		return pRet;
	}
	void CCShow::startWithTarget(CCNode *pTarget)
	{
		CCActionInstant::startWithTarget(pTarget);
		pTarget->setIsVisible(true);
	}
	CCFiniteTimeAction *CCShow::reverse()
	{
		return (CCFiniteTimeAction*)(CCHide::action());
	}
	//
	// Hide
	//
	CCHide * CCHide::action()
	{
		CCHide *pRet = new CCHide();
		pRet->autorelease();
		return pRet;
	}
	void CCHide::startWithTarget(CCNode *pTarget)
	{
		CCActionInstant::startWithTarget(pTarget);
		pTarget->setIsVisible(false);
	}

	CCFiniteTimeAction *CCHide::reverse()
	{
		return (CCFiniteTimeAction*)(CCShow::action());
	}

	//
	// ToggleVisibility
	//
	CCToggleVisibility * CCToggleVisibility::action()
	{
		CCToggleVisibility *pRet = new CCToggleVisibility();
		pRet->autorelease();
		return pRet;
	}
	void CCToggleVisibility::startWithTarget(CCNode *pTarget)
	{
		CCActionInstant::startWithTarget(pTarget);
		pTarget->setIsVisible(! pTarget->getIsVisible());
	}
	//
	// FlipX
	//
	CCFlipX *CCFlipX::actionWithFlipX(bool x)
	{
		CCFlipX *pRet = new CCFlipX();
		pRet->initWithFlipX(x);
		pRet->autorelease();
		return pRet;
	}
	bool CCFlipX::initWithFlipX(bool x)
	{
		m_bFlipX = x;
		return true;
	}
	void CCFlipX::startWithTarget(CCNode *pTarget)
	{
		CCActionInstant::startWithTarget(pTarget);
		((CCSprite*)(pTarget))->setFlipX(m_bFlipX);
	}

	CCFiniteTimeAction* CCFlipX::reverse()
	{
		return CCFlipX::actionWithFlipX(!m_bFlipX);
	}

	CCObject * CCFlipX::copyWithZone(CCZone *pZone)
	{
		CCZone *pNewZone = NULL;
		CCFlipX *pRet = NULL;
		if (pZone && pZone->m_pCopyObject)
		{
			pRet = (CCFlipX*)(pZone->m_pCopyObject);
		}
		else
		{
			pRet = new CCFlipX();
			pZone = pNewZone = new CCZone(pRet);
		}
		CCActionInstant::copyWithZone(pZone);
		pRet->initWithFlipX(m_bFlipX);
		CC_SAFE_DELETE(pNewZone);
		return pRet;
	}

	//
	// FlipY
	//
	CCFlipY * CCFlipY::actionWithFlipY(bool y)
	{
		CCFlipY *pRet = new CCFlipY();
		pRet->initWithFlipY(y);
		pRet->autorelease();
		return pRet;
	}
	bool CCFlipY::initWithFlipY(bool y)
	{
		m_bFlipY = y;
		return true;
	}

	void CCFlipY::startWithTarget(CCNode *pTarget)
	{
		CCActionInstant::startWithTarget(pTarget);
		((CCSprite*)(pTarget))->setFlipY(m_bFlipY);
	}

	CCFiniteTimeAction* CCFlipY::reverse()
	{
		return CCFlipY::actionWithFlipY(!m_bFlipY);
	}

	CCObject * CCFlipY::copyWithZone(CCZone *pZone)
	{
		CCZone *pNewZone = NULL;
		CCFlipY *pRet = NULL;
		if (pZone && pZone->m_pCopyObject)
		{
			pRet = (CCFlipY*)(pZone->m_pCopyObject);
		}
		else
		{
			pRet = new CCFlipY();
			pZone = pNewZone = new CCZone(pRet);
		}
		CCActionInstant::copyWithZone(pZone);
		pRet->initWithFlipY(m_bFlipY);
		CC_SAFE_DELETE(pNewZone);
		return pRet;
	}

	//
	// Place
	//
	CCPlace * CCPlace::actionWithPosition(CCPoint pos)
	{
		CCPlace *pRet = new CCPlace();
		pRet->initWithPosition(pos);
		pRet->autorelease();
		return pRet;
	}
	bool CCPlace::initWithPosition(CCPoint pos)
	{
		m_tPosition = pos;
		return true;
	}

	CCObject * CCPlace::copyWithZone(CCZone *pZone)
	{
		CCZone *pNewZone = NULL;
		CCPlace *pRet = NULL;
		if (pZone && pZone->m_pCopyObject)
		{
			pRet = (CCPlace*)(pZone->m_pCopyObject);
		}
		else
		{
			pRet = new CCPlace();
			pZone = pNewZone = new CCZone(pRet);
		}
		CCActionInstant::copyWithZone(pZone);
		pRet->initWithPosition(m_tPosition);
		CC_SAFE_DELETE(pNewZone);
		return pRet;
	}

	void CCPlace::startWithTarget(CCNode *pTarget)
	{
		CCActionInstant::startWithTarget(pTarget);
		m_pTarget->setPosition(m_tPosition);
	}

	//
	// CallFunc
	//

	CCCallFunc * CCCallFunc::actionWithTarget(SelectorProtocol* pSelectorTarget, SEL_CallFunc selector)
	{
		CCCallFunc *pRet = new CCCallFunc();
		if(pRet->initWithTarget(pSelectorTarget))
		{
			pRet->m_pCallFunc = selector;
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

	CCCallFunc* CCCallFunc::actionWithScriptFuncName(const char* pszFuncName)
	{
		CCCallFunc *pRet = new CCCallFunc();
		if(pRet->initWithScriptFuncName(pszFuncName))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

	bool CCCallFunc::initWithScriptFuncName(const char *pszFuncName)
	{
		this->m_scriptFuncName = string(pszFuncName);
		return true;
	}

	bool CCCallFunc::initWithTarget(SelectorProtocol* pSelectorTarget)
	{
		if (pSelectorTarget)
		{
			pSelectorTarget->selectorProtocolRetain();
		}
		if (m_pSelectorTarget)
		{
			m_pSelectorTarget->selectorProtocolRelease();
		}
		m_pSelectorTarget = pSelectorTarget;
		return true;
	}

	CCObject * CCCallFunc::copyWithZone(cocos2d::CCZone *pZone)
	{
		CCZone* pNewZone = NULL;
		CCCallFunc* pRet = NULL;
		if(pZone && pZone->m_pCopyObject) //in case of being called at sub class
			pRet = (CCCallFunc*)(pZone->m_pCopyObject);
		else
		{
			pRet = new CCCallFunc();
			pZone = pNewZone = new CCZone(pRet);
		}
		CCActionInstant::copyWithZone(pZone);
		pRet->initWithTarget(m_pSelectorTarget);
		pRet->m_pCallFunc = m_pCallFunc;
		pRet->m_scriptFuncName = m_scriptFuncName;
		CC_SAFE_DELETE(pNewZone);
		return pRet;
	}
	void CCCallFunc::startWithTarget(CCNode *pTarget)
	{
		CCActionInstant::startWithTarget(pTarget);
		this->execute();
	}
	void CCCallFunc::execute()
	{
		if(m_pCallFunc)
		{
			(m_pSelectorTarget->*m_pCallFunc)();
		}

		if (CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine())
		{
			CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()->executeCallFunc(m_scriptFuncName.c_str());
		}
	}
	//
	// CallFuncN
	//
	void CCCallFuncN::execute()
	{
		if(m_pCallFuncN)
		{
			(m_pSelectorTarget->*m_pCallFuncN)(m_pTarget);
		}

		if (CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine())
		{
			CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()->executeCallFuncN(m_scriptFuncName.c_str(),
					                                                                           m_pTarget);
		}
	}
	CCCallFuncN * CCCallFuncN::actionWithTarget(SelectorProtocol* pSelectorTarget, SEL_CallFuncN selector)
	{
		CCCallFuncN *pRet = new CCCallFuncN();
		if(pRet->initWithTarget(pSelectorTarget, selector))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

	CCCallFuncN* CCCallFuncN::actionWithScriptFuncName(const char *pszFuncName)
	{
		CCCallFuncN *pRet = new CCCallFuncN();
		if(pRet->initWithScriptFuncName(pszFuncName))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

	bool CCCallFuncN::initWithTarget(SelectorProtocol* pSelectorTarget, SEL_CallFuncN selector)
	{
		if( CCCallFunc::initWithTarget(pSelectorTarget) )
		{
			m_pCallFuncN = selector;
			return true;
		}
		return false;
	}

	CCObject * CCCallFuncN::copyWithZone(CCZone* zone)
	{
		CCZone* pNewZone = NULL;
		CCCallFuncN* pRet = NULL;
		if(zone && zone->m_pCopyObject) //in case of being called at sub class
			pRet = (CCCallFuncN*)(zone->m_pCopyObject);
		else
		{
			pRet = new CCCallFuncN();
			zone = pNewZone = new CCZone(pRet);
		}
		CCCallFunc::copyWithZone(zone);
		pRet->initWithTarget(m_pSelectorTarget, m_pCallFuncN);
		CC_SAFE_DELETE(pNewZone);
		return pRet;
	}
	//
	// CallFuncND
	//
	CCCallFuncND * CCCallFuncND::actionWithTarget(SelectorProtocol* pSelectorTarget, SEL_CallFuncND selector, void* d)
	{
		CCCallFuncND* pRet = new CCCallFuncND();
		if (pRet->initWithTarget(pSelectorTarget, selector, d))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

	CCCallFuncND* CCCallFuncND::actionWithScriptFuncName(const char* pszFuncName, void *d)
	{
		CCCallFuncND* pRet = new CCCallFuncND();
		if (pRet->initWithScriptFuncName(pszFuncName))
		{
			pRet->autorelease();
			pRet->m_pData = d;
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

	bool CCCallFuncND::initWithTarget(SelectorProtocol* pSelectorTarget, SEL_CallFuncND selector, void* d)
	{
		if( CCCallFunc::initWithTarget(pSelectorTarget) )
		{
			m_pData = d;
			m_pCallFuncND = selector;
			return true;
		}
		return false;
	}

	CCObject * CCCallFuncND::copyWithZone(CCZone* zone)
	{
		CCZone* pNewZone = NULL;
		CCCallFuncND* pRet = NULL;
		if(zone && zone->m_pCopyObject) //in case of being called at sub class
			pRet = (CCCallFuncND*)(zone->m_pCopyObject);
		else
		{
			pRet = new CCCallFuncND();
			zone = pNewZone = new CCZone(pRet);
		}
		CCCallFunc::copyWithZone(zone);
		pRet->initWithTarget(m_pSelectorTarget, m_pCallFuncND, m_pData);
		CC_SAFE_DELETE(pNewZone);
		return pRet;
	}

	void CCCallFuncND::execute()
	{
		if(m_pCallFuncND)
		{
			(m_pSelectorTarget->*m_pCallFuncND)(m_pTarget, m_pData);
		}

		if (CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine())
		{
			CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()->executeCallFuncND(m_scriptFuncName.c_str(),
				                                                                            m_pTarget,
				                                                                            m_pData);
		}

	}

    //
    // CCCallFuncO
    //
    CCCallFuncO::CCCallFuncO()
		: m_pObject(NULL)
    {
    }

    CCCallFuncO::~CCCallFuncO()
    {
		CC_SAFE_RELEASE(m_pObject);
    }

    void CCCallFuncO::execute()
    {
        if(m_pCallFuncO)
        {
            (m_pSelectorTarget->*m_pCallFuncO)(m_pObject);
        }

		if (CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine())
		{
			CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()->executeCallFunc0(m_scriptFuncName.c_str(),
				                                                                            m_pObject);
		}
    }
    CCCallFuncO * CCCallFuncO::actionWithTarget(SelectorProtocol* pSelectorTarget, SEL_CallFuncO selector, CCObject* pObject)
    {
        CCCallFuncO *pRet = new CCCallFuncO();
        if(pRet->initWithTarget(pSelectorTarget, selector, pObject))
        {
            pRet->autorelease();
            return pRet;
        }
        CC_SAFE_DELETE(pRet);
        return NULL;
    }

	CCCallFuncO* CCCallFuncO::actionWithScriptFuncName(const char *pszFuncName)
	{
		CCCallFuncO *pRet = new CCCallFuncO();
		if(pRet->initWithScriptFuncName(pszFuncName))
		{
			pRet->autorelease();
			return pRet;
		}
		CC_SAFE_DELETE(pRet);
		return NULL;
	}

    bool CCCallFuncO::initWithTarget(SelectorProtocol* pSelectorTarget, SEL_CallFuncO selector, CCObject* pObject)
    {
        if( CCCallFunc::initWithTarget(pSelectorTarget) )
        {
            m_pObject = pObject;
			CC_SAFE_RETAIN(m_pObject)

            m_pCallFuncO = selector;
            return true;
        }
        return false;
    }
    CCObject * CCCallFuncO::copyWithZone(CCZone* zone)
    {
        CCZone* pNewZone = NULL;
        CCCallFuncO* pRet = NULL;
        if(zone && zone->m_pCopyObject) //in case of being called at sub class
            pRet = (CCCallFuncO*)(zone->m_pCopyObject);
        else
        {
            pRet = new CCCallFuncO();
            zone = pNewZone = new CCZone(pRet);
        }
        CCCallFunc::copyWithZone(zone);
        pRet->initWithTarget(m_pSelectorTarget, m_pCallFuncO, m_pObject);
        CC_SAFE_DELETE(pNewZone);
        return pRet;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package javax.ims;

/**
 * An ImsException indicates an unexpected error condition in a method.
 *
 * @author Cheambe Alice <alice.cheambe@fraunhofer.fokus.de>
 *
 */
public class ImsException extends Exception
{

	private static final long serialVersionUID = 1L;

	/**
	 * Constructs an ImsException with null  as its error detail message.
	 */
    public ImsException()
    {
    }

    /**
     * Constructs an ImsException with the specified detail message.
     * The error message string reason can later be retrieved by the Throwable.getMessage()
     * method of class java.lang.Throwable.
     *
     * @param reason - the detail message
     */
    public ImsException(String reason)
    {
        super(reason);
    }

    public ImsException(String reason, Throwable t)
    {
        super(reason, t);
    }

}


text:
// Copyright 2010-2011 James Roper
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package de.undercouch.bson4jackson.serializers;

import java.io.IOException;
import java.util.Calendar;

import com.fasterxml.jackson.databind.SerializerProvider;

import de.undercouch.bson4jackson.BsonGenerator;

/**
 * Serializes calendars as BSON date type objects
 *
 * @author James Roper
 * @since 1.3
 */
public class BsonCalendarSerializer extends BsonSerializer<Calendar> {
	@Override
	public void serialize(Calendar calendar, BsonGenerator bsonGenerator, SerializerProvider serializerProvider)
			throws IOException {
		if (calendar == null) {
			serializerProvider.defaultSerializeNull(bsonGenerator);
		} else {
			bsonGenerator.writeDateTime(calendar.getTime());
		}
	}
}


text:
from __future__ import unicode_literals

from django.contrib.auth.hashers import make_password
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render

def user_login(request):
    """
        @username
        @password
        Desc: For User login
    """
    if request.method == "POST":
        # Make sure the credentials supplied
        if 'username' not in request.POST or request.POST['username'] == "":
            return JsonResponse({'message': 'Please Provide the Username and Password', 'status': 'fail'})

        # @params
        username = request.POST['username']
        password = request.POST['password']

        # UserCheck
        user = authenticate(username = username, password = password)

        # If user not exists
        if user is None:
            return JsonResponse({'message': 'Invalid User Credentials', 'status':'fail'})

        # If user found, login and return success response
        login(request, user)
        return JsonResponse({'message': 'User Logined Successfully', 'status':'success'})
    return render(request, "authentication/login_register.html", {})

def user_logout(request):
    """
        Desc: For User logout
    """
    logout(request)
    return HttpResponseRedirect('/auth/login/')


text:
var _arrayFromIterator = require('./_arrayFromIterator');
var _has = require('./_has');
var identical = require('../identical');
var keys = require('../keys');
var type = require('../type');

module.exports = function _equals(a, b, stackA, stackB) {
  if (identical(a, b)) {
    return true;
  }

  if (type(a) !== type(b)) {
    return false;
  }

  if (a == null || b == null) {
    return false;
  }

  if (typeof a.equals === 'function' || typeof b.equals === 'function') {
    return typeof a.equals === 'function' && a.equals(b) &&
           typeof b.equals === 'function' && b.equals(a);
  }

  switch (type(a)) {
    case 'Array':
    case 'Object':
      break;
    case 'Boolean':
    case 'Number':
    case 'String':
      if (!(typeof a === typeof b && identical(a.valueOf(), b.valueOf()))) {
        return false;
      }
      break;
    case 'Date':
      if (!identical(a.valueOf(), b.valueOf())) {
        return false;
      }
      break;
    case 'RegExp':
      if (!(a.source === b.source &&
            a.global === b.global &&
            a.ignoreCase === b.ignoreCase &&
            a.multiline === b.multiline &&
            a.sticky === b.sticky &&
            a.unicode === b.unicode)) {
        return false;
      }
      break;
    case 'Map':
    case 'Set':
      if (!_equals(_arrayFromIterator(a.entries()), _arrayFromIterator(b.entries()), stackA, stackB)) {
        return false;
      }
      break;
    case 'Int8Array':
    case 'Uint8Array':
    case 'Uint8ClampedArray':
    case 'Int16Array':
    case 'Uint16Array':
    case 'Int32Array':
    case 'Uint32Array':
    case 'Float32Array':
    case 'Float64Array':
      break;
    case 'ArrayBuffer':
      break;
    default:
      // Values of other types are only equal if identical.
      return false;
  }

  var keysA = keys(a);
  if (keysA.length !== keys(b).length) {
    return false;
  }

  var idx = stackA.length - 1;
  while (idx >= 0) {
    if (stackA[idx] === a) {
      return stackB[idx] === b;
    }
    idx -= 1;
  }

  stackA.push(a);
  stackB.push(b);
  idx = keysA.length - 1;
  while (idx >= 0) {
    var key = keysA[idx];
    if (!(_has(key, b) && _equals(b[key], a[key], stackA, stackB))) {
      return false;
    }
    idx -= 1;
  }
  stackA.pop();
  stackB.pop();
  return true;
};


text:
title: Exploring the use of brain-sensing technologies for natural interactions.
subtitle: ''
summary: ''
authors:
- Matthew Pike
tags: []
categories: []
date: '2017-01-01'
lastmod: 2020-10-18T21:27:02+08:00
featured: false
draft: false

# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
  caption: ''
  focal_point: ''
  preview_only: false

# Projects (optional).
#   Associate this post with one or more of your projects.
#   Simply enter your project's folder or file name without extension.
#   E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
#   Otherwise, set `projects = []`.
projects: []
publishDate: '2020-10-18T13:27:02.588329Z'
publication_types:
- '7'
abstract: ''
publication: ''
---


text:
package org.apache.hadoop.hbase.master.procedure;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.StartTestingClusterOption;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.master.HMaster;
import org.apache.hadoop.hbase.master.assignment.AssignmentManager;
import org.apache.hadoop.hbase.procedure2.Procedure;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.metrics2.impl.JmxCacheBuster;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProcedureProtos.CreateTableState;

@Category({ MasterTests.class, MediumTests.class })
public class TestCreateTableNoRegionServer {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestCreateTableNoRegionServer.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestCreateTableNoRegionServer.class);

  private static final HBaseTestingUtil UTIL = new HBaseTestingUtil();

  private static TableName TABLE_NAME = TableName.valueOf("test");

  private static byte[] FAMILY = Bytes.toBytes("f1");

  private static CountDownLatch ARRIVE;

  private static CountDownLatch RESUME;

  public static final class HMasterForTest extends HMaster {

    public HMasterForTest(Configuration conf) throws IOException {
      super(conf);
    }

    private boolean isInAssignRegionsState() {
      try {
        for (StackTraceElement e : Thread.currentThread().getStackTrace()) {
          if (
            e.getClassName().equals(CreateTableProcedure.class.getName())
              && e.getMethodName().equals("executeFromState")
          ) {
            for (Procedure<?> proc : getProcedures()) {
              if (
                proc instanceof CreateTableProcedure && !proc.isFinished()
                  && ((CreateTableProcedure) proc).getCurrentStateId()
                      == CreateTableState.CREATE_TABLE_ASSIGN_REGIONS_VALUE
              ) {
                return true;
              }
            }
          }
        }
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
      return false;
    }

    @Override
    public AssignmentManager getAssignmentManager() {
      if (ARRIVE != null && isInAssignRegionsState()) {
        ARRIVE.countDown();
        ARRIVE = null;
        try {
          RESUME.await();
        } catch (InterruptedException e) {
        }
      }
      return super.getAssignmentManager();
    }
  }

  @BeforeClass
  public static void setUp() throws Exception {
    UTIL.startMiniCluster(
      StartTestingClusterOption.builder().masterClass(HMasterForTest.class).build());
    // this may cause dead lock if there is no live region server and want to start a new server.
    // In JmxCacheBuster we will reinitialize the metrics system so it will get some metrics which
    // will need to access meta, since there is no region server, the request will hang there for a
    // long time while holding the lock of MetricsSystemImpl, but when start a new region server, we
    // also need to update metrics in handleReportForDutyResponse, since we are all in the same
    // process and uses the same metrics instance, we hit dead lock.
    JmxCacheBuster.stop();
  }

  @AfterClass
  public static void tearDown() throws Exception {
    UTIL.shutdownMiniCluster();
  }

  @Test
  public void testCreate() throws Exception {
    TableDescriptor td = TableDescriptorBuilder.newBuilder(TABLE_NAME)
      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILY)).build();
    Admin admin = UTIL.getAdmin();
    ARRIVE = new CountDownLatch(1);
    RESUME = new CountDownLatch(1);
    Future<Void> future = admin.createTableAsync(td);
    ARRIVE.await();

    UTIL.getMiniHBaseCluster().stopRegionServer(0).join();

    // make sure we the region server is done.
    UTIL.waitFor(30000,
      () -> UTIL.getMiniHBaseCluster().getMaster().getServerManager().getOnlineServers().isEmpty());
    RESUME.countDown();

    Thread.sleep(10000);
    // the procedure should still be in the CREATE_TABLE_ASSIGN_REGIONS state, but here, we just
    // warn it as it may cause more serious problem later.
    for (Procedure<?> proc : UTIL.getMiniHBaseCluster().getMaster().getProcedures()) {
      if (
        proc instanceof CreateTableProcedure && !proc.isFinished()
          && ((CreateTableProcedure) proc).getCurrentStateId()
              != CreateTableState.CREATE_TABLE_ASSIGN_REGIONS_VALUE
      ) {
        LOG.warn("Create table procedure {} assigned regions without a region server!", proc);
      }
    }
    UTIL.getMiniHBaseCluster().startRegionServer();
    // the creation should finally be done
    future.get(30, TimeUnit.SECONDS);
    // make sure we could put to the table
    try (Table table =
      UTIL.getConnection().getTableBuilder(TABLE_NAME, null).setOperationTimeout(5000).build()) {
      table.put(new Put(Bytes.toBytes(0)).addColumn(FAMILY, Bytes.toBytes("q"), Bytes.toBytes(0)));
    }
  }
}


text:
@echo off

REM Usage: rabbitmq-echopid.bat <rabbitmq_nodename>
REM
REM <rabbitmq_nodename> (s)name of the erlang node to connect to (required)

setlocal

set TDP0=%~dp0

REM Get default settings with user overrides for (RABBITMQ_)<var_name>
REM Non-empty defaults should be set in rabbitmq-env
call "!TDP0!\rabbitmq-env.bat" %~n0

if "%1"=="" goto fail

:: set timeout vars ::
set TIMEOUT=10
set TIMER=1

:: check that wmic exists ::
set WMIC_PATH=%SYSTEMROOT%\System32\Wbem\wmic.exe
if not exist "%WMIC_PATH%" (
  goto fail
)

:getpid
for /f "usebackq tokens=* skip=1" %%P IN (`%%WMIC_PATH%% process where "name='erl.exe' and commandline like '%%%RABBITMQ_NAME_TYPE% %1%%'" get processid 2^>nul`) do (
  set PID=%%P
  goto echopid
)

:echopid
:: check for pid not found ::
if "%PID%" == "" (
  PING 127.0.0.1 -n 2 > nul
  set /a TIMER+=1
  if %TIMEOUT%==%TIMER% goto fail
  goto getpid
)

:: show pid ::
echo %PID%

:: all done ::
:ok
endlocal
EXIT /B 0

:: something went wrong ::
:fail
endlocal
EXIT /B 1


text:
import {ChangeDetectionStrategy, Component, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {MatDialog} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {deleteEle, downEle, upEle, UtilService} from '../../../core/services/util.service';
import {Field} from '../../models/field';
import {FieldUpdateDialogComponent} from '../field-update-dialog/field-update-dialog.component';

@Component({
  selector: 'jwjh-field-input',
  templateUrl: './field-input.component.html',
  styleUrls: ['./field-input.component.less'],
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => FieldInputComponent),
    multi: true
  }],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FieldInputComponent implements ControlValueAccessor {
  fields$ = new BehaviorSubject<Field[]>(null);
  onModelChange: Function = () => {
  }
  onModelTouched: Function = () => {
  }

  constructor(private dialog: MatDialog,
              private utilService: UtilService) {
    this.fields$.subscribe(it => this.onModelChange(it));
  }

  update(field: Field, ev: Event): void {
    this.dialog.open(FieldUpdateDialogComponent, {
      disableClose: true,
      panelClass: 'my-dialog',
      data: {field}
    }).afterClosed()
      .filter(it => it)
      .subscribe(it => {
        const fields = [...(this.fields$.value || [])];
        if (field) {
          const i = fields.indexOf(field);
          fields.splice(i, 1, it);
        } else {
          fields.push(it);
        }
        this.fields$.next(fields);
      });
  }

  up(field: Field, ev: Event): void {
    const fields = upEle(this.fields$.value, field);
    this.fields$.next(fields);
  }

  down(field: Field, ev: Event): void {
    const fields = downEle(this.fields$.value, field);
    this.fields$.next(fields);
  }

  delete(field: Field, ev: Event): void {
    this.utilService.showConfirm()
      .subscribe(() => {
        const fields = deleteEle(this.fields$.value, field);
        this.fields$.next(fields);
      });
  }

  writeValue(obj: Field[]): void {
    this.fields$.next(obj);
  }

  registerOnChange(fn: any): void {
    this.onModelChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onModelTouched = fn;
  }
}


text:
add_to_gem_group :development do
  gem_latest_version 'pry-rails'
end


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using Mozu.Api;
using Mozu.Api.Security;
using Mozu.Api.Test.Helpers;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Threading;

#endregion

namespace Mozu.Api.Test.Factories.Commerce.Orders
{
	/// <summary>
	/// Use the Extended Properties resource to store tracking strings for your orders. Extended properties can help you track affiliate sources.
	/// </summary>
	public partial class ExtendedPropertyFactory : BaseDataFactory
	{

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = ExtendedPropertyFactory.GetExtendedProperties(handler : handler,  orderId :  orderId,  draft :  draft,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<List<ExtendedProperty>/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static List<Mozu.Api.Contracts.CommerceRuntime.Commerce.ExtendedProperty> GetExtendedProperties(ServiceClientMessageHandler handler,
 		 string orderId, bool? draft = null,
		 HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Commerce.Orders.ExtendedPropertyClient.GetExtendedPropertiesClient(
				 orderId :  orderId,  draft :  draft		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = ExtendedPropertyFactory.AddExtendedProperties(handler : handler,  extendedProperties :  extendedProperties,  orderId :  orderId,  updateMode :  updateMode,  version :  version,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<List<ExtendedProperty>/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static List<Mozu.Api.Contracts.CommerceRuntime.Commerce.ExtendedProperty> AddExtendedProperties(ServiceClientMessageHandler handler,
 		 List<Mozu.Api.Contracts.CommerceRuntime.Commerce.ExtendedProperty> extendedProperties, string orderId, string updateMode = null, string version = null,
		 HttpStatusCode expectedCode = HttpStatusCode.Created, HttpStatusCode successCode = HttpStatusCode.Created)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Commerce.Orders.ExtendedPropertyClient.AddExtendedPropertiesClient(
				 extendedProperties :  extendedProperties,  orderId :  orderId,  updateMode :  updateMode,  version :  version		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = ExtendedPropertyFactory.UpdateExtendedProperty(handler : handler,  extendedProperty :  extendedProperty,  orderId :  orderId,  key :  key,  updateMode :  updateMode,  version :  version,  upsert :  upsert,  responseFields :  responseFields,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<ExtendedProperty/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static Mozu.Api.Contracts.CommerceRuntime.Commerce.ExtendedProperty UpdateExtendedProperty(ServiceClientMessageHandler handler,
 		 Mozu.Api.Contracts.CommerceRuntime.Commerce.ExtendedProperty extendedProperty, string orderId, string key, string updateMode = null, string version = null, bool? upsert = null, string responseFields = null,
		 HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Commerce.Orders.ExtendedPropertyClient.UpdateExtendedPropertyClient(
				 extendedProperty :  extendedProperty,  orderId :  orderId,  key :  key,  updateMode :  updateMode,  version :  version,  upsert :  upsert,  responseFields :  responseFields		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = ExtendedPropertyFactory.UpdateExtendedProperties(handler : handler,  extendedProperties :  extendedProperties,  orderId :  orderId,  updateMode :  updateMode,  version :  version,  upsert :  upsert,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<List<ExtendedProperty>/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static List<Mozu.Api.Contracts.CommerceRuntime.Commerce.ExtendedProperty> UpdateExtendedProperties(ServiceClientMessageHandler handler,
 		 List<Mozu.Api.Contracts.CommerceRuntime.Commerce.ExtendedProperty> extendedProperties, string orderId, string updateMode = null, string version = null, bool? upsert = null,
		 HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Commerce.Orders.ExtendedPropertyClient.UpdateExtendedPropertiesClient(
				 extendedProperties :  extendedProperties,  orderId :  orderId,  updateMode :  updateMode,  version :  version,  upsert :  upsert		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = ExtendedPropertyFactory.DeleteExtendedProperty(handler : handler,  orderId :  orderId,  key :  key,  updateMode :  updateMode,  version :  version,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<Stream/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static System.IO.Stream DeleteExtendedProperty(ServiceClientMessageHandler handler,
 		 string orderId, string key, string updateMode = null, string version = null,
		 HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Commerce.Orders.ExtendedPropertyClient.DeleteExtendedPropertyClient(
				 orderId :  orderId,  key :  key,  updateMode :  updateMode,  version :  version		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = ExtendedPropertyFactory.DeleteExtendedProperties(handler : handler,  keys :  keys,  orderId :  orderId,  updateMode :  updateMode,  version :  version,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<Stream/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static System.IO.Stream DeleteExtendedProperties(ServiceClientMessageHandler handler,
 		 List<string> keys, string orderId, string updateMode = null, string version = null,
		 HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Commerce.Orders.ExtendedPropertyClient.DeleteExtendedPropertiesClient(
				 keys :  keys,  orderId :  orderId,  updateMode :  updateMode,  version :  version		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

	}

}


text:
// Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\Shaders
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:47

#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using DungeonQuest.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using DungeonQuest.Game;
#endregion

namespace DungeonQuest.Shaders
{
	/// <summary>
	/// The VBScreenHelper class helps you to create and use vertex buffers for
	/// on screen rendering used in PreScreen and PostScreen shaders.
	/// You don't have to create a VB for every shader anymore, just call
	/// VBScreenHelper.Render() and everything will be created for you and
	/// reused if same parameters are requested again!
	/// Supports also Grid screen rendering required for radial motion blur.
	/// </summary>
	public class VBScreenHelper
	{
		#region VBScreen helper class
		/// <summary>
		/// VBScreen holds all data for the vbScreens list to reuse existing
		/// VBScreens. Handles also the VB, creation and rendering.
		/// </summary>
		private class VBScreen
		{
			#region Variables
			/// <summary>
			/// Vertex buffer to render stuff on screen.
			/// </summary>
			private VertexBuffer vbScreen;
			private VertexDeclaration decl;
			#endregion

			#region Constructor
			/// <summary>
			/// Create VB screen
			/// </summary>
			public VBScreen()
			{
				VertexPositionTexture[] vertices = new VertexPositionTexture[]
				{
					new VertexPositionTexture(
						new Vector3(-1.0f, -1.0f, 0.5f),
						new Vector2(0, 1)),
					new VertexPositionTexture(
						new Vector3(-1.0f, 1.0f, 0.5f),
						new Vector2(0, 0)),
					new VertexPositionTexture(
						new Vector3(1.0f, -1.0f, 0.5f),
						new Vector2(1, 1)),
					new VertexPositionTexture(
						new Vector3(1.0f, 1.0f, 0.5f),
						new Vector2(1, 0)),
				};
				vbScreen = new VertexBuffer(
					BaseGame.Device,
					typeof(VertexPositionTexture),
					vertices.Length,
					BufferUsage.WriteOnly);

				vbScreen.SetData(vertices);

				decl = new VertexDeclaration(
					BaseGame.Device, VertexPositionTexture.VertexElements);

				/*do we still have to do this?
				// Recreate vertexBuffer if device was lost and is reseted again
				BaseGame.Device.DeviceReset +=
					new System.EventHandler(OnCreateVBScreen);
				 */
			} // VBScreen()
			#endregion

			#region Render
			/// <summary>
			/// Render
			/// </summary>
			public void Render()
			{
				// Rendering is pretty straight forward (if you know how anyway).
				BaseGame.Device.VertexDeclaration = decl;
				BaseGame.Device.Vertices[0].SetSource(vbScreen, 0,
					VertexPositionTexture.SizeInBytes);
				BaseGame.Device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
			} // Render()
			#endregion
		} // class VBScreen
		#endregion

		#region Render
		/// <summary>
		/// Vb screen instance
		/// </summary>
		static VBScreen vbScreenInstance = null;
		/// <summary>
		/// Just render a vertex buffer with the screen coordinates.
		/// No subTexelSize stuff is performed, do that in the fx file.
		/// </summary>
		public static void Render()
		{
			if (vbScreenInstance == null)
				vbScreenInstance = new VBScreen();

			vbScreenInstance.Render();
		} // Render()
		#endregion

		#region GridScreen helper class
		/// <summary>
		/// Another vertex and index buffer for a screen grid, basically
		/// used for the same purpose as VBScreen, but allows us to create
		/// a grid (e.g. 10x10), very useful for advanced post screen shaders.
		/// </summary>
		private class GridScreen
		{
			#region Variables
			/// <summary>
			/// Grid dimension
			/// </summary>
			int gridWidth, gridHeight;
			/// <summary>
			/// Index buffer
			/// </summary>
			IndexBuffer indexBuffer = null;
			/// <summary>
			/// Vertex buffer
			/// </summary>
			VertexBuffer vertexBuffer = null;

			/// <summary>
			/// Vertex declaration
			/// </summary>
			VertexDeclaration decl;
			#endregion

			#region Constructor
			/// <summary>
			/// Create grid screen
			/// </summary>
			/// <param name="setGridDimension">Set grid dimension</param>
			public GridScreen(int setGridWidth, int setGridHeight)
			{
				if (setGridWidth < 2 ||
					setGridHeight < 2)
					throw new ArgumentException(
						"setGridWidth=" + setGridWidth + ", setGridHeight=" +setGridHeight,
						"Grid size must be at least (2, 2).");
				gridWidth = setGridWidth;
				gridHeight = setGridHeight;

				// Create vertex buffer
				vertexBuffer = new VertexBuffer(
					BaseGame.Device,
					typeof(VertexPositionTexture),
					gridWidth * gridHeight,
					BufferUsage.WriteOnly);

				// Create all vertices
				VertexPositionTexture[] vertices =
					new VertexPositionTexture[gridWidth * gridHeight];
				// Just simply create all vertices of the grid
				for (int x = 0; x < gridWidth; x++)
					for (int y = 0; y < gridHeight; y++)
					{
						vertices[x + y * gridWidth] =
							new VertexPositionTexture(new Vector3(
							-1.0f + 2.0f * (float)x / (float)(gridWidth - 1),
							-1.0f + 2.0f * (float)y / (float)(gridHeight - 1),
							0.5f),
							new Vector2((float)x / (float)(gridWidth - 1),
							// XNA expect bottom up for the screen rendering.
							1.0f - ((float)y / (float)(gridHeight - 1))));
					} // for for (int)
				vertexBuffer.SetData(vertices);

				// Index buffer
				indexBuffer = new IndexBuffer(
					BaseGame.Device,
					typeof(ushort),
					(gridWidth - 1) * (gridHeight - 1) * 2 * 3,
					BufferUsage.WriteOnly);

				ushort[] indices = new ushort[
					(gridWidth - 1) * (gridHeight - 1) * 3 * 2];
				// Just simply create all indices of the grid
				int num = 0;
				for (int x = 0; x < gridWidth - 1; x++)
					for (int y = 0; y < gridHeight - 1; y++)
					{
						ushort index1 = (ushort)(x + y * gridWidth);
						ushort index2 = (ushort)((x + 1) + y * gridWidth);
						ushort index3 = (ushort)((x + 1) + (y + 1) * gridWidth);
						ushort index4 = (ushort)(x + (y + 1) * gridWidth);

						indices[num] = index1;
						indices[num + 1] = index3;
						indices[num + 2] = index2;
						indices[num + 3] = index1;
						indices[num + 4] = index4;
						indices[num + 5] = index3;

						num += 6;
					} // for for (int)
				indexBuffer.SetData(indices);

				decl = new VertexDeclaration(
					BaseGame.Device, VertexPositionTexture.VertexElements);
			} // GridScreen(setGridDimension)
			#endregion

			#region Render
			/// <summary>
			/// Render
			/// </summary>
			public void Render()
			{
				// Rendering is pretty straight forward (if you know how anyway).
				BaseGame.Device.VertexDeclaration = decl;
				BaseGame.Device.Vertices[0].SetSource(vertexBuffer, 0,
					VertexPositionTexture.SizeInBytes);
				BaseGame.Device.Indices = indexBuffer;
				BaseGame.Device.DrawIndexedPrimitives(PrimitiveType.TriangleList,
					0, 0, gridWidth * gridHeight,
					0, (gridWidth - 1) * (gridHeight - 1) * 2);
			} // Render()
			#endregion
		} // class GridScreen
		#endregion

		#region Render 10x10 screen grid
		/// <summary>
		/// Grid screen 1 0x 10 instance
		/// </summary>
		static GridScreen gridScreen10x10Instance = null;
		/// <summary>
		/// Just render a 10x10 grid with help of GridScreen on the screen.
		/// No subTexelSize stuff is performed, do that in the fx file.
		/// </summary>
		public static void Render10x10Grid()
		{
			if (gridScreen10x10Instance == null)
				gridScreen10x10Instance = new GridScreen(10, 10);

			gridScreen10x10Instance.Render();
		} // Render10x10Grid()
		#endregion
	} // class VBScreenHelper
} // namespace DungeonQuest.Shaders


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace ForumProject.Models
{
    public class CommentViewModel
    {
        public int CommentId { get; set; }

        [Required]
        [StringLength(2500)]
        public string Content { get; set; }

        public int PostId { get; set; }

        [ForeignKey("PostId")]
        public virtual Post Post { get; set; }

        [ForeignKey("Author")]
        public string AuthorId { get; set; }

        public DateTime DateCreated { get; set; }
    }
}


text:
layout: post
title: Install TPLINK WN725N on Raspberry Pi
tags: "raspberry-pi electronics"
categories: notes tutorials
published: true
---


text:
package vvb

import (
	"encoding/xml"
	"fmt"
	"io"
)

// Endpoint for games requests, %s is replaced with the series code.
const epGames = "http://www.volleyvvb.be/Competitie/wedstrijden_xml.php?reeks=%s"

// gamesQuery represents the result of a games query.
type gamesQuery struct {
	Results []*Game `xml:"wedstrijd"`
}

// Game represents a single game in a GamesQuery result.
type Game struct {
	Nr       uint16 `xml:"nr"`
	Date     string `xml:"datum"`          // Date (yyyy-mm-dd)
	Time     string `xml:"aanvangsuur"`    // Start time (hh:mm)
	Series   string `xml:"reeks"`          // Series shortcode
	Home     string `xml:"thuisploeg"`     // Name of home team
	Visitors string `xml:"bezoekersploeg"` // Name of visiting team
	Venue    string `xml:"sporthal"`       // Venue name
	Score    string `xml:"uitslag"`        // Total score
	Set1     string `xml:"uitslag_set_1"`  // Scores for set 1, if available.
	Set2     string `xml:"uitslag_set_2"`  // Scores for set 2, if available.
	Set3     string `xml:"uitslag_set_3"`  // Scores for set 3, if available.
	Set4     string `xml:"uitslag_set_4"`  // Scores for set 4, if available.
	Set5     string `xml:"uitslag_set_5"`  // Scores for set 5, if available.
}

// GetRankings fetches rankings from volleyvvb.be
func GetGames(series string) (r []*Game, err error) {

	// Fast path: Series codes are always at least 3 characters in length.
	if len(series) < 3 {
		return
	}

	// Contact XML api at volleyvvb.be
	body, err := get(fmt.Sprintf(epGames, series))
	if err != nil || body == nil {
		return
	}
	defer body.Close()

	query := new(gamesQuery)
	dec := xml.NewDecoder(body)

	// Ignore charsets for now
	dec.CharsetReader = func(c string, in io.Reader) (io.Reader, error) {
		return in, nil
	}

	// Attempt to decode games response
	if err = dec.Decode(query); err != nil {
		return
	}

	return query.Results, nil

}


text:
<resources>
    <string name="app_name">ClearEditText</string>
</resources>


text:
/**
 * CreativeSetService.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.google.api.ads.dfp.v201306;

public interface CreativeSetService extends javax.xml.rpc.Service {
    public java.lang.String getCreativeSetServiceInterfacePortAddress();

    public com.google.api.ads.dfp.v201306.CreativeSetServiceInterface getCreativeSetServiceInterfacePort() throws javax.xml.rpc.ServiceException;

    public com.google.api.ads.dfp.v201306.CreativeSetServiceInterface getCreativeSetServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException;
}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="AWS - Terraform - DevPaas Tenant ELB+ASG - 2 - apply" type="BashConfigurationType" factoryName="Bash" folderName="AWS">
    <option name="INTERPRETER_OPTIONS" value="" />
    <option name="INTERPRETER_PATH" value="$INTERPRETER_PATH$" />
    <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/devpaas-vm/terraform/providers/amazon-ebs/devpaas-distribute-vms-asg/vpc" />
    <option name="PARENT_ENVS" value="true" />
    <option name="SCRIPT_NAME" value="$PROJECT_DIR$/devpaas-vm/terraform/providers/amazon-ebs/devpaas-distribute-vms-asg/vpc/aws-devpaas-dv-manage-vpc.sh" />
    <option name="PARAMETERS" value="apply marmac_marcomaccio_rsa eu-west-1 10.0.0.0/16 10.0.1.0/24 10.0.2.0/24 mm-dp-jumpbox ami-11be7268 t2.micro mm-dp-revprx-srv ami-5e884527 t2.micro mm-dp-jenkins-srv ami-4422e03d t2.medium mm-dp-nexus-srv ami-89814cf0 t2.medium mm-dp-sonarqube-srv ami-68884511 t2.medium" />
    <module name="" />
    <envs>
      <env name="AWS_PROFILE" value="marmac-marcomaccio-eu-west-1" />
    </envs>
    <method />
  </configuration>
</component>


text:
#ifndef _IDENTT_HTTP_SERVER_CONFIG_HPP_
#define _IDENTT_HTTP_SERVER_CONFIG_HPP_

#include <string>

namespace identt {
namespace http {

struct ServerConfig {
	ServerConfig(std::string address, unsigned short port):
		address(address),port(port), reuse_address(true) {}
	unsigned short port;
	std::string address;
	bool reuse_address;
};

} // namespace http
} // namespace identt
#endif	/* _IDENTT_HTTP_SERVER_CONFIG_HPP_ */


text:
package com.phaseii.rxm.roomies.database.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.phaseii.rxm.roomies.database.contract.RoomiesContract;
import com.phaseii.rxm.roomies.database.model.RoomiesModel;
import com.phaseii.rxm.roomies.database.model.UserDetails;
import com.phaseii.rxm.roomies.database.provider.UserDetailsProvider;
import com.phaseii.rxm.roomies.utils.QueryParam;
import com.phaseii.rxm.roomies.utils.ServiceParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static android.provider.BaseColumns._ID;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.UserDetails.USER_SENDER_ID;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.UserDetails.USER_USERNAME;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.UserDetails.USER_USER_ALIAS;
import static com.phaseii.rxm.roomies.utils.RoomiesHelper.listToProjection;

/**
 * Created by Snehankur on 6/29/2015.
 */
public class UserDetailsDaoImpl implements RoomiesDao {

    private Context mContext;
    private String[] projection;
    private String selection;
    private String[] selectionArgs;
    private String sortOrder;
    private UserDetails user;
    private ContentValues values;
    private Uri userDetailsUri;

    public UserDetailsDaoImpl(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public List<? extends RoomiesModel> getDetails(Map<ServiceParam, ?> queryMap) {

        List<QueryParam> projectionList = (List<QueryParam>) queryMap.get(ServiceParam.PROJECTION);
        List<QueryParam> selectionList = (List<QueryParam>) queryMap.get(ServiceParam.SELECTION);
        List<String> selectionArgsList = (List<String>) queryMap.get(ServiceParam.SELECTION_ARGS);
        String sortOrder = (String) queryMap.get(ServiceParam.SORT_ORDER);

        String[] projection = listToProjection(projectionList);
        selection = null;
        selectionArgs = null;
        if (null != selectionList && selectionList.size() > 0) {

            for (QueryParam select : selectionList) {
                if (null == selection) {
                    selection = select.toString() + "=?";
                } else {
                    selection = selection + " AND " + select.toString() + "=?";
                }
            }
        }
        if (null != selectionArgsList && null != selection && selectionArgsList.size() > 0) {
            selectionArgs = new String[selectionArgsList.size()];
            selectionArgsList.toArray(selectionArgs);
        }

        String queryArg = null;
        Map<QueryParam, String> queryParams = (Map<QueryParam, String>) queryMap.get
                (ServiceParam.QUERY_ARGS);
        if (null != queryParams && queryParams.size() > 0) {
            for (QueryParam param : queryParams.keySet()) {
                if (param.equals(QueryParam.USER_ID)) {
                    queryArg = "month/" + queryParams.get(param);
                } else if (param.equals(QueryParam.USER_ALIAS)) {
                    queryArg = "room/" + queryParams.get(param);
                } else if (param.equals(QueryParam.SENDER_ID)) {
                    queryArg = "room/" + queryParams.get(param);
                }
            }
        }
        if (null != queryArg) {
            userDetailsUri = Uri.withAppendedPath(UserDetailsProvider.CONTENT_URI,
                    queryArg);
        } else {
            userDetailsUri = UserDetailsProvider.CONTENT_URI;
        }

        Cursor cursor = null;
        List<UserDetails> userDetailsList = new ArrayList<>();
        try {
            cursor = mContext.getContentResolver().query(userDetailsUri, projection, selection,
                    selectionArgs, sortOrder);
            if (null != cursor) {
                cursor.moveToFirst();
                while (!cursor.isAfterLast()) {

                    UserDetails user = new UserDetails();
                    user.setUserId(cursor.getColumnIndex(_ID) >= 0 ? cursor.getInt(cursor
                            .getColumnIndex(_ID)) : -1);
                    user.setUsername(cursor.getColumnIndex(USER_USERNAME) >= 0 ? cursor.getString
                            (cursor.getColumnIndex(USER_USERNAME)) : null);
                    user.setUserAlias(
                            cursor.getColumnIndex(USER_USER_ALIAS) >= 0 ? cursor.getString(cursor
                                    .getColumnIndex(USER_USER_ALIAS)) : null);
                    user.setSenderId(cursor.getColumnIndex(USER_SENDER_ID) >= 0 ?
                            cursor.getString(cursor.getColumnIndex(USER_SENDER_ID)) : null);
                    userDetailsList.add(user);
                    cursor.moveToNext();
                }
            }
        } finally {
            if (null != cursor && !cursor.isClosed()) {
                cursor.close();
            }
        }

        return userDetailsList;
    }

    @Override
    public int insertDetails(Map<ServiceParam, ? extends RoomiesModel> detailsMap) {
        user = (UserDetails) detailsMap.get(ServiceParam.MODEL);
        int row = 0;
        values = new ContentValues();
        values.put(RoomiesContract.UserDetails.USER_USERNAME, null != user.getUsername() ? user
                .getUsername() : null);
        values.put(RoomiesContract.UserDetails.USER_USER_ALIAS,
                null != user.getUserAlias() ? user.getUserAlias() : null);
        values.put(RoomiesContract.UserDetails.USER_SENDER_ID, null != user.getSenderId() ? user
                .getSenderId() : null);
        Uri resultUri = mContext.getContentResolver().insert(UserDetailsProvider.CONTENT_URI,
                values);
        row = Integer.parseInt(resultUri.getLastPathSegment());

        return row;
    }

    /**
     *
     * @param detailsMap
     * @return
     */
    @Override public int deleteDetails(Map<ServiceParam, ?> detailsMap) {
        return 0;
    }

    @Override
    public int updateDetails(Map<ServiceParam, ?> detailsMap) {
        prepareStatement(detailsMap);
        int rowsUpdated = mContext.getContentResolver().update(UserDetailsProvider.CONTENT_URI,
                values, selection, selectionArgs);
        return rowsUpdated;
    }

    public void prepareStatement(Map<ServiceParam, ?> detailsMap) {

        List<QueryParam> selectionList = (List<QueryParam>) detailsMap.get(ServiceParam.SELECTION);
        List<String> selectionArgsList = (List<String>) detailsMap.get(ServiceParam.SELECTION_ARGS);

        if (null != selectionList && selectionList.size() > 0) {
            selection = null;
            for (QueryParam select : selectionList) {
                if (null == selection) {
                    selection = select.toString() + "=?";
                } else {
                    selection = selection + " AND " + select.toString() + "=?";
                }
            }
        }

        if (null != selectionArgsList && null != selection && selectionArgsList.size() > 0) {
            selectionArgs = new String[selectionArgsList.size()];
            selectionArgsList.toArray(selectionArgs);
        }

        if (null != detailsMap.get(ServiceParam.MODEL)) {
            values = new ContentValues();
            user = (UserDetails) detailsMap.get(ServiceParam.MODEL);

            if (null != user.getUsername()) {
                values.put(RoomiesContract.UserDetails.USER_USERNAME, user.getUsername());
            }
            if (null != user.getUserAlias()) {
                values.put(RoomiesContract.UserDetails.USER_USER_ALIAS, user.getUserAlias());
            }
            if (null != user.getSenderId()) {
                values.put(RoomiesContract.UserDetails.USER_SENDER_ID, user.getSenderId());
            }
            if (null != user.getPhone()) {
                values.put(RoomiesContract.UserDetails.USER_PHONE, user.getPhone());
            }
            if (null != user.getLocation()) {
                values.put(RoomiesContract.UserDetails.USER_LOCATION, user.getLocation());
            }
            if (null != user.getAboutMe()) {
                values.put(RoomiesContract.UserDetails.USER_ABOUT_ME, user.getAboutMe());
            }
        }
    }
}


text:
package com.hehe.sharingilive;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.hehe.sharingilive.homepage.HomeActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
              startActivity(new Intent(MainActivity.this, HomeActivity.class));
            }
        },1000);
    }
}


text:
Get the metadata of an object by id:

    {
      "operation": "getHead",
      "id": "s3-key-of-my-object.txt"
    }

Get the whole object by id (not advisable to pull objects through Lambda, you should just pass the S3 URL instead):

    {
      "operation": "getObject",
      "id": "s3-key-of-my-object.txt"
    }

Get a list of objects:

    {
      "operation": "list"
    }

Test the Lambda function:

    {
      "operation": "ping"
    }


text:
package web

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/EconomistDigitalSolutions/ramlapi"
	"github.com/EconomistDigitalSolutions/watchman/journal"
	"github.com/buddhamagnet/raml"
	"github.com/buddhamagnet/yaml"
	"github.com/gorilla/mux"
)

var (
	// Router is the package level mux router.
	Router     *mux.Router
	api        *raml.APIDefinition
	buildstamp string
	githash    string
)

// NewRouter creates a mux router, sets up
// a static handler and registers the dynamic
// routes and middleware handlers with the mux.
func NewRouter(ramlFile, build, hash string) {
	buildstamp = build
	githash = hash
	Router = mux.NewRouter().StrictSlash(true)
	// Assemble middleware as required.
	assembleMiddleware()
	assembleRoutes()
}

// assembleMiddleware sets up the middleware stack.
func assembleMiddleware() {
	http.Handle("/",
		JSONMiddleware(
			LoggingMiddleware(
				RecoverMiddleware(Router))))
}

func assembleRoutes() {
	var err error

	// If bundling is enabled, read the RAML
	// from bundle.go
	if os.Getenv("BUNDLE_ASSETS") == "1" {
		ramlFile := os.Getenv("RAMLFILE_NAME")

		if ramlFile == "" {
			ramlFile = "api.raml"
		}

		bundle, err := GoberryBundle.Open(ramlFile)
		if err != nil {
			log.Fatal(err)
		}
		data, err := ioutil.ReadAll(bundle)
		if err != nil {
			log.Fatal(err)
		}
		err = yaml.Unmarshal(data, &api)
		if err != nil {
			log.Fatal(err)
		}
		// Otherwise, read the file from the filesystem.
	} else {
		ramlPath := os.Getenv("RAMLFILE_PATH")

		if ramlPath == "" {
			ramlPath = "api.raml"
		}

		api, err = ramlapi.Process(ramlPath)
		if err != nil {
			log.Fatal(err)
		}
	}
	journal.LogChannel("raml-processor", fmt.Sprintf("processing API spec for %s", api.Title))
	journal.LogChannel("raml-processor", fmt.Sprintf("base URI at %s", api.BaseUri))
	err = ramlapi.Build(api, routerFunc)
	if err != nil {
		log.Fatal(err)
	}
}

func routerFunc(ep *ramlapi.Endpoint) {

	path := ep.Path

	for _, up := range ep.URIParameters {
		if up.Pattern != "" {
			path = strings.Replace(
				path,
				fmt.Sprintf("{%s}", up.Key),
				fmt.Sprintf("{%s:%s}", up.Key, up.Pattern),
				1)
		}
	}

	route := Router.
		Methods(ep.Verb).
		Path(path).
		Handler(RouteMap[ep.Handler])

	for _, param := range ep.QueryParameters {
		if param.Required {
			if param.Pattern != "" {
				route.Queries(param.Key, fmt.Sprintf("{%s:%s}", param.Key, param.Pattern))
			} else {
				route.Queries(param.Key, "")
			}
		}
	}
}


text:
'use strict';

class SQLAdapter {

  generateConnectionString(host, port, database, user, password) {}
  parseConnectionString(str) {}

  generateClearDatabaseQuery() {}
  generateCreateDatabaseQuery() {}
  generateDropDatabaseQuery() {}

  generateIndex() {}
  generateConstraint() {}

  generateColumn(columnName, type, properties) {}
  generateAlterColumn(columnName, type, properties) {}
  generateAlterColumnSetNull(columnName, type, properties) {}
  generatePrimaryKey(columnName, type, properties) {}
  generateUniqueKey(columnName, type, properties) {}

  generateAlterTableRename(table, newTableName) {}

  generateAlterTableColumnType(table, columnName, columnType, columnProperties) {}
  generateAlterTableAddPrimaryKey(table, columnName) {}
  generateAlterTableDropPrimaryKey(table, columnName) {}
  generateAlterTableAddUniqueKey(table, columnName) {}
  generateAlterTableDropUniqueKey(table, columnName) {}

  generateAlterTableAddColumn(table, columnName, columnType, columnProperties) {}
  generateAlterTableDropColumn(table, columnName) {}
  generateAlterTableRenameColumn(table, columnName, newColumnName) {}

  generateCreateIndex(table, columnName, indexType) {}
  generateDropIndex(table, columnName) {}

  generateSimpleForeignKeyQuery(table, referenceTable) {}
  generateDropSimpleForeignKeyQuery(table, referenceTable) {}

  sanitize(type, value) {

    let fnSanitize = this.sanitizeType[type];
    return fnSanitize ? fnSanitize(value) : value;

  }

  escapeField(name) {
    return ['', name, ''].join(this.escapeFieldCharacter);
  }

  getTypeProperties(typeName, optionalValues) {

    let type = this.types[typeName];
    let typeProperties = type ? (type.properties || {}) : {};

    optionalValues = optionalValues || {};

    let outputType = Object.create(this.typePropertyDefaults);
    this.typeProperties.forEach(function(v) {
      if (optionalValues.hasOwnProperty(v)) {
        outputType[v] = optionalValues[v];
      } else if(typeProperties.hasOwnProperty(v)) {
        outputType[v] = typeProperties[v];
      }
    });

    return outputType;

  }

  getTypeDbName(typeName) {
    let type = this.types[typeName];
    return type ? type.dbName : 'INTEGER';
  }

  generateColumnsStatement(table, columns) {
    let self = this;
    return columns
      .map(function(columnData) {
        return self.generateColumn(columnData.name, self.getTypeDbName(columnData.type), self.getTypeProperties(columnData.type, columnData.properties));
      })
      .join(',');
  }

  getAutoIncrementKeys(columns) {

    let self = this;
    return columns.filter(function(columnData) {
      return self.getTypeProperties(columnData.type, columnData.properties).auto_increment;
    });

  };

  getPrimaryKeys(columns) {

    let self = this;
    return columns
      .filter(function(columnData) {
        return self.getTypeProperties(columnData.type, columnData.properties).primary_key;
      });

  }

  getUniqueKeys(columns) {

    let self = this;
    return columns
      .filter(function(columnData) {
        let type = self.getTypeProperties(columnData.type, columnData.properties);
        return (!type.primary_key && type.unique);
      });

  }

  generatePrimaryKeysStatement(table, columns) {
    let self = this;
    return this.getPrimaryKeys(columns)
      .map(function(columnData) {
        return self.generatePrimaryKey(table, columnData.name);
      })
      .join(',');
  }

  generateUniqueKeysStatement(table, columns) {

    return this.getUniqueKeys(columns)
      .map(columnData => this.generateUniqueKey(table, columnData.name))
      .join(',');

  }

  generateCreateTableQuery(table, columns) {

    return [
      'CREATE TABLE ',
        this.escapeField(table),
      '(',
        [
          this.generateColumnsStatement(table, columns),
          this.generatePrimaryKeysStatement(table, columns),
          this.generateUniqueKeysStatement(table, columns)
        ].filter(function(v) { return !!v; }).join(','),
      ')'
    ].join('');

  }

  generateDropTableQuery(table, ifExists) {

    return `DROP TABLE ${ifExists?'IF EXISTS ':''}${this.escapeField(table)}`;

  }

  generateTruncateTableQuery(table) {

    return `TRUNCATE TABLE ${this.escapeField(table)} RESTART IDENTITY`;

  }

  generateSelectQuery(subQuery, table, columns, multiFilter, joinArray, groupByArray, orderByArray, limitObj, paramOffset) {

    let formatTableField = (table, column) => `${this.escapeField(table)}.${this.escapeField(column)}`;

    if (typeof subQuery === 'object' && subQuery !== null) {
      subQuery = this.escapeField(subQuery.table);
    } else {
      subQuery = subQuery ? `(${subQuery})` : table;
    }

    groupByArray = groupByArray || [];
    orderByArray = orderByArray || [];

    return [
      'SELECT ',
        columns.map(field => {
          field = typeof field === 'string' ? {columnNames: [field], alias: field, transformation: v => v} : field;
          let defn = field.transformation.apply(null, field.columnNames.map(columnName => {
            return formatTableField(field.name || field.table || table, columnName);
          }));
          return `(${defn}) AS ${this.escapeField(field.alias)}`;
        }).join(','),
      ' FROM ',
        subQuery,
        ' AS ',
        this.escapeField(table),
        this.generateJoinClause(table, joinArray, paramOffset),
        this.generateWhereClause(table, multiFilter, paramOffset),
        this.generateGroupByClause(table, groupByArray),
        this.generateOrderByClause(table, orderByArray, groupByArray),
        this.generateLimitClause(limitObj)
    ].join('');

  }

  generateCountQuery(subQuery, table) {

    return [
      `SELECT COUNT(*) `,
      `AS __total__ FROM `,
      subQuery ? `(${subQuery}) AS ` : '',
      `${this.escapeField(table)}`
    ].join('');

  }

  generateUpdateQuery(table, columnNames) {

    return this.generateUpdateAllQuery(table, columnNames[0], columnNames.slice(1), [], 1);

  }

  generateUpdateAllQuery(table, pkColumn, columnNames, columnFunctions, offset, subQuery) {

    let fields = columnNames
      .map(this.escapeField.bind(this))
      .concat(columnFunctions.map(f => this.escapeField(f[0])));

    let params = columnNames
      .map((v, i) => '$' + (i + offset + 1))
      .concat(columnFunctions.map(f => {
        let fn = f[2];
        let fields = f[1];
        fields = fields instanceof Array ? fields : [fields];
        return fn.apply(null, fields.map(field => this.escapeField(field)));
      }));

    return [
      `UPDATE ${this.escapeField(table)}`,
      ` SET (${fields.join(',')}) = (${params.join(',')})`,
      ` WHERE (`,
        this.escapeField(pkColumn),
        subQuery ? ` IN (${subQuery})` : ` = $1`,
      `) RETURNING *`
    ].join('');

  }

  generateDeleteQuery(table, columnNames) {

    return [
      'DELETE FROM ',
        this.escapeField(table),
      ' WHERE (',
        columnNames.map(this.escapeField.bind(this)).join(','),
      ') = (',
        columnNames.map(function(v, i) { return '$' + (i + 1); }).join(','),
      ') RETURNING *'
    ].join('');

  }

  generateDeleteAllQuery(table, columnName, values, joins) {

    let subQuery;

    if (!joins) {

      subQuery = `${values.map((v, i) => '\$' + (i + 1))}`;

    } else {

      subQuery = [
        `SELECT ${this.escapeField(table)}.${this.escapeField(columnName)} FROM ${this.escapeField(table)}`
      ];

      subQuery = subQuery.concat(
        joins.slice().reverse().map((j, i) => {
          return [
            `INNER JOIN ${this.escapeField(j.prevTable)} ON `,
            `${this.escapeField(j.prevTable)}.${this.escapeField(j.prevColumn)} = `,
            `${this.escapeField(j.joinTable)}.${this.escapeField(j.joinColumn)}`,
            i === joins.length - 1 ?
              ` AND ${this.escapeField(j.prevTable)}.${this.escapeField(j.prevColumn)} IN (${values.map((v, i) => '\$' + (i + 1))})` : ''
          ].join('')
        })
      ).join(' ');

    }

    return [
      `DELETE FROM ${this.escapeField(table)}`,
      `WHERE ${this.escapeField(table)}.${this.escapeField(columnName)}`,
      `IN (${subQuery})`
    ].join(' ');
  }

  generateInsertQuery(table, columnNames) {
    return [
      'INSERT INTO ',
        this.escapeField(table),
      '(',
        columnNames.map(this.escapeField.bind(this)).join(','),
      ') VALUES(',
        columnNames.map(function(v, i) { return '$' + (i + 1); }).join(','),
      ') RETURNING *'
    ].join('');
  }

  generateAlterTableQuery(table, columnName, type, properties) {

    let queries = [];

    if (type) {
      queries.push(
        this.generateAlterTableColumnType(
          table,
          columnName,
          this.getTypeDbName(type),
          this.getTypeProperties(type, properties)
        )
      );
    }

    if (properties.hasOwnProperty('primary_key')) {
      queries.push(
        [
          this.generateAlterTableDropPrimaryKey,
          this.generateAlterTableAddPrimaryKey
        ][properties.primary_key | 0].call(this, table, columnName)
      );
    } else if (properties.hasOwnProperty('unique')) {
      queries.push(
        [
          this.generateAlterTableDropUniqueKey,
          this.generateAlterTableAddUniqueKey
        ][properties.unique | 0].call(this, table, columnName)
      );
    }

    return queries.join(';');

  }

  generateAlterTableAddColumnQuery(table, columnName, type, properties) {

    return this.generateAlterTableAddColumn(
      table,
      columnName,
      this.getTypeDbName(type),
      this.getTypeProperties(type, properties)
    );

  }

  generateAlterTableDropColumnQuery(table, columnName) {

    return this.generateAlterTableDropColumn(table, columnName);

  }

  generateAlterTableRenameColumnQuery(table, columnName, newColumnName) {

    return this.generateAlterTableRenameColumn(table, columnName, newColumnName);

  }

  generateCreateIndexQuery(table, columnName, indexType) {

    indexType = indexType || 'btree';

    return this.generateCreateIndex(table, columnName, indexType);

  }

  generateDropIndexQuery(table, columnName) {

    return this.generateDropIndex(table, columnName);

  }

  preprocessWhereObj(table, whereObj) {
    return whereObj;
  }

  parseWhereObj(table, whereObj) {

    return whereObj.map((where, i) => {
      return {
        table: where.table,
        columnName: where.columnName,
        refName: [this.escapeField(where.table || table), this.escapeField(where.columnName)].join('.'),
        comparator: where.comparator,
        value: where.value,
        ignoreValue: !!this.comparatorIgnoresValue[where.comparator],
        joined: where.joined,
        joins: where.joins
      };
    });

  }

  createMultiFilter(table, whereObjArray) {

    return whereObjArray
      .filter(v => v)
      .sort((a, b) => a.joined === b.joined ? a.table > b.table : a.joined > b.joined) // important! must be sorted.
      .map(v => this.preprocessWhereObj(table, v))
      .map(v => this.parseWhereObj(table, v));

  }

  generateWhereClause(table, multiFilter, paramOffset) {

    paramOffset = Math.max(0, parseInt(paramOffset) || 0);

    if (!multiFilter || !multiFilter.length) {
      return '';
    }

    return ` WHERE ${this.generateOrClause(table, multiFilter, paramOffset)}`;

  }

  generateOrClause(table, multiFilter, paramOffset) {

    paramOffset = Math.max(0, parseInt(paramOffset) || 0);

    if (!multiFilter || !multiFilter.length) {
      return '';
    }

    return ('(' + multiFilter.map(whereObj => {
      return this.generateAndClause(table, whereObj);
    }).join(') OR (') + ')').replace(/__VAR__/g, () => `\$${1 + (paramOffset++)}`);

  }

  generateAndClause(table, whereObjArray) {

    let comparators = this.comparators;

    if (!whereObjArray.length) {
      return '';
    }

    let lastTable = null;
    let clauses = [];
    let joinedClauses = [];

    for (let i = 0; i < whereObjArray.length; i++) {

      let whereObj = whereObjArray[i];
      let joined = whereObj.joined;
      let table = whereObj.table;

      if (!joined) {

        clauses.push(comparators[whereObj.comparator](whereObj.refName, whereObj.value));

      } else {

        let currentJoinedClauses = [];

        if (lastTable === table) {

          currentJoinedClauses = joinedClauses[joinedClauses.length - 1].clauses;

        } else {

          joinedClauses.push({
            table: table,
            joins: whereObj.joins,
            clauses: currentJoinedClauses
          });

          clauses.push(null);

        }

        currentJoinedClauses.push(comparators[whereObj.comparator](whereObj.refName, whereObj.value));

      }

    }

    joinedClauses = joinedClauses.map(jc => {

      return [
        `(`,
          `SELECT ${this.escapeField(jc.table)}.${this.escapeField('id')} `,
          `FROM ${this.escapeField(jc.table)} `,
          jc.joins.map((join, i) => {
            return [
              `INNER JOIN ${this.escapeField(join.joinTable)} AS ${this.escapeField(join.joinAlias)} ON `,
              `${this.escapeField(join.joinAlias)}.${this.escapeField(join.joinColumn)} = `,
              `${this.escapeField(join.prevTable || table)}.${this.escapeField(join.prevColumn)}`,
              i === jc.joins.length - 1 ?
                [
                  ` AND `,
                  `${this.escapeField(join.joinAlias)}.${this.escapeField(join.joinColumn)} = `,
                  `${this.escapeField(jc.table)}.${this.escapeField(join.joinColumn)} `,
                  `AND (${jc.clauses.join(' AND ')}) `
                ].join('') : ''
            ].join('')
          }).join(' '),
          `LIMIT 1`,
        `) IS NOT NULL`
      ].join('');

    });

    clauses = clauses.map(c => {
      if (!c) {
        return joinedClauses.shift();
      }
      return c;
    });

    return clauses.join(' AND ');

  }

  getParamsFromMultiFilter(multiFilter) {
    return [].concat.apply([], multiFilter)
      .filter(whereObj => !whereObj.ignoreValue)
      .map(whereObj => whereObj.value);
  }

  generateOrderByClause(table, orderByArray, groupByArray) {

    return !orderByArray.length ? '' : ' ORDER BY ' + orderByArray.map(v => {
      let columns = v.columnNames.map(columnName => `${this.escapeField(table)}.${this.escapeField(columnName)}`);
      return `${(v.transformation || (v => v)).apply(null, columns)} ${v.direction}`;
    }).join(', ');

  }

  generateJoinClause(table, joinArray, paramOffset) {

    paramOffset = Math.max(0, parseInt(paramOffset) || 0);
    let joinedAlready = {};

    return (!joinArray || !joinArray.length) ? '' :
      joinArray.map(joinData => {

        joinData = joinData.filter(join => !joinedAlready[join.joinAlias]);

        return joinData.map((join, i) => {

          joinedAlready[join.joinAlias] = true;

          let joinColumns = join.joinColumn instanceof Array ? join.joinColumn : [join.joinColumn]
          let prevColumns = join.prevColumn instanceof Array ? join.prevColumn : [join.prevColumn]

          let statements = [];

          joinColumns.forEach(joinColumn => {
            prevColumns.forEach(prevColumn => {
              statements.push(
                `${this.escapeField(join.joinAlias)}.${this.escapeField(joinColumn)} = ` +
                `${this.escapeField(join.prevAlias || table)}.${this.escapeField(prevColumn)}`
              );
            });
          });

          let filterClause = this.generateOrClause(join.joinAlias, join.multiFilter, paramOffset);
          join.multiFilter && join.multiFilter.forEach(arr => paramOffset += arr.length);

          return [
            ` LEFT JOIN ${this.escapeField(join.joinTable)}`,
            ` AS ${this.escapeField(join.joinAlias)}`,
            ` ON (${statements.join(' OR ')}`,
            filterClause ? ` AND ${filterClause}` : '',
            ')'
          ].join('');

        }).join('')

      }).join('');

  }

  generateGroupByClause(table, groupByArray) {

    return !groupByArray.length ? '' : ' GROUP BY ' + groupByArray.map(v => {
      let columns = v.columnNames.map(column => `${this.escapeField(table)}.${this.escapeField(column)}`);
      return v.transformation.apply(null, columns);
    }).join(', ');

  }

  generateLimitClause(limitObj) {

    return (!limitObj) ? '' : [
      ' LIMIT ',
      limitObj.offset,
      ', ',
      limitObj.count
    ].join('');

  }

  aggregate(aggregator) {

    return typeof aggregator === 'function' ? aggregator : (
      (this.aggregates.hasOwnProperty(aggregator) ?
        this.aggregates[aggregator] :
        this.aggregates[this.defaultAggregate])
    );

  }

}

SQLAdapter.prototype.typeProperties = [
  'length',
  'nullable',
  'unique',
  'primary_key',
  'auto_increment',
  'array',
  'defaultValue'
];

SQLAdapter.prototype.typePropertyDefaults = {
  length: null,
  nullable: true,
  unique: false,
  primary_key: false,
  auto_increment: false,
  array: false,
  defaultValue: null
};

SQLAdapter.prototype.indexTypes = [];

SQLAdapter.prototype.comparators = {
  is: field => `${field} = __VAR__`,
  not: field => `${field} <> __VAR__`,
  lt: field => `${field} < __VAR__`,
  lte: field => `${field} <= __VAR__`,
  gt: field => `${field} > __VAR__`,
  gte: field => `${field} >= __VAR__`,
  contains: field => `${field} LIKE '%' || __VAR__ || '%'`,
  icontains: field => `${field} ILIKE '%' || __VAR__ || '%'`,
  startswith: field => `${field} LIKE __VAR__ || '%'`,
  istartswith: field => `${field} ILIKE __VAR__ || '%'`,
  endswith: field => `${field} LIKE '%' || __VAR__`,
  iendswith: field => `${field} ILIKE '%' || __VAR__`,
  like: field => `${field} LIKE __VAR__`,
  ilike: field => `${field} ILIKE __VAR__`,
  is_null: field => `${field} IS NULL`,
  not_null: field => `${field} IS NOT NULL`,
  in: field => `ARRAY[${field}] <@ __VAR__`,
  not_in: field => `NOT (ARRAY[${field}] <@ __VAR__)`
};

SQLAdapter.prototype.comparatorIgnoresValue = {
  is_null: true,
  not_null: true
};

SQLAdapter.prototype.documentTypes = [];

SQLAdapter.prototype.aggregates = {
  'sum': field => `SUM(${field})`,
  'avg': field => `AVG(${field})`,
  'min': field => `MIN(${field})`,
  'max': field => `MAX(${field})`,
  'count': field => `COUNT(${field})`,
  'distinct': field => `COUNT(DISTINCT(${field}))`,
  'none': field => `NULL`,
  'min_date': field => `MIN(DATE_TRUNC('day', ${field}))`,
  'max_date': field => `MAX(DATE_TRUNC('day', ${field}))`,
  'count_true': field => `COUNT(CASE WHEN ${field} THEN 1 ELSE NULL END)`
};

SQLAdapter.prototype.defaultAggregate = 'none';

SQLAdapter.prototype.types = {};
SQLAdapter.prototype.sanitizeType = {};
SQLAdapter.prototype.escapeFieldCharacter = '';
SQLAdapter.prototype.columnDepthDelimiter = '';
SQLAdapter.prototype.whereDepthDelimiter = '';

SQLAdapter.prototype.supportsForeignKey = false;

module.exports = SQLAdapter;


text:
                    <a href="<?php echo URL; ?>WordSaladController/initializeMatrix">

Initialize Matrix

                      <a href="<?php echo URL; ?>WordSaladController/trainMatrix">

Train Matrix

                      <a href="<?php echo URL; ?>BackupLogController/createBackup">

Create Backup

      <?php $this->model->PrintMatrix(); ?>


text:
/**
 * Minified by jsDelivr using Terser v3.14.1.
 * Original file: /npm/jquery@3.4.1/src/data/var/dataUser.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
define(["../Data"],function(e){"use strict";return new e});
//# sourceMappingURL=/sm/3781bfe2f0395cd3268ecee2fa6ce694be53d187adc1e8926d7d8e205133c18f.map


text:
/**
 * Make sure that the root of the the F
 */
Layout.setRoot('body');


text:
"""Tests for CachedDataReader class."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# Dependency imports
import tensorflow.compat.v1 as tf

from kfac.python.ops.kfac_utils import data_reader

class DataReaderTest(tf.test.TestCase):

  def test_read_batch(self):
    max_batch_size = 10
    batch_size_schedule = [2, 4, 6, 8]
    data_set = tf.random_uniform(shape=(max_batch_size, 784), maxval=1.)
    var_data = data_reader.CachedDataReader(
        (data_set,), max_batch_size)
    cur_batch_size = tf.placeholder(
        shape=(), dtype=tf.int32, name='cur_batch_size')
    # Force create the ops
    data = var_data(cur_batch_size)[0]
    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())
      coord = tf.train.Coordinator()
      tf.train.start_queue_runners(sess=sess, coord=coord)
      for batch_size in batch_size_schedule:
        data_ = sess.run(
            data, feed_dict={cur_batch_size: batch_size})
        self.assertEqual(len(data_), batch_size)
        self.assertEqual(len(data_[0]), 784)

  def test_cached_batch(self):
    max_batch_size = 100
    data_set = tf.random_uniform(shape=(max_batch_size, 784), maxval=1.)
    var_data = data_reader.CachedDataReader(
        (data_set,), max_batch_size)
    cur_batch_size = tf.placeholder(
        shape=(), dtype=tf.int32, name='cur_batch_size')
    # Force create the ops
    data = var_data(cur_batch_size)[0]
    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())
      coord = tf.train.Coordinator()
      tf.train.start_queue_runners(sess=sess, coord=coord)
      data_ = sess.run(data, feed_dict={cur_batch_size: 25})
      stored_data_ = sess.run(var_data.cached_batch)[0]
      self.assertListEqual(list(data_[1]), list(stored_data_[1]))

if __name__ == '__main__':
  tf.disable_v2_behavior()
  tf.test.main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:springfield="http://www.u2ware.com/schema/springfield"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc
		http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/util
		http://www.springframework.org/schema/util/spring-util.xsd
		http://www.u2ware.com/schema/springfield
		http://www.u2ware.com/schema/springfield/u2ware-springfield.xsd">

	<!--
	#############################################################
	# properties
	#############################################################
	-->
	<util:properties id="prop"
		location="classpath:com/yourcompany/yourproject/root-context.properties" />

	<!--
	#############################################################
	# dataSource
	#############################################################
	 -->
	<jdbc:embedded-database id="dataSource" type="HSQL" />

	<!--
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
	    <property name="driverClass" value="org.postgresql.Driver"/>
	    <property name="jdbcUrl" value="jdbc:postgresql://localhost/springfield"/>
	    <property name="user" value="postgres"/>
	    <property name="password" value="postgres"/>
	</bean>
	-->

	<!--
	#############################################################
	# initialize-database
	#############################################################
	 -->
	<jdbc:initialize-database data-source="dataSource" >
		<jdbc:script location="classpath:com/yourcompany/yourproject/database.ddl"/>
	</jdbc:initialize-database>

	<!--
	#############################################################
	# component-scan (springfield 의 자동 생성 빈을 교체하기 위해서는 springfield:modules 보다 앞쪽에 선언되어야 함)
	#############################################################
	-->
	<context:component-scan base-package="com.yourcompany.yourproject"/>

	<!--
	#############################################################
	# springfield
	#############################################################
	-->
	<springfield:modules base-package="com.yourcompany.yourproject" data-source-ref="dataSource"/>

</beans>


text:
package api

import (
	"bytes"
	"context"
	"encoding/binary"
	"errors"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"time"

	gocoap "github.com/dustin/go-coap"
	"github.com/go-zoo/bone"
	"github.com/golang/protobuf/ptypes"
	"github.com/mainflux/mainflux"
	"github.com/mainflux/mainflux/coap"
	log "github.com/mainflux/mainflux/logger"
	"github.com/mainflux/mainflux/messaging"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

const (
	protocol                   = "coap"
	senMLJSON gocoap.MediaType = 110
	senMLCBOR gocoap.MediaType = 112
)

var (
	errBadRequest        = errors.New("bad request")
	errBadOption         = errors.New("bad option")
	errMalformedSubtopic = errors.New("malformed subtopic")
	channelRegExp        = regexp.MustCompile(`^/?channels/([\w\-]+)/messages(/[^?]*)?(\?.*)?$`)
)

var (
	auth       mainflux.ThingsServiceClient
	logger     log.Logger
	pingPeriod time.Duration
)

type handler func(conn *net.UDPConn, addr *net.UDPAddr, msg *gocoap.Message) *gocoap.Message

//MakeHTTPHandler creates handler for version endpoint.
func MakeHTTPHandler() http.Handler {
	b := bone.New()
	b.GetFunc("/version", mainflux.Version(protocol))
	b.Handle("/metrics", promhttp.Handler())

	return b
}

// MakeCOAPHandler creates handler for CoAP messages.
func MakeCOAPHandler(svc coap.Service, tc mainflux.ThingsServiceClient, l log.Logger, responses chan<- string, pp time.Duration) gocoap.Handler {
	auth = tc
	logger = l
	pingPeriod = pp
	return mux(svc, responses)
}

func mux(svc coap.Service, responses chan<- string) gocoap.Handler {
	return gocoap.FuncHandler(func(conn *net.UDPConn, addr *net.UDPAddr, msg *gocoap.Message) *gocoap.Message {
		path := msg.PathString()
		if !channelRegExp.Match([]byte(path)) {
			logger.Info(fmt.Sprintf("path %s not found", path))
			return &gocoap.Message{
				Type:      gocoap.NonConfirmable,
				Code:      gocoap.NotFound,
				MessageID: msg.MessageID,
				Token:     msg.Token,
			}
		}
		// Allow "/" to be a part of the path.
		if strings.HasPrefix(path, "/") {
			msg.SetPathString(path[1:])
		}
		switch msg.Code {
		case gocoap.GET:
			return observe(svc, responses)(conn, addr, msg)
		default:
			return receive(svc, msg)
		}
	})
}

func id(msg *gocoap.Message) string {
	vars := strings.Split(msg.PathString(), "/")
	if len(vars) > 1 {
		return vars[1]
	}
	return ""
}

func subtopic(msg *gocoap.Message) string {
	path := msg.PathString()
	pos := 0
	for i, c := range path {
		if c == '/' {
			pos++
		}
		if pos == 3 {
			return path[i:]
		}
	}
	return ""
}

func authorize(msg *gocoap.Message, res *gocoap.Message, cid string) (string, error) {
	// Device Key is passed as Uri-Query parameter, which option ID is 15 (0xf).
	query := msg.Option(gocoap.URIQuery)
	queryStr, ok := query.(string)
	if !ok {
		res.Code = gocoap.BadRequest
		return "", errBadRequest
	}

	params, err := url.ParseQuery(queryStr)
	if err != nil {
		res.Code = gocoap.BadRequest
		return "", errBadRequest
	}

	auths, ok := params["authorization"]
	if !ok || len(auths) != 1 {
		res.Code = gocoap.BadRequest
		return "", errBadRequest
	}

	key := auths[0]

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	id, err := auth.CanAccessByKey(ctx, &mainflux.AccessByKeyReq{Token: key, ChanID: cid})
	if err != nil {
		e, ok := status.FromError(err)
		if ok {
			switch e.Code() {
			case codes.PermissionDenied:
				res.Code = gocoap.Forbidden
			default:
				res.Code = gocoap.ServiceUnavailable
			}
			return "", err
		}
		res.Code = gocoap.InternalServerError
	}

	return id.GetValue(), nil
}

func fmtSubtopic(msg *gocoap.Message) (string, error) {
	subtopic := subtopic(msg)
	if subtopic == "" {
		return subtopic, nil
	}

	subtopic = strings.Replace(subtopic, "/", ".", -1)

	elems := strings.Split(subtopic, ".")
	filteredElems := []string{}
	for _, elem := range elems {
		if elem == "" {
			continue
		}

		if len(elem) > 1 && (strings.Contains(elem, "*") || strings.Contains(elem, ">")) {
			return "", errMalformedSubtopic
		}

		filteredElems = append(filteredElems, elem)
	}

	subtopic = strings.Join(filteredElems, ".")

	return subtopic, nil
}

func receive(svc coap.Service, msg *gocoap.Message) *gocoap.Message {
	// By default message is NonConfirmable, so
	// NonConfirmable response is sent back.
	res := &gocoap.Message{
		Type: gocoap.NonConfirmable,
		// According to https://tools.ietf.org/html/rfc7252#page-47: If the POST
		// succeeds but does not result in a new resource being created on the
		// server, the response SHOULD have a 2.04 (Changed) Response Code.
		Code:      gocoap.Changed,
		MessageID: msg.MessageID,
		Token:     msg.Token,
		Payload:   []byte{},
	}

	if msg.IsConfirmable() {
		res.Type = gocoap.Acknowledgement
		res.SetOption(gocoap.ContentFormat, gocoap.AppJSON)
		if len(msg.Payload) == 0 {
			res.Code = gocoap.BadRequest
			return res
		}
	}

	chanID := id(msg)
	if chanID == "" {
		res.Code = gocoap.NotFound
		return res
	}

	subtopic, err := fmtSubtopic(msg)
	if err != nil {
		res.Code = gocoap.BadRequest
		return res
	}

	publisher, err := authorize(msg, res, chanID)
	if err != nil {
		res.Code = gocoap.Forbidden
		return res
	}

	created, err := ptypes.TimestampProto(time.Now())
	if err != nil {
		return nil
	}

	m := messaging.Message{
		Channel:   chanID,
		Subtopic:  subtopic,
		Publisher: publisher,
		Protocol:  protocol,
		Payload:   msg.Payload,
		Created:   created,
	}

	if err := svc.Publish(m); err != nil {
		res.Code = gocoap.InternalServerError
	}

	return res
}

func observe(svc coap.Service, responses chan<- string) handler {
	return func(conn *net.UDPConn, addr *net.UDPAddr, msg *gocoap.Message) *gocoap.Message {
		res := &gocoap.Message{
			Type:      gocoap.Acknowledgement,
			Code:      gocoap.Content,
			MessageID: msg.MessageID,
			Token:     msg.Token,
			Payload:   []byte{},
		}
		res.SetOption(gocoap.ContentFormat, gocoap.AppJSON)

		chanID := id(msg)
		if chanID == "" {
			res.Code = gocoap.NotFound
			return res
		}

		subtopic, err := fmtSubtopic(msg)
		if err != nil {
			res.Code = gocoap.BadRequest
			return res
		}

		publisher, err := authorize(msg, res, chanID)
		if err != nil {
			res.Code = gocoap.Forbidden
			logger.Warn(fmt.Sprintf("Failed to authorize: %s", err))
			return res
		}

		obsID := fmt.Sprintf("%x-%s-%s", msg.Token, publisher, chanID)

		if msg.Type == gocoap.Acknowledgement {
			responses <- obsID
			return nil
		}

		if value, ok := msg.Option(gocoap.Observe).(uint32); (ok && value == 1) || msg.Type == gocoap.Reset {
			svc.Unsubscribe(obsID)
		}

		if value, ok := msg.Option(gocoap.Observe).(uint32); ok && value == 0 {
			res.AddOption(gocoap.Observe, 1)
			o := coap.NewObserver()
			if err := svc.Subscribe(chanID, subtopic, obsID, o); err != nil {
				logger.Warn(err.Error())
				res.Code = gocoap.InternalServerError
				return res
			}

			go handleMessage(conn, addr, o, msg)
			go ping(svc, obsID, conn, addr, o, msg)
			go cancel(o)
		}

		return res
	}
}

func cancel(observer *coap.Observer) {
	<-observer.Cancel
	close(observer.Messages)
	observer.StoreExpired(true)
}

func handleMessage(conn *net.UDPConn, addr *net.UDPAddr, o *coap.Observer, msg *gocoap.Message) {
	notifyMsg := *msg
	notifyMsg.Type = gocoap.NonConfirmable
	notifyMsg.Code = gocoap.Content
	notifyMsg.RemoveOption(gocoap.URIQuery)
	for {
		msg, ok := <-o.Messages
		if !ok {
			return
		}

		notifyMsg.Payload = msg.Payload
		notifyMsg.MessageID = o.LoadMessageID()
		buff := new(bytes.Buffer)
		observe := uint64(notifyMsg.MessageID)
		if err := binary.Write(buff, binary.BigEndian, observe); err != nil {
			logger.Warn(fmt.Sprintf("Failed to generate Observe option value: %s", err))
			continue
		}

		observeVal := buff.Bytes()
		notifyMsg.SetOption(gocoap.Observe, observeVal[len(observeVal)-3:])

		if err := gocoap.Transmit(conn, addr, notifyMsg); err != nil {
			logger.Warn(fmt.Sprintf("Failed to send message to observer: %s", err))
		}
	}
}

func ping(svc coap.Service, obsID string, conn *net.UDPConn, addr *net.UDPAddr, o *coap.Observer, msg *gocoap.Message) {
	pingMsg := *msg
	pingMsg.Payload = []byte{}
	pingMsg.Type = gocoap.Confirmable
	pingMsg.RemoveOption(gocoap.URIQuery)
	// According to RFC (https://tools.ietf.org/html/rfc7641#page-18), CON message must be sent at least every
	// 24 hours. Deafault value of pingPeriod is 12.
	t := time.NewTicker(pingPeriod * time.Hour)
	defer t.Stop()
	for {
		select {
		case _, ok := <-t.C:
			if !ok || o.LoadExpired() {
				return
			}

			o.StoreExpired(true)
			timeout := float64(coap.AckTimeout)
			logger.Info(fmt.Sprintf("Ping client %s.", obsID))
			for i := 0; i < coap.MaxRetransmit; i++ {
				pingMsg.MessageID = o.LoadMessageID()
				gocoap.Transmit(conn, addr, pingMsg)
				time.Sleep(time.Duration(timeout * coap.AckRandomFactor))
				if !o.LoadExpired() {
					break
				}
				timeout = 2 * timeout
			}

			if o.LoadExpired() {
				svc.Unsubscribe(obsID)
				return
			}
		case <-o.Cancel:
			return
		}
	}
}


text: angular.module('gepsens', ['gepsens.services']);