text:
var express = require('express')
    path    = require('path');

var app        = module.exports = express(),
    moduleName = path.basename(module.id, ".js");

app.get('/invoices', function(req, res ) {
    var token = req.get('X-API-ACCESS-Token');
    if( token === 'leapingzebras' ) {
        var response = {
            invoices: [
                { id: 23211, date: '30/11/14', value: '39892.32' },
                { id: 23299, date: '28/11/14', value: '42.10' }
            ]
        }
        res.send(response);
    } else {
        res.status(401).send('You are not authorized to access this resource');
    }
});

app.get('/secret', function( req, res ) {
    var token = req.get('X-API-ACCESS-Token');
    if( token === 'leapingzebras' ) {
        var nextLevelUri = module.parent.exports.getNextLevel(moduleName).uri;
        var levelIndex = module.parent.exports.namedIndex[moduleName].index;
        var response =
            module.parent.exports.generateResponse(levelIndex,
            {
                message: "Congratulations, you have made it to the next level!",
            },
            {
                next: nextLevelUri
            },
            [
                "OWASP A3:2017 - Sensitive Data Exposure",
                "Single page apps are often too easy to reverse-engineer, if not carefully designed",
                "Don't put access codes in publicly viewable places"
            ]);
        res.send(response);
    } else {
        res.status(401).send('You are not authorized to access this resource');
    }

});


text:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout
from django import forms
from django.utils.translation import ugettext_noop

from corehq.apps.programs.models import Program
from corehq.apps.products.models import Product
from corehq.apps.commtrack.util import all_sms_codes
import json

class CurrencyField(forms.DecimalField):
    """
    Allows a field to accept human readable currency values.

    Example: $1,400.25 will be accepted and stored as 1400.25
    """

    def clean(self, value):
        for c in ['$', ',']:
            value = value.replace(c, '')

        return super(CurrencyField, self).clean(value)

