text:
package com.github.ddth.cacheadapter.cacheimpl.guava;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.ddth.cacheadapter.AbstractCache;
import com.github.ddth.cacheadapter.AbstractCacheFactory;
import com.github.ddth.cacheadapter.CacheEntry;
import com.github.ddth.cacheadapter.CacheException;
import com.github.ddth.cacheadapter.ICacheLoader;
import com.github.ddth.cacheadapter.utils.CacheUtils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

/**
 * In-memory cache, use
 * Guava as the
 * underlying cache engine.
 *
 * @author Thanh Ba Nguyen <btnguyen2k@gmail.com>
 * @since 0.1.0
 */
public class GuavaCache extends AbstractCache {

    private final Logger LOGGER = LoggerFactory.getLogger(GuavaCache.class);

    /**
     * To override the {@link #setCloneCacheEntries(boolean)} setting.
     *
     * @since 0.6.1
     */
    public final static String CACHE_PROP_CLONE_CACHE_ENTRIES = "cache.clone_cache_entries";

    private LoadingCache<String, Object> cache;
    private boolean cloneCacheEntries = true;

    public GuavaCache() {
    }

    public GuavaCache(String name, AbstractCacheFactory cacheFactory) {
        super(name, cacheFactory);
    }

    public GuavaCache(String name, AbstractCacheFactory cacheFactory, long capacity) {
        super(name, cacheFactory, capacity);
    }

    public GuavaCache(String name, AbstractCacheFactory cacheFactory, long capacity,
            long expireAfterWrite, long expireAfterAccess) {
        super(name, cacheFactory, capacity, expireAfterWrite, expireAfterAccess);
    }