class ProductForm(forms.Form):
    name = forms.CharField(max_length=100)
    code = forms.CharField(label=ugettext_noop("Product ID"), max_length=100, required=False)
    description = forms.CharField(max_length=500, required=False, widget=forms.Textarea)
    unit = forms.CharField(label=ugettext_noop("Units"), max_length=100, required=False)
    program_id = forms.ChoiceField(label=ugettext_noop("Program"), choices=(), required=True)
    cost = CurrencyField(max_digits=8, decimal_places=2, required=False)

    def __init__(self, product, *args, **kwargs):
        self.product = product

        kwargs['initial'] = self.product._doc
        kwargs['initial']['code'] = self.product.code

        super(ProductForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.label_class = 'col-sm-3 col-md-4 col-lg-2'
        self.helper.field_class = 'col-sm-4 col-md-5 col-lg-3'

        programs = Program.by_domain(self.product.domain, wrap=False)
        self.fields['program_id'].choices = tuple((prog['_id'], prog['name']) for prog in programs)

        # make sure to select default program if
        # this is a new product
        if not product._id:
            self.initial['program_id'] = Program.default_for_domain(self.product.domain)._id

        self.helper.layout = Layout(
            'name',
            'code',
            'description',
            'unit',
            'program_id',
            'cost'
        )

    def clean_name(self):
        name = self.cleaned_data['name']

        other_products = [p for p in Product.by_domain(self.product.domain) if p._id != self.product._id]
        if name in [p.name for p in other_products]:
            raise forms.ValidationError('name already in use')

        return name

    def clean_code(self):
        code = self.cleaned_data['code'].lower()

        conflict = None
        sms_codes = all_sms_codes(self.product.domain)
        if code in sms_codes:
            conflict = sms_codes[code]
            if conflict[0] == 'product' and conflict[1]._id == self.product._id:
                conflict = None

        if conflict:
            conflict_name = {
                'product': lambda o: o.name,
                'action': lambda o: o.caption,
                'command': lambda o: o['caption'],
            }[conflict[0]](conflict[1])
            raise forms.ValidationError('product id not unique (conflicts with %s "%s")' % (conflict[0], conflict_name))

        return code.lower()

    def save(self, instance=None, commit=True):
        if self.errors:
            raise ValueError('form does not validate')

        product = instance or self.product

        for field in ('name', 'code', 'program_id', 'unit', 'description', 'cost'):
            setattr(product, field, self.cleaned_data[field])

        product_data = self.data.get('product_data')
        if product_data:
            product.product_data = json.loads(product_data)

        if commit:
            product.save()

        return product

redpajama_set_name: RedPajamaGithub


text:
#include "com/mapswithme/core/jni_helper.hpp"
#include "com/mapswithme/maps/Framework.hpp"
#include "com/mapswithme/maps/SearchEngine.hpp"
#include "com/mapswithme/maps/discovery/Locals.hpp"
#include "com/mapswithme/maps/promo/Promo.hpp"

#include "map/discovery/discovery_manager.hpp"
#include "map/search_product_info.hpp"

#include "search/result.hpp"

#include "partners_api/locals_api.hpp"
#include "partners_api/promo_api.hpp"

#include "geometry/mercator.hpp"

#include "platform/preferred_languages.hpp"

#include <memory>
#include <utility>
#include <vector>

using namespace std::placeholders;

namespace
{
jclass g_discoveryManagerClass = nullptr;
jfieldID g_discoveryManagerInstanceField;
jmethodID g_onResultReceivedMethod;
jmethodID g_onLocalExpertsReceivedMethod;
jmethodID g_onCityGalleryReceivedMethod;
jmethodID g_onErrorMethod;
uint32_t g_lastRequestId = 0;

void PrepareClassRefs(JNIEnv * env)
{
  if (g_discoveryManagerClass != nullptr)
    return;

  g_discoveryManagerClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/discovery/DiscoveryManager");

  g_discoveryManagerInstanceField = jni::GetStaticFieldID(env, g_discoveryManagerClass, "INSTANCE",
                                                          "Lcom/mapswithme/maps/discovery/DiscoveryManager;");

  jobject discoveryManagerInstance = env->GetStaticObjectField(g_discoveryManagerClass,
                                                               g_discoveryManagerInstanceField);

  g_onResultReceivedMethod = jni::GetMethodID(env, discoveryManagerInstance, "onResultReceived",
                                              "([Lcom/mapswithme/maps/search/SearchResult;I)V");

  g_onLocalExpertsReceivedMethod = jni::GetMethodID(env, discoveryManagerInstance,
                                                    "onLocalExpertsReceived",
                                                    "([Lcom/mapswithme/maps/discovery/LocalExpert;)V");
  g_onCityGalleryReceivedMethod = jni::GetMethodID(env, discoveryManagerInstance,
                                                   "onPromoCityGalleryReceived",
                                                   "(Lcom/mapswithme/maps/promo/PromoCityGallery;)V");
  g_onErrorMethod = jni::GetMethodID(env, discoveryManagerInstance, "onError", "(I)V");
}

struct DiscoveryCallback
{
  void operator()(uint32_t const requestId, search::Results const & results,
                  std::vector<search::ProductInfo> const & productInfo,
                  discovery::ItemType const type, m2::PointD const & viewportCenter) const
  {
    if (g_lastRequestId != requestId)
      return;

    ASSERT(g_discoveryManagerClass != nullptr, ());
    JNIEnv * env = jni::GetEnv();

    auto const lat = MercatorBounds::YToLat(viewportCenter.y);
    auto const lon = MercatorBounds::XToLon(viewportCenter.x);
    jni::TScopedLocalObjectArrayRef jResults(
        env, BuildSearchResults(results, productInfo, true /* hasPosition */, lat, lon));
    jobject discoveryManagerInstance = env->GetStaticObjectField(g_discoveryManagerClass,
                                                                 g_discoveryManagerInstanceField);
    env->CallVoidMethod(discoveryManagerInstance, g_onResultReceivedMethod,
                        jResults.get(), static_cast<jint>(type));

    jni::HandleJavaException(env);
  }

  void operator()(uint32_t const requestId, std::vector<locals::LocalExpert> const & experts) const
  {
    if (g_lastRequestId != requestId)
      return;

    ASSERT(g_discoveryManagerClass != nullptr, ());
    JNIEnv * env = jni::GetEnv();

    jni::TScopedLocalObjectArrayRef jLocals(env, ToLocalExpertsArray(experts));
    jobject discoveryManagerInstance = env->GetStaticObjectField(g_discoveryManagerClass,
                                                                 g_discoveryManagerInstanceField);
    env->CallVoidMethod(discoveryManagerInstance, g_onLocalExpertsReceivedMethod, jLocals.get());

    jni::HandleJavaException(env);
  }

  void operator()(uint32_t const requestId, promo::CityGallery const & cityGallery) const
  {
    if (g_lastRequestId != requestId)
      return;

    ASSERT(g_discoveryManagerClass != nullptr, ());
    JNIEnv * env = jni::GetEnv();

    jni::TScopedLocalRef gallery(env, promo::MakeCityGallery(env, cityGallery));
    jobject discoveryManagerInstance =
        env->GetStaticObjectField(g_discoveryManagerClass, g_discoveryManagerInstanceField);
    env->CallVoidMethod(discoveryManagerInstance, g_onCityGalleryReceivedMethod, gallery.get());

    jni::HandleJavaException(env);
  }
};

void OnDiscoveryError(uint32_t const requestId, discovery::ItemType const type)
{
  if (g_lastRequestId != requestId)
    return;

  ASSERT(g_discoveryManagerClass != nullptr, ());

  JNIEnv * env = jni::GetEnv();
  jobject discoveryManagerInstance = env->GetStaticObjectField(g_discoveryManagerClass,
                                                               g_discoveryManagerInstanceField);
  env->CallVoidMethod(discoveryManagerInstance, g_onErrorMethod, static_cast<jint>(type));

  jni::HandleJavaException(env);
}
}  // namespace

extern "C" {

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_discovery_DiscoveryManager_nativeDiscover(JNIEnv * env, jclass,
                                                                   jobject params)
{
  PrepareClassRefs(env);

  discovery::ClientParams p;
  auto const paramsClass = env->GetObjectClass(params);
  static auto const currencyField = env->GetFieldID(paramsClass, "mCurrency", "Ljava/lang/String;");
  {
    auto const currency = static_cast<jstring>(env->GetObjectField(params, currencyField));
    string const res = jni::ToNativeString(env, currency);
    if (!res.empty())
      p.m_currency = res;
  }

  static auto const langField = env->GetFieldID(paramsClass, "mLang", "Ljava/lang/String;");
  {
    auto const lang = static_cast<jstring>(env->GetObjectField(params, langField));
    string const res = languages::Normalize(jni::ToNativeString(env, lang));
    if (!res.empty())
      p.m_lang = res;
  }

  static auto const itemsCountField = env->GetFieldID(paramsClass, "mItemsCount", "I");
  {
    auto const count = env->GetIntField(params, itemsCountField);
    ASSERT_GREATER(count, 0, ());
    p.m_itemsCount = static_cast<size_t>(count);
  }

  static auto const itemTypesField = env->GetFieldID(paramsClass, "mItemTypes", "[I");
  {
    auto const array = static_cast<jintArray>(env->GetObjectField(params, itemTypesField));
    auto const length = env->GetArrayLength(array);
    ASSERT_GREATER(length, 0, ());

    auto const dtor = [array, env](jint * data) { env->ReleaseIntArrayElements(array, data, 0); };
    std::unique_ptr<jint, decltype(dtor)> data{env->GetIntArrayElements(array, nullptr), dtor};

    std::vector<discovery::ItemType> itemTypes;
    for (jsize i = 0; i < length; ++i)
      itemTypes.emplace_back(static_cast<discovery::ItemType>(data.get()[i]));

    p.m_itemTypes = std::move(itemTypes);
  }

  g_lastRequestId = g_framework->NativeFramework()->Discover(std::move(p), DiscoveryCallback(),
                                                             std::bind(&OnDiscoveryError, _1, _2));
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_discovery_DiscoveryManager_nativeGetLocalExpertsUrl(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, g_framework->NativeFramework()->GetDiscoveryLocalExpertsUrl());
}
}  // extern "C"


text:
package net.sf.antcontrib.math;

/**
 * An object which can evaluate to a numeric value.
 *
 * @author inger
 */

public interface Evaluateable {
	Number evaluate();
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Page\Admin\CatalogPromotion\ProductVariant;

use Sylius\Behat\Page\Admin\Crud\IndexPage as BaseIndexPage;

class IndexPage extends BaseIndexPage implements IndexPageInterface
{
    public function showProductOf(string $variantCode): void
    {
        $this->getElement('show_product_button')->click();
    }

    protected function getDefinedElements(): array
    {
        return array_merge(parent::getDefinedElements(), [
            'show_product_button' => 'a.ui.button:contains("Show product")',
        ]);
    }
}


text:
ZmqServer::ZmqServer(QObject *parent) : QThread(parent)
{
    L = 0 ;
    synchro = new QSemaphore(0);
}

void ZmqServer::addBlock( SampleBlock *b ) {
    if( b == NULL )
        return ;
    queue.enqueue(b);
    synchro->release(1);
}

void ZmqServer::run() {
    char message[3] ;
    int length ;
    void *context = zmq_ctx_new ();
    void *socket = zmq_socket (context, ZMQ_PUB);
    zmq_bind (socket, "tcp://*:5563");
    if( DEBUG_ZMQ_SRV ) qDebug() << "ZmqServer::run() starting" ;

    message[0] = 'I' ;
    message[1] = 'Q' ;
    message[3] = 0 ;

    for( ; ; ) {
        synchro->acquire(1);
        SampleBlock *b = queue.dequeue() ;
        if( b == NULL )
            continue ;

        TYPECPX *samples = b->getData() ;
        length = b->getLength() ;

        // send header
        zmq_send( socket, (const void *)message, 2, ZMQ_SNDMORE ) ;

        // send size
        zmq_send( socket, (const void *)&length, sizeof(int), ZMQ_SNDMORE );

        // send data
        zmq_send( socket, (const void *)samples, length*sizeof(TYPECPX), 0);

        if( b->isLastBlock() ) {
            // this is the last block of current frame
            // send another ZMQ frame with 0 length to inform readers
            zmq_send( socket, (const void *)message, 2, ZMQ_SNDMORE ) ;
            length = 0 ;
            zmq_send( socket, (const void *)&length, sizeof(int), 0 );
        }

        delete b ;

        if( DEBUG_ZMQ_SRV ) qDebug() << "zmq frame pushed" ;

    }
    qDebug() << "ZmqServer::run() end ???" ;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<configurationDescriptor version="95">
  <logicalFolder name="root" displayName="root" projectFiles="true" kind="ROOT">
    <logicalFolder name="HeaderFiles"
                   displayName="Header Files"
                   projectFiles="true">
      <logicalFolder name="f3" displayName="Auxiliary" projectFiles="true">
        <itemPath>Auxiliary/auxFunc.h</itemPath>
        <itemPath>Auxiliary/complex.h</itemPath>
        <itemPath>Auxiliary/timer.h</itemPath>
      </logicalFolder>
      <logicalFolder name="f2" displayName="ImageFilters" projectFiles="true">
        <itemPath>ImageFilters/clahe.h</itemPath>
        <itemPath>ImageFilters/contrast.h</itemPath>
        <itemPath>ImageFilters/filters.h</itemPath>
        <itemPath>ImageFilters/fourier.h</itemPath>
        <itemPath>ImageFilters/mask.h</itemPath>
        <itemPath>ImageFilters/transformations.h</itemPath>
      </logicalFolder>
      <logicalFolder name="f1" displayName="ImageProcessing" projectFiles="true">
        <itemPath>ImageProcessing/PointLL.h</itemPath>
        <itemPath>ImageProcessing/RegionLL.h</itemPath>
        <itemPath>ImageProcessing/maxTreshHold.h</itemPath>
      </logicalFolder>
      <logicalFolder name="f4" displayName="TiffImage" projectFiles="true">
        <itemPath>TiffImage/readTiff.h</itemPath>
        <itemPath>TiffImage/tiffFile.h</itemPath>
        <itemPath>TiffImage/writeTiff.h</itemPath>
      </logicalFolder>
    </logicalFolder>
    <logicalFolder name="ResourceFiles"
                   displayName="Resource Files"
                   projectFiles="true">
      <logicalFolder name="InputImages" displayName="InputImages" projectFiles="true">
        <itemPath>InputImages/a0.tif</itemPath>
        <itemPath>InputImages/a1.tif</itemPath>
        <itemPath>InputImages/a2.tif</itemPath>
        <itemPath>InputImages/a3.tif</itemPath>
        <itemPath>InputImages/b0.tif</itemPath>
        <itemPath>InputImages/b1.tif</itemPath>
        <itemPath>InputImages/b2.tif</itemPath>
        <itemPath>InputImages/c0.tif</itemPath>
        <itemPath>InputImages/c1.tif</itemPath>
        <itemPath>InputImages/c2.tif</itemPath>
        <itemPath>InputImages/oct_simul.tif</itemPath>
      </logicalFolder>
      <logicalFolder name="OutputImages"
                     displayName="OutputImages"
                     projectFiles="true">
      </logicalFolder>
      <logicalFolder name="OutputLog" displayName="OutputLog" projectFiles="true">
      </logicalFolder>
    </logicalFolder>
    <logicalFolder name="SourceFiles"
                   displayName="Source Files"
                   projectFiles="true">
      <logicalFolder name="f3" displayName="Auxiliary" projectFiles="true">
        <itemPath>Auxiliary/auxFunc.c</itemPath>
        <itemPath>Auxiliary/complex.c</itemPath>
      </logicalFolder>
      <logicalFolder name="f2" displayName="ImageFilters" projectFiles="true">
        <itemPath>ImageFilters/clahe.c</itemPath>
        <itemPath>ImageFilters/contrast.c</itemPath>
        <itemPath>ImageFilters/filters.c</itemPath>
        <itemPath>ImageFilters/fourier.c</itemPath>
        <itemPath>ImageFilters/mask.c</itemPath>
        <itemPath>ImageFilters/transformations.c</itemPath>
      </logicalFolder>
      <logicalFolder name="f1" displayName="ImageProcessing" projectFiles="true">
        <itemPath>ImageProcessing/PointLL.c</itemPath>
        <itemPath>ImageProcessing/RegionLL.c</itemPath>
        <itemPath>ImageProcessing/maxTreshHold.c</itemPath>
      </logicalFolder>
      <logicalFolder name="f3" displayName="Main" projectFiles="true">
        <itemPath>Main/main.c</itemPath>
      </logicalFolder>
      <logicalFolder name="f5" displayName="Test" projectFiles="true">
        <itemPath>Test/peakfinder.c</itemPath>
      </logicalFolder>
      <logicalFolder name="f4" displayName="TiffImage" projectFiles="true">
        <itemPath>TiffImage/readTiff.c</itemPath>
        <itemPath>TiffImage/tiffFile.c</itemPath>
        <itemPath>TiffImage/writeTiff.c</itemPath>
      </logicalFolder>
    </logicalFolder>
    <logicalFolder name="TestFiles"
                   displayName="Test Files"
                   projectFiles="false"
                   kind="TEST_LOGICAL_FOLDER">
    </logicalFolder>
    <logicalFolder name="ExternalFiles"
                   displayName="Important Files"
                   projectFiles="false"
                   kind="IMPORTANT_FILES_FOLDER">
      <itemPath>Makefile</itemPath>
    </logicalFolder>
  </logicalFolder>
  <sourceRootList>
    <Elem>.</Elem>
  </sourceRootList>
  <projectmakefile>Makefile</projectmakefile>
  <confs>
    <conf name="Debug" type="1">
      <toolsSet>
        <compilerSet>default</compilerSet>
        <dependencyChecking>true</dependencyChecking>
        <rebuildPropChanged>false</rebuildPropChanged>
      </toolsSet>
      <compileType>
        <cTool>
          <commandLine>-lm -ltiff -O3</commandLine>
          <warningLevel>2</warningLevel>
        </cTool>
        <ccTool>
          <warningLevel>2</warningLevel>
        </ccTool>
        <linkerTool>
          <commandLine>-lm -ltiff</commandLine>
        </linkerTool>
      </compileType>
      <item path="Auxiliary/auxFunc.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="Auxiliary/auxFunc.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="Auxiliary/complex.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="Auxiliary/complex.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="Auxiliary/timer.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/clahe.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/clahe.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/contrast.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/contrast.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/filters.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/filters.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/fourier.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/fourier.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/mask.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/mask.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/transformations.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/transformations.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageProcessing/PointLL.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageProcessing/PointLL.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageProcessing/RegionLL.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageProcessing/RegionLL.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageProcessing/maxTreshHold.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageProcessing/maxTreshHold.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/a0.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/a1.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/a2.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/a3.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/b0.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/b1.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/b2.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/c0.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/c1.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/c2.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/oct_simul.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="Main/main.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="Test/peakfinder.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="TiffImage/readTiff.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="TiffImage/readTiff.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="TiffImage/tiffFile.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="TiffImage/tiffFile.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="TiffImage/writeTiff.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="TiffImage/writeTiff.h" ex="false" tool="3" flavor2="0">
      </item>
    </conf>
    <conf name="Release" type="1">
      <toolsSet>
        <compilerSet>default</compilerSet>
        <dependencyChecking>true</dependencyChecking>
        <rebuildPropChanged>false</rebuildPropChanged>
      </toolsSet>
      <compileType>
        <cTool>
          <developmentMode>5</developmentMode>
        </cTool>
        <ccTool>
          <developmentMode>5</developmentMode>
        </ccTool>
        <fortranCompilerTool>
          <developmentMode>5</developmentMode>
        </fortranCompilerTool>
        <asmTool>
          <developmentMode>5</developmentMode>
        </asmTool>
      </compileType>
      <item path="Auxiliary/auxFunc.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="Auxiliary/auxFunc.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="Auxiliary/complex.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="Auxiliary/complex.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="Auxiliary/timer.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/clahe.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/clahe.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/contrast.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/contrast.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/filters.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/filters.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/fourier.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/fourier.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/mask.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/mask.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageFilters/transformations.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageFilters/transformations.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageProcessing/PointLL.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageProcessing/PointLL.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageProcessing/RegionLL.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageProcessing/RegionLL.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="ImageProcessing/maxTreshHold.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="ImageProcessing/maxTreshHold.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/a0.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/a1.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/a2.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/a3.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/b0.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/b1.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/b2.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/c0.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/c1.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/c2.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="InputImages/oct_simul.tif" ex="false" tool="3" flavor2="0">
      </item>
      <item path="Main/main.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="Test/peakfinder.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="TiffImage/readTiff.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="TiffImage/readTiff.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="TiffImage/tiffFile.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="TiffImage/tiffFile.h" ex="false" tool="3" flavor2="0">
      </item>
      <item path="TiffImage/writeTiff.c" ex="false" tool="0" flavor2="0">
      </item>
      <item path="TiffImage/writeTiff.h" ex="false" tool="3" flavor2="0">
      </item>
    </conf>
  </confs>
</configurationDescriptor>


text:
type Portal = StructurePortal;

/**
 * A non-player structure. Instantly teleports your creeps to a distant room acting as a room exit tile. Portals appear randomly in the
 * central room of each sector.
 */
declare class StructurePortal extends Structure {

  /**
   * The position object in the destination room.
   */
  public destination: RoomPosition;

  /**
   * The amount of game ticks when the portal disappears, or undefined when the portal is stable.
   */
  public ticksToDecay: number | undefined;

  /**
   * A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.
   *
   * NOTE: we override the room from Structure since we are guaranteed the type
   */
  public readonly id: StructureId<Portal>;

  /**
   * One of the STRUCTURE_* constants.
   *
   * NOTE: we override the room from Structure since we are guaranteed the type
   */
  public readonly structureType: StructureType<Portal>;

}


text:
What is django-contactform?
===========================

django-contactform is an Django application providing generic,
class-based contact form.

It is full-featured, ready to use application that lets quickly add
a contact form to the service. It comes with built-in feature to
send emails to managers/webmasters and throttling option to prevent spamming.

Usage
=====

Obligatory steps
----------------

To get started one needs to subclass ``views.ContactView`` and override
both of the following methods:

* ``get_subject``,
* ``get_from_email``.

For example::

    from contactform.views import ContactView

    class MyContactView(ContactView):
        def get_subject(self, form):
            return "Contact from MySite"

        def get_from_email(self, form):
            return "MySite <no-reply@example.com>"

Next step is to create two templates:

* ``contactform/contact_form.html`` – renders the form,
* ``contactform/email_body.txt`` – renders the body of an e-mail sent to
  recipients.

The ``email_body.txt`` template's context is populated with ``form``
and ``fields`` variables, which are submitted and validated form
and ``form.cleaned_data`` respectively. Note, that ``fields`` variable is
provided only for convenience and ``form.cleaned_data`` might be used as well.

One must also configure e-mail sending in Django settings. In most cases
setting ``EMAIL_HOST``, ``EMAIL_HOST_USER`` and ``EMAIL_HOST_PASSWORD`` will do.
For more information, please consult `Django documentation about settings`_.

.. _Django documentation about settings:
    https://docs.djangoproject.com/en/dev/ref/settings/

Optional steps
--------------

Recipients list defaults to list derived from ``settings.MANAGERS``,
but it may be changed by overriding ``recipients`` class variable
or ``get_recipients`` method.

Additional e-mail headers may be added by overriding ``get_headers`` method.
One common reason to do this is to provide ``Reply-To`` header. For example::

    class MyContactView(ContactView):
        def get_headers(self, form):
            return  {'Reply-To': u"{0}<{1}>".format(form.cleaned_data['name'], form.cleaned_data['email'])}

This will result in setting ``Reply-To`` header to name and e-mail provided
by the user submitting the form.

Throttling settings default to 3 e-mails per minute and 10 per hour. It's
configurable by overriding ``messages_per_minute`` and ``messages_per_hour``
class variables or – for more control – ``sending_allowed`` method.

Logs
====

django-contactform logs every submission of the form by creating
``models.ContactLog``. It stores information about IP and e-mail along with
date and status (message sent or throttled).

These logs are used internally to decide if the submission quota was
exceeded or not, but may also be used to detect abuses.

What it looks like?
===================

Everybody loves screenshots, right? But actually the look of the form
depends on how designer styles it. Here is humble example to show the idea.

Rendered form:

.. image:: http://img846.imageshack.us/img846/8231/contactlogform.png
  :alt: Rendered form

And some screenshots of admin showing ContactLogs.

Admin list view:

.. image:: http://img217.imageshack.us/img217/3503/contactloglistview.png
  :alt: Admin list view

Admin item view:

.. image:: http://img543.imageshack.us/img543/2531/contactlogchangeview.png
  :alt: Admin item view

Installation
============

django-contactform is installed just like any other Django application:

1. Put *contactform* directory in any path, where python can find it
2. Add *contactform* to ``installed_apps`` in settings.py
3. Run ```manage.py syncdb``` to create database tables for contactform logs
4. (optional) Register ModelAdmin classes found in ``contactform/admin.py`` file in your admin site

Disclaimer
==========

django-contactform is a work in progress and it's API is considered unstable.
It is very likely, the backward compatibility won't be maintained in
next few releases.

License
=======

Copyright (c) 2012, Aleksander Zdyb
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
#ifndef FROG_SCENE_HPP
#define FROG_SCENE_HPP

#include "FROG/Core/AppInfo.hpp"
#include "FROG/Core/AssetManager.hpp"
#include "FROG/Core/GameState.hpp"
#include "FROG/Core/GameObject.hpp"
#include "FROG/Rendering/Renderer.hpp"
#include "FROG/Rendering/Spritesheet.hpp"

#include <set>
#include <memory>

#include <SFML/Audio/SoundBuffer.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Texture.hpp>

namespace frog{

  /*!
   * Scenes are main bricks of a game. They are special states.
   */
  class Scene : public GameState
  {

  public:
    typedef std::shared_ptr<Scene> PTR;

    //// attributes ////
    Renderer renderer;
  protected:
    AssetManager<std::string, sf::Texture> defaultTextureManager;
    AssetManager<std::string, sf::Font> defaultFontManager;
    AssetManager<std::string, sf::SoundBuffer> defaultSoundManager;
    AssetManager<std::string, Spritesheet<std::string> > defaultSpritesheetManager;

    //// operations ////
  public:

    Scene(AppInfo&);
    Scene(const Scene&);
    Scene(const GameState&);

    virtual ~Scene();

    /*!
     * @brief Loads the state from a file
     * @param file File to extract data from
     * @return True if the loading has succeeded
     */
    bool loadFromFile(const std::string& file);

    // unusable because of templates
    // void fillAssetManager(AssetManager&, tinyxml2::XMLElement *);

    /*
     * @brief updates the scene and renders it.
     * @details calls preupdate, updates all the registered GameObjects, and
     * call postupdate. Finally, the scene's renderer updates.
     */
    virtual void update();

    static PTR create(AppInfo&);
    static PTR create(const Scene&);
    static PTR create(const GameState&);

    virtual bool addObject(GameObject * go); // avoid

    virtual bool addObject(const GameObject::PTR& go);

    /*!
     * \brief Removes an object from the scene's systems
     * \details If the object is not present, nothing happens
     * \param go GameObject to remove
     */
    virtual void removeObject(GameObject * go); // avoid

    virtual void removeObject(const GameObject::PTR& go);

  protected:

    void addToEngines(const GameObject::PTR& go);

    void removeFromEngines(const GameObject::PTR& go);

  };

}

#endif


text: Copyright 2012 © Stanley Cen


text:
// This file is automatically generated.

package adila.db;

/*
 * LG Optimus L40
 *
 * DEVICE: w3ts
 * MODEL: LG-D180f
 */
final class w3ts {
    public static final String DATA = "LG|Optimus L40|";
}


text:
@import 'components/AuthSetter.css';
@import 'components/Commit.css';
@import 'components/CommitDetail.css';
@import 'components/Contributors.css';
@import 'components/Diff.css';
@import 'components/History.css';
@import 'components/ProjectUrl.css';
@import 'components/TypicalCommit.css';

body {
	position: relative;
	color: #000000;
	height: 100vh;
	background-color: #FFFFFF;
	font-family: Arial, Helvetica, Helvetica Neue, serif;
	overflow: hidden;
	margin: 0;
}

.layout {
	display: flex;
	flex-direction: column;
	height: 100vh;
}
.layout-content {
	padding: 15px 15px 70px;
	flex: 1;
	width: 100%;
	overflow-y: auto;
	box-sizing: border-box;
}

@keyframes loading {
	0% {
		transform: perspective(120px) rotateX(0deg) rotateY(0deg);
	}
	50% {
		transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
	}
	100% {
		transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
	}
}
.loading {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}
.loading:before {
	width: 40px;
	height: 40px;
	background-color: #333;
	margin: 100px auto;
	animation: loading 1.2s infinite ease-in-out;
	display: block;
	content: '';
}

@keyframes delayHardReset {
	0% {
		opacity: 0;
	}
	100% {
		opacity: 1;
	}
}
.hardReset {
	position: fixed;
	left: 0;
	bottom: 0;
	right: 0;
	text-align: center;
	padding: 1em;
	animation: delayHardReset 1s 5s both;
}
.hardReset-title {
	font-size: 0.8em;
}
.hardReset-action {
	background: none;
	border: 1px solid #000000;
	padding: 1em 2em;
	color: inherit;
	cursor: pointer;
}
.hardReset-action:hover,
.hardReset-action:focus {
	box-shadow: 0 0 10px #000000;
}
.hardReset-action:focus {
	color: #FFFFFF;
	background-color: #000000;
}


text:
//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Microsoft.WindowsAPICodePack.Net
{
    [ComImport, ClassInterface((short)0), Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B")]
    [ComSourceInterfaces("Microsoft.Windows.NetworkList.Internal.INetworkEvents\0Microsoft.Windows.NetworkList.Internal.INetworkConnectionEvents\0Microsoft.Windows.NetworkList.Internal.INetworkListManagerEvents\0"), TypeLibType((short)2)]

    internal class NetworkListManagerClass : INetworkListManager
    {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(7)]
        public virtual extern Connectivity GetConnectivity();

        [return: MarshalAs(UnmanagedType.Interface)]
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2)]
        public virtual extern INetwork GetNetwork([In] Guid gdNetworkId);

        [return: MarshalAs(UnmanagedType.Interface)]
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(4)]
        public virtual extern INetworkConnection GetNetworkConnection([In] Guid gdNetworkConnectionId);

        [return: MarshalAs(UnmanagedType.Interface)]
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(3)]
        public virtual extern IEnumerable GetNetworkConnections();

        [return: MarshalAs(UnmanagedType.Interface)]
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)]
        public virtual extern IEnumerable GetNetworks([In] NetworkConnectivityLevels Flags);

        [DispId(6)]
        public virtual extern bool IsConnected
        {
            [MethodImpl(MethodImplOptions.InternalCall,
                MethodCodeType = MethodCodeType.Runtime), DispId(6)]
            get;
        }

        [DispId(5)]
        public virtual extern bool IsConnectedToInternet
        {
            [MethodImpl(MethodImplOptions.InternalCall,
                MethodCodeType = MethodCodeType.Runtime), DispId(5)]
            get;
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />

  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

  <title>Help - Defining Show Type</title>
  <meta name="description" content="Definitions of the Show Type" />
  <meta name="author" content="James Oliver" />

  		Back to Definitions

Type 23

Acoustic

Includes any acoustic music that falls under the pop/rock genre


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * ChangePasswordForm is the model behind the change password form.
 */
class ChangePasswordForm extends Model
{
    public $shouldValidateOldPassword = true;
    public $oldPassword;
	public $newPassword;
	public $confirmNewPassword;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // all passwords are both required
            [['oldPassword', 'newPassword', 'confirmNewPassword'], 'required'],
            [['oldPassword', 'newPassword', 'confirmNewPassword'], 'string', 'max' => 32],
            // old password is validated by validateOldPassword()
            ['oldPassword', 'validateOldPassword'],
            // new password is validated by validateNewPassword()
            ['newPassword', 'validateNewPassword'],
            // confirm new password is validated by validateConfirmNewPassword()
            ['confirmNewPassword', 'validateConfirmNewPassword'],
        ];
    }

    /**
     * Validates the old password.
     * This method serves as the inline validation for old password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateOldPassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = Yii::$app->user->identity;
            if (!$user && shouldValidateOldPassword && !$user->validatePassword($this->oldPassword)) {
            	if(preg_match('/(?i)msie [1-6]/',$_SERVER['HTTP_USER_AGENT'])) {
            		// if IE <= 6
            		echo 'alert("Incorrect password.")';
            	} else {
            		$this->addError($attribute, 'Incorrect password.');
            	}
            }
        }
    }

    /**
     * Validates the new password.
     * This method serves as the inline validation for new password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateNewPassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if ($this->newPassword === Yii::$app->params['DEFAULT_PASSWORD']) {
                if(preg_match('/(?i)msie [1-6]/',$_SERVER['HTTP_USER_AGENT'])) {
                    // if IE <= 6
                    echo 'alert("New password should not use default password.")';
                } else {
                    $this->addError($attribute, 'New password should not use default password.');
                }
            } else if ($this->oldPassword === $this->newPassword) {
                if(preg_match('/(?i)msie [1-6]/',$_SERVER['HTTP_USER_AGENT'])) {
                    // if IE <= 6
                    echo 'alert("New password should not be the same with old password.")';
                } else {
                    $this->addError($attribute, 'New password should not be the same with old password.');
                }
            }
        }
    }

	/**
     * Validates the confirm new password.
     * This method serves as the inline validation for confirm new password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateConfirmNewPassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
        	if ($this->confirmNewPassword != $this->newPassword) {
        		if(preg_match('/(?i)msie [1-6]/',$_SERVER['HTTP_USER_AGENT'])) {
            		// if IE <= 6
            		echo 'alert("The new password and confirmation password do not match.")';
            	} else {
            		$this->addError($attribute, 'The new password and confirmation password do not match.');
            	}
        	}
        }
    }

	/**
     * Changes the password of user using the provided old password, new password and confirm new password.
     * @return boolean whether the user has changed password successfully
     */
    public function changePassword()
    {
        if ($this->validate()) {
			$user = Yii::$app->modelFinder->findAccountModel(Yii::$app->user->identity->id);
			$user->password = md5($this->newPassword);
			return $user->save();
        } else {
            return false;
        }
    }

}


text:
author: slowe
categories: Explanation
comments: true
date: 2013-12-18T09:00:00Z
slug: managing-open-vswitch-with-puppet
tags:
- Automation
- Libvirt
- Linux
- LXC
- Networking
- OVS
- Puppet
title: Managing Open vSwitch with Puppet
url: /2013/12/18/managing-open-vswitch-with-puppet/
wordpress_id: 3388
---

In this post, I'm going to show you how to manage [Open vSwitch (OVS)](http://openvswitch.org/) using the popular open source configuration management tool [Puppet](http://www.puppetlabs.com/). This is not the first time I've written about this topic; in the past I showed you how to [automate OVS configuration with Puppet][1] via a hack utilizing [some RHEL-OVS integrations][2]. This post, however, focuses on the use of an actual Puppet module that will manage the configuration of OVS, a much cleaner solution---in my view, at least---than leveraging the file-based integrations I discussed earlier.

The Puppet module I'll be using and discussing in this post is the L23Network module (found [here](https://github.com/xenolog/l23network) on GitHub). This is an extremely flexible and useful module, capable of not only configuring and managing network interfaces but also capable of managing the configuration of OVS. The latter functionality---managing the configuration of OVS---will be the primary focus of this article (with one exception).

The L23Network module is pretty well-documented, so I won't bother regurgitating the documentation here. Instead, I'll just try to provide some specific examples, and tie those examples back to some of the various OVS configurations I've shown you in earlier posts.