    public GuavaCache(String name, AbstractCacheFactory cacheFactory, long capacity,
            long expireAfterWrite, long expireAfterAccess, ICacheLoader cacheLoader) {
        super(name, cacheFactory, capacity, expireAfterWrite, expireAfterAccess, cacheLoader);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public GuavaCache init() {
        super.init();

        /*
         * Parse custom property: clone-cache-entries
         */
        boolean oldCloneCacheEntries = this.cloneCacheEntries;
        try {
            this.cloneCacheEntries = Boolean
                    .parseBoolean(getCacheProperty(CACHE_PROP_CLONE_CACHE_ENTRIES));
        } catch (Exception e) {
            this.cloneCacheEntries = oldCloneCacheEntries;
            if (getCacheProperty(CACHE_PROP_CLONE_CACHE_ENTRIES) != null) {
                LOGGER.warn(e.getMessage(), e);
            }
        }

        int numProcessores = Runtime.getRuntime().availableProcessors();
        CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
                .concurrencyLevel(numProcessores * 2);
        if (getCapacity() > 0) {
            cacheBuilder.maximumSize(getCapacity());
        }

        long expireAfterAccess = getExpireAfterAccess();
        long expireAfterWrite = getExpireAfterWrite();
        if (expireAfterAccess > 0) {
            cacheBuilder.expireAfterAccess(expireAfterAccess, TimeUnit.SECONDS);
        } else if (expireAfterWrite > 0) {
            cacheBuilder.expireAfterWrite(expireAfterWrite, TimeUnit.SECONDS);
        }

        CacheLoader<String, Object> guavaCacheLoader = new CacheLoader<String, Object>() {
            @Override
            public Object load(String key) throws Exception {
                ICacheLoader cacheLoader = getCacheLoader();
                Object result = cacheLoader != null ? cacheLoader.load(key) : null;
                if (result != null) {
                    return result;
                } else {
                    throw new CacheException.CacheEntryNotFoundException();
                }
            }
        };
        cache = cacheBuilder.build(guavaCacheLoader);

        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void destroy() {
        try {
            super.destroy();
        } finally {
            try {
                if (cache != null) {
                    cache.invalidateAll();
                    cache = null;
                }
            } catch (Exception e) {
                // EMPTY
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isCapacitySupported() {
        return true;
    }

    /**
     * If {@code true}, cache entries are cloned when fetching out of cache,
     * default value is {@code false}.
     *
     * @return
     * @since 0.4.1.1
     */
    public boolean isCloneCacheEntries() {
        return cloneCacheEntries;
    }

    /**
     * If {@code true}, cache entries are cloned when fetching out of cache,
     * default value is {@code true}.
     *
     * @return
     * @since 0.4.1.1
     */
    public boolean getCloneCacheEntries() {
        return cloneCacheEntries;
    }

    /**
     * If {@code true}, cache entries are cloned when fetching out of cache.
     *
     * @param cloneCacheEntries
     * @return
     * @since 0.4.1.1
     */
    public GuavaCache setCloneCacheEntries(boolean cloneCacheEntries) {
        this.cloneCacheEntries = cloneCacheEntries;
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public long getSize() {
        return cache.size();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void set(String key, Object entry) {
        cache.put(key, CacheUtils.tryClone(entry));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void set(String key, Object entry, long expireAfterWrite, long expireAfterAccess) {
        if (!(entry instanceof CacheEntry)) {
            CacheEntry ce = new CacheEntry(key, CacheUtils.tryClone(entry), expireAfterWrite,
                    expireAfterAccess);
            entry = ce;
        } else {
            entry = CacheUtils.tryClone(entry);
        }
        cache.put(key, entry);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void delete(String key) {
        cache.invalidate(key);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteAll() {
        cache.invalidateAll();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean exists(String key) {
        return cache.getIfPresent(key) != null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object internalGet(String key) {
        try {
            Object result = cache.get(key);
            if (result instanceof CacheEntry) {
                // update entry's private TTL if needed.
                CacheEntry ce = (CacheEntry) result;
                if (ce.touch()) {
                    set(key, ce);
                }
            }
            return cloneCacheEntries ? CacheUtils.tryClone(result) : result;
        } catch (Exception e) {
            Throwable t = e.getCause();
            if (t instanceof CacheException.CacheEntryNotFoundException) {
                return null;
            } else {
                throw t instanceof CacheException ? (CacheException) t : new CacheException(t);
            }
        }
    }
}


text:
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    return app

redpajama_set_name: RedPajamaGithub


text:
'''
pyCESM:  Python translation of CESM 1.2.1 code
$CCSMROOT/models/atm/cam/src/physics/cam/wv_sat_methods.F90

Brian Rose
June 2015

Documentation from CESM code:
--------------------------------

module wv_sat_methods

! This portable module contains all CAM methods for estimating
! the saturation vapor pressure of water.
!
! wv_saturation provides CAM-specific interfaces and utilities
! based on these formulae.
!
! Typical usage of this module:
!
! Init:
! call wv_sat_methods_init(r8, tmelt, h2otrip, tboil, errstring)
!
! Get scheme index from a name string:
! scheme_idx = wv_sat_get_scheme_idx(scheme_name)
! if (.not. wv_sat_valid_idx(scheme_idx)) <throw some error>
!
! Get pressures:
! es = wv_sat_svp_water(t, scheme_idx)
! es = wv_sat_svp_ice(t, scheme_idx)
!
! Use ice/water transition range:
! es = wv_sat_svp_trice(t, ttrice, scheme_idx)
!
! Note that elemental functions cannot be pointed to, nor passed
! as arguments. If you need to do either, it is recommended to
! wrap the function so that it can be given an explicit (non-
! elemental) interface.
'''
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import numpy as np
from pyCESM.physconst import tmelt, h2otrip, epsilo
from pyCESM.wv_saturation import ttrice

omeps = 1. - epsilo
#! This value is slightly high, but it seems to be the value for the
#! steam point of water originally (and most frequently) used in the
#! Goff & Gratch scheme.
tboil = 373.16

# !---------------------------------------------------------------------
# ! UTILITIES
# !---------------------------------------------------------------------

#! Get saturation specific humidity given pressure and SVP.
#! Specific humidity is limited to range 0-1.
def wv_sat_svp_to_qsat(es, p):
    #  ! If pressure is less than SVP, set qs to maximum of 1.
    qsat = np.where(p <= es, 1., epsilo*es / (p - omeps*es))
    return qsat

#! Get saturation "mass mixing ratio".
#! It is almost always preferable to use saturation
#! specific humidity rather than this mixing ratio,
#! which blows up at low pressure.
def wv_sat_svp_to_qmmr(es, p):
    # ! When this function is used in regions of very low
    # ! pressure, we set it to "huge" rather than using
    #  ! the small denominator.
    #if ( (p - es) < epsilon(1.0_r8)**2 ) then
    # qmmr = huge(1.0_r8)
    # else
     #qmmr = epsilo*es / (p - es)
    #end if
    #  BRIAN: didn't implement that switch
    return epsilo*es / (p - es)

def wv_sat_qsat_water(t, p, method='GoffGratch'):
    '''
  !------------------------------------------------------------------!
  ! Purpose:                                                         !
  !   Calculate SVP over water at a given temperature, and then      !
  !   calculate and return saturation specific humidity.             !
  !------------------------------------------------------------------!

  ! Inputs
  real(r8), intent(in) :: t    ! Temperature
  real(r8), intent(in) :: p    ! Pressure
  ! Outputs
  real(r8), intent(out) :: es  ! Saturation vapor pressure
  real(r8), intent(out) :: qs  ! Saturation specific humidity

  integer,  intent(in), optional :: idx ! Scheme index
    '''
    es = wv_sat_svp_water(t, method=method)
    qs = wv_sat_svp_to_qsat(es, p)
    # ! Ensures returned es is consistent with limiters on qs.
    es = np.where(es > p, p, es)
    return es, qs

def wv_sat_qsat_ice(t, p, method='GoffGratch'):
    '''
  !------------------------------------------------------------------!
  ! Purpose:                                                         !
  !   Calculate SVP over ice at a given temperature, and then        !
  !   calculate and return saturation specific humidity.             !
  !------------------------------------------------------------------!

  ! Inputs
  real(r8), intent(in) :: t    ! Temperature
  real(r8), intent(in) :: p    ! Pressure
  ! Outputs
  real(r8), intent(out) :: es  ! Saturation vapor pressure
  real(r8), intent(out) :: qs  ! Saturation specific humidity

  integer,  intent(in), optional :: idx ! Scheme index
    '''
    es = wv_sat_svp_ice(t, method=method)
    qs = wv_sat_svp_to_qsat(es, p)
    # ! Ensures returned es is consistent with limiters on qs.
    es = np.where(es > p, p, es)
    return es, qs

def wv_sat_qsat_trans(t, p, method='GoffGratch'):
    '''
  !------------------------------------------------------------------!
  ! Purpose:                                                         !
  !   Calculate SVP over ice at a given temperature, and then        !
  !   calculate and return saturation specific humidity.             !
  !------------------------------------------------------------------!

  ! Inputs
  real(r8), intent(in) :: t    ! Temperature
  real(r8), intent(in) :: p    ! Pressure
  ! Outputs
  real(r8), intent(out) :: es  ! Saturation vapor pressure
  real(r8), intent(out) :: qs  ! Saturation specific humidity

  integer,  intent(in), optional :: idx ! Scheme index
    '''
    es = wv_sat_svp_trans(t, method=method)
    qs = wv_sat_svp_to_qsat(es, p)
    # ! Ensures returned es is consistent with limiters on qs.
    es = np.where(es > p, p, es)
    return es, qs

# !---------------------------------------------------------------------
# ! SVP INTERFACE FUNCTIONS
# !---------------------------------------------------------------------

def wv_sat_svp_water(t, method='GoffGratch'):
    if method is 'GoffGratch':
        es = GoffGratch_svp_water(t)
    elif method is 'MurphyKoop':
        es = MurphyKoop_svp_water(t)
    elif method is 'OldGoffGratch':
        es = OldGoffGratch_svp_water(t)
    elif method is 'Bolton':
        es = Bolton_svp_water(t)
    else:
        raise ValueError('method not recognized.')
    return es

def wv_sat_svp_ice(t, method='GottGratch'):
    if method is 'GoffGratch':
        es = GoffGratch_svp_ice(t)
    elif method is 'MurphyKoop':
        es = MurphyKoop_svp_ice(t)
    elif method is 'OldGoffGratch':
        es = OldGoffGratch_svp_ice(t)
    elif method is 'Bolton':
        es = Bolton_svp_water(t)
    else:
        raise ValueError('method not recognized.')
    return es

def wv_sat_svp_trans(t, method='GoffGratch'):
    eswater = np.where(t >= tmelt-ttrice, wv_sat_svp_water(t, method), 0.)
    esice = wv_sat_svp_ice(t, method)
    weight = np.where((tmelt - t) > ttrice, 1., (tmelt - t)/ttrice)
    estrans = weight*esice + (1.0 - weight)*eswater
    es = np.where(t < tmelt, estrans, eswater)
    return es  # in Pa

# ! ---------------------------------------------------------------------
# ! SVP METHODS
# !---------------------------------------------------------------------

#! Goff & Gratch (1946)
def GoffGratch_svp_water(t):
    '''Goff and Gratch (1946) formula for saturation vapor pressure
    OVER WATER.
    Input is temperature in K
    Output is saturation vapor pressure in Pa.

    Comments in CESM code say  ! uncertain below -70 C
    '''
    es = (10.**(-7.90298*(tboil/t - 1.) +
                5.02808 * np.log10(tboil/t) -
                1.3816E-7 * (10.**(11.344 * (1.-t/tboil)) - 1.) +
                8.1328E-3 * (10.**(-3.49149 * (tboil/t - 1.)) - 1.) +
                np.log10(1013.246)))*100.
    return es  # in Pa

def GoffGratch_svp_ice(t):
    '''Goff and Gratch (1946) formula for saturation vapor pressure
    OVER ICE.
    Input is temperature in K
    Output is saturation vapor pressure in Pa.

    Comments in CESM code say  ! good down to -100 C
    '''
    es = (10.**(-9.09718 * (h2otrip/t - 1.) -
               3.56654 * np.log10(h2otrip/t) +
               0.876793 * (1. - t/h2otrip) +
               np.log10(6.1071)))*100.
    return es

#
#! Murphy & Koop (2005)
#
def MurphyKoop_svp_water(t):
#  ! (good for 123 < T < 332 K)
    es = np.exp(54.842763 - (6763.22 / t) - (4.210 * np.log(t)) +
                (0.000367 * t) + (np.tanh(0.0415 * (t - 218.8)) *
                (53.878 - (1331.22 / t) - (9.44523 * np.log(t)) +
                 0.014025 * t)))
    return es  # in Pa

def MurphyKoop_svp_ice(t):
#  ! (good down to 110 K)
    es = np.exp(9.550426 - (5723.265 / t) + (3.53068 * np.log(t))
             - (0.00728332 * t))
    return es  # in Pa

#
#! Old CAM implementation, also labelled Goff & Gratch (1946)
#
#! The water formula differs only due to compiler-dependent order of
#! operations, so differences are roundoff level, usually 0.
#
#! The ice formula gives fairly close answers to the current
#! implementation, but has been rearranged, and uses the
#! 1 atm melting point of water as the triple point.
#! Differences are thus small but above roundoff.
#
#! A curious fact: although using the melting point of water was
#! probably a mistake, it mildly improves accuracy for ice svp,
#! since it compensates for a systematic error in Goff & Gratch.

def OldGoffGratch_svp_water(t):
    ps = 1013.246
    e1 = 11.344*(1.0 - t/tboil)
    e2 = -3.49149*(tboil/t - 1.0)
    f1 = -7.90298*(tboil/t - 1.0)
    f2 = 5.02808*np.log10(tboil/t)
    f3 = -1.3816*(10.0**e1 - 1.0)/10000000.0
    f4 = 8.1328*(10.0**e2 - 1.0)/1000.0
    f5 = np.log10(ps)
    f = f1 + f2 + f3 + f4 + f5
    es = (10.0**f)*100.
    return es  # in Pa

def OldGoffGratch_svp_ice(t):
    term1 = 2.01889049 / (tmelt/t)
    term2 = 3.56654 * np.log(tmelt/t)
    term3 = 20.947031 * (tmelt/t)
    es = 575.185606E10 * np.exp(-(term1 + term2 + term3))
    return es  # in Pa

#! Bolton (1980)
#! zm_conv deep convection scheme contained this SVP calculation.
#! It appears to be from D. Bolton, 1980, Monthly Weather Review.
#! Unlike the other schemes, no distinct ice formula is associated
#! with it. (However, a Bolton ice formula exists in CLUBB.)
#
#! The original formula used degrees C, but this function
#! takes Kelvin and internally converts.
#

def Bolton_svp_water(t):
    c1 = 611.2
    c2 = 17.67
    c3 = 243.5
    es = c1*np.exp((c2*(t - tmelt))/((t - tmelt)+c3))
    return es  # in Pa


text:
// <auto-generated />
using Climbing.Web.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.ValueGeneration;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using System;

namespace Database.Postgres.Migrations
{
    [DbContext(typeof(ClimbingContext))]
    [Migration("20171110173835_InitialCreate")]
    partial class InitialCreate
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
                .HasAnnotation("ProductVersion", "2.0.0-rtm-26452");

            modelBuilder.Entity("Climbing.Web.Model.Logging.Ltr", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTimeOffset>("WhenChanged")
                        .HasColumnName("when_changed");

                    b.Property<DateTimeOffset>("WhenCreated")
                        .ValueGeneratedOnAdd()
                        .HasColumnName("when_created");

                    b.HasKey("Id");

                    b.ToTable("ltr");
                });

            modelBuilder.Entity("Climbing.Web.Model.Logging.LtrObject", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ChangeTypeString")
                        .IsRequired()
                        .HasColumnName("ChangeType")
                        .HasMaxLength(16)
                        .IsUnicode(false);

                    b.Property<string>("LogObjectClass")
                        .IsRequired()
                        .HasMaxLength(255)
                        .IsUnicode(false);

                    b.Property<Guid>("LtrId");

                    b.Property<Guid>("ObjectId");

                    b.Property<DateTimeOffset>("WhenChanged")
                        .HasColumnName("when_changed");

                    b.Property<DateTimeOffset>("WhenCreated")
                        .ValueGeneratedOnAdd()
                        .HasColumnName("when_created");

                    b.HasKey("Id");

                    b.HasIndex("LtrId");

                    b.ToTable("ltr_objects");
                });

            modelBuilder.Entity("Climbing.Web.Model.Logging.LtrObjectProperties", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("LtrObjectId");

                    b.Property<string>("NewValue");

                    b.Property<string>("OldValue");

                    b.Property<string>("PropertyName")
                        .IsRequired()
                        .HasMaxLength(255)
                        .IsUnicode(false);

                    b.Property<string>("PropertyType")
                        .IsRequired()
                        .HasMaxLength(255)
                        .IsUnicode(false);

                    b.Property<DateTimeOffset>("WhenChanged")
                        .HasColumnName("when_changed");

                    b.Property<DateTimeOffset>("WhenCreated")
                        .ValueGeneratedOnAdd()
                        .HasColumnName("when_created");

                    b.HasKey("Id");

                    b.HasIndex("LtrObjectId");

                    b.ToTable("ltr_object_properties");
                });

            modelBuilder.Entity("Climbing.Web.Model.Person", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime>("DateOfBirth")
                        .HasColumnName("date_of_birth");

                    b.Property<string>("Email")
                        .HasColumnName("email")
                        .HasMaxLength(255)
                        .IsUnicode(true);

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnName("name")
                        .HasMaxLength(255)
                        .IsUnicode(true);

                    b.Property<string>("Surname")
                        .IsRequired()
                        .HasColumnName("surname")
                        .HasMaxLength(255)
                        .IsUnicode(true);

                    b.Property<DateTimeOffset>("WhenChanged")
                        .HasColumnName("when_changed");

                    b.Property<DateTimeOffset>("WhenCreated")
                        .ValueGeneratedOnAdd()
                        .HasColumnName("when_created");

                    b.HasKey("Id");

                    b.HasIndex("Surname", "Name", "DateOfBirth")
                        .IsUnique();

                    b.ToTable("people");
                });

            modelBuilder.Entity("Climbing.Web.Model.Team", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Code")
                        .IsRequired()
                        .HasColumnName("code")
                        .HasMaxLength(32)
                        .IsUnicode(false);

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnName("name")
                        .HasMaxLength(255)
                        .IsUnicode(true);

                    b.Property<Guid?>("ParentId")
                        .HasColumnName("parent_team_id");

                    b.Property<DateTimeOffset>("WhenChanged")
                        .HasColumnName("when_changed");

                    b.Property<DateTimeOffset>("WhenCreated")
                        .ValueGeneratedOnAdd()
                        .HasColumnName("when_created");

                    b.HasKey("Id");

                    b.HasIndex("Code")
                        .IsUnique();

                    b.HasIndex("ParentId");

                    b.HasIndex("Name", "ParentId")
                        .IsUnique();

                    b.ToTable("teams");
                });

            modelBuilder.Entity("Climbing.Web.Model.Logging.LtrObject", b =>
                {
                    b.HasOne("Climbing.Web.Model.Logging.Ltr", "Ltr")
                        .WithMany("Objects")
                        .HasForeignKey("LtrId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Climbing.Web.Model.Logging.LtrObjectProperties", b =>
                {
                    b.HasOne("Climbing.Web.Model.Logging.LtrObject", "LtrObject")
                        .WithMany("Properties")
                        .HasForeignKey("LtrObjectId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Climbing.Web.Model.Team", b =>
                {
                    b.HasOne("Climbing.Web.Model.Team", "Parent")
                        .WithMany("Children")
                        .HasForeignKey("ParentId");
                });
#pragma warning restore 612, 618
        }
    }
}


text:
package engi

import (
	"fmt"
	"log"

	"github.com/hajimehoshi/ebiten/v2"
)

type Drawable interface {
	Texture() *ebiten.Image
	Width() float64
	Height() float64
	View() (float64, float64, float64, float64)
}

type Batch struct {
}

func (b *Batch) Screen() *ebiten.Image {
	return screen
}

func NewBatch(width, height float64) *Batch {
	batch := &Batch{}
	return batch
}

func (b *Batch) Begin() {}

func (b *Batch) End() {}

func (b *Batch) SetProjection(width, height float64) {
	fmt.Println("setproj", width, height)
}

func (b *Batch) Draw(r Drawable, x, y, originX, originY, scaleX, scaleY, rotation float64, colorpack uint32, transparency float64) {
	scr := screen
	if scr == nil {
		log.Println("scr is nil")
		return
	}
	opt := &ebiten.DrawImageOptions{}

	opt.GeoM.Scale(scaleX, scaleY)
	opt.GeoM.Translate(x, y)
	opt.GeoM.Rotate(rotation)

	if colorpack != 0xffffff || transparency != 1 {
		blue := float64(uint8(colorpack & 0x000000FF))         // 10
		green := float64(uint8((colorpack & 0x0000FF00) >> 8)) // 154
		red := float64(uint8((colorpack & 0x00FF0000) >> 16))  // 0
		alpha := float64(transparency)
		opt.ColorM.Scale(red/255.0, green/255.0, blue/255.0, alpha)
	}

	tex := r.Texture()
	scr.DrawImage(tex, opt)
}

func (b *Batch) Draw2(img *ebiten.Image, opt *ebiten.DrawImageOptions) {
	scr := screen
	if scr == nil {
		log.Println("scr is nil")
		return
	}
	scr.DrawImage(img, opt)
}


text:
namespace at { namespace detail {

template <typename T>
inline T load(const void* data, ScalarType src_type) {
  return AT_DISPATCH_ALL_TYPES(CPU(src_type), "load", [&]() {
    return at::convert<T>(*(scalar_t*)data);
  });
}

template <typename T>
inline void store(T value, void* dst, ScalarType dst_type) {
  AT_DISPATCH_ALL_TYPES(CPU(dst_type), "store", [&]() {
    *(scalar_t*)dst = at::convert<scalar_t>(value);
  });
}

}} // namespace at::detail


text:
using namespace std;
using namespace GeographicLib;

int main() {
  try {
    throw GeographicErr("Test throwing an exception");
  }
  catch (const GeographicErr& e) {
    cout << "Caught exception: " << e.what() << "\n";
  }
  return 0;
}


text:
sed -i -e "s/\[VIRTUALHOST\]/$VIRTUALHOST/g" /etc/apache2/sites-available/999-host.conf

a2enmod proxy
a2enmod proxy_fcgi
a2enconf servername
a2ensite 000-default
a2ensite 999-host

/usr/sbin/apache2ctl -D FOREGROUND


text:
title: Stefan Armbruster
username: stefan.armbruster
picture: stefan.armbruster.png
social:
  twitter:
  github:
  stackoverflow:
  facebook:
  xing:
  lanyrd:
---
**Stefan Armbruster** ist seid ca. 5 Jahren bei Neo Technology als Field
Engineer für den europäischen Raum tätig und hilft, Projekte mit
Graphdatenbanken "in die Spur" zu bringen. Nach seinem Physik-Studium
war er knapp fünfzehn Jahre lang als freiberuflicher Consultant im
Java-Umfeld tätig. Als Linux-Veteran seit den Tagen des 1.0er Kernel
interessiert er sich auch für alle DevOps Themen. Seine Freizeit
verbringt er mit der Suche nach dem perfekten Espresso und ist seit
vielen Jahren Mitglied der freiwilligen Feuerwehr.


text:
package v4

import (
	"encoding/hex"
	"fmt"
	"strings"
	"testing"
	"time"

	"github.com/aws/aws-sdk-go/aws/credentials"
)

type periodicBadCredentials struct {
	call        int
	credentials *credentials.Credentials
}

func (p *periodicBadCredentials) Get() (credentials.Value, error) {
	defer func() {
		p.call++
	}()

	if p.call%2 == 0 {
		return credentials.Value{}, fmt.Errorf("credentials error")
	}

	return p.credentials.Get()
}

type chunk struct {
	headers, payload []byte
}

func mustDecodeHex(b []byte, err error) []byte {
	if err != nil {
		panic(err)
	}

	return b
}

func TestStreamingChunkSigner(t *testing.T) {
	const (
		region        = "us-east-1"
		service       = "transcribe"
		seedSignature = "9d9ab996c81f32c9d4e6fc166c92584f3741d1cb5ce325cd11a77d1f962c8de2"
	)

	staticCredentials := credentials.NewStaticCredentials("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "")
	currentTime := time.Date(2019, 1, 27, 22, 37, 54, 0, time.UTC)

	cases := map[string]struct {
		credentials        credentialValueProvider
		chunks             []chunk
		expectedSignatures map[int]string
		expectedErrors     map[int]string
	}{
		"signature calculation": {
			credentials: staticCredentials,
			chunks: []chunk{
				{headers: []byte("headers"), payload: []byte("payload")},
				{headers: []byte("more headers"), payload: []byte("more payload")},
			},
			expectedSignatures: map[int]string{
				0: "681a7eaa82891536f24af7ec7e9219ee251ccd9bac2f1b981eab7c5ec8579115",
				1: "07633d9d4ab4d81634a2164934d1f648c7cbc6839a8cf0773d818127a267e4d6",
			},
		},
		"signature calculation errors": {
			credentials: &periodicBadCredentials{credentials: staticCredentials},
			chunks: []chunk{
				{headers: []byte("headers"), payload: []byte("payload")},
				{headers: []byte("headers"), payload: []byte("payload")},
				{headers: []byte("more headers"), payload: []byte("more payload")},
				{headers: []byte("more headers"), payload: []byte("more payload")},
			},
			expectedSignatures: map[int]string{
				1: "681a7eaa82891536f24af7ec7e9219ee251ccd9bac2f1b981eab7c5ec8579115",
				3: "07633d9d4ab4d81634a2164934d1f648c7cbc6839a8cf0773d818127a267e4d6",
			},
			expectedErrors: map[int]string{
				0: "credentials error",
				2: "credentials error",
			},
		},
	}

	for name, tt := range cases {
		t.Run(name, func(t *testing.T) {
			chunkSigner := &StreamSigner{
				region:      region,
				service:     service,
				credentials: tt.credentials,
				prevSig:     mustDecodeHex(hex.DecodeString(seedSignature)),
			}

			for i, chunk := range tt.chunks {
				var expectedError string
				if len(tt.expectedErrors) != 0 {
					_, ok := tt.expectedErrors[i]
					if ok {
						expectedError = tt.expectedErrors[i]
					}
				}

				signature, err := chunkSigner.GetSignature(chunk.headers, chunk.payload, currentTime)
				if err == nil && len(expectedError) > 0 {
					t.Errorf("expected error, but got nil")
					continue
				} else if err != nil && len(expectedError) == 0 {
					t.Errorf("expected no error, but got %v", err)
					continue
				} else if err != nil && len(expectedError) > 0 && !strings.Contains(err.Error(), expectedError) {
					t.Errorf("expected %v, but got %v", expectedError, err)
					continue
				} else if len(expectedError) > 0 {
					continue
				}

				expectedSignature, ok := tt.expectedSignatures[i]
				if !ok {
					t.Fatalf("expected signature not provided for test case")
				}

				if e, a := expectedSignature, hex.EncodeToString(signature); e != a {
					t.Errorf("expected %v, got %v", e, a)
				}
			}
		})
	}
}


text:
from . import pyloggingconf
from .debugfile import DebugFile
from .listeners import LibraryListeners, Listeners
from .logger import LOGGER
from .loggerhelper import AbstractLogger
from .xmllogger import XmlLogger

class Output(AbstractLogger):

    def __init__(self, settings):
        AbstractLogger.__init__(self)
        self._xmllogger = XmlLogger(settings.output, settings.log_level)
        self.listeners = Listeners(settings.listeners, settings.log_level)
        self.library_listeners = LibraryListeners(settings.log_level)
        self._register_loggers(DebugFile(settings.debug_file))
        self._settings = settings

    def _register_loggers(self, debug_file):
        LOGGER.register_xml_logger(self._xmllogger)
        LOGGER.register_listeners(self.listeners or None, self.library_listeners)
        if debug_file:
            LOGGER.register_logger(debug_file)

    def register_error_listener(self, listener):
        LOGGER.register_error_listener(listener)

    def close(self, result):
        self._xmllogger.visit_statistics(result.statistics)
        self._xmllogger.close()
        LOGGER.unregister_xml_logger()
        LOGGER.output_file('Output', self._settings['Output'])

    def start_suite(self, suite):
        LOGGER.start_suite(suite)

    def end_suite(self, suite):
        LOGGER.end_suite(suite)

    def start_test(self, test):
        LOGGER.start_test(test)

    def end_test(self, test):
        LOGGER.end_test(test)

    def start_keyword(self, kw):
        LOGGER.start_keyword(kw)

    def end_keyword(self, kw):
        LOGGER.end_keyword(kw)

    def message(self, msg):
        LOGGER.log_message(msg)

    def set_log_level(self, level):
        pyloggingconf.set_level(level)
        self.listeners.set_log_level(level)
        self.library_listeners.set_log_level(level)
        return self._xmllogger.set_log_level(level)


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>66 emnlp-2010-Inducing Word Senses to Improve Web Search Result Clustering</title>

emnlp emnlp2010 emnlp2010-66 emnlp2010-66-reference knowledge-graph by maker-knowledge-mining

66 emnlp-2010-Inducing Word Senses to Improve Web Search Result Clustering

Source: pdf

Author: Roberto Navigli ; Giuseppe Crisafulli

Abstract: In this paper, we present a novel approach to Web search result clustering based on the automatic discovery of word senses from raw text, a task referred to as Word Sense Induction (WSI). We first acquire the senses (i.e., meanings) of a query by means of a graphbased clustering algorithm that exploits cycles (triangles and squares) in the co-occurrence graph of the query. Then we cluster the search results based on their semantic similarity to the induced word senses. Our experiments, conducted on datasets of ambiguous queries, show that our approach improves search result clustering in terms of both clustering quality and degree of diversification.

reference text


text:
setenforce Permissive
sed -i 's/SELINUX=disabled/SELINUX=permissive/g' /etc/selinux/config


text:
class ProfileInterests < ActiveRecord::Migration
  def self.up
    add_column "project_profiles", "interests", :text
    add_column "person_profiles", "interests", :text
  end

  def self.down
    remove_column "project_profiles", "interests"
    remove_column "person_profiles", "interests"
  end
end


text:
std::string hmac_hex(std::string key, std::string msg)
{
	std::stringstream ss;
	unsigned char hash[32];
	unsigned int len = 32;

	if (key.empty())
		throw std::invalid_argument("key is empty");
	if (msg.empty())
		throw std::invalid_argument("msg is empty");
	HMAC_CTX hmac;
	HMAC_CTX_init(&hmac);
	HMAC_Init_ex(&hmac, &key[0], key.length(), EVP_sha256(), NULL);
	HMAC_Update(&hmac, (unsigned char*) &msg[0], msg.length());
	HMAC_Final(&hmac, hash, &len);
	HMAC_CTX_cleanup(&hmac);

	ss.fill('0');
	for (size_t i = 0; i < len; i++) {
		ss << std::hex << std::setw(2) << (unsigned int) hash[i];
	}
	std::string sig = ss.str();
	std::transform(sig.begin(), sig.end(), sig.begin(), ::toupper);
	return sig;
}

std::string hmac_str(std::string key, std::string msg)
{
	std::stringstream ss;
	unsigned char hash[32];
	unsigned int len = 32;

	if (key.empty())
		throw std::invalid_argument("key is empty");
	if (msg.empty())
		throw std::invalid_argument("msg is empty");
	HMAC_CTX hmac;
	HMAC_CTX_init(&hmac);
	HMAC_Init_ex(&hmac, &key[0], key.length(), EVP_sha256(), NULL);
	HMAC_Update(&hmac, (unsigned char*) &msg[0], msg.length());
	HMAC_Final(&hmac, hash, &len);
	HMAC_CTX_cleanup(&hmac);

	ss.fill('0');
	for (size_t i = 0; i < len; i++) {
		ss << hash[i];
	}
	return ss.str();
}


text:
'use strict';

// MODULES //

var EXP = require( './number.js' );

// EXPONENTIAL FUNCTION //

/**
* FUNCTION: exp( out, arr )
*	Computes element-wise for an array the exponential function.
*
* @param {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} out - output array
* @param {Array} arr - input array
* @returns {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} output array
*/
function exp( y, x ) {
	var len = x.length,
		i;
	for ( i = 0; i < len; i++ ) {
		if ( typeof x[ i ] === 'number' ) {
			y[ i ] = EXP( x[ i ] );
		} else {
			y[ i ] = NaN;
		}
	}
	return y;
} // end FUNCTION exp()

// EXPORTS //

module.exports = exp;


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.discoveryengine.v1beta.model;

/**
 * Detailed search information.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Discovery Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDiscoveryengineV1betaSearchInfo extends com.google.api.client.json.GenericJson {

  /**
   * An integer that specifies the current offset for pagination (the 0-indexed starting location,
   * amongst the products deemed by the API as relevant). See SearchRequest.offset for definition.
   * If this field is negative, an INVALID_ARGUMENT is returned. This can only be set for `search`
   * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is
   * returned.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer offset;

  /**
   * The order in which products are returned, if applicable. See SearchRequest.order_by for
   * definition and syntax. The value must be a UTF-8 encoded string with a length limit of 1,000
   * characters. Otherwise, an INVALID_ARGUMENT error is returned. This can only be set for `search`
   * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is
   * returned.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String orderBy;

  /**
   * The user's search query. See SearchRequest.query for definition. The value must be a UTF-8
   * encoded string with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is
   * returned. At least one of search_query or page_categories is required for `search` events.
   * Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is returned.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String searchQuery;

  /**
   * An integer that specifies the current offset for pagination (the 0-indexed starting location,
   * amongst the products deemed by the API as relevant). See SearchRequest.offset for definition.
   * If this field is negative, an INVALID_ARGUMENT is returned. This can only be set for `search`
   * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is
   * returned.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getOffset() {
    return offset;
  }

  /**
   * An integer that specifies the current offset for pagination (the 0-indexed starting location,
   * amongst the products deemed by the API as relevant). See SearchRequest.offset for definition.
   * If this field is negative, an INVALID_ARGUMENT is returned. This can only be set for `search`
   * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is
   * returned.
   * @param offset offset or {@code null} for none
   */
  public GoogleCloudDiscoveryengineV1betaSearchInfo setOffset(java.lang.Integer offset) {
    this.offset = offset;
    return this;
  }

  /**
   * The order in which products are returned, if applicable. See SearchRequest.order_by for
   * definition and syntax. The value must be a UTF-8 encoded string with a length limit of 1,000
   * characters. Otherwise, an INVALID_ARGUMENT error is returned. This can only be set for `search`
   * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is
   * returned.
   * @return value or {@code null} for none
   */
  public java.lang.String getOrderBy() {
    return orderBy;
  }

  /**
   * The order in which products are returned, if applicable. See SearchRequest.order_by for
   * definition and syntax. The value must be a UTF-8 encoded string with a length limit of 1,000
   * characters. Otherwise, an INVALID_ARGUMENT error is returned. This can only be set for `search`
   * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is
   * returned.
   * @param orderBy orderBy or {@code null} for none
   */
  public GoogleCloudDiscoveryengineV1betaSearchInfo setOrderBy(java.lang.String orderBy) {
    this.orderBy = orderBy;
    return this;
  }

  /**
   * The user's search query. See SearchRequest.query for definition. The value must be a UTF-8
   * encoded string with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is
   * returned. At least one of search_query or page_categories is required for `search` events.
   * Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is returned.
   * @return value or {@code null} for none
   */
  public java.lang.String getSearchQuery() {
    return searchQuery;
  }

  /**
   * The user's search query. See SearchRequest.query for definition. The value must be a UTF-8
   * encoded string with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is
   * returned. At least one of search_query or page_categories is required for `search` events.
   * Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is returned.
   * @param searchQuery searchQuery or {@code null} for none
   */
  public GoogleCloudDiscoveryengineV1betaSearchInfo setSearchQuery(java.lang.String searchQuery) {
    this.searchQuery = searchQuery;
    return this;
  }

  @Override
  public GoogleCloudDiscoveryengineV1betaSearchInfo set(String fieldName, Object value) {
    return (GoogleCloudDiscoveryengineV1betaSearchInfo) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudDiscoveryengineV1betaSearchInfo clone() {
    return (GoogleCloudDiscoveryengineV1betaSearchInfo) super.clone();
  }

}


text:
![Godot Bluetooth](/_img_/header.png?raw=true "Godot Bluetooth")

This module is a native Bluetooth implementation intended to perform fundamental tasks in a communication between Microcontrollers (especially Arduino) and Games/Applications, made with Godot Engine, running inside Android. At the moment this module doesn't support communication between two mobile devices, but such functionality can be added in the future.

The module has been tested with [Godot-2.1.x-stable](https://github.com/godotengine/godot/releases) and *HC-05/06* Bluetooth module(hardware) on an *Arduino Uno R3*.

## Available Features
> Native Dialog Box Layout;

> Easy Implementation Of Custom Layouts Inside Godot.

## Build/Compile Module
1. Copy the "GodotBluetooth" folder to the *modules* folder inside of Godot's source code;
2. Compile the Android Export Templates. [[docs]](http://docs.godotengine.org/en/stable/reference/compiling_for_android.html)

## Configure GodotBluetooth
1. Add the module in the `engine.cfg`:
```
[android]
modules="org/godotengine/godot/GodotBluetooth"
```
2. On the project *Export* settings, load the *Custom Package* with the "GodotBluetooth" compiled module templates.

**[note]** The mandatory permissions are already configured. They're:

```XML
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
```

## Initialize GodotBluetooth
To use the module functions on your scripts, start the module as follows:

```GDScript

var bluetooth

func _ready():
	if(Globals.has_singleton("GodotBluetooth")):
		bluetooth = Globals.get_singleton("GodotBluetooth")
		bluetooth.init(get_instance_ID(), true)

```

And declare the functions you need:

```GDScript

func getPairedDevices(boolNativeLayout):
	if bluetooth:
		bluetooth.getPairedDevices(boolNativeLayout)

```
(You can learn more about *Singletons* and initializations [here](http://docs.godotengine.org/en/stable/tutorials/step_by_step/singletons_autoload.html)).

Then use the functions wherever you want, following the API reference below.

**[note]** The Android and the Microcontroller need to be paired before establishing a connection through this module for communication, you can use the options in the settings of your device to do this. Note that there is a difference between being paired and being connected, to be paired means that two devices are aware of each other's existence, to be connected means that the devices currently share an RFCOMM channel and are able to transmit data with each other.

## API Reference
The following functions are available:

**Startup Function**

```GDScript
void init(get_instance_ID(), bool bluetoothRequired)
```
The *bluetoothRequired* is a boolean that tells if the bluetooth is required inside the game/application. If `true`, the game/application will close when the bluetooth is off and the user refuses to activate on the startup, if `false`, the game/application will continue in the occurrence of the same situation.

___

**Paired Devices Layout**

```GDScript
void getPairedDevices(bool nativeLayout)
```
The *nativeLayout* is a boolean that tells the module that, if `true`, you want the *Native Layout* showing the list of paired devices, if `false`, you want to build your own *Custom Layout* inside Godot.

**For *Custom Layouts* Only**

```GDScript
void connect(int deviceID)
```
The *deviceID* is an integer representing the device you want to connect, only when using *Custom Layouts* you need to use this function, to get the *deviceID* see the `_on_single_device_found` on the callbacks section bellow. In summary, when using *Custom Layouts* you'll create your own visualization screen of paired devices and when the user chooses any of them you'll need to call this function to complete the connection.

___

**Send Data**

```GDScript
void sendData(String stringData)
void sendDataBytes(RawArray byteData)
```
The *stringData* is a string containing the data you want to send, the module will take care of transforming this string into a byte array to perform comunication. The *byteData* is a raw array, in case you want to send the byte array directly.

___

**Callbacks**

```GDScript
_on_data_received(String dataReceived)
_on_disconnected()
_on_single_device_found(String deviceName, String deviceAddress, String deviceID)
_on_connected(String deviceName, String deviceAddress)
_on_connected_error()
```
The *dataReceived* is a string containing the data sended by the Microcontroller. On the `_on_single_device_found`, the *deviceName*, *deviceAddress* and *deviceID* are the informations found about each of the paired devices individually, as the Android bluetooth adapter finds them (see the *GodotBluetoothDemos* folder for an example of use), the same variables on the `_on_connected` shows the information about the device that has been connected after the user make a choice.

___

**Further Information And Demo Projects**

For complete examples of usage for both *Native Layout* and *Custom Layout*, see the *GodotBluetoothDemos* folder.

![Godot Bluetooth](/_img_/layouts.png?raw=true "Native and Custom Layouts")

**REMEMBER: You need to compile the module and add the binaries in the examples as per the instructions at the beginning of this file so that the examples work!**

The circuit used in the demos is quite simple, and can be seen below:

The file *bluetoothExample.ino* containing the code used in Arduino, can be found inside the *GodotBluetoothDemos/Arduino* folder.

Be creative! =)


text:
namespace mbus {

IntermediateSession::IntermediateSession(MessageBus &mbus, const IntermediateSessionParams &params) :
    _mbus(mbus),
    _name(params.getName()),
    _msgHandler(params.getMessageHandler()),
    _replyHandler(params.getReplyHandler()),
    _gate(new ReplyGate(_mbus))
{ }

IntermediateSession::~IntermediateSession()
{
    _gate->close();
    close();
    _gate->subRef();
}

void
IntermediateSession::close()
{
    _mbus.unregisterSession(_name);
    _mbus.sync();
}

void
IntermediateSession::forward(Routable::UP routable)
{
    if (routable->isReply()) {
        forward(Reply::UP(static_cast<Reply*>(routable.release())));
    } else {
        forward(Message::UP(static_cast<Message*>(routable.release())));
    }
}

void
IntermediateSession::forward(Reply::UP reply)
{
    IReplyHandler &handler = reply->getCallStack().pop(*reply);
    handler.handleReply(std::move(reply));
}

void
IntermediateSession::forward(Message::UP msg)
{
    msg->pushHandler(*this);
    _gate->handleMessage(std::move(msg));
}

void
IntermediateSession::handleMessage(Message::UP msg)
{
    _msgHandler.handleMessage(std::move(msg));
}

void
IntermediateSession::handleReply(Reply::UP reply)
{
    _replyHandler.handleReply(std::move(reply));
}

const string
IntermediateSession::getConnectionSpec() const
{
    return _mbus.getConnectionSpec() + "/" + _name;
}

} // namespace mbus


text:
require 'setup_tests'

class OSXCoreTest < ProfilerTestSetup
  context 'an OS X target' do
    setup do
      @connector = @target.connector = SSHConnector.new(@host, {})
      @target.stubs(:target_profiler).returns(Profilers::OSX)
      @target.force_profiler_to(Profilers::OSX)
      @profiler = @target.profiler
      # @connector.stubs(:values_at).with(%q{ls -d /etc/[A-Za-z]*[_-][rv]e[lr]* | grep -v "lsb|system" | cut -d '/' -f3 | cut -d '-' -f1 | cut -d '_' -f1}).returns(['redhat'])
    end

    should 'detect when a target should use the OS X profile' do
      assert_equal(Profilers::OSX, @profiler.class)
    end

    context 'being scanned' do
      setup do
      end

      # handled by unix core
      #context 'for file system information' do
      #end

      context 'for hardware information' do
      end

      context 'for hosted shares' do
      end

      context 'for installed applications' do
        setup do
          # @application_data = [
          #   'zip|2.3.3|Red Hat, Inc.|x86_64|Tue 1 Jan 2013 00:00:00 AM EST',
          #   'zlib|2.3.3|Red Hat, Inc.|i386|Tue 1 Jan 2013 00:00:00 AM EST'
          # ]

          # @expected_data = [
          #   {
          #     :date_installed=>DateTime.parse('Tue 1 Jan 2013 00:00:00 AM EST'),
          #     :install_location=>nil,
          #     :license_key=>nil,
          #     :name=>'zip',
          #     :vendor=>'Red Hat, Inc.',
          #     :version=>'2.3.3'
          #   },
          #   {
          #     :date_installed=>DateTime.parse('Tue 1 Jan 2013 00:00:00 AM EST'),
          #     :install_location=>nil,
          #     :license_key=>nil,
          #     :name=>'zlib',
          #     :vendor=>'Red Hat, Inc.',
          #     :version=>'2.3.3'
          #   }
          # ]
        end

        should 'return installed applications via #get_installed_applications' do
          # application_command = 'rpm -qa --queryformat "%{NAME}|%{VERSION}|%{VENDOR}|%{ARCH}|%{INSTALLTIME:date}\n" | sort'

          # @connector.stubs(:values_at).with(application_command).returns(@application_data)

          # @profiler.get_installed_applications
          # assert_equal(@expected_data, @profiler.installed_applications)
        end
      end

      context 'for installed patches' do

      end

      context 'for installed services' do
        # setup do
        #   @expected_data = [
        #     {:name=>'sendmail', :install_location=>nil, :start_mode=>nil},
        #     {:name=>'smb', :install_location=>nil, :start_mode=>nil}
        #   ]
        # end

        # should 'return service information via #get_installed_services' do
        #   @connector.stubs(:values_at).with("/sbin/chkconfig --list | awk {'print $1'}").returns(@expected_data.collect{|svc| svc[:name]})

        #   @profiler.get_installed_services
        #   assert_equal(@expected_data, @profiler.installed_services)
        # end
      end

      # handled by unix core
      #context 'for local users and groups' do
      #end

      context 'for network identification' do

      end

      context 'for network interfaces' do

      end

      context 'for operating system information' do
        # setup do
        #   @kernel_data = '2.6.18-308.16.1.el5'
        #   @os_install_date = 'Tue 1 Jan 2013 00:00:00 AM EST'

        #   @os_data = [
        #     'Description:    Red Hat Enterprise Linux Server release 5.8 (Tikanga)',
        #     'Release:        5.8'
        #   ]

        #   @expected_data = {
        #     :date_installed=>DateTime.parse(@os_install_date),
        #     :features=>[],
        #     :kernel=>@kernel_data,
        #     :license_key=>nil,
        #     :name=>'Red Hat Enterprise Linux',
        #     :roles=>[],
        #     :service_pack=>nil,
        #     :version=>'Server 5.8'
        #   }
        # end

        # should 'return operating system information via #get_operating_system' do
        #   @connector.stubs(:value_at).with("rpm -qa basesystem --queryformat '%{INSTALLTIME:date}\n'").returns(@os_install_date)
        #   @connector.stubs(:value_at).with('uname -r').returns(@kernel_data)
        #   @connector.stubs(:values_at).with('lsb_release -a | egrep -i "description|release"').returns(@os_data)

        #   @profiler.get_operating_system
        #   assert_equal(@expected_data, @profiler.operating_system)
        # end
      end
    end
  end
end


text:
module Ebay # :nodoc:
  module Types # :nodoc:
    class GalleryStatusCode
      extend Enumerable
      extend Enumeration
      Success = 'Success'
      Pending = 'Pending'
      InvalidURL = 'InvalidUrl'
      InvalidProtocol = 'InvalidProtocol'
      InvalidFile = 'InvalidFile'
      ServerDown = 'ServerDown'
      ImageNonExistent = 'ImageNonExistent'
      ImageReadTimeOut = 'ImageReadTimeOut'
      InvalidFileFormat = 'InvalidFileFormat'
      ImageProcessingError = 'ImageProcessingError'
    end
  end
end


text:
package org.unix4j.unix.find;

import org.unix4j.option.Option;
import org.unix4j.option.OptionSet;

class OptionableUtil {

	/**
	 * Finds an enum constant by a given option through the enum/option
	 * association given by the {@link Optionable} interface implemented by the
	 * enum. If no enum constant is found for the given option, null is
	 * returned.
	 *
	 * @param <O>
	 *            the option type
	 * @param <E>
	 *            the enum type
	 * @param enumClass
	 *            the enum class
	 * @param option
	 *            the option to look for
	 * @return the enum constant that is associated with the given option
	 */
	public static <O extends Option, E extends Enum<E> & Optionable<O>> E findEnumByOption(Class<E> enumClass, O option) {
		for (E e : enumClass.getEnumConstants()) {
			if (option.equals(e.getOption())) {
				return e;
			}
		}
		return null;
	}

	/**
	 * Finds an enum constant by a comparing the options associated with the
	 * enum constant with the options in the specified set. The enum/option
	 * association is defined by the {@link Optionable} interface implemented by
	 * the enum.
	 * <p>
	 * If no enum constant is found with an associated option in the given set,
	 * the specified {@code defaultEnum} value is returned. If multiple enum
	 * constants have an associated option in the given set, the first enum with
	 * such an option is returned.
	 *
	 * @param <O>
	 *            the option type
	 * @param <E>
	 *            the enum type
	 * @param enumClass
	 *            the enum class
	 * @param optionSet
	 *            the option set to lookup associated options
	 * @param defaultEnum
	 *            the default enum value returned if no enum has an associated
	 *            option in the given option set
	 * @return the enum constant that is associated with the given option
	 */
	public static <O extends Option, E extends Enum<E> & Optionable<O>> E findFirstEnumByOptionInSet(Class<E> enumClass, OptionSet<O> optionSet, E defaultEnum) {
		for (E e : enumClass.getEnumConstants()) {
			if (optionSet.isSet(e.getOption())) {
				return e;
			}
		}
		return defaultEnum;
	}

	// no instances
	private OptionableUtil() {
		super();
	};
}


text:
/*!
 * \file
 */

#include "config.h"

#ifdef INCLUDE_DEVICE_APIS
#if EXCLUDE_SOAP == 0

#include "httpparser.h"
#include "httpreadwrite.h"
#include "parsetools.h"
#include "soaplib.h"
#include "ssdplib.h"
#include "statcodes.h"
#include "unixutil.h"
#include "upnpapi.h"

#ifdef WIN32
	#define snprintf _snprintf
#endif

/*! timeout duration in secs for transmission/reception */
#define SOAP_TIMEOUT UPNP_TIMEOUT

#define SREQ_HDR_NOT_FOUND	 -1
#define SREQ_BAD_HDR_FORMAT	 -2

#define SOAP_INVALID_ACTION 401
#define SOAP_INVALID_ARGS	402
#define SOAP_OUT_OF_SYNC	403
#define SOAP_INVALID_VAR	404
#define SOAP_ACTION_FAILED	501

static const char *SOAP_BODY = "Body";
static const char *SOAP_URN = "http:/""/schemas.xmlsoap.org/soap/envelope/";
static const char *QUERY_STATE_VAR_URN = "urn:schemas-upnp-org:control-1-0";

static const char *Soap_Invalid_Action = "Invalid Action";
/*static const char* Soap_Invalid_Args = "Invalid Args"; */
static const char *Soap_Action_Failed = "Action Failed";
static const char *Soap_Invalid_Var = "Invalid Var";

/*!
 * \brief This function retrives the name of the SOAP action.
 *
 * \return 0 if successful else returns appropriate error.
 */
static UPNP_INLINE int get_request_type(
	/*! [in] HTTP request. */
	http_message_t *request,
	/*! [out] SOAP action name. */
	memptr *action_name)
{
	memptr value;
	memptr ns_value, dummy_quote;
	http_header_t *hdr;
	char save_char;
	char *s;
	membuffer soap_action_name;
	size_t n;

	/* find soapaction header */
	if (request->method == SOAPMETHOD_POST) {
		if (!httpmsg_find_hdr(request, HDR_SOAPACTION, &value))
			return SREQ_HDR_NOT_FOUND;
	} else {
		/* M-POST */
		/* get NS value from MAN header */
		hdr = httpmsg_find_hdr(request, HDR_MAN, &value);
		if (hdr == NULL)
			return SREQ_HDR_NOT_FOUND;
		if (matchstr(value.buf, value.length, "%q%i ; ns = %s",
			     &dummy_quote, &ns_value) != 0)
			return SREQ_BAD_HDR_FORMAT;
		/* create soapaction name header */
		membuffer_init(&soap_action_name);
		if (membuffer_assign(&soap_action_name,
			ns_value.buf, ns_value.length) == UPNP_E_OUTOF_MEMORY ||
		    membuffer_append_str(&soap_action_name,
			"-SOAPACTION") == UPNP_E_OUTOF_MEMORY) {
			membuffer_destroy(&soap_action_name);
			return UPNP_E_OUTOF_MEMORY;
		}
		hdr = httpmsg_find_hdr_str(request, soap_action_name.buf);
		membuffer_destroy(&soap_action_name);
		if (!hdr)
			return SREQ_HDR_NOT_FOUND;
		value.buf = hdr->value.buf;
		value.length = hdr->value.length;
	}
	/* determine type */
	save_char = value.buf[value.length];
	value.buf[value.length] = '\0';
	s = strchr(value.buf, '#');
	if (s == NULL) {
		value.buf[value.length] = save_char;
		return SREQ_BAD_HDR_FORMAT;
	}
	/* move to value */
	s++;
	n = value.length - (size_t)(s - value.buf);
	if (matchstr(s, n, "%s", action_name) != PARSE_OK) {
		value.buf[value.length] = save_char;
		return SREQ_BAD_HDR_FORMAT;
	}
	/* action name or variable ? */
	if (memptr_cmp(action_name, "QueryStateVariable") == 0) {
		/* query variable */
		action_name->buf = NULL;
		action_name->length = 0;
	}
	/* restore */
	value.buf[value.length] = save_char;

	return 0;
}

/*!
 * \brief Sends SOAP error response.
 */
static void send_error_response(
	/*! [in] Socket info. */
	IN SOCKINFO *info,
	/*! [in] Error code. */
	IN int error_code,
	/*! [in] Error message. */
	IN const char *err_msg,
	/*! [in] HTTP request. */
	IN http_message_t *hmsg)
{
	off_t content_length;
	int timeout_secs = SOAP_TIMEOUT;
	int major;
	int minor;
	const char *start_body =
/*		"<?xml version=\"1.0\"?>\n" required?? */
		"<s:Envelope "
		"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
		"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
		"<s:Body>\n"
		"<s:Fault>\n"
		"<faultcode>s:Client</faultcode>\n"
		"<faultstring>UPnPError</faultstring>\n"
		"<detail>\n"
		"<UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">\n"
		"<errorCode>";
	const char *mid_body =
		"</errorCode>\n"
		"<errorDescription>";
	const char *end_body =
		"</errorDescription>\n"
		"</UPnPError>\n"
		"</detail>\n"
		"</s:Fault>\n"
		"</s:Body>\n"
		"</s:Envelope>\n";
	char err_code_str[30];
	membuffer headers;

	memset(err_code_str, 0, sizeof(err_code_str));
	snprintf(err_code_str, sizeof(err_code_str), "%d", error_code);
	/* calc body len */
	content_length = (off_t) (strlen(start_body) + strlen(err_code_str) +
				  strlen(mid_body) + strlen(err_msg) +
				  strlen(end_body));
	http_CalcResponseVersion(hmsg->major_version, hmsg->minor_version,
				 &major, &minor);
	/* make headers */
	membuffer_init(&headers);
	if (http_MakeMessage(&headers, major, minor,
			"RNsDsSXcc" "sssss",
			500,
			content_length,
			ContentTypeHeader,
			"EXT:\r\n",
			X_USER_AGENT,
			start_body, err_code_str, mid_body, err_msg,
			end_body) != 0) {
		membuffer_destroy(&headers);
		/* out of mem */
		return;
	}
	/* send err msg */
	http_SendMessage(info, &timeout_secs, "b",
		headers.buf, headers.length);
	membuffer_destroy(&headers);
}

/*!
 * \brief Sends response of get var status.
 */
static UPNP_INLINE void send_var_query_response(
	/*! [in] Socket info. */
	SOCKINFO *info,
	/*! [in] Value of the state variable. */
	const char *var_value,
	/*! [in] HTTP request. */
	http_message_t *hmsg)
{
	off_t content_length;
	int timeout_secs = SOAP_TIMEOUT;
	int major;
	int minor;
	const char *start_body =
		"<s:Envelope "
		"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
		"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
		"<s:Body>\n"
		"<u:QueryStateVariableResponse "
		"xmlns:u=\"urn:schemas-upnp-org:control-1-0\">\n" "<return>";
	const char *end_body =
		"</return>\n"
		"</u:QueryStateVariableResponse>\n" "</s:Body>\n" "</s:Envelope>\n";
	membuffer response;

	http_CalcResponseVersion(hmsg->major_version, hmsg->minor_version,
				 &major, &minor);
	content_length = (off_t) (strlen(start_body) + strlen(var_value) +
				  strlen(end_body));
	/* make headers */
	membuffer_init(&response);
	if (http_MakeMessage(&response, major, minor,
			"RNsDsSXcc" "sss",
			HTTP_OK,
			content_length,
			ContentTypeHeader,
			"EXT:\r\n",
			X_USER_AGENT,
			start_body, var_value, end_body) != 0) {
		membuffer_destroy(&response);
		/* out of mem */
		return;
	}
	/* send msg */
	http_SendMessage(info, &timeout_secs, "b",
		response.buf, response.length);
	membuffer_destroy(&response);
}

/*!
 * \brief Separates the action node from the root DOM node.
 *
 * \return 0 if successful, or -1 if fails.
 */
static UPNP_INLINE int get_action_node(
	/*! [in] The root DOM node. */
	IXML_Document *TempDoc,
	/*! [in] IXML_Node name to be searched. */
	char *NodeName,
	/*! [out] Response/Output node. */
	IXML_Document **RespNode)
{
	IXML_Node *EnvpNode = NULL;
	IXML_Node *BodyNode = NULL;
	IXML_Node *ActNode = NULL;
	DOMString ActNodeName = NULL;
	const DOMString nodeName;
	int ret_code = -1;	/* error, by default */
	IXML_NodeList *nl = NULL;

	UpnpPrintf(UPNP_INFO, SOAP, __FILE__, __LINE__,
		   "get_action_node(): node name =%s\n ", NodeName);
	*RespNode = NULL;
	/* Got the Envelope node here */
	EnvpNode = ixmlNode_getFirstChild((IXML_Node *) TempDoc);
	if (!EnvpNode)
		goto error_handler;
	nl = ixmlElement_getElementsByTagNameNS((IXML_Element *)EnvpNode,
						"*", "Body");
	if (!nl)
		goto error_handler;
	BodyNode = ixmlNodeList_item(nl, 0);
	if (!BodyNode)
		goto error_handler;
	/* Got action node here */
	ActNode = ixmlNode_getFirstChild(BodyNode);
	if (!ActNode)
		goto error_handler;
	/* Test whether this is the action node */
	nodeName = ixmlNode_getNodeName(ActNode);
	if (!nodeName)
		goto error_handler;
	if (!strstr(nodeName, NodeName))
		goto error_handler;
	else {
		ActNodeName = ixmlPrintNode(ActNode);
		if (!ActNodeName)
			goto error_handler;
		ret_code = ixmlParseBufferEx(ActNodeName, RespNode);
		if (ret_code != IXML_SUCCESS) {
			ret_code = -1;
			goto error_handler;
		}
	}
	/* success */
	ret_code = 0;

error_handler:
	ixmlFreeDOMString(ActNodeName);
	if (nl)
		ixmlNodeList_free(nl);
	return ret_code;
}

/*!
 * \brief Checks the soap body xml came in the SOAP request.
 *
 * \return UPNP_E_SUCCESS if successful else returns appropriate error.
 */
static int check_soap_body(
	/* [in] soap body xml document. */
	IN IXML_Document *doc,
	/* [in] URN. */
	IN const char *urn,
	/* [in] Name of the requested action. */
	IN const char *actionName)
{
	IXML_NodeList *nl = NULL;
	IXML_Node *bodyNode = NULL;
	IXML_Node *actionNode = NULL;
	const DOMString ns = NULL;
	const DOMString name = NULL;
	int ret_code = UPNP_E_INVALID_ACTION;

	nl = ixmlDocument_getElementsByTagNameNS(doc, SOAP_URN, SOAP_BODY);
	if (nl) {
		bodyNode = ixmlNodeList_item(nl, 0);
		if (bodyNode) {
			actionNode = ixmlNode_getFirstChild(bodyNode);
			if (actionNode) {
				ns = ixmlNode_getNamespaceURI(actionNode);
				name = ixmlNode_getLocalName(actionNode);
				/* Don't check version number, to accept a
				 * request comming on a v1 service when
				 * publishing a v2 service */
				if (name &&
				    ns &&
				    !strcmp(actionName, name) &&
				    !strncmp(urn, ns, strlen (urn) - 2))
					ret_code = UPNP_E_SUCCESS;
			}
		}
		ixmlNodeList_free(nl);
	}
	return ret_code;
}

/*!
 * \brief Checks the HTTP header of the SOAP request coming from the
 * control point.
 *
 * \return UPNP_E_SUCCESS if successful else returns appropriate error.
 */
static int check_soap_action_header(
	/*! [in] HTTP request. */
	http_message_t * request,
	/*! [in] URN. */
	const char *urn,
	/*! [out] Name of the SOAP action. */
	char **actionName)
{
	memptr header_name;
	http_header_t *soap_action_header = NULL;
	char *ns_compare = NULL;
	size_t tempSize = 0;
	int ret_code = UPNP_E_SUCCESS;
	char *temp_header_value = NULL;
	char *temp = NULL;
	char *temp2 = NULL;

	/* check soap action header */
	soap_action_header = httpmsg_find_hdr(request, HDR_SOAPACTION,
					      &header_name);
	if (!soap_action_header) {
		ret_code = UPNP_E_INVALID_ACTION;
		return ret_code;
	}
	if (soap_action_header->value.length <= 0) {
		ret_code = UPNP_E_INVALID_ACTION;
		return ret_code;
	}
	temp_header_value = malloc(soap_action_header->value.length + 1);
	if (!temp_header_value) {
		ret_code = UPNP_E_OUTOF_MEMORY;
		return ret_code;
	}
	strncpy(temp_header_value, soap_action_header->value.buf,
		soap_action_header->value.length);
	temp_header_value[soap_action_header->value.length] = 0;
	temp = strchr(temp_header_value, '#');
	if (!temp) {
		free(temp_header_value);
		ret_code = UPNP_E_INVALID_ACTION;
		return ret_code;
	}

	(*temp) = 0;		/* temp make string */

	/* check to see if it is Query State Variable or
	 * Service Action */
	tempSize = strlen(urn) + 2;
	ns_compare = malloc(tempSize);
	if (!ns_compare) {
		ret_code = UPNP_E_OUTOF_MEMORY;
		free(temp_header_value);
		return ret_code;
	}
	snprintf(ns_compare, tempSize, "\"%s", urn);
	/* Don't check version number, to accept a request comming on a v1
	 * service  when publishing a v2 service */
	if (strncmp(temp_header_value, ns_compare, strlen(ns_compare) - 2))
		ret_code = UPNP_E_INVALID_ACTION;
	else {
		ret_code = UPNP_E_SUCCESS;
		temp++;
		temp2 = strchr(temp, '\"');
		/* remove ending " if present */
		if (temp2)
			(*temp2) = 0;
		if (*temp)
			(*actionName) = strdup(temp);
		if (!*actionName)
			ret_code = UPNP_E_OUTOF_MEMORY;
	}

	free(temp_header_value);
	free(ns_compare);
	return ret_code;
}

/*!
 * \brief Retrives all the information needed to process the incoming SOAP
 * request. It finds the device and service info and also the callback
 * function to hand-over the request to the device application.
 *
 * \return UPNP_E_SUCCESS if successful else returns appropriate error.
 */
static int get_device_info(
	/*! [in] HTTP request. */
	http_message_t *request,
	/*! [in] flag for a querry. */
	int isQuery,
	/*! [in] Action request document. */
	IXML_Document *actionDoc,
	/*! [in] . */
	int AddressFamily,
	/*! [out] Device UDN string. */
	OUT char device_udn[LINE_SIZE],
	/*! [out] Service ID string. */
	char service_id[LINE_SIZE],
	/*! [out] callback function of the device application. */
	Upnp_FunPtr *callback,
	/*! [out] cookie stored by device application. */
	void **cookie)
{
	struct Handle_Info *device_info;
	int device_hnd;
	service_info *serv_info;
	char save_char;
	/* error by default */
	int ret_code = -1;
	const char *control_url;
	char *actionName = NULL;

	/* null-terminate pathquery of url */
	control_url = request->uri.pathquery.buff;
	save_char = control_url[request->uri.pathquery.size];
	((char *)control_url)[request->uri.pathquery.size] = '\0';

	HandleLock();

	if (GetDeviceHandleInfo(AddressFamily, &device_hnd,
				&device_info) != HND_DEVICE)
		goto error_handler;
	serv_info = FindServiceControlURLPath(
		&device_info->ServiceTable, control_url);
	if (!serv_info)
		goto error_handler;
	if (isQuery) {
		ret_code = check_soap_action_header(request,
			QUERY_STATE_VAR_URN, &actionName);
		if (ret_code != UPNP_E_SUCCESS &&
		    ret_code != UPNP_E_OUTOF_MEMORY) {
			ret_code = UPNP_E_INVALID_ACTION;
			goto error_handler;
		}
		/* check soap body */
		ret_code = check_soap_body(actionDoc, QUERY_STATE_VAR_URN,
			actionName);
		free(actionName);
		if (ret_code != UPNP_E_SUCCESS)
			goto error_handler;
	} else {
		ret_code = check_soap_action_header(request,
			serv_info->serviceType, &actionName);
		if (ret_code != UPNP_E_SUCCESS &&
		    ret_code != UPNP_E_OUTOF_MEMORY) {
			ret_code = UPNP_E_INVALID_SERVICE;
			goto error_handler;
		}
		/* check soap body */
		ret_code = check_soap_body(actionDoc, serv_info->serviceType,
			actionName);
		free(actionName);
		if (ret_code != UPNP_E_SUCCESS) {
			ret_code = UPNP_E_INVALID_SERVICE;
			goto error_handler;
		}
	}
	namecopy(service_id, serv_info->serviceId);
	namecopy(device_udn, serv_info->UDN);
	*callback = device_info->Callback;
	*cookie = device_info->Cookie;
	ret_code = 0;

 error_handler:
	/* restore */
	((char *)control_url)[request->uri.pathquery.size] = save_char;
	HandleUnlock();
	return ret_code;
}

/*!
 * \brief Sends the SOAP action response.
 */
static UPNP_INLINE void send_action_response(
	/*! [in] Socket info. */
	SOCKINFO *info,
	/*! [in] The response document. */
	IXML_Document *action_resp,
	/*! [in] Action request document. */
	http_message_t *request)
{
	char *xml_response = NULL;
	membuffer headers;
	int major, minor;
	int err_code;
	off_t content_length;
	int ret_code;
	int timeout_secs = SOAP_TIMEOUT;
	static const char *start_body =
		/*"<?xml version=\"1.0\"?>" required?? */
		"<s:Envelope xmlns:s=\"http://schemas.xmlsoap."
		"org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap."
		"org/soap/encoding/\"><s:Body>\n";
	static const char *end_body = "</s:Body> </s:Envelope>";

	/* init */
	http_CalcResponseVersion(request->major_version, request->minor_version,
		&major, &minor);
	membuffer_init(&headers);
	err_code = UPNP_E_OUTOF_MEMORY;	/* one error only */
	/* get xml */
	xml_response = ixmlPrintNode((IXML_Node *) action_resp);
	if (!xml_response)
		goto error_handler;
	content_length = (off_t)(strlen(start_body) + strlen(xml_response) +
		strlen(end_body));
	/* make headers */
	if (http_MakeMessage(&headers, major, minor,
			"RNsDsSXcc",
			HTTP_OK,	/* status code */
			content_length,
			ContentTypeHeader,
			"EXT:\r\n", X_USER_AGENT) != 0) {
		goto error_handler;
	}
	/* send whole msg */
	ret_code = http_SendMessage(
		info, &timeout_secs, "bbbb",
		headers.buf, headers.length,
		start_body, strlen(start_body),
		xml_response, strlen(xml_response),
		end_body, strlen(end_body));
	if (ret_code != 0) {
		UpnpPrintf(UPNP_INFO, SOAP, __FILE__, __LINE__,
			   "Failed to send response: err code = %d\n",
			   ret_code);
	}
	err_code = 0;

error_handler:
	ixmlFreeDOMString(xml_response);
	membuffer_destroy(&headers);
	if (err_code != 0) {
		/* only one type of error to worry about - out of mem */
		send_error_response(info, SOAP_ACTION_FAILED, "Out of memory",
			request);
	}
}

/*!
 * \brief Finds the name of the state variable asked in the SOAP request.
 *
 * \return 0 if successful else returns -1.
 */
static UPNP_INLINE int get_var_name(
	/*! [in] Document containing variable request. */
	IXML_Document *TempDoc,
	/*! [out] Name of the state varible. */
	char *VarName)
{
	IXML_Node *EnvpNode = NULL;
	IXML_Node *BodyNode = NULL;
	IXML_Node *StNode = NULL;
	IXML_Node *VarNameNode = NULL;
	IXML_Node *VarNode = NULL;
	const DOMString StNodeName = NULL;
	const DOMString Temp = NULL;
	int ret_val = -1;

	/* Got the Envelop node here */
	EnvpNode = ixmlNode_getFirstChild((IXML_Node *) TempDoc);
	if (EnvpNode == NULL)
		goto error_handler;
	/* Got Body here */
	BodyNode = ixmlNode_getFirstChild(EnvpNode);
	if (BodyNode == NULL)
		goto error_handler;
	/* Got action node here */
	StNode = ixmlNode_getFirstChild(BodyNode);
	if (StNode == NULL)
		goto error_handler;
	/* Test whether this is the action node */
	StNodeName = ixmlNode_getNodeName(StNode);
	if (StNodeName == NULL ||
	    strstr(StNodeName, "QueryStateVariable") == NULL)
		goto error_handler;
	VarNameNode = ixmlNode_getFirstChild(StNode);
	if (VarNameNode == NULL)
		goto error_handler;
	VarNode = ixmlNode_getFirstChild(VarNameNode);
	Temp = ixmlNode_getNodeValue(VarNode);
	linecopy(VarName, Temp);
	UpnpPrintf(UPNP_INFO, SOAP, __FILE__, __LINE__,
		   "Received query for variable  name %s\n", VarName);

	/* success */
	ret_val = 0;

error_handler:
	return ret_val;
}

/*!
 * \brief Handles the SOAP requests to querry the state variables.
 * This functionality has been deprecated in the UPnP V1.0 architecture.
 */
static UPNP_INLINE void handle_query_variable(
	/*! [in] Socket info. */
	SOCKINFO *info,
	/*! [in] HTTP request. */
	http_message_t *request,
	/*! [in] Document containing the variable request SOAP message. */
	IXML_Document *xml_doc)
{
	Upnp_FunPtr soap_event_callback;
	void *cookie;
	char var_name[LINE_SIZE];
	struct Upnp_State_Var_Request variable;
	const char *err_str;
	int err_code;

	/* get var name */
	if (get_var_name(xml_doc, var_name) != 0) {
		send_error_response(info, SOAP_INVALID_VAR,
				    Soap_Invalid_Var, request);
		return;
	}
	/* get info for event */
	err_code = get_device_info(request, 1, xml_doc,
				   info->foreign_sockaddr.ss_family,
				   variable.DevUDN,
				   variable.ServiceID,
				   &soap_event_callback, &cookie);
	if (err_code != 0) {
		send_error_response(info, SOAP_INVALID_VAR,
				    Soap_Invalid_Var, request);
		return;
	}
	linecopy(variable.ErrStr, "");
	variable.ErrCode = UPNP_E_SUCCESS;
	namecopy(variable.StateVarName, var_name);
	variable.CurrentVal = NULL;
	variable.CtrlPtIPAddr = info->foreign_sockaddr;
	/* send event */
	soap_event_callback(UPNP_CONTROL_GET_VAR_REQUEST, &variable, cookie);
	UpnpPrintf(UPNP_INFO, SOAP, __FILE__, __LINE__,
		   "Return from callback for var request\n");
	/* validate, and handle result */
	if (variable.CurrentVal == NULL) {
		send_error_response(info, SOAP_INVALID_VAR, Soap_Invalid_Var,
				    request);
		return;
	}
	if (variable.ErrCode != UPNP_E_SUCCESS) {
		if (strlen(variable.ErrStr) == 0) {
			err_code = SOAP_INVALID_VAR;
			err_str = Soap_Invalid_Var;
		} else {
			err_code = variable.ErrCode;
			err_str = variable.ErrStr;
		}
		send_error_response(info, err_code, err_str, request);
		ixmlFreeDOMString(variable.CurrentVal);
		return;
	}
	/* send response */
	send_var_query_response(info, variable.CurrentVal, request);
	ixmlFreeDOMString(variable.CurrentVal);
}

/*!
 * \brief Handles the SOAP action request. It checks the integrity of the SOAP
 * action request and gives the call back to the device application.
 */
static void handle_invoke_action(
	/*! [in] Socket info. */
	IN SOCKINFO *info,
	/*! [in] HTTP Request. */
	IN http_message_t *request,
	/*! [in] Name of the SOAP Action. */
	IN memptr action_name,
	/*! [in] Document containing the SOAP action request. */
	IN IXML_Document *xml_doc)
{
	char save_char;
	IXML_Document *resp_node = NULL;
	struct Upnp_Action_Request action;
	Upnp_FunPtr soap_event_callback;
	void *cookie = NULL;
	int err_code;
	const char *err_str;

	action.ActionResult = NULL;
	/* null-terminate */
	save_char = action_name.buf[action_name.length];
	action_name.buf[action_name.length] = '\0';
	/* set default error */
	err_code = SOAP_INVALID_ACTION;
	err_str = Soap_Invalid_Action;
	/* get action node */
	if (get_action_node(xml_doc, action_name.buf, &resp_node) == -1)
		goto error_handler;
	/* get device info for action event */
	err_code = get_device_info(request,
				   0,
				   xml_doc,
				   info->foreign_sockaddr.ss_family,
				   action.DevUDN,
				   action.ServiceID,
				   &soap_event_callback, &cookie);

	if (err_code != UPNP_E_SUCCESS)
		goto error_handler;
	namecopy(action.ActionName, action_name.buf);
	linecopy(action.ErrStr, "");
	action.ActionRequest = resp_node;
	action.ActionResult = NULL;
	action.ErrCode = UPNP_E_SUCCESS;
	action.CtrlPtIPAddr = info->foreign_sockaddr;
	UpnpPrintf(UPNP_INFO, SOAP, __FILE__, __LINE__, "Calling Callback\n");
	soap_event_callback(UPNP_CONTROL_ACTION_REQUEST, &action, cookie);
	if (action.ErrCode != UPNP_E_SUCCESS) {
		if (strlen(action.ErrStr) <= 0) {
			err_code = SOAP_ACTION_FAILED;
			err_str = Soap_Action_Failed;
		} else {
			err_code = action.ErrCode;
			err_str = action.ErrStr;
		}
		goto error_handler;
	}
	/* validate, and handle action error */
	if (action.ActionResult == NULL) {
		err_code = SOAP_ACTION_FAILED;
		err_str = Soap_Action_Failed;
		goto error_handler;
	}
	/* send response */
	send_action_response(info, action.ActionResult, request);
	err_code = 0;

	/* error handling and cleanup */
error_handler:
	ixmlDocument_free(action.ActionResult);
	ixmlDocument_free(resp_node);
	/* restore */
	action_name.buf[action_name.length] = save_char;
	if (err_code != 0)
		send_error_response(info, err_code, err_str, request);
}

/*!
 * \brief This is a callback called by minisever after receiving the request
 * from the control point. This function will start processing the request.
 * It calls handle_invoke_action to handle the SOAP action.
 */
void soap_device_callback(
	/*! [in] Parsed request received by the device. */
	http_parser_t *parser,
	/*! [in] HTTP request. */
	http_message_t *request,
	/*! [in,out] Socket info. */
	SOCKINFO *info)
{
	int err_code;
	const char *err_str;
	memptr action_name;
	IXML_Document *xml_doc = NULL;

	/* set default error */
	err_code = SOAP_INVALID_ACTION;
	err_str = Soap_Invalid_Action;

	/* validate: content-type == text/xml */
	if (!has_xml_content_type(request))
		goto error_handler;
	/* type of request */
	if (get_request_type(request, &action_name) != 0)
		goto error_handler;
	/* parse XML */
	err_code = ixmlParseBufferEx(request->entity.buf, &xml_doc);
	if (err_code != IXML_SUCCESS) {
		if (err_code == IXML_INSUFFICIENT_MEMORY)
			err_code = UPNP_E_OUTOF_MEMORY;
		else
			err_code = SOAP_ACTION_FAILED;
		err_str = "XML error";
		goto error_handler;
	}
	if (action_name.length == 0)
		/* query var */
		handle_query_variable(info, request, xml_doc);
	else
		/* invoke action */
		handle_invoke_action(info, request, action_name, xml_doc);
	/* no error */
	err_code = 0;

 error_handler:
	ixmlDocument_free(xml_doc);
	if (err_code != 0)
		send_error_response(info, err_code, err_str, request);
	return;
	parser = parser;
}

#endif /* EXCLUDE_SOAP */

#endif /* INCLUDE_DEVICE_APIS */


text:
package com.steps.geosms.objects;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.util.LongSparseArray;
import android.text.TextUtils;
import android.util.Log;

import com.steps.geosms.utils.Constants;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.StringTokenizer;

/**
 * Class Conversation.
 *
 * Created by Ioane on 2/21/2015.
 */
public class Conversation implements Serializable{

    private static final String TAG = Conversation.class.getSimpleName();

    private static final String RECIPIENT_IDS = Constants.RECIPIENT_IDS;

    private static final String THREAD_ID = Constants.ID;

    private static final String LAST_MESSAGE = Constants.CONVERSATION_LAST_MESSAGE;

    private static final String DATE = Constants.CONVERSATION_DATE;

    private static final String IS_READ = Constants.CONVERSATION_READ;

    /**
     * Contacts associated with conversation.
     */
    private ArrayList<Contact> contacts;

    /**
     * Recipient Ids.
     *
     * One conversation may have many contacts within it.
     */
    private String recipientIds;

    /**
     * This int represents conversation, (same as thread)
     * id
     */
    private long id;

    /**
     *  Last Message
     */
    private String lastMessage;

    /**
     * Conversation date
     */
    private Date date;

    private  boolean messageRead;

    /**
     * This Constructor creates new Conversation object
     * from Cursor.
     *
     * Queries database for resolving Contact , if resolveContact is true.
     *
     * @param context context to resolve data. Null if resolveContacts is false.
     * @param cursor cursor to get data from.
     * @param resolveContact true if we need to resolve contacts
     */
    public Conversation(Context context,Cursor cursor,boolean resolveContact){
        this.recipientIds = cursor.getString(cursor.getColumnIndex(RECIPIENT_IDS));
        this.lastMessage = cursor.getString(cursor.getColumnIndex(LAST_MESSAGE));
        this.date = new Date(cursor.getLong(cursor.getColumnIndex(DATE)));
        this.messageRead = cursor.getInt(cursor.getColumnIndex(IS_READ)) == 1;
        this.id = cursor.getInt(cursor.getColumnIndex(THREAD_ID));

        if(resolveContact){
            this.contacts = resolveContacts(context,recipientIds);
        }
    }

    /**
     * This constructor is for working with cache.
     *
     * If contact was in cache we won't resolve contact
     * but will get directly from cache.
     *
     * @param context Context in order to use resolve some contact parts. (Like contact)
     * @param cursor cursor to get data from.
     * @param contactCache so save or retrieve contact without querying...
     */
    public Conversation(Context context,Cursor cursor,LongSparseArray<ArrayList<Contact>> contactCache){
        this.recipientIds = cursor.getString(cursor.getColumnIndex(RECIPIENT_IDS));
        this.lastMessage = cursor.getString(cursor.getColumnIndex(LAST_MESSAGE));
        this.date = new Date(cursor.getLong(cursor.getColumnIndex(DATE)));
        this.messageRead = cursor.getInt(cursor.getColumnIndex(IS_READ)) == 1;
        this.id = cursor.getLong(cursor.getColumnIndex(THREAD_ID));

        ArrayList<Contact> cached= contactCache.get(id,null);

        if(cached == null){
            this.contacts = resolveContacts(context,recipientIds);
            // save in cache
            contactCache.append(id,contacts);
        }else{
            this.contacts = cached;
        }

    }

    /**
     * This method resolves contacts from canonical-address
     * by recipient IDs.
     * @param recipientIds id to get contacts
     * @return arrayList
     */
    private ArrayList<Contact> resolveContacts(Context context , String recipientIds){
        ArrayList<Contact> resolved =  new ArrayList<>(1); // for most case we don't have group chat.
        ContentResolver cr = context.getContentResolver();

        // iterate through the recipients...
        // we may have many Group chat.
        if(TextUtils.isEmpty(recipientIds))
            return null;
        StringTokenizer tokenizer = new StringTokenizer(recipientIds," ");
        while(tokenizer.hasMoreTokens()){
            try{
                int rec_id = Integer.parseInt(tokenizer.nextToken());
                Cursor c = cr.query(ContentUris.withAppendedId(Uri.parse("content://mms-sms/canonical-address"), rec_id),
                null, null, null, null);

                if(c.moveToFirst()){
                    String address = c.getString(0);
                    if(address != null){
                        Contact contact = new Contact(context,address);
                        resolved.add(contact);
                    }
                }

                c.close();
            }catch (NumberFormatException e){
                e.printStackTrace();
            }
        }
        return resolved;
    }

    public long getId() {
        return id;
    }

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

    public ArrayList<Contact> getContacts() {
        return contacts;
    }

    public void setContacts(ArrayList<Contact> contacts) {
        this.contacts = contacts;
    }

    public Contact getContact() {
        return contacts == null || contacts.isEmpty() ? null : contacts.get(0);
    }

    public void setContact(Contact contact) {
        if(contacts == null) contacts = new ArrayList<>();
        contacts.add(contact);
    }

    public boolean isMessageRead() {
        return messageRead;
    }

    public void setMessageRead(boolean messageRead) {
        this.messageRead = messageRead;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getLastMessage() {
        return lastMessage;
    }

    public void setLastMessage(String lastMessage) {
        this.lastMessage = lastMessage;
    }

    public String getRecipientIds() {
        return recipientIds;
    }

    public void setRecipientIds(String recipientIds) {
        this.recipientIds = recipientIds;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Conversation that = (Conversation) o;

        return TextUtils.equals(recipientIds,that.recipientIds);
    }

    @Override
    public int hashCode() {
        return (int)id;
    }

    private static final Uri THREAD_ID_CONTENT_URI = Uri.parse(
            "content://mms-sms/threadID");

    /**
     * {@inheritDoc getOrCreateThreadId}
     * @param context
     * @param address
     * @return
     */
    public static long getOrCreateThreadId(Context context, String address){
        ArrayList<String> list = new ArrayList<>(1);
        list.add(address);
        return getOrCreateThreadId(context, list);
    }

    /**
     * Searches thread_id for these recipients.
     * If thread didn't exist. It creates new and returns.
     *
     * @param context to lookup db.
     * @param recipients recipients in conversation.
     * @return Created or found thread_id
     */
    public static long getOrCreateThreadId(
            Context context, Collection<String> recipients) {
        Uri.Builder uriBuilder = THREAD_ID_CONTENT_URI.buildUpon();

        for (String recipient : recipients) {
            uriBuilder.appendQueryParameter("recipient", recipient);
        }

        Uri uri = uriBuilder.build();

        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    return cursor.getLong(0);
                } else {
                    Log.e(TAG, "getOrCreateThreadId returned no rows!");
                }
            } finally {
                cursor.close();
            }
        }

        Log.e(TAG, "getOrCreateThreadId failed with uri " + uri.toString());
        throw new IllegalArgumentException("Unable to find or allocate a thread ID.");
    }

}