First, let's get "the one exception" I mentioned earlier out of the way. In OVS environments, you'll often need to bring up a physical interface without assigning that interface an IP address. For example, consider a physical interface that is providing bridged connectivity to guest domains (VMs) on an OVS bridge. You'll want the interface to be up, but the interface does not need an IP address. Using the L23Network module, you can accomplish that with this piece of code in your manifest:

    l23network::l3::ifconfig {'eth1': ipaddr => 'none'}

Now that `eth1` is up, you could create a bridge to which to attach it with this code:

    l23network::l2::bridge {'br-ex': }

And then you could actually attach `eth1` like this:

    l23network::l2::port {'eth1': bridge => 'br-ex'}

You could then provide multi-VLAN bridged connectivity to guest domains via libvirt as I explained in my post on [using VLANs with libvirt and OVS][3]. (Or, if you are [using LXC with libvirt and OVS][4], you could provide multi-VLAN bridged connectivity to containers.)

The L23Network module can also work with other types of interfaces, not just physical interfaces. Want to create an internal interface, perhaps to use as a tunnel endpoint for GRE tunnel as I described [here][5]? Use this snippet of Puppet code:

    l23network::l2::port {'tep0': bridge => 'br-tun', type => 'internal'}

You could then assign the newly-created `tep0` interface an IP address on your transport network like this:

    l23network::l3::ifconfig {'tep0': ipaddr => '10.1.1.1/24'}

(In theory, you could also use the L23Network module to create an internal interface so as to [run host management through OVS][6], but then you could run into issues communicating with the Puppet server over the same interfaces the Puppet server is configuring.)

I haven't yet used L23Network to create/manage patch ports or GRE ports, but the documentation indicates the module is capable of doing so. This is an area that I plan to explore in a bit more detail in the near future (in my copious free time).

Based on the snippets I've given you above, it should be pretty straightforward how to combine these various pieces together to fully configure and manage OVS instances across a large number of systems. However, if you have any questions, feel free to post them in the comments below. I also welcome all other courteous feedback; you are encouraged to start (or join) the conversation.

[1]: {{< relref "2013-02-26-automating-open-vswitch-configuration-with-puppet.md" >}}
[2]: {{< relref "2013-02-07-exploring-rhel-ovs-integrations.md" >}}
[3]: {{< relref "2012-11-07-using-vlans-with-ovs-and-libvirt.md" >}}
[4]: {{< relref "2013-12-03-connecting-lxc-to-open-vswitch-using-libvirt.md" >}}
[5]: {{< relref "2013-05-07-using-gre-tunnels-with-open-vswitch.md" >}}
[6]: {{< relref "2012-10-30-running-host-management-on-open-vswitch.md" >}}


text:
anymatch [![Build Status](https://travis-ci.org/es128/anymatch.svg)](https://travis-ci.org/es128/anymatch) [![Coverage Status](https://img.shields.io/coveralls/es128/anymatch.svg)](https://coveralls.io/r/es128/anymatch?branch=master)
======
Javascript module to match a string against a regular expression, glob, string,
or function that takes the string as an argument and returns a truthy or falsy
value. The matcher can also be an array of any or all of these. Useful for
allowing a very flexible user-defined config to define things like file paths.

[![NPM](https://nodei.co/npm/anymatch.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/anymatch/)
[![NPM](https://nodei.co/npm-dl/anymatch.png?height=3&months=9)](https://nodei.co/npm-dl/anymatch/)

Usage
-----
`npm install anymatch --save`

#### anymatch (matchers, testString, [returnIndex], [startIndex], [endIndex])
* __matchers__: (_Array|String|RegExp|Function_)
String to be directly matched, string with glob patterns, regular expression
test, function that takes the testString as an argument and returns a truthy
value if it should be matched, or an array of any number and mix of these types.
* __testString__: (_String_) The string to test against the matchers.
* __returnIndex__: (_Boolean [optional]_) If true, return the array index of
the first matcher that that testString matched, or -1 if no match, instead of a
boolean result.
* __startIndex, endIndex__: (_Integer [optional]_) Can be used to define a
subset out of the array of provided matchers to test against. Can be useful
with bound matcher functions (see below). When used with `returnIndex = true`
preserves original indexing. Behaves the same as `Array.prototype.slice` (i.e.
includes array members up to, but not including endIndex).

```js
var anymatch = require('anymatch');

var matchers = [
	'path/to/file.js',
	'path/anyjs/**/*.js',
	/foo.js$/,
	function (string) {
		return string.indexOf('bar') !== -1 && string.length > 10
	}
];

anymatch(matchers, 'path/to/file.js'); // true
anymatch(matchers, 'path/anyjs/baz.js'); // true
anymatch(matchers, 'path/to/foo.js'); // true
anymatch(matchers, 'path/to/bar.js'); // true
anymatch(matchers, 'bar.js'); // false

// returnIndex = true
anymatch(matchers, 'foo.js', true); // 2
anymatch(matchers, 'path/anyjs/foo.js', true); // 1

// skip matchers
anymatch(matchers, 'path/to/file.js', false, 1); // false
anymatch(matchers, 'path/anyjs/foo.js', true, 2, 3); // 2
anymatch(matchers, 'path/to/bar.js', true, 0, 3); // -1
```

#### anymatch (matchers)
You can also pass in only your matcher(s) to get a curried function that has
already been bound to the provided matching criteria. This can be used as an
`Array.prototype.filter` callback.

```js
var matcher = anymatch(matchers);

matcher('path/to/file.js'); // true
matcher('path/anyjs/baz.js', true); // 1
matcher('path/anyjs/baz.js', true, 2); // -1

['foo.js', 'bar.js'].filter(matcher); // ['foo.js']
```

Change Log
----------
[See release notes page on GitHub](https://github.com/es128/anymatch/releases)

License
-------
[ISC](https://raw.github.com/es128/anymatch/master/LICENSE)


text:
'use strict';

const path = require('path');
const {sync: spawnSync} = require('cross-spawn');

const JEST_RUNTIME = path.resolve(__dirname, '../../bin/jest-runtime.js');

const run = args =>
  spawnSync(JEST_RUNTIME, args, {
    cwd: process.cwd(),
    encoding: 'utf8',
    env: process.env,
  });

describe('Runtime', () => {
  describe('cli', () => {
    it('fails with no path', () => {
      const expectedOutput =
        'Please provide a path to a script. (See --help for details)\n';
      expect(run([]).stdout).toBe(expectedOutput);
    });

    it('displays script output', () => {
      const scriptPath = path.resolve(__dirname, './test_root/logging.js');
      expect(run([scriptPath, '--no-cache']).stdout).toMatch('Hello, world!\n');
    });

    it('always disables automocking', () => {
      const scriptPath = path.resolve(__dirname, './test_root/logging.js');
      const output = run([
        scriptPath,
        '--no-cache',
        '--config=' +
          JSON.stringify({
            automock: true,
          }),
      ]);
      expect(output.stdout).toMatch('Hello, world!\n');
    });

    it('throws script errors', () => {
      const scriptPath = path.resolve(__dirname, './test_root/throwing.js');
      expect(run([scriptPath, '--no-cache']).stderr).toMatch(
        'Error: throwing\n',
      );
    });
  });
});


text:
//
//  NSArray+SCAddition.m
//  SCFramework
//
//  Created by Angzn on 3/5/14.
//  Copyright (c) 2014 Richer VC. All rights reserved.
//

#import "NSArray+Ext.h"
#import <objc/runtime.h>

@implementation NSArray (Ext)

/**
 *  @brief 判断是否为空
 */
- (BOOL)isNotEmpty
{
    return (![(NSNull *)self isEqual:[NSNull null]]
            && [self isKindOfClass:[NSArray class]]
            && self.count > 0);
}

@end

@implementation NSMutableArray(Ext)

+ (void)load
{
//    [self swizzeAddobject];
}

+ (void)swizzeAddobject
{
    Method old = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(addObject:));
    Method new = class_getInstanceMethod(self, @selector(addSaveObject:));
    if (!old || !new) {
        return;
    }
    method_exchangeImplementations(old, new);
}

//NSArray添加数据,如果数据为NSNull类型,则添加@""
- (void)addSaveObject:(id)anObject
{
    if (anObject!=nil) {
        [self addSaveObject:anObject];
    }else{
        [self addSaveObject:@""];
    }
}

+ (NSMutableArray *)arrayWithCapacity:(NSUInteger)capacity
                           withObject:(id)theObject
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:capacity];
    for (int i = 0; i < capacity; ++i) {
        [array replaceObjectAtIndex:i withObject:theObject];
    }
    return array;
}

- (void)replaceAllObjectsWithObject:(id)theObject
{
    if (!self.isNotEmpty) {
        return;
    }
    if (!theObject) {
        return;
    }
    for (int i = 0; i < [self count]; ++i) {
        [self replaceObjectAtIndex:i withObject:theObject];
    }
}

- (void)replaceAllObjectsWithNULL
{
    [self replaceAllObjectsWithObject:[NSNull null]];
}

@end


text:
{{ person.firstName }} {{ person.lastName }}

{{ person.about }}

                        Message {{ person.firstName }}

{{ person.infoFollowers }} {{ person.infoFollowers === 1 ? 'follower' : 'followers' }}

    <offers [list]="offers" [profile]=isMyProfile()></offers>


text:
package ru.VirtaMarketAnalyzer.parser;

import org.junit.jupiter.api.Test;
import ru.VirtaMarketAnalyzer.data.Manufacture;
import ru.VirtaMarketAnalyzer.data.ProductRecipe;
import ru.VirtaMarketAnalyzer.main.Wizard;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertFalse;

class ManufactureListParserTest {

    @Test
    void getManufacturesTest() throws IOException {
        final String realm = "olga";
        final List<Manufacture> manufactures = ManufactureListParser.getManufactures(Wizard.host, realm);
        assertFalse(manufactures.isEmpty());
        final Map<String, List<ProductRecipe>> productRecipes = ProductRecipeParser.getProductRecipes(Wizard.host, realm, manufactures);
        assertFalse(productRecipes.isEmpty());
    }
}


text:
using System.Text.Json;
using Azure.AI.TextAnalytics.Models;
using Azure.Core;

namespace Azure.AI.TextAnalytics
{
    public partial class CurrencyResolution : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Iso4217))
            {
                writer.WritePropertyName("iso4217");
                writer.WriteStringValue(Iso4217);
            }
            writer.WritePropertyName("unit");
            writer.WriteStringValue(Unit);
            writer.WritePropertyName("value");
            writer.WriteNumberValue(Value);
            writer.WritePropertyName("resolutionKind");
            writer.WriteStringValue(ResolutionKind.ToString());
            writer.WriteEndObject();
        }

        internal static CurrencyResolution DeserializeCurrencyResolution(JsonElement element)
        {
            Optional<string> iso4217 = default;
            string unit = default;
            double value = default;
            ResolutionKind resolutionKind = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("iso4217"))
                {
                    iso4217 = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("unit"))
                {
                    unit = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("value"))
                {
                    value = property.Value.GetDouble();
                    continue;
                }
                if (property.NameEquals("resolutionKind"))
                {
                    resolutionKind = new ResolutionKind(property.Value.GetString());
                    continue;
                }
            }
            return new CurrencyResolution(resolutionKind, iso4217.Value, unit, value);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace StackExchange.Redis
{
    /// <summary>
    /// Describes a sorted-set element with the corresponding value
    /// </summary>
    public struct SortedSetEntry : IEquatable<SortedSetEntry>, IComparable, IComparable<SortedSetEntry>
    {
        internal readonly RedisValue element;
        internal readonly double score;

        /// <summary>
        /// Initializes a SortedSetEntry value
        /// </summary>
        public SortedSetEntry(RedisValue element, double score)
        {
            this.element = element;
            this.score = score;
        }
        /// <summary>
        /// The unique element stored in the sorted set
        /// </summary>
        public RedisValue Element => element;

        /// <summary>
        /// The score against the element
        /// </summary>
        public double Score => score;

        /// <summary>
        /// The score against the element
        /// </summary>
#if !CORE_CLR
        [Browsable(false)]
#endif
        [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Please use Score", false)]
        public double Value { get { return score; } }

        /// <summary>
        /// The unique element stored in the sorted set
        /// </summary>
#if !CORE_CLR
        [Browsable(false)]
#endif
        [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Please use Element", false)]
        public RedisValue Key { get { return element; } }

        /// <summary>
        /// Converts to a key/value pair
        /// </summary>
        public static implicit operator KeyValuePair<RedisValue,double>(SortedSetEntry value)
        {
            return new KeyValuePair<RedisValue, double>(value.element, value.score);
        }
        /// <summary>
        /// Converts from a key/value pair
        /// </summary>
        public static implicit operator SortedSetEntry(KeyValuePair<RedisValue, double> value)
        {
            return new SortedSetEntry(value.Key, value.Value);
        }

        /// <summary>
        /// See Object.ToString()
        /// </summary>
        public override string ToString()
        {
            return element + ": " + score;
        }
        /// <summary>
        /// See Object.GetHashCode()
        /// </summary>
        public override int GetHashCode()
        {
            return element.GetHashCode() ^ score.GetHashCode();
        }
        /// <summary>
        /// Compares two values for equality
        /// </summary>
        public override bool Equals(object obj)
        {
            return obj is SortedSetEntry && Equals((SortedSetEntry)obj);
        }

        /// <summary>
        /// Compares two values for equality
        /// </summary>
        public bool Equals(SortedSetEntry value)
        {
            return score == value.score && element == value.element;
        }

        /// <summary>
        /// Compares two values by score
        /// </summary>
        public int CompareTo(SortedSetEntry value)
        {
            return score.CompareTo(value.score);
        }

        /// <summary>
        /// Compares two values by score
        /// </summary>
        public int CompareTo(object value)
        {
            return value is SortedSetEntry ? CompareTo((SortedSetEntry)value) : -1;
        }

        /// <summary>
        /// Compares two values for equality
        /// </summary>
        public static bool operator ==(SortedSetEntry x, SortedSetEntry y)
        {
            return x.score == y.score && x.element == y.element;
        }
        /// <summary>
        /// Compares two values for non-equality
        /// </summary>
        public static bool operator !=(SortedSetEntry x, SortedSetEntry y)
        {
            return x.score != y.score || x.element != y.element;
        }

    }
}


text:
package com.tvd12.ezyfox.codec;

public interface EzyObjectToStringEncoder extends EzyObjectToByteEncoder {

    <T> T encode(Object msg, Class<T> outType) throws Exception;
}


text:
<!-- START install generated instructions please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN yarn update-examples TO UPDATE -->Create and start the example:

```bash
npx create-razzle-app --example with-jsxstyle with-jsxstyle

cd with-jsxstyle
yarn start
```
<!-- END install generated instructions please keep comment here to allow auto update -->

## Idea behind the example
This is demo shows how to use [JSXXtyle](https://github.com/smyte/jsxstyle) and the new server rendering API
with Razzle. On each request, JSXStyle will extract out styles into a variable called `styles` will all the critical CSS in the render
tree that we can then just drop into our `<head>`

```js
import { injectAddRule, resetCache } from 'jsxstyle/lib/styleCache';

// ..

server
  .disable('x-powered-by')
  .use(express.static(process.env.RAZZLE_PUBLIC_DIR))
  .get('/*', (req, res) => {
    resetCache();
    let styles = '';
    const context = {};
    injectAddRule(rule => (styles += rule + '\n'));

    const markup = renderToString(
      <StaticRouter context={context} location={req.url}>
        <App />
      </StaticRouter>
    );

    if (context.url) {
      res.redirect(context.url);
    } else {
      res.send(
        `<!doctype html>
    <html lang="">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta charSet='utf-8' />
        <title>Welcome to Razzle</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style type="text/css">${styles || ''}</style>
        ${assets.client.css
          ? `<link rel="stylesheet" href="${assets.client.css}">`
          : ''}
        <script src="${assets.client.js}" defer></script>
    </head>
    <body>
        <div id="root">${markup}</div>
    </body>
</html>`
      );
    }
  });
```


text:
* shouldn't require _action_mailer_ unless really needed by the mailer

# rails catcher
  * make sure we push through request info for exceptions
  * wire ignore exceptions in rails catcher
  * wire up common idioms (or easy ability to) to grab current_user from request, current_url, etc


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2008-2013  David Soergel  <dev@davidsoergel.com>
  ~ Licensed under the Apache License, Version 2.0
  ~ http://www.apache.org/licenses/LICENSE-2.0
  -->

<web-app>
  <display-name>NCBI Taxonomy Server</display-name>

  <!-- Security roles referenced by this web application -->
  <security-role>
    <description>
      The role that is required to log in to the application
    </description>
    <role-name>ncbitaxonomy</role-name>
  </security-role>

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Ncbi Taxonomy Services</web-resource-name>
      <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>ncbitaxonomy</role-name>
    </auth-constraint>
  </security-constraint>

  <!--
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Default</web-resource-name>
      <url-pattern>/</url-pattern>
    </web-resource-collection>
    <auth-constraint/>
  </security-constraint>

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Ncbi Taxonomy Services</web-resource-name>
      <url-pattern>/ncbiTaxonomy</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>ncbitaxonomy</role-name>
    </auth-constraint>
  </security-constraint>

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Ncbi Taxonomy Services</web-resource-name>
      <url-pattern>/ncbiTaxonomyWithUnitBranchLengths</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>ncbitaxonomy</role-name>
    </auth-constraint>
  </security-constraint>

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>Ncbi Taxonomy Services</web-resource-name>
      <url-pattern>/ncbiCiccarelliHybrid</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>ncbitaxonomy</role-name>
    </auth-constraint>
  </security-constraint>
-->
  <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>NcbiTaxonomy</realm-name>
  </login-config>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/ncbitaxonomy.xml</param-value>
    <!--<param-value>/WEB-INF/jandyserver.xml</param-value>-->
  </context-param>

  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

  <!-- <context-param>
    <param-name>parentContextKey</param-name>
    <param-value>jandyDb.xml</param-value>
  </context-param>-->

  <servlet>
    <servlet-name>remoting</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>remoting</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>


text:
export {
  default as makeSimpleRestDataProvider,
} from './simpleRestDataProvider';
export { default as dummyDataProvider } from './dummyDataProvider';


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <TITLE>Class Template filter</TITLE>
    <LINK REL="stylesheet" HREF="../../../../boost.css">
    <LINK REL="stylesheet" HREF="../theme/iostreams.css">

Class Template filter

Description

Headers

Reference

Description

    The class templates filter, wfilter, multichar_filter, multichar_wfilter and their specializations are provided by the Iostreams library for use as base classes for user-defined Filters. These base classes supply the member types char_type and category used internally by the Iostreams library to classify filters.

    The supplied category member is convertible to closable_tag and to localizable_tag. This allows users to define models of the concepts Closable and Localizable simply by providing definitions of member functions close and imbue.

Headers

<boost/iostreams/concepts.hpp>

Reference

Synopsis

namespace boost{ namespace iostreams {

template<typename Mode, typename Ch = char>
struct filter;

template<typename Mode, typename Ch = wchar_t>
struct wfilter : filter<Mode, Ch> { };

typedef filter<input>      input_filter;
typedef wfilter<input>     input_wfilter;
typedef filter<output>     output_filter;
typedef wfilter<output>    output_wfilter;
typedef filter<seekable>   seekable_filter;
typedef wfilter<seekable>  seekable_wfilter;
typedef filter<dual_use>   dual_use_filter;
typedef wfilter<dual_use>  dual_use_wfilter;

template<typename Mode, typename Ch = char>
struct multichar_filter : filter<Mode, Ch> {
    typedef see below  category;
};

template<typename Mode, typename Ch = wchar_t>
struct multichar_wfilter : multichar_filter<Mode, Ch> { };

typedef multichar_filter<input>     multichar_input_filter;
typedef multichar_filter<input>     multichar_input_wfilter;
typedef multichar_filter<output>    multichar_output_filter;
typedef multichar_filter<output>    multichar_output_wfilter;
typedef multichar_filter<dual_use>  multichar_dual_use_filter;
typedef multichar_filter<dual_use>  multichar_dual_use_wfilter;

template<typename Mode, typename Ch = char>
struct filter {
    typedef Ch         char_type;
    typedef see below  category;

    template<typename Device>
    void close(Device&);

    template<typename Device>
    void close(Device&, std::ios_base::openmode);

    void imbue(const std::locale&);
};

} } // End namespace boost::io

Class Template filter

Description

Convenience base class for defining Filters

Template parameters

        Mode	-
        A mode tag.

        Ch	-
        The character type

filter::category

    typedef see below category;

    A category tag convertible to Mode, filter_tag, closable_tag and localizable_tag.

filter::close

    template<typename Device>
    void close(Device&);

    template<typename Device>
    void close(Device&, std::ios_base::openmode);

    Both overloads are implemented as no-ops. The second is available only if Mode is convertible to bidirectional. The first is available only if Mode is not convertible to bidirectional.

    Required by Closable.

filter::imbue

    void imbue(const std::locale&);

    Implemented as a no-op. Required by Localizable.

Class Template multichar_filter

Description

Convenience base class for defining Multi-Character Filters. Derived class of filter whose member type category is convertible to the template parameter Mode and to multichar_filter_tag, closable_tag and localizable_tag.

Template parameters

        Mode	-
        A mode tag.

        Ch	-
        The character type

© Copyright 2008 CodeRage, LLC
© Copyright 2004-2007 Jonathan Turkanis

    Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
Inserir novo cliente

      <form class="form-horizontal" role="form" ng-submit="addRow()">

          Nome Fantasia:

            <input type="text" class="form-control" name="fantasyName" ng-required="true"
              ng-model="fantasyName" />

          Razão Social:

            <input type="text" class="form-control" name="corporateName" ng-required="true"
              ng-model="corporateName" />

          CNPJ:

            <input type="text" class="form-control" name="cnpj" kp-mask="{{cnpjMask}}" kp-clean-field="true" kp-placeholder=""  ng-required="true" model-view-value="true"
              ng-model="cnpj" />

          Endereço:

            <input type="text" class="form-control" name="street" ng-required="true"
              ng-model="street" />

          Cidade:

            <input type="text" class="form-control" name="city" ng-required="true"
              ng-model="city" />

          Estado:

            <input type="text" class="form-control" name="state" ng-required="true"
              ng-model="state" />

          Cep:

            <input type="text" class="form-control" name="zipcode" kp-mask="{{zipcodeMask}}" kp-clean-field="true" kp-placeholder="" ng-required="true"
              ng-model="zipcode" />

          Rede:

            <select class="form-control" ng-model="network" ng-options="network.name for network in networks">

            </select>

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

      </form>

      Filtro:
      <input type="text" class="form-control"  ng-model="searchKeyword">

      Items por página:
      <input type="number" min="1" max="100" class="form-control" ng-model="pageSize">

            Nome Fantasia
            Razão Social
            CNPJ
            Rede
            Rua
            Cidade
            Estado
            CEP

            {{client.fantasyName}}
            {{client.corporateName}}
            {{client.cnpj}}
            {{client.network}}
            {{client.street}}
            {{client.city}}
            {{client.state}}
            {{client.zipcode}}

        <dir-pagination-controls template-url="bower_components/angular-utils-pagination/dirPagination.tpl.html"></dir-pagination-controls>


text:
@implementation SwiftLintXcodeTRVSXcode

+ (id)currentEditor {
  if ([[self windowController]
          isKindOfClass:NSClassFromString(@"IDEWorkspaceWindowController")]) {
    IDEWorkspaceWindowController *workspaceController =
        (IDEWorkspaceWindowController *)[self windowController];
    IDEEditorArea *editorArea = [workspaceController editorArea];
    IDEEditorContext *editorContext = [editorArea lastActiveEditorContext];
    return [editorContext editor];
  }
  return nil;
}

+ (IDESourceCodeDocument *)sourceCodeDocument {
  if ([[self currentEditor]
          isKindOfClass:NSClassFromString(@"IDESourceCodeEditor")]) {
    return [[self currentEditor] sourceCodeDocument];
  }

  if ([[self currentEditor]
          isKindOfClass:NSClassFromString(@"IDESourceCodeComparisonEditor")] &&
      [[[self currentEditor] primaryDocument]
          isKindOfClass:NSClassFromString(@"IDESourceCodeDocument")]) {
    return (IDESourceCodeDocument *)[[self currentEditor] primaryDocument];
  }

  return nil;
}

+ (NSTextView *)textView {
  if ([[self currentEditor]
          isKindOfClass:NSClassFromString(@"IDESourceCodeEditor")]) {
    return [[self currentEditor] textView];
  }

  if ([[self currentEditor]
          isKindOfClass:NSClassFromString(@"IDESourceCodeComparisonEditor")]) {
    return [[self currentEditor] keyTextView];
  }

  return nil;
}

+ (BOOL)textViewHasSelection {
  return [[self textView] selectedRange].length > 0;
}

+ (NSRange)wholeRangeOfTextView {
  return NSMakeRange(0, [[[self textView] textStorage] length]);
}

+ (NSArray *)selectedFileNavigableItems {
  if (![[self windowController]
          isKindOfClass:NSClassFromString(@"IDEWorkspaceWindowController")])
    return nil;

  IDEWorkspaceWindowController *workspaceController =
      (IDEWorkspaceWindowController *)[self windowController];
  IDEWorkspaceTabController *workspaceTabController =
      [workspaceController activeWorkspaceTabController];
  IDENavigatorArea *navigatorArea = [workspaceTabController navigatorArea];
  id currentNavigator = [navigatorArea currentNavigator];

  if (![currentNavigator
          isKindOfClass:NSClassFromString(@"IDEStructureNavigator")])
    return nil;

  NSMutableArray *array = [NSMutableArray array];

  [[currentNavigator selectedObjects]
      enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
          if (![obj isKindOfClass:NSClassFromString(@"IDEFileNavigableItem")])
            return;

          IDEFileNavigableItem *fileNavigableItem = obj;
          NSString *uti = fileNavigableItem.documentType.identifier;
          if ([[NSWorkspace sharedWorkspace]
                            type:uti
                  conformsToType:(NSString *)kUTTypeSourceCode]) {
            [array addObject:fileNavigableItem];
          }
      }];

  return array;
}

+ (NSWindowController *)windowController {
  return [[NSApp keyWindow] windowController];
}

@end


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface uk.nhs.interoperability.infrastructure.ITKAddress (ITK API 0.1-SNAPSHOT API)</title>
<meta name="date" content="2013-05-04">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
uk.nhs.interoperability.infrastructure.ITKAddress

Packages that use ITKAddress

Package
Description

uk.nhs.interoperability.capabilities

Additional ITK API capabilities/extensions for features that are not fully specified by the (normative) written ITK Specifications

uk.nhs.interoperability.infrastructure

Base / infrastructure classes necessary to support ITK Transport and distribution.

Uses of ITKAddress in uk.nhs.interoperability.capabilities

Methods in uk.nhs.interoperability.capabilities with parameters of type ITKAddress

Modifier and Type
Method and Description

ITKTransportRoute
DirectoryOfServices.resolveDestination(String serviceId,
                  ITKAddress address)

Resolve the ITKTransportRoute for the supplied service
 and logical destination address.

Uses of ITKAddress in uk.nhs.interoperability.infrastructure

Methods in uk.nhs.interoperability.infrastructure that return ITKAddress

Modifier and Type
Method and Description

ITKAddress
ITKMessageProperties.getFromAddress()

Obtains the originators ITK address

ITKAddress
ITKAckDetails.getIntendedRecipient()

Provides the ITKAddress for the intended recipient of the message
 being acknowledged

ITKAddress
ITKMessageProperties.getToAddress()

Obtains the destination address for the associated ITK Message.

 Note Whilst the ITK Specifications allow for multiple recipients
 to be specified this version of the ITK API only supports a single recipient
 to be defined as this satisfies the majority of anticipated use-cases.

Methods in uk.nhs.interoperability.infrastructure with parameters of type ITKAddress

Modifier and Type
Method and Description

void
ITKMessageProperties.setFromAddress(ITKAddress fromAddress)

Sets the originators address for this message.

void
ITKMessageProperties.setToAddress(ITKAddress toAddress)

Sets the destination address for the associated ITK Message.

 Note Whilst the ITK Specifications allow for multiple recipients
 to be specified this version of the ITK API only supports a single recipient
 to be defined as this satisfies the majority of anticipated use-cases.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

All content is available under the Open Government Licence, except where otherwise stated

                                  All example source code is available under Apache 2.0, except where otherwise stated


text:
Demonstrates an interrupt-driven method for an Arduino to respond to LDR light threshold triggers.

## Notes

This demonstrates three circuit concepts:
* a light sensor comprising a light-dependent resistor (LDR) and [Wheatstone Bridge](http://en.wikipedia.org/wiki/Wheatstone_bridge).
* a threshold detector using an OpAmp comparator.
* triggering an arduino function when light exceeds the OpAmp threshold

Two LDRs are in the circuit to provide dual or stereo light detection. There is nothing special about running two LDRs.
The circuit could equally be built with just one if that is all the application required.

### Calibrating the Wheatstone Bridge

The particular LDR used has a range of about 200Ω (bright light) to 20kΩ (dark).
However the ambient light conditions used for testing the circuit exhibited a typical range of 2kΩ-5kΩ,
hence 4.7kΩ is selected as the common resistor value in the bridge so that we can drive positive and negative voltages from the bridge.
A variable resistor opposes the LDR, so that the actual threshold level can be trimmed.

The voltage differential measured across the bridge - from the base of the pot to the base of the LDR -
will tend to rise in lighter conditions as the LDR resistance drops.
As conditions get darker, the LDR resistance rises until a point there the voltage differential will go negative.

### Comparator

The voltage differential of the Wheatstone Bridge is fed to an OpAmp comparator (an LM324 Low Power Quad Op-Amp).
By feeding the LDR end of the differential to the negative input of the comparator, it acts as a low-threshold trigger.
Reversing the inputs to the comparator could be used for a high-threshold trigger.

### Arduino Triggering

While it would be completely OK to sample the OpAmp outputs in a loop, in this case we are using hardware interrupts to
trigger when each the OpAmp output transits from low to high (RISING interrupt).

The interrupt service routine simply sets a flag corresponding to the LDR that activated.

The flags are then used and cleared by the main script when it gets around to checking LDR status.
For demonstration purposes, a high flag is used to switch a corresponding indicator LED so that it is possible to see
when an LDR interrupt has been successfully processed.

### Behaviour

For plots of received light to triggering, see the [LDRComparator](../../Electronics101/LDRComparator) project.
It uses the same LDR wheatstone Bridge and monitors results with an Arduino.

### Construction

The build uses an Arduino Nano on a breadboard, with all components powered by an external 5V regulated supply.

![The Breadboard](./assets/StereoLightTrigger_bb.jpg?raw=true)

![The Schematic](./assets/StereoLightTrigger_schematic.jpg?raw=true)

![The Build](./assets/StereoLightTrigger_build.jpg?raw=true)

## Credits and References

* [LM324 datasheet](https://www.futurlec.com/Linear/LM324N.shtml) - Low Power Quad Op-Amp
* [Properly terminating an unused op amp](http://www.electronicproducts.com/Analog_Mixed_Signal_ICs/Amplifiers/Properly_terminating_an_unused_op_amp.aspx)
* A similar application of an OpAmp is in "Project 06 - Hi-Lo Trip Detector" from [Beginning Digital Electronics Through Projects](http://www.amazon.com/gp/product/0750672692/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=0750672692&linkCode=as2&tag=itsaprli-20&linkId=S6GVIV6DHZABMHTA)


text:
package pl.mmorpg.prototype.server.objects.monsters;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import pl.mmorpg.prototype.clientservercommon.StatisticsCalculator;
import pl.mmorpg.prototype.clientservercommon.StatisticsOperations;
import pl.mmorpg.prototype.clientservercommon.packets.monsters.properties.MonsterProperties;
import pl.mmorpg.prototype.clientservercommon.packets.monsters.properties.Statistics;
import pl.mmorpg.prototype.server.collision.interfaces.CollisionMap;
import pl.mmorpg.prototype.server.collision.pixelmap.PixelCollisionMap;
import pl.mmorpg.prototype.server.communication.PacketsMaker;
import pl.mmorpg.prototype.server.communication.PacketsSender;
import pl.mmorpg.prototype.clientservercommon.EquipmentPosition;
import pl.mmorpg.prototype.data.entities.components.InventoryPosition;
import pl.mmorpg.prototype.server.exceptions.*;
import pl.mmorpg.prototype.server.objects.GameObject;
import pl.mmorpg.prototype.server.objects.MovableGameObject;
import pl.mmorpg.prototype.server.objects.effects.Effect;
import pl.mmorpg.prototype.server.objects.items.equipment.EquipableItem;
import pl.mmorpg.prototype.server.objects.items.Item;
import pl.mmorpg.prototype.server.objects.items.StackableItem;
import pl.mmorpg.prototype.server.objects.items.Useable;
import pl.mmorpg.prototype.server.objects.monsters.abilities.Ability;
import pl.mmorpg.prototype.server.objects.monsters.abilities.TimedAbility;
import pl.mmorpg.prototype.server.path.search.BestFirstPathFinder;
import pl.mmorpg.prototype.server.path.search.PathFinder;
import pl.mmorpg.prototype.server.path.search.PathSimplifier;
import pl.mmorpg.prototype.server.path.search.collisionDetectors.RestrictedAreaGameObjectCollisionDetector;
import pl.mmorpg.prototype.server.path.search.distanceComparators.DistanceComparator;
import pl.mmorpg.prototype.server.path.search.distanceComparators.ManhattanDistanceComparator;
import pl.mmorpg.prototype.server.resources.Assets;
import pl.mmorpg.prototype.server.states.PlayState;

import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public abstract class Monster extends MovableGameObject implements ItemUser, EquipableItemsUser
{
	private static final float RELEASE_TARGET_DISTANCE = 400.0f;
	private static final BitmapFont font = Assets.getFont();
	private static final PathFinder pathFinder = new BestFirstPathFinder();

	// Only equipped items
	private final Map<EquipmentPosition, ItemWithEffectWrapper> equipmentPositionToEffectMap = new ConcurrentHashMap<>();
	// All items
	private final Map<Long, Item> items = new ConcurrentHashMap<>();
	private final List<Ability> abilities = new LinkedList<>();
	private final Map<Class<? extends Effect>, Effect> ongoingEffects = new ConcurrentHashMap<>();
	private LinkedList<Point> currentPath = new LinkedList<>();

	protected final MonsterProperties properties;
	// Actual statistics after modifications (by buffs, equipment, items etc)
	private Statistics actualStatistics;
	private Monster targetedMonster = null;
	private final RestrictedAreaGameObjectCollisionDetector collisionDetector;
	private float hitTime = 1000.0f;
	protected PlayState linkedState;

    private List<Monster> targetedBy = new LinkedList<>();

    public Monster(Texture lookout, long id, PlayState playState, MonsterProperties properties)
    {
        super(lookout, id, playState);
		linkedState = playState;
        this.properties = properties;
        this.actualStatistics = StatisticsCalculator.calculateStatistics(properties);
		collisionDetector = new RestrictedAreaGameObjectCollisionDetector(playState.getCollisionMap(), this);
    }

    @Override
    public void update(float deltaTime)
    {
        super.update(deltaTime);
        targetedMonsterHandle(deltaTime);
        abilitiesUsageHandle();
        ongoingEffectsHandle(deltaTime);
		pathFollowingHandle(deltaTime);
	}

	private void targetedMonsterHandle(float deltaTime)
	{
		if (isTargetingAnotherMonster())
        {
			if(distance(getTargetedMonster()) >= RELEASE_TARGET_DISTANCE)
				stopTargetingMonster();
			else
				attackHandle(deltaTime);
        }
	}

	public boolean isTargetingAnotherMonster()
    {
        return targetedMonster != null;
    }

    private void attackHandle(float deltaTime)
    {
        hitTime += deltaTime;
        if (canAttackTarget())
        {
            hitTime = 0.0f;
            normalAttack(targetedMonster);
        }
    }

    private boolean canAttackTarget()
    {
        return hitTime >= actualStatistics.attackSpeed && distance(targetedMonster) <= actualStatistics.attackRange;
    }

    private double distance(Monster targetedMonster)
    {
        float selfCenterX = getX() + getWidth() / 2;
        float targetCenterX = targetedMonster.getX() + targetedMonster.getWidth() / 2;
        float deltaX = targetCenterX - selfCenterX;
        float selfCenterY = getY() + getHeight() / 2;
        float targetCenterY = targetedMonster.getY() + targetedMonster.getHeight() / 2;
        float deltaY = targetCenterY - selfCenterY;
		return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    }

    private void normalAttack(Monster target)
    {
        int damage = DamageCalculator.getDamage(this, target);
        target.properties.hp -= damage;
        linkedState.sendToAll(PacketsMaker.makeNormalDamagePacket(target.getId(), damage));
        if (target.properties.hp <= 0)
        {
            this.killed(target);
            target.die();
        }
    }

    private void abilitiesUsageHandle()
	{
		for(Ability ability : abilities)
		{
			if(ability instanceof TimedAbility)
				((TimedAbility)ability).updateWithDeltaTime(Gdx.graphics.getDeltaTime());
			if(ability.shouldUse())
			{
				if(ability.shouldBeUsedOnItself())
					ability.use(this, (PacketsSender)linkedState);
				else if(ability.shouldBeUsedOnTargetedMonster() && isTargetingAnotherMonster())
					ability.use(targetedMonster, (PacketsSender)linkedState);
			}
		}
	}

	private void ongoingEffectsHandle(float deltaTime)
	{
		ongoingEffects.forEach((effectType, effect) -> handleEffect(deltaTime, effectType, effect));
	}

	private void handleEffect(float deltaTime, Class<? extends Effect> effectType, Effect effect)
	{
		effect.update(deltaTime);
		if(effect.shouldDeactivate())
		{
			effect.deactivate();
			ongoingEffects.remove(effectType);
		}
	}

	private void pathFollowingHandle(float deltaTime)
	{
		if (!currentPath.isEmpty())
			followPath(deltaTime);
	}

	private void followPath(float deltaTime)
	{
		Point nearestTarget = currentPath.getFirst();
		makeStepToPoint(deltaTime, linkedState.getCollisionMap(), nearestTarget.x, nearestTarget.y);
		if (nearPoint(nearestTarget))
			currentPath.pollFirst();
	}

	private boolean nearPoint(Point nearestTarget)
	{
		return Math.abs(getX() - nearestTarget.x) + Math.abs(getY() - nearestTarget.y) < 2.0f;
	}

	protected void findPathTo(int x, int y)
	{
		//TODO FIX modulos
		int modulo = 3;
		Point startPoint = new Point((int)getX() - (int)getX()%modulo, (int)getY() - (int)getY()%modulo);
		Point endPoint = new Point(x - x% modulo, y - y%modulo);
		DistanceComparator distanceComparator = new ManhattanDistanceComparator(endPoint);
		Collection<? extends Point> path = pathFinder.find(startPoint, endPoint, distanceComparator, collisionDetector);
		System.out.println("Path");
		currentPath = new PathSimplifier().simplify(path);
		Collections.reverse(currentPath);
	}

	public boolean isFollowingPath() {
    	return !currentPath.isEmpty();
	}

	@Override
    public void render(Batch batch)
    {
        super.render(batch);
        font.draw(batch, String.valueOf(properties.hp), getX() + 3, getY() + 40);

		drawDebugPath(batch);
	}

	private void drawDebugPath(Batch batch)
	{
		Texture debugTexture = Assets.get("debug.png");
		for(Point point : currentPath)
			batch.draw(debugTexture, point.x, point.y, 3, 3);
	}

	public void targetMonster(Monster target)
    {
        targetedMonster = target;
        target.addBeingTargetedBy(this);
    }

    public Monster getTargetedMonster()
    {
        return targetedMonster;
    }

    private void addBeingTargetedBy(Monster source)
    {
        targetedBy.add(source);
    }

    public void die()
    {
        linkedState.remove(getId());
        linkedState.sendToAll(PacketsMaker.makeRemovalPacket(getId()));
        for (Monster targetedBY : targetedBy)
            targetedBY.targetedMonster = null;
    }

    public void killed(Monster target)
    {
        targetedMonster = null;
    }

    public MonsterProperties getProperties()
    {
        return properties;
    }

    public boolean isInGame()
    {
    	return linkedState.has(getId());
    }

    protected void stopTargetingMonster()
    {
    	targetedMonster = null;
    }

    @Override
    public void onRemoval()
    {
    	for (Monster targetedBY : targetedBy)
            targetedBY.targetedMonster = null;
    	super.onRemoval();
    }

    @Override
	public void addItemAllowStacking(Item newItem)
    {
    	if(newItem instanceof StackableItem)
    	{
    		for(Item item : items.values())
    			if(item.getIdentifier().equals(newItem.getIdentifier()))
    			{
    				((StackableItem)item).stackWith((StackableItem)newItem);
    				return;
    			}

    	}
    	items.put(newItem.getId(), newItem);
    }

	@Override
	public void addItemDenyStacking(Item newItem)
	{
    	items.put(newItem.getId(), newItem);
	}

    @Override
    public void addItemsAllowStacking(Collection<Item> items)
    {
    	items.forEach(this::addItemAllowStacking);
    }

	@Override
	public void addItemsDenyStacking(Collection<Item> items)
	{
    	items.forEach(this::addItemDenyStacking);
	}

    @Override
	public void useItem(long id, PacketsSender packetSender)
    {
        useItem(id, this, packetSender);
    }

    @Override
	public void useItem(long id, Monster target, PacketsSender packetSender)
    {
        Item characterItem = items.get(id);
        if (characterItem == null)
            throw new CharacterDoesntHaveItemException(id);
        if (!(characterItem instanceof Useable))
            throw new CannotUseThisItemException(characterItem);
        ((Useable) characterItem).use(target, packetSender);
    }

    @Override
	public Collection<Item> getItems()
    {
        return items.values();
    }

	@Override
	public Item getItem(long itemId)
	{
		return items.get(itemId);
	}

    @Override
    public void removeItem(long id)
    {
    	if(items.remove(id) == null)
    		throw new NoSuchItemToRemoveException(id);
    }

    protected void addAbility(Ability ability)
    {
    	abilities.add(ability);
    }

    public void addEffect(Effect effect)
    {
    	Effect sameTypeEffect = ongoingEffects.get(effect.getClass());
    	if(sameTypeEffect != null && sameTypeEffect.canStackWith(effect))
    		sameTypeEffect.stackWithOtherEffect(effect);
    	else
    	{
    		effect.activate();
    		ongoingEffects.put(effect.getClass(), effect);
    	}
    }

    public void heal(int healPower)
    {
        MonsterProperties targetProperties = this.properties;
        if(targetProperties.hp >= actualStatistics.maxHp)
        	return;
        int previous = targetProperties.hp;
        targetProperties.hp += healPower;
        if(targetProperties.hp > actualStatistics.maxHp)
            targetProperties.hp = actualStatistics.maxHp;
        int delta = targetProperties.hp - previous;

        linkedState.sendToAll(PacketsMaker.makeHpNotifiedIncreasePacket(delta, getId()));
    }

	public Statistics getStatistics()
	{
		return actualStatistics;
	}

	public void modifyByDeltaStatistics(Statistics deltaStatistics)
	{
		StatisticsOperations.modifyByDeltaStatistics(actualStatistics, deltaStatistics);
	}

	public void recalculateStatistics()
	{
		Collection<ItemWithEffectWrapper> deactivatedEffects = deactivateEquipmentEffects();
		actualStatistics = StatisticsCalculator.calculateStatistics(properties);
		deactivatedEffects.forEach(wrapper -> applyEquipmentItemEffect(wrapper.getItem()));
	}

	private Collection<ItemWithEffectWrapper> deactivateEquipmentEffects()
	{
		Collection<ItemWithEffectWrapper> toDeactivate = new ArrayList<>(equipmentPositionToEffectMap.values());
		toDeactivate.forEach(wrapper -> wrapper.getEffect().deactivate());
		equipmentPositionToEffectMap.clear();
		return toDeactivate;
	}

	@Override
	public void equip(EquipableItem equipableItem, EquipmentPosition equipmentPosition)
	{
		if(!canEquip(equipableItem, equipmentPosition))
			throw new CannotEquipItemException(equipableItem, equipmentPosition);

		if (!this.containsItem(equipableItem.getId()))
			addItemDenyStacking(equipableItem);

		equipableItem.setEquipmentPosition(equipmentPosition);
		equipableItem.setInventoryPosition(null);
		applyEquipmentItemEffect(equipableItem);
	}

	public void applyEquipmentItemEffect(EquipableItem equipableItem)
	{
		Effect itemEffect = equipableItem.createStatisticsModificationEffect(this);
		addEffect(itemEffect);
		equipmentPositionToEffectMap.put(equipableItem.getEquipmentPosition(),
				new ItemWithEffectWrapper(equipableItem, itemEffect));
	}

	@Override
	public boolean canTakeOff(EquipableItem equipableItem, InventoryPosition destinationPosition)
	{
		return hasItemInPosition(equipableItem.getEquipmentPosition()) && !hasItemInPosition(destinationPosition);
	}

	private boolean hasItemInPosition(EquipmentPosition equipmentPosition)
	{
		return equipmentPositionToEffectMap.containsKey(equipmentPosition);
	}

	public Item getItem(EquipmentPosition equipmentPosition)
	{
		return Optional.ofNullable(equipmentPositionToEffectMap.get(equipmentPosition))
				.map(ItemWithEffectWrapper::getItem)
				.orElse(null);
	}

	@Override
	public void takeOff(EquipableItem equipableItem, InventoryPosition destinationPosition)
	{
		if(!canTakeOff(equipableItem, destinationPosition))
			throw new CannotTakeOffItemException(equipableItem, destinationPosition);

		ItemWithEffectWrapper wrapper = equipmentPositionToEffectMap.remove(equipableItem.getEquipmentPosition());
		if (wrapper.getItem().getId() != equipableItem.getId())
			throw new GameException("This should not happen");

		wrapper.getEffect().deactivate();

		equipableItem.setEquipmentPosition(EquipmentPosition.NONE);
		equipableItem.setInventoryPosition(destinationPosition);
	}

	public Item getItem(InventoryPosition position)
	{
		//Linear search, may need to improve
		return getItems().stream()
				.filter(item -> item.getInventoryPosition() != null)
				.filter(item -> item.getInventoryPosition().equals(position))
				.findAny().orElse(null);
	}

	public boolean hasItemInPosition(InventoryPosition position)
	{
		return getItem(position) != null;
	}
}