text:
<?php
/*
Plugin Name: Revolution Slider
Plugin URI: http://www.themepunch.com/codecanyon/revolution_wp/
Description: Revolution Slider - Premium responsive slider
Author: ThemePunch
Version: 3.0.5
Author URI: http://themepunch.com
*/

$revSliderVersion = "3.0.5";
$currentFile = __FILE__;
$currentFolder = dirname($currentFile);

//include frameword files
require_once $currentFolder . '/inc_php/framework/include_framework.php';

//include bases
require_once $folderIncludes . 'base.class.php';
require_once $folderIncludes . 'elements_base.class.php';
require_once $folderIncludes . 'base_admin.class.php';
require_once $folderIncludes . 'base_front.class.php';

//include product files
require_once $currentFolder . '/inc_php/revslider_settings_product.class.php';
require_once $currentFolder . '/inc_php/revslider_globals.class.php';
require_once $currentFolder . '/inc_php/revslider_operations.class.php';
require_once $currentFolder . '/inc_php/revslider_slider.class.php';
require_once $currentFolder . '/inc_php/revslider_output.class.php';
require_once $currentFolder . '/inc_php/revslider_slide.class.php';
require_once $currentFolder . '/inc_php/revslider_widget.class.php';
require_once $currentFolder . '/inc_php/revslider_params.class.php';

try{

	//register the kb slider widget
	UniteFunctionsWPRev::registerWidget("RevSlider_Widget");

	//add shortcode
	function rev_slider_shortcode($args){

		$sliderAlias = UniteFunctionsRev::getVal($args,0);
		ob_start();
		$slider = RevSliderOutput::putSlider($sliderAlias);
		$content = ob_get_contents();
		ob_clean();
		ob_end_clean();

		//handle slider output types
		if(!empty($slider)){
			$outputType = $slider->getParam("output_type","");
			switch($outputType){
				case "compress":
					$content = str_replace("\n", "", $content);
					$content = str_replace("\r", "", $content);
					return($content);
				break;
				case "echo":
					echo $content;		//bypass the filters
				break;
				default:
					return($content);
				break;
			}
		}else
			return($content);		//normal output

	}

	add_shortcode( 'rev_slider', 'rev_slider_shortcode' );

	if(is_admin()){		//load admin part
		require_once $currentFolder."/revslider_admin.php";

		$productAdmin = new RevSliderAdmin($currentFile);

	}else{		//load front part

		/**
		 *
		 * put rev slider on the page.
		 * the data can be slider ID or slider alias.
		 */
		function putRevSlider($data,$putIn = ""){
			$operations = new RevOperations();
			$arrValues = $operations->getGeneralSettingsValues();
			$includesGlobally = UniteFunctionsRev::getVal($arrValues, "includes_globally","on");
			$strPutIn = UniteFunctionsRev::getVal($arrValues, "pages_for_includes");
			$isPutIn = RevSliderOutput::isPutIn($strPutIn,true);

			if($isPutIn == false && $includesGlobally == "off"){
				$output = new RevSliderOutput();
				$option1Name = "Include RevSlider libraries globally (all pages/posts)";
				$option2Name = "Pages to include RevSlider libraries";
				$output->putErrorMessage(__("If you want to use the PHP function \"putRevSlider\" in your code please make sure to check \" ",REVSLIDER_TEXTDOMAIN).$option1Name.__(" \" in the backend's \"General Settings\" (top right panel).

 Or add the current page to the \"",REVSLIDER_TEXTDOMAIN).$option2Name.__("\" option box."));
				return(false);
			}

			RevSliderOutput::putSlider($data,$putIn);
		}

		require_once $currentFolder."/revslider_front.php";
		$productFront = new RevSliderFront($currentFile);
	}

}catch(Exception $e){
	$message = $e->getMessage();
	$trace = $e->getTraceAsString();
	echo _e("Revolution Slider Error:",REVSLIDER_TEXTDOMAIN)."".$message."";
}


text:
title: 'Poeh Cultural Center'
date: 2012-07-05T12:33:00.000-07:00
draft: false
slug: poeh-cultural-center
tags: [Best of New Mexico]
---

![](/images/blog/legacy/P1140737+%28Large%29.JPG)

![](/images/blog/legacy/P1140742+%28Large%29.JPG)

![](/images/blog/legacy/P1140744+%28Large%29.JPG)

![](/images/blog/legacy/P1140755+%28Large%29.JPG)

![](/images/blog/legacy/P1140763+%28Large%29.JPG)

[Poeh Cultural Center](http://poehcenter.com/center/poeh-cultural-center/facilities.html) (between Santa Fe and espanola)
I ♥ this collection of buildings because it represents everything that is right about using history to define a modern place. The complex uses ancient forms of materials and methods, but in entirely modern ways. It is awesome!!!

redpajama_set_name: RedPajamaGithub


text:
# Redis源码阅读:set是怎么做交并集运算的?

今天我们来看看 Redis 中的set是如何存储数据,然后如何做交集、并集、差集运算的,所以我们一共会探索 `SADD`, `SISMEMBER`,
`SINTER`, `SUNION`, `SDIFF` 这五个命令的实现。

首先我们从 `SADD` 开始:

```c
    {"sadd",saddCommand,-3,
     "write use-memory fast @set",
     0,NULL,1,1,1,0,0,0},

void saddCommand(client *c) {
    robj *set;
    int j, added = 0;

    set = lookupKeyWrite(c->db,c->argv[1]);
    if (checkType(c,set,OBJ_SET)) return;

    if (set == NULL) {
        set = setTypeCreate(c->argv[2]->ptr);
        dbAdd(c->db,c->argv[1],set);
    }

    for (j = 2; j < c->argc; j++) {
        if (setTypeAdd(set,c->argv[j]->ptr)) added++;
    }
    if (added) {
        signalModifiedKey(c,c->db,c->argv[1]);
        notifyKeyspaceEvent(NOTIFY_SET,"sadd",c->argv[1],c->db->id);
    }
    server.dirty += added;
    addReplyLongLong(c,added);
}

/* Factory method to return a set that *can* hold "value". When the object has
 * an integer-encodable value, an intset will be returned. Otherwise a regular
 * hash table. */
robj *setTypeCreate(sds value) {
    if (isSdsRepresentableAsLongLong(value,NULL) == C_OK)
        return createIntsetObject();
    return createSetObject();
}

/* Add the specified value into a set.
 *
 * If the value was already member of the set, nothing is done and 0 is
 * returned, otherwise the new element is added and 1 is returned. */
int setTypeAdd(robj *subject, sds value) {
    // ...
}
```

首先我们看到 `setTypeCreate`,这是一个共长方法,如果 `isSdsRepresentableAsLongLong` 返回是 `C_OK`,就会调用
`createIntsetObject` 并且返回,否则返回 `createSetObject`。我们分别看看这两个方法:

```c
robj *createIntsetObject(void) {
    intset *is = intsetNew();
    robj *o = createObject(OBJ_SET,is);
    o->encoding = OBJ_ENCODING_INTSET;
    return o;
}

robj *createSetObject(void) {
    dict *d = dictCreate(&setDictType,NULL);
    robj *o = createObject(OBJ_SET,d);
    o->encoding = OBJ_ENCODING_HT;
    return o;
}
```

可以看到,如果要存储的值,如果可以存成 long long,那么就会用 `intset` 来存,否则就用 `dict`。我们先来看后者,
也就是如果放在 `dict` 里,是怎么实现的:

```c
/* Add the specified value into a set.
 *
 * If the value was already member of the set, nothing is done and 0 is
 * returned, otherwise the new element is added and 1 is returned. */
int setTypeAdd(robj *subject, sds value) {
    long long llval;
    if (subject->encoding == OBJ_ENCODING_HT) {
        dict *ht = subject->ptr;
        dictEntry *de = dictAddRaw(ht,value,NULL);
        if (de) {
            dictSetKey(ht,de,sdsdup(value));
            dictSetVal(ht,de,NULL);
            return 1;
        }
```

可以看到,其实就是用一个 `dict` 来存储数据,key为我们要存的数据,value为NULL。接下来我们来看看如果是 `intset` 将会怎么处理:

```c
/* Add the specified value into a set.
 *
 * If the value was already member of the set, nothing is done and 0 is
 * returned, otherwise the new element is added and 1 is returned. */
int setTypeAdd(robj *subject, sds value) {
    // ...
    } else if (subject->encoding == OBJ_ENCODING_INTSET) {
        if (isSdsRepresentableAsLongLong(value,&llval) == C_OK) { // 如果值可以表示成long long
            uint8_t success = 0;
            subject->ptr = intsetAdd(subject->ptr,llval,&success); // 添加
            if (success) {
                /* Convert to regular set when the intset contains
                 * too many entries. */
                if (intsetLen(subject->ptr) > server.set_max_intset_entries)
                // 如果保存的数据量超过 server.set_max_intset_entries,也转换成 dict 来保存
                    setTypeConvert(subject,OBJ_ENCODING_HT);
                return 1;
            }
        } else {
            /* Failed to get integer from object, convert to regular set. */
            setTypeConvert(subject,OBJ_ENCODING_HT);

            /* The set *was* an intset and this value is not integer
             * encodable, so dictAdd should always work. */
            serverAssert(dictAdd(subject->ptr,sdsdup(value),NULL) == DICT_OK);
            return 1;
        }
```

到底为止,我们了解到了,Redis保存set有两种形式,当数据都是整数,而且保存的数据量小于一定量时,用的是 `intset`,否则
用 `dict` 来保存。接下来我们来看看 `intset` 是怎么实现的。

## intset 实现

我们从 `setTypeCreate` 开始入手:

```c
robj *setTypeCreate(sds value) {
    if (isSdsRepresentableAsLongLong(value,NULL) == C_OK)
        return createIntsetObject();
    return createSetObject();
}

robj *createIntsetObject(void) {
    intset *is = intsetNew();
    robj *o = createObject(OBJ_SET,is);
    o->encoding = OBJ_ENCODING_INTSET;
    return o;
}

/* Create an empty intset. */
intset *intsetNew(void) {
    intset *is = zmalloc(sizeof(intset));
    is->encoding = intrev32ifbe(INTSET_ENC_INT16);
    is->length = 0;
    return is;
}

typedef struct intset {
    uint32_t encoding;
    uint32_t length;
    int8_t contents[];
} intset;
```

看样子,该不会又是 `ziplist` 那一套吧?

```c
/* Insert an integer in the intset */
intset *intsetAdd(intset *is, int64_t value, uint8_t *success) {
    uint8_t valenc = _intsetValueEncoding(value);
    uint32_t pos;
    if (success) *success = 1;

    /* Upgrade encoding if necessary. If we need to upgrade, we know that
     * this value should be either appended (if > 0) or prepended (if < 0),
     * because it lies outside the range of existing values. */
    if (valenc > intrev32ifbe(is->encoding)) {
        /* This always succeeds, so we don't need to curry *success. */
        return intsetUpgradeAndAdd(is,value);
    } else {
        /* Abort if the value is already present in the set.
         * This call will populate "pos" with the right position to insert
         * the value when it cannot be found. */
        if (intsetSearch(is,value,&pos)) {
            if (success) *success = 0;
            return is;
        }

        is = intsetResize(is,intrev32ifbe(is->length)+1);
        if (pos < intrev32ifbe(is->length)) intsetMoveTail(is,pos,pos+1);
    }

    _intsetSet(is,pos,value);
    is->length = intrev32ifbe(intrev32ifbe(is->length)+1);
    return is;
}

/* Note that these encodings are ordered, so:
 * INTSET_ENC_INT16 < INTSET_ENC_INT32 < INTSET_ENC_INT64. */
#define INTSET_ENC_INT16 (sizeof(int16_t))
#define INTSET_ENC_INT32 (sizeof(int32_t))
#define INTSET_ENC_INT64 (sizeof(int64_t))

/* Return the required encoding for the provided value. */
static uint8_t _intsetValueEncoding(int64_t v) {
    if (v < INT32_MIN || v > INT32_MAX)
        return INTSET_ENC_INT64;
    else if (v < INT16_MIN || v > INT16_MAX)
        return INTSET_ENC_INT32;
    else
        return INTSET_ENC_INT16;
}

/* Search for the position of "value". Return 1 when the value was found and
 * sets "pos" to the position of the value within the intset. Return 0 when
 * the value is not present in the intset and sets "pos" to the position
 * where "value" can be inserted. */
static uint8_t intsetSearch(intset *is, int64_t value, uint32_t *pos) {
    int min = 0, max = intrev32ifbe(is->length)-1, mid = -1;
    int64_t cur = -1;

    /* The value can never be found when the set is empty */
    if (intrev32ifbe(is->length) == 0) {
        if (pos) *pos = 0;
        return 0;
    } else {
        /* Check for the case where we know we cannot find the value,
         * but do know the insert position. */
        if (value > _intsetGet(is,max)) {
            if (pos) *pos = intrev32ifbe(is->length);
            return 0;
        } else if (value < _intsetGet(is,0)) {
            if (pos) *pos = 0;
            return 0;
        }
    }

    // 二分查找
    while(max >= min) {
        mid = ((unsigned int)min + (unsigned int)max) >> 1;
        cur = _intsetGet(is,mid);
        if (value > cur) {
            min = mid+1;
        } else if (value < cur) {
            max = mid-1;
        } else {
            break;
        }
    }

    if (value == cur) {
        if (pos) *pos = mid;
        return 1;
    } else {
        if (pos) *pos = min;
        return 0;
    }
}

/* Resize the intset */
static intset *intsetResize(intset *is, uint32_t len) {
    uint32_t size = len*intrev32ifbe(is->encoding);
    is = zrealloc(is,sizeof(intset)+size);
    return is;
}
```

从上面可以看出来,intset又是 `ziplist` 那一套,`is->encoding` 记录当前保存的数据,都是什么类型,比如可以选择的
类型为 `int16_t`, `int32_t`,`int64_t`,然后在 `is->content` 处保存数据,但是是以有序的形式保存。

所以我们现在了解到,`intset` 有两个特点:

- `intset` 和 `ziplist` 一样,也是以连续内存块的形式保存数据,然后保存了数据的编码(其实也就是大小)
- `intset` 的数据是有序保存的,因此查找时可以用二分查找,插入时也可以二分查找出要插入的位置

## 集合运算(交集并集差集)是怎么实现的

最后我们来看一眼,交集并集差集分别是怎么实现的。

交集:

```c
    {"sinter",sinterCommand,-2,
     "read-only to-sort @set",
     0,NULL,1,-1,1,0,0,0},

void sinterCommand(client *c) {
    sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
}

void sinterGenericCommand(client *c, robj **setkeys,
                          unsigned long setnum, robj *dstkey) {
                          // ...
    /* Sort sets from the smallest to largest, this will improve our
     * algorithm's performance */
    qsort(sets,setnum,sizeof(robj*),qsortCompareSetsByCardinality);
                          // ...
    /* Iterate all the elements of the first (smallest) set, and test
     * the element against all the other sets, if at least one set does
     * not include the element it is discarded */
    si = setTypeInitIterator(sets[0]);
    while((encoding = setTypeNext(si,&elesds,&intobj)) != -1) {
        for (j = 1; j < setnum; j++) {
            if (sets[j] == sets[0]) continue;
            if (encoding == OBJ_ENCODING_INTSET) {
                /* intset with intset is simple... and fast */
                if (sets[j]->encoding == OBJ_ENCODING_INTSET &&
                    !intsetFind((intset*)sets[j]->ptr,intobj))
                {
                    break;
                /* in order to compare an integer with an object we
                 * have to use the generic function, creating an object
                 * for this */
                } else if (sets[j]->encoding == OBJ_ENCODING_HT) {
                    elesds = sdsfromlonglong(intobj);
                    if (!setTypeIsMember(sets[j],elesds)) {
                        sdsfree(elesds);
                        break;
                    }
                    sdsfree(elesds);
                }
            } else if (encoding == OBJ_ENCODING_HT) {
                if (!setTypeIsMember(sets[j],elesds)) {
                    break;
                }
            }
        }
    }
    // ...
}
```

可以看到,做交集的逻辑,其实就是先根据集合大小把集合排序。然后以最小的集合为基准,遍历每一个元素,然后去遍历其它set,
只要有一个不是子元素,就可以跳过这个元素了。

并集:

```c
    {"sunion",sunionCommand,-2,
     "read-only to-sort @set",
     0,NULL,1,-1,1,0,0,0},

void sunionCommand(client *c) {
    sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,SET_OP_UNION);
}

void sunionDiffGenericCommand(client *c, robj **setkeys, int setnum,
                              robj *dstkey, int op) {
                              // ...
    /* We need a temp set object to store our union. If the dstkey
     * is not NULL (that is, we are inside an SUNIONSTORE operation) then
     * this set object will be the resulting object to set into the target key*/
    dstset = createIntsetObject();

    if (op == SET_OP_UNION) {
        /* Union is trivial, just add every element of every set to the
         * temporary set. */
        for (j = 0; j < setnum; j++) {
            if (!sets[j]) continue; /* non existing keys are like empty sets */

            si = setTypeInitIterator(sets[j]);
            while((ele = setTypeNextObject(si)) != NULL) {
                if (setTypeAdd(dstset,ele)) cardinality++;
                sdsfree(ele);
            }
            setTypeReleaseIterator(si);
        }
    // ...
}
```

并集很简单,遍历所有集合,把元素全都加进去即可。

差集:

```c
    {"sdiff",sdiffCommand,-2,
     "read-only to-sort @set",
     0,NULL,1,-1,1,0,0,0},

void sdiffCommand(client *c) {
    sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,SET_OP_DIFF);
}

void sunionDiffGenericCommand(client *c, robj **setkeys, int setnum,
                              robj *dstkey, int op) {
                              // ...

    } else if (op == SET_OP_DIFF && sets[0] && diff_algo == 1) {
        /* DIFF Algorithm 1:
         *
         * We perform the diff by iterating all the elements of the first set,
         * and only adding it to the target set if the element does not exist
         * into all the other sets.
         *
         * This way we perform at max N*M operations, where N is the size of
         * the first set, and M the number of sets. */
        si = setTypeInitIterator(sets[0]);
        while((ele = setTypeNextObject(si)) != NULL) {
            for (j = 1; j < setnum; j++) {
                if (!sets[j]) continue; /* no key is an empty set. */
                if (sets[j] == sets[0]) break; /* same set! */
                if (setTypeIsMember(sets[j],ele)) break;
            }
            if (j == setnum) {
                /* There is no other set with this element. Add it. */
                setTypeAdd(dstset,ele);
                cardinality++;
            }
            sdsfree(ele);
        }
        setTypeReleaseIterator(si);
    } else if (op == SET_OP_DIFF && sets[0] && diff_algo == 2) {
        /* DIFF Algorithm 2:
         *
         * Add all the elements of the first set to the auxiliary set.
         * Then remove all the elements of all the next sets from it.
         *
         * This is O(N) where N is the sum of all the elements in every
         * set. */
        for (j = 0; j < setnum; j++) {
            if (!sets[j]) continue; /* non existing keys are like empty sets */

            si = setTypeInitIterator(sets[j]);
            while((ele = setTypeNextObject(si)) != NULL) {
                if (j == 0) {
                    if (setTypeAdd(dstset,ele)) cardinality++;
                } else {
                    if (setTypeRemove(dstset,ele)) cardinality--;
                }
                sdsfree(ele);
            }
            setTypeReleaseIterator(si);

            /* Exit if result set is empty as any additional removal
             * of elements will have no effect. */
            if (cardinality == 0) break;
        }
    // ...
}
```

做差集有两种方式,一种是遍历第一个集合,如果元素不在后面所有集合内,就加入;第二种是把第一个集合所有元素加到结果集合里,
然后再把所有在后面的集合里的元素,从这个结果集合里移除。

## 总结

这篇文章里,我们看了一下Redis是如何实现set这个数据结构的,Redis会在内容为整数并且数量足够小时,使用一种类似 `ziplist`
的方式,也就是 `intset` 来保存数据,其它情况,则会使用一个 `dict` 来保存数据,此外我们分别看了一下三种常见的集合运算
是怎么实现的。


text:
class UserAgent
  module Browsers
    # Podverse/F-Droid Android Mobile App/
    # Podverse/Android Mobile App/Mozilla/5.0 (Linux; Android 10; LYA-L29 Build/HUAWEILYA-L29; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.91 Mobile Safari/537.36
    # Podverse/7 CFNetwork/902.2 Darwin/17.7.0
    # Podverse/iOS Mobile App/Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89
    # Podverse/iOS Mobile App/Mozilla/5.0 (iPad; CPU OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
    # Podverse/Feed Parser
    class Podverse < Base
      PODVERSE      = 'Podverse'
      VERSION_REGEX = /[\d\.]+/.freeze

      ##
      # @param agent [Array]
      #     Array of useragent product
      # @return [Boolean]
      #     True if the useragent matches this browser
      def self.extend?(agent)
        agent.detect { |useragent| useragent.product == PODVERSE }
      end

      ##
      # @return [String]
      #     The browser name
      def browser
        PODVERSE
      end

      ##
      # @return [true] This is a mobile app
      def mobile?
        true
      end

      ##
      # @return [String] The OS of the app
      def os
        app = detect_product(DARWIN)
        return [IOS, OperatingSystems::Darwin::IOS[app.version.to_s]].compact.join(' ') if app

        app = app_with_comments
        return OperatingSystems.normalize_os(app.comment[1]) if app && app.comment[1]

        case platform
        when ANDROID then ANDROID
        when IOS, IPAD, IPHONE, IPOD_TOUCH then IOS
        end
      end

      ##
      # @return [String] The platform of the app
      def platform
        ua = to_s
        case ua
        when ANDROID_REGEX
          ANDROID
        when IPAD_REGEX
          IPAD
        when IPOD_REGEX
          IPOD_TOUCH
        when IPHONE_REGEX
          IPHONE
        when IOS_REGEX, DARWIN_REGEX
          IOS
        end
      end

      ##
      # @return [String] The version of the app
      def version
        application.version if VERSION_REGEX.match?(application.version.to_s)
      end
    end
  end
end


text: Just another lightweight render.


text:
<?php

namespace Documents\Functional\Ticket\MODM160;

use Cloudtek\DynamoDM\Mapping\Annotation as ODM;

/** @ODM\Document(table="embedded_test") */
class EmbedOneLevel0
{
    /**
     * @ODM\Attribute(type="string")
     * @ODM\HashKey
     * @ODM\GeneratedValue(strategy="uuid")
     */
    public $id;
    /** @ODM\Attribute(type="string") */
    public $name;
    /** @ODM\EmbedOne(targetDocument=EmbedOneLevel1::class) */
    public $level1;
}


text:
package se.jiderhamn.tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import se.jiderhamn.JUnitClassloaderRunner;

/**
 * @author Mattias Jiderhamn
 */
@RunWith(JUnitClassloaderRunner.class)
public class CustomThreadLocalCustomValueTest {

  private static final ThreadLocal<Value> customThreadLocal = new ThreadLocal<Value>() {
    /** Override method to create an anonymous subclass loaded by our classloader */
    @Override
    protected Value initialValue() {
      return new Value();
    }
  };

  @Test
  public void setCustomThreadLocalValue() {
    customThreadLocal.set(new Value());
  }

  /** Custom value class, that will prevent garbage collection */
  private static class Value {

  }

  // TODO: Preventor
}


text:
from OpenPNM.Phases import GenericPhase
from OpenPNM.Phases import models as fm

class Mercury(GenericPhase):
    r"""
    Creates Phase object with a default name 'Hg' and preset values for
    mercury.

    Parameters
    ----------
    network : OpenPNM Network object
        The network to which this phase object will be attached.

    Notes
    -----
    This explicit association is necessary so the Phase object can initialize
    data arrays of the correct size to store network data.
    The initial properties are all at std conditions of T = 298 K and P = 1 atm.

    References
    ----------
    [1] Thermophysical Properties of Materials for Nuclear Engineering: IAEA,
        Vienna, 2008. ISBN 978-92-0-106508-7:

    Examples
    --------
    >>> import OpenPNM
    >>> pn = OpenPNM.Network.TestNet()
    >>> hg = OpenPNM.Phases.Mercury(network=pn)

    """
    def __init__(self, name=None, **kwargs):
        super().__init__(name=name, **kwargs)
        self._generate()

    def _generate(self):
        self['pore.molecular_weight'] = 0.2006                         # kg/mol
        self['pore.critical_pressure'] = 1.662E8                       # Pa
        self['pore.critical_temperature'] = 1733                       # K
        self['pore.critical_volume'] = 0.000189                        # kg/m3
        self['pore.contact_angle'] = 140                               # Degree
        self.models.add(propname='pore.vapor_pressure',                 # Pa
                        model=fm.vapor_pressure.antoine,
                        A=9.85767, B=3007.129, C=-10.001)
        self.models.add(propname='pore.density',                        # kg/m3
                        model=fm.misc.linear,
                        poreprop='pore.temperature',
                        b=14280.9, m=-2.47004)
        self.models.add(propname='pore.molar_density',
                        model=fm.molar_density.standard)                # mol/m3
        self.models.add(propname='pore.surface_tension',                # N/m
                        model=fm.misc.linear,
                        poreprop='pore.temperature',
                        b=0.56254, m=-0.00028)
        self.models.add(propname='pore.thermal_conductivity',           # W/m.K
                        model=fm.misc.polynomial,
                        poreprop='pore.temperature',
                        a=[3.98691, 0.0170967, -0.0000063862])
        self.models.add(propname='pore.viscosity',                      # kg/m.s
                        model=fm.misc.polynomial,
                        poreprop='pore.temperature',
                        a=[0.00355837, -0.0000100131, 1.23684E-08, -5.16836E-12])


text:
using namespace fs;

TEST_SUITE(is_empty_test_suite)

TEST_CASE(signature_test)
{
    const path p; ((void)p);
    std::error_code ec; ((void)ec);
    ASSERT_NOT_NOEXCEPT(is_empty(p, ec));
    ASSERT_NOT_NOEXCEPT(is_empty(p));
}

TEST_CASE(test_exist_not_found)
{
    const path p = StaticEnv::DNE;
    std::error_code ec;
    TEST_CHECK(is_empty(p, ec) == false);
    TEST_CHECK(ec);
    TEST_CHECK_THROW(filesystem_error, is_empty(p));
}

TEST_CASE(test_is_empty_directory)
{
    TEST_CHECK(!is_empty(StaticEnv::Dir));
    TEST_CHECK(!is_empty(StaticEnv::SymlinkToDir));
}

TEST_CASE(test_is_empty_directory_dynamic)
{
    scoped_test_env env;
    TEST_CHECK(is_empty(env.test_root));
    env.create_file("foo", 42);
    TEST_CHECK(!is_empty(env.test_root));
}

TEST_CASE(test_is_empty_file)
{
    TEST_CHECK(is_empty(StaticEnv::EmptyFile));
    TEST_CHECK(!is_empty(StaticEnv::NonEmptyFile));
}

TEST_CASE(test_is_empty_fails)
{
    scoped_test_env env;
    const path dir = env.create_dir("dir");
    const path dir2 = env.create_dir("dir/dir2");
    permissions(dir, perms::none);

    std::error_code ec;
    TEST_CHECK(is_empty(dir2, ec) == false);
    TEST_CHECK(ec);

    TEST_CHECK_THROW(filesystem_error, is_empty(dir2));
}

TEST_CASE(test_directory_access_denied)
{
    scoped_test_env env;
    const path dir = env.create_dir("dir");
    const path file1 = env.create_file("dir/file", 42);
    permissions(dir, perms::none);

    std::error_code ec = GetTestEC();
    TEST_CHECK(is_empty(dir, ec) == false);
    TEST_CHECK(ec);
    TEST_CHECK(ec != GetTestEC());

    TEST_CHECK_THROW(filesystem_error, is_empty(dir));
}

TEST_CASE(test_fifo_fails)
{
    scoped_test_env env;
    const path fifo = env.create_fifo("fifo");

    std::error_code ec = GetTestEC();
    TEST_CHECK(is_empty(fifo, ec) == false);
    TEST_CHECK(ec);
    TEST_CHECK(ec != GetTestEC());

    TEST_CHECK_THROW(filesystem_error, is_empty(fifo));
}

TEST_SUITE_END()


text:
#include "AquariusCore/Util/TypeReDef/TypeReDef.hpp"
#include "AquariusCore/Util/TinyUtil/CommonUtil.h"
#include "AquariusCore/Util/TinyUtil/TimeUtil.h"
#include <stdarg.h>
#include <sys/timeb.h>
#include <time.h>
#include "boost/date_time.hpp"
#include "AquariusCore/Logger/AquariusLogger.h"
#include "AquariusCore/Logger/LogVisitor/FileLogVisitor.h"
#include "AquariusCore/Logger/LogVisitor/ScreenLogVisitor.h"
#include "AquariusCore/Logger/LogVisitor/ILogVisitor.hpp"

CAquariusLogger::CAquariusLogger(void)
    :m_nFullLogLevelMask(0)
{
}

CAquariusLogger::~CAquariusLogger(void)
{
    // Free every log visitor
    for each (ILogVisitor* pValue in m_vLogVisitor)
    {
        delete pValue;
        pValue = nullptr;
    }
    m_vLogVisitor.clear();
}

void CAquariusLogger::GetLogTime(std::string& strTimePoint)
{
    // Get time buffer
#ifdef LINUX
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    time_t nUTCTime = tv.tv_sec;
    int nMS = tv.tv_usec / 1000;
#else
    struct _timeb stTimeBuffer;
    _ftime_s( &stTimeBuffer );
    time_t nUTCTime = stTimeBuffer.time;
    int nMS = stTimeBuffer.millitm;
#endif
    // Convert to local time
    struct tm stTM = CTimeUtil::UTCTimeToLocalTime(nUTCTime);
    // Format to string
    const char* TIME_FORMAT = "%04d-%02d-%02d %02d:%02d:%02d.%d";
    char buff[64] = { 0 };
    a_sprintf(buff, TIME_FORMAT,
        stTM.tm_year + 1900,
        stTM.tm_mon + 1,
        stTM.tm_mday,
        stTM.tm_hour,
        stTM.tm_min,
        stTM.tm_sec,
        nMS);
    strTimePoint.append(buff);
}

void CAquariusLogger::Logger( ELogLevel nLevel, const char* pszFunctionName, const char* pszMsgFormat, ... )
{
    // 1. Check log level
    std::vector<ILogVisitor*>& vLogVisitor = GetSingleton().m_vLogVisitor;
    if (0 == ((AUINT32)nLevel & GetSingleton().m_nFullLogLevelMask) && 0 != vLogVisitor.size())
    {
        return;
    }
    // 2. Build a log msg
    LogMsg stLogMsg;
    stLogMsg.nLogLevel = nLevel;
    GetLogTime(stLogMsg.strTimePoint);
    stLogMsg.nThreadId = CCommonUtil::GetThisThreadId();
    stLogMsg.BuildLogHeader(pszFunctionName);
    // 3. parse var parameter
    va_list vaList;
    va_start(vaList, pszMsgFormat);
#ifdef WIN32
    vsprintf_s(stLogMsg.buffLogContent, pszMsgFormat, vaList);
#else
    vsprintf(stLogMsg.buffLogContent, pszMsgFormat, vaList);
#endif
    va_end(vaList);
    // 4. Get log visitor list and loop every visitor to record log
    for each (ILogVisitor* pLogVisitor in vLogVisitor)
    {
        if (nullptr == pLogVisitor)
        {
            JUNIOR_LOG("nullptr == pLogVisitor!");
            continue;
        }
        pLogVisitor->RecordLog(stLogMsg);
    }
    if (0 == vLogVisitor.size())
    {
        printf("[UnInitLog]%s%s\n", stLogMsg.buffLogHeader, stLogMsg.buffLogContent);
    }
}

bool CAquariusLogger::Initialize(const char* pszConfigFilePath, const std::string& strAppName)
{
    if (!CLogConfig::GetSingleton().LoadConfigFile(pszConfigFilePath))
    {
        JUNIOR_LOG("CLogConfig::LoadConfigFile failed!");
        return false;
    }
    CLogConfig::GetSingleton().SetAppName(strAppName);
    bool bResult = true;
    // Get config list
    const std::vector<const LogVisitorConfigBase*>& vLogVisitorConfig = CLogConfig::GetSingleton().GetLogVisitorConfigList();
    for each (const LogVisitorConfigBase* pValue in vLogVisitorConfig)
    {
        // Add log visitor by config
        if (!GetSingleton().AddLogVisitor(pValue))
        {
            JUNIOR_LOG("AddLogVisitor Failed");
            bResult = false;
            break;
        }
    }
    if (bResult)
    {
        CAquariusLogger::Logger(LL_DEBUG, "===LoggerInitialized===");
    }
    return bResult;
}

bool CAquariusLogger::Initialize( const std::string& strAppName )
{
    return Initialize(nullptr, strAppName);
}

ILogVisitor* CAquariusLogger::CreateLogVisitor(const std::string& strLogVisitorName) const
{
    // Create log visitor by name
    ILogVisitor* pLogVisitor = nullptr;
    if (0 == strLogVisitorName.compare(LOG_VISITOR_NAME_SCREEN))
    {
        pLogVisitor = new CScreenLogVisitor();
    }
    else if (0 == strLogVisitorName.compare(LOG_VISITOR_NAME_FILE))
    {
        pLogVisitor = new CFileLogVisitor();
    }
    else
    {
        JUNIOR_LOG("Invalid visitor name");
    }
    return pLogVisitor;
}

bool CAquariusLogger::AddLogVisitor(const LogVisitorConfigBase* pLogVisitorConfig)
{
    // 1. Check config content
    if (nullptr == pLogVisitorConfig)
    {
        JUNIOR_LOG("nullptr == pLogVisitorConfig");
        return false;
    }
    // 2. Create visitor by class type
    ILogVisitor* pLogVisitor = CreateLogVisitor(pLogVisitorConfig->strLogVisitorName);
    if (nullptr == pLogVisitor)
    {
        JUNIOR_LOG("nullptr == pLogVisitor");
        return false;
    }
    // 3. Init log visitor
    if (!pLogVisitor->InitializeLogVisitor(pLogVisitorConfig))
    {
        JUNIOR_LOG("LogVisitor->Initialize failed");
        delete pLogVisitor;
        pLogVisitor = nullptr;
        return false;
    }
    m_vLogVisitor.push_back(pLogVisitor);
    m_nFullLogLevelMask |= pLogVisitorConfig->nLogLevelMask;
    return true;
}


text:
namespace {

// Test that if we have an existing password in the Keychain and we are
// authorized by the user to read it then we get it back correctly.
TEST(EncryptorPasswordTest, FindPasswordSuccess) {
  MockKeychain keychain(0);
  keychain.set_find_generic_result(noErr);
  EncryptorPassword password(keychain);
  EXPECT_FALSE(password.GetEncryptorPassword().empty());
  EXPECT_FALSE(keychain.called_add_generic());
  EXPECT_EQ(0, keychain.password_data_count());
}

// Test that if we do not have an existing password in the Keychain then it
// gets added successfully and returned.
TEST(EncryptorPasswordTest, FindPasswordNotFound) {
  MockKeychain keychain(0);
  keychain.set_find_generic_result(errSecItemNotFound);
  EncryptorPassword password(keychain);
  EXPECT_FALSE(password.GetEncryptorPassword().empty());
  EXPECT_TRUE(keychain.called_add_generic());
  EXPECT_EQ(0, keychain.password_data_count());
}

// Test that if get denied access by the user then we return an empty password.
// And we should not try to add one.
TEST(EncryptorPasswordTest, FindPasswordNotAuthorized) {
  MockKeychain keychain(0);
  keychain.set_find_generic_result(errSecAuthFailed);
  EncryptorPassword password(keychain);
  EXPECT_TRUE(password.GetEncryptorPassword().empty());
  EXPECT_FALSE(keychain.called_add_generic());
  EXPECT_EQ(0, keychain.password_data_count());
}

// Test that if some random other error happens then we return an empty
// password, and we should not try to add one.
TEST(EncryptorPasswordTest, FindPasswordOtherError) {
  MockKeychain keychain(0);
  keychain.set_find_generic_result(errSecNotAvailable);
  EncryptorPassword password(keychain);
  EXPECT_TRUE(password.GetEncryptorPassword().empty());
  EXPECT_FALSE(keychain.called_add_generic());
  EXPECT_EQ(0, keychain.password_data_count());
}

// Test that subsequent additions to the keychain give different passwords.
TEST(EncryptorPasswordTest, PasswordsDiffer) {
  MockKeychain keychain1(0);
  keychain1.set_find_generic_result(errSecItemNotFound);
  EncryptorPassword encryptor_password1(keychain1);
  std::string password1 = encryptor_password1.GetEncryptorPassword();
  EXPECT_FALSE(password1.empty());
  EXPECT_TRUE(keychain1.called_add_generic());
  EXPECT_EQ(0, keychain1.password_data_count());

  MockKeychain keychain2(0);
  keychain2.set_find_generic_result(errSecItemNotFound);
  EncryptorPassword encryptor_password2(keychain2);
  std::string password2 = encryptor_password2.GetEncryptorPassword();
  EXPECT_FALSE(password2.empty());
  EXPECT_TRUE(keychain2.called_add_generic());
  EXPECT_EQ(0, keychain2.password_data_count());

  // And finally check that the passwords are different.
  EXPECT_NE(password1, password2);
}

}  // namespace


text:
(async function(testRunner) {
  testRunner.log('Tests basic functionality of Tatget.autoAttachRelated.');
  const bp = testRunner.browserP();

  const createChildFrame = function(url) {
    return new Promise(resolve => {
      const frame = document.createElement(`iframe`);
      frame.src = url;
      frame.addEventListener('load', resolve);
      document.body.appendChild(frame);
    });
  }

  async function expectTargetsDetached(count) {
    for (let i = 0; i < count; ++i)
      await bp.Target.onceDetachedFromTarget();
    testRunner.log(`Detached from ${count} targets`);
  }

  const page1 = await testRunner.createPage();
  const page2 = await testRunner.createPage();
  const page1_session = await page1.createSession();
  const page2_session = await page2.createSession();

  bp.Target.onAttachedToTarget(event => {
    const params = event.params;
    testRunner.log(`Attached to ${params.targetInfo.type} target: ${params.targetInfo.url} (waiting: ${params.waitingForDebugger})`);
  });

  // page1 will auto-attach, but page2 will not.
  await bp.Target.autoAttachRelated({targetId: page1.targetId(), waitForDebuggerOnStart: false});

  page1_session.evaluate(`(${createChildFrame})('http://devtools.oopif.test:8080/inspector-protocol/resources/iframe.html')`);
  const frame1_attached = (await bp.Target.onceAttachedToTarget()).params;
  const frame1SessionId = frame1_attached.sessionId;
  const frame1TargetId = frame1_attached.targetInfo.targetId;
  const frame1_session = new TestRunner.Session(testRunner, frame1SessionId);

  await page2_session.evaluateAsync(`(${createChildFrame})('https://devtools.oopif.test:8443/inspector-protocol/resources/iframe.html')`);

  // This one should auto-attach and wait.
  await bp.Target.autoAttachRelated({targetId: frame1TargetId, waitForDebuggerOnStart: true});
  frame1_session.evaluate(`(${createChildFrame})('http://inner-frame.test:8080/inspector-protocol/resources/iframe.html')`);

  const frame11SessionId = (await bp.Target.onceAttachedToTarget()).params.sessionId;
  const frame11_dp = (new TestRunner.Session(testRunner, frame11SessionId)).protocol;
  await frame11_dp.Runtime.runIfWaitingForDebugger();

  // Change waitForDebuggerOnStart for the tartget we already observe...
  await bp.Target.autoAttachRelated({targetId: page1.targetId(), waitForDebuggerOnStart: true});
  // and assure it has the effect.
  page1_session.evaluate(`(${createChildFrame})('http://devtools.oopif.test:8080/inspector-protocol/resources/iframe.html?frame3')`);
  const frame3SessionId = (await bp.Target.onceAttachedToTarget()).params.sessionId;
  const frame3_dp = (new TestRunner.Session(testRunner, frame3SessionId)).protocol;
  frame3_dp.Runtime.runIfWaitingForDebugger();

  page1_session.evaluate(`document.body.textContent='';`);
  await expectTargetsDetached(3);

  testRunner.log(`Disalbing auto-attach`);
  // Disable auto-attach altogether.
  bp.Target.setAutoAttach({autoAttach: false, waitForDebuggerOnStart: false, flatten: true});
  await page1_session.evaluate(`(${createChildFrame})('http://devtools.oopif.test:8080/inspector-protocol/resources/iframe.html')`);
  testRunner.log(`Re-enabling auto-attach for page1`);
  bp.Target.autoAttachRelated({targetId: page1.targetId(), waitForDebuggerOnStart: false});
  await bp.Target.onceAttachedToTarget();
  await bp.Target.onceAttachedToTarget();
  // Now disable auto-attach again and assure the target is detached.
  bp.Target.setAutoAttach({autoAttach: false, waitForDebuggerOnStart: false, flatten: true});
  await expectTargetsDetached(1);

  testRunner.log('DONE');
  testRunner.completeTest();
});


text:
race-timer
==========

Timing system for qualifications in the Highlevel Downhill http://roguerace.com


text:
CREATE TABLE games (
  id SERIAL,
  name TEXT NOT NULL,
  description TEXT NOT NULL,
  submitterid INT NOT NULL,
  partner TEXT NOT NULL,
  thumbnailurl TEXT NOT NULL,
  jamid INT NOT NULL,
  CONSTRAINT "games_PK" PRIMARY KEY (id)
);


text:
In order to generate a new API Key in your Slightline UI navigate to **Administartion** > **Arbor API WEB Services**

### Configuration params
**NOTE**: If using 6.0.2 or lower version, put your API Key in the **Password** field, leave the **User** field empty.


text:
package securityservice.ui.entity;

import iobjects.*;
import iobjects.entity.*;
import iobjects.ui.*;
import iobjects.ui.entity.*;

import securityservice.entity.*;

/**
 * Utilitário para criação de controles para a classe Usuario.
 */
public class UsuarioUI {

  /**
   * Retorna a representação JavaScript de um LookupSearch contendo valores da
   * entidade Usuario.
   * @param facade Fachada.
   * @param param Param cujas propriedades irão gerar o controle de seleção.
   * @param width int Largura do controle de seleção na página ou 0 (zero) para
   *              que ele se ajuste automaticamente ao seu conteiner.
   * @param style String Estilo de formatação do ExternalLookup.
   * @param onChangeScript Código JavaScript para ser executado quando o usuário
   *                       alterar o valor do elemento HTML.
   * @param readOnly True para apenas leitura.
   * @return Retorna a representação JavaScript de um LookupSearch contendo valores da
   * entidade Usuario.
   * @throws Exception Em caso de exceção na tentativa de acesso ao banco de dados.
   */
  static public String lookupSearchForParam(Facade  facade,
                                            Param   param,
                                            int     width,
                                            String  style,
                                            String  onChangeScript,
                                            boolean readOnly) throws Exception {
    // retorna
    return LookupSearch.script(facade,
                               param.getName(),
                               Usuario.CLASS_NAME,
                               new EntityField[]{Usuario.FIELD_NOME},
                               Usuario.FIELD_NOME,
                               "",
                               "(" + Usuario.FIELD_INATIVO.getFieldName() + " = " + Usuario.NAO + ")",
                               Usuario.FIELD_USUARIO_ID,
                               param.getValue(),
                               param.getScriptConstraint(),
                               param.getScriptConstraintErrorMessage(),
                               width,
                               style,
                               onChangeScript,
                               readOnly);
  }

  /**
   * Retorna a representação JavaScript de um LookupSearch contendo valores da
   * entidade Usuario.
   * @param facade Fachada.
   * @param entityLookup EntityLookup cujas propriedades irão gerar o controle de seleção.
   * @param entityInfo EntityInfo contendo os valores do registro que está sendo
   *                   editado/inserido.
   * @param width int Largura do controle de seleção na página ou 0 (zero) para
   *              que ele se ajuste automaticamente ao seu conteiner.
   * @param style String Estilo de formatação do ExternalLookup.
   * @param onChangeScript Código JavaScript para ser executado quando o usuário
   *                       alterar o valor do elemento HTML.
   * @param readOnly True para apenas leitura.
   * @return Retorna a representação JavaScript de um LookupSearch contendo valores da
   * entidade Usuario.
   * @throws Exception Em caso de exceção na tentativa de acesso ao banco de dados.
   */
  static public String lookupSearchForLookup(Facade       facade,
                                             EntityLookup entityLookup,
                                             EntityInfo   entityInfo,
                                             int          width,
                                             String       style,
                                             String       onChangeScript,
                                             boolean      readOnly) throws Exception {
    // obtém Usuario ID
    Integer usuarioId = (Integer)entityInfo.getPropertyValue(entityLookup.getKeyFields()[0].getFieldAlias());
    // retorna
    return LookupSearch.script(facade,
                               entityLookup.getKeyFields()[0].getFieldAlias(),
                               Usuario.CLASS_NAME,
                               new EntityField[]{Usuario.FIELD_NOME},
                               Usuario.FIELD_NOME,
                               "",
                               "(" + Usuario.FIELD_INATIVO.getFieldName() + " = " + Usuario.NAO + ")",
                               Usuario.FIELD_USUARIO_ID,
                               (usuarioId > 0 ? usuarioId + "" : ""),
                               entityLookup.getKeyFields()[0].getScriptConstraint(),
                               entityLookup.getKeyFields()[0].getScriptConstraintErrorMessage(),
                               width,
                               style,
                               onChangeScript,
                               readOnly);
  }

  private UsuarioUI() {
  }

}


text:
module Agcod
  module Error
    class ConfigurationError < RuntimeError

    end
  end
end


text:
Homeventory is home inventory management app, designed for mobile use.  Now you can track the groceries you frequently use and never be stuck at the store trying to remember if you need to buy that dishwasher detergent.

<https://homeventory.herokuapp.com>

**Architecture:**

Homeventory is built on the Ruby on Rails framework, and draws from a PostgreSQL database.  The client side was done manually with jQuery and templated with ERB (Embedded Ruby).  The layout was managed with Bootstrap and Sass was used as a CSS preprocessor.

Inside, the app draws on the Factual Products API for search results and attaching images to product information, and uses OAuth to provide Facebook user authentication.

**Design Work:**

Wireframe: <https://ninjamock.com/s/TV7WD>

**User Stories:**

Everyone has had the experience of forgetting a shopping list on a grocery trip and being forced to try to recall from memory everything you need, inevitably forgetting something (or a few things). Perhaps even worse is returning home from a grocery trip to realize you're out of something essential that somehow slipped past you, and now you have to make a second trip to the grocery store to get it. Homeventory was created to give users a way to keep track of their home inventory that is always accessible so that they can cut down on trips to the grocery store and make sure they never have to go without the items they need.

**Implementation Methodology:**

After an initial session clarifying our user stories and intended app purpose, we made wireframes and got a feel for the user experience. One of the harder steps for us involved structuring our tables - initially we were envisioning more models but ended up consolidating down by using boolean toggling within our main items table. This table structure also continued to evolve throughout the project with numerous added migrations. We also discussed our goals for this project and categorized them based on feasibility and importance to basic function. This helped up focus on the most important tasks, particularly

After this planning stage we distributed the work (two people working front-end, two on back-end), started the basic routes/controllers, and began work on a unified design template. We continually discussed user experience and did our best to keep required clicks for any action to a minimum. We also regularly revisited our master goals list to make sure we weren't taking on any tasks that would affect our overall ability to make a clean functioning app.

After getting to a point that we were all happy with, we started testing and refining. Inconsistencies in styling were removed and all buttons and routes were tested. We repeated this process after deployment and corrected a few small issues.

**Installing locally:**

1. Clone the project or download the zip file.
2. From the command line inside the project directory, run "bundle install".
3. Again on the command line, run "rake db:create".
4. Run "rake db:migrate".
4. To start the server on localhost:3000, run "foreman run rails server".
Now you're up and running Homeventory!


text:
geoambiente
===========

2014 space apps project


text:
<?php

/**
 * @group comment
 * @group slashes
 * @ticket 21767
 */
class Tests_Comment_Slashes extends WP_UnitTestCase {
	function setUp() {
		parent::setUp();
		// we need an admin user to bypass comment flood protection
		$this->author_id = $this->factory->user->create( array( 'role' => 'administrator' ) );
		$this->old_current_user = get_current_user_id();
		wp_set_current_user( $this->author_id );

		// it is important to test with both even and odd numbered slashes as
		// kses does a strip-then-add slashes in some of its function calls
		$this->slash_1 = 'String with 1 slash \\';
		$this->slash_2 = 'String with 2 slashes \\\\';
		$this->slash_3 = 'String with 3 slashes \\\\\\';
		$this->slash_4 = 'String with 4 slashes \\\\\\\\';
		$this->slash_5 = 'String with 5 slashes \\\\\\\\\\';
		$this->slash_6 = 'String with 6 slashes \\\\\\\\\\\\';
		$this->slash_7 = 'String with 7 slashes \\\\\\\\\\\\\\';

		$_SERVER['REMOTE_ADDR'] = null;
	}

	function tearDown() {
		wp_set_current_user( $this->old_current_user );
		parent::tearDown();
	}

	/**
	 * Tests the extended model function that expects slashed data
	 *
	 */
	function test_wp_new_comment() {
		$post_id = $this->factory->post->create();

		// not testing comment_author_email or comment_author_url
		// as slashes are not permitted in that data
		$data = array(
			'comment_post_ID' => $post_id,
			'comment_author' => $this->slash_1,
			'comment_author_url' => '',
			'comment_author_email' => '',
			'comment_type' => '',
			'comment_content' => $this->slash_7,
		);
		$id = wp_new_comment( $data );

		$comment = get_comment($id);

		$this->assertEquals( wp_unslash( $this->slash_1 ), $comment->comment_author );
		$this->assertEquals( wp_unslash( $this->slash_7 ), $comment->comment_content );

		$data = array(
			'comment_post_ID' => $post_id,
			'comment_author' => $this->slash_2,
			'comment_author_url' => '',
			'comment_author_email' => '',
			'comment_type' => '',
			'comment_content' => $this->slash_4,
		);
		$id = wp_new_comment( $data );

		$comment = get_comment($id);

		$this->assertEquals( wp_unslash( $this->slash_2 ), $comment->comment_author );
		$this->assertEquals( wp_unslash( $this->slash_4 ), $comment->comment_content );
	}

	/**
	 * Tests the controller function that expects slashed data
	 *
	 */
	function test_edit_comment() {
		$post_id = $this->factory->post->create();
		$comment_id = $this->factory->comment->create(array(
			'comment_post_ID' => $post_id
		));

		// not testing comment_author_email or comment_author_url
		// as slashes are not permitted in that data
		$_POST = array();
		$_POST['comment_ID'] = $comment_id;
		$_POST['comment_status'] = '';
		$_POST['newcomment_author'] = $this->slash_1;
		$_POST['newcomment_author_url'] = '';
		$_POST['newcomment_author_email'] = '';
		$_POST['content'] = $this->slash_7;
		$_POST = add_magic_quotes( $_POST );

		edit_comment();
		$comment = get_comment( $comment_id );

		$this->assertEquals( $this->slash_1, $comment->comment_author );
		$this->assertEquals( $this->slash_7, $comment->comment_content );

		$_POST = array();
		$_POST['comment_ID'] = $comment_id;
		$_POST['comment_status'] = '';
		$_POST['newcomment_author'] = $this->slash_2;
		$_POST['newcomment_author_url'] = '';
		$_POST['newcomment_author_email'] = '';
		$_POST['content'] = $this->slash_4;
		$_POST = add_magic_quotes( $_POST );

		edit_comment();
		$comment = get_comment( $comment_id );

		$this->assertEquals( $this->slash_2, $comment->comment_author );
		$this->assertEquals( $this->slash_4, $comment->comment_content );
	}

	/**
	 * Tests the model function that expects slashed data
	 *
	 */
	function test_wp_insert_comment() {
		$post_id = $this->factory->post->create();

		$comment_id = wp_insert_comment(array(
			'comment_post_ID' => $post_id,
			'comment_author' => $this->slash_1,
			'comment_content' => $this->slash_7,
		));
		$comment = get_comment( $comment_id );

		$this->assertEquals( wp_unslash( $this->slash_1 ), $comment->comment_author );
		$this->assertEquals( wp_unslash( $this->slash_7 ), $comment->comment_content );

		$comment_id = wp_insert_comment(array(
			'comment_post_ID' => $post_id,
			'comment_author' => $this->slash_2,
			'comment_content' => $this->slash_4,
		));
		$comment = get_comment( $comment_id );

		$this->assertEquals( wp_unslash( $this->slash_2 ), $comment->comment_author );
		$this->assertEquals( wp_unslash( $this->slash_4 ), $comment->comment_content );
	}

	/**
	 * Tests the model function that expects slashed data
	 *
	 */
	function test_wp_update_comment() {
		$post_id = $this->factory->post->create();
		$comment_id = $this->factory->comment->create(array(
			'comment_post_ID' => $post_id
		));

		wp_update_comment(array(
			'comment_ID' => $comment_id,
			'comment_author' => $this->slash_1,
			'comment_content' => $this->slash_7,
		));
		$comment = get_comment( $comment_id );

		$this->assertEquals( wp_unslash( $this->slash_1 ), $comment->comment_author );
		$this->assertEquals( wp_unslash( $this->slash_7 ), $comment->comment_content );

		wp_update_comment(array(
			'comment_ID' => $comment_id,
			'comment_author' => $this->slash_2,
			'comment_content' => $this->slash_4,
		));
		$comment = get_comment( $comment_id );

		$this->assertEquals( wp_unslash( $this->slash_2 ), $comment->comment_author );
		$this->assertEquals( wp_unslash( $this->slash_4 ), $comment->comment_content );
	}

}


text:
package pt.up.fe.specs.projecteuler.euler001_025;

import java.math.BigInteger;

import org.junit.Test;

import pt.up.fe.specs.projecteuler.utils.ParseUtils;

/**
 * 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
 *
 * What is the sum of the digits of the number 21000?
 *
 * @author JoaoBispo
 *
 */
public class Euler016 {

	@Test
	public void test() {

		String result = new BigInteger("2").pow(1000).toString();

		int sum = ParseUtils.sumDigits(result);
		/*
		 * int sum = 0; for (int i = 0; i < result.length(); i++) { sum +=
		 * Integer.valueOf(result.substring(i, i + 1)); }
		 */

		System.out.println("SOLUTION:" + sum);

	}

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MemberMutability.cs" company="OBeautifulCode">
//   Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
//   Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Reflection.Recipes source.
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------

namespace OBeautifulCode.Reflection.Recipes
{
    using global::System;
    using global::System.Diagnostics.CodeAnalysis;

    using OBeautifulCode.CodeAnalysis.Recipes;

    /// <summary>
    /// Scopes the search for members based on mutability.
    /// </summary>
    [Flags]
    [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames", Justification = ObcSuppressBecause.CA1714_FlagsEnumsShouldHavePluralNames_TheNameIsPlural)]
#if !OBeautifulCodeReflectionSolution
    [global::System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Reflection.Recipes", "See package version number")]
    internal
#else
    public
#endif
    enum MemberMutability
    {
        /// <summary>
        /// None (default).
        /// </summary>
        None = 0,

        /// <summary>
        /// Include members where mutability is applicable (i.e. fields and properties).
        /// </summary>
        Applicable = 1,

        /// <summary>
        /// Include members where mutability is not applicable (i.e. constructors, methods, events).
        /// </summary>
        NotApplicable = 2,

        /// <summary>
        /// Include readable properties and all fields, otherwise not applicable.
        /// </summary>
        Readable = 4,

        /// <summary>
        /// Include writable members.
        /// This is only applicable to fields (readonly and const fields are NOT considered writable) and properties.
        /// </summary>
        Writable = 8,

        /// <summary>
        /// Include members that cannot be written-to.
        /// This is only applicable to fields (readonly and const fields are considered to be not writable) and properties.
        /// </summary>
        NotWritable = 16,

        /// <summary>
        /// Include properties that are not readable.
        /// </summary>
        NotReadable = 32,

        /// <summary>
        /// Include members that cannot be written-to.
        /// This is only applicable to fields (readonly and const) and properties.
        /// </summary>
        ReadOnlyOrConst = NotWritable,

        /// <summary>
        /// Include properties that are not readable.
        /// </summary>
        WriteOnly = NotReadable,

        /// <summary>
        /// Include members where mutability is not applicable and where applicable,
        /// include members with any kind of mutability.
        /// </summary>
        All = Applicable | NotApplicable | Readable | Writable | NotWritable | NotReadable,
    }
}


text:
    @Component is an Angular decorator

    No semicolon here (as it attaches itself to the class below

    The Decorator goes directly above the decorated entity (class in this case)

    Component name is the class name (AppComponent).

    Create a class called 'AppComponent'

    Create a class called 'AppModule'

    All set! Bootstrap your application

Export the class

    Add a Component decorator for the class

    Add a selector to the component decorator and set it to 'my-app'

    Add a template that contains: h1 with a text "Hello MewTube!"

    Add a NgModule decorator for the class

    Add 'BrowserModule' to the NgModule decorator imports

    Add 'AppComponent' to the 'declarations' property of the decorator

    Add 'AppComponent' to the 'bootstrap' property of the decorator

<slide-deck slideShortcuts slidesRouting slides-tracking>
  <codelab-progress-bar></codelab-progress-bar>
  <slide-arrows></slide-arrows>

    <codelab-title-slide
      title="Create your first Angular app"
      i18n-title="@@CreateYFirstAgApp"
      description="You will learn how to create your first Angular component, put it in a module, and bootstrap the app."
      i18n-description
      prereqs="Knowing TypeScript basics would help a lot"
      i18n-prereqs
    ></codelab-title-slide>

    <codelab-breadcrumb i18n>What is Angular?</codelab-breadcrumb>

        Angular is a development platform for building mobile and desktop
        applications. Angular lets you extend HTML's syntax to express
        your application's components clearly and succinctly. Angular's binding
        and Dependency Injection eliminate much of the code you would
        otherwise have to write.

    <codelab-breadcrumb i18n>Intro</codelab-breadcrumb>

Given an HTML file:

      Let's create an Angular app which replaces the hello-world HTML
      element with the app's contents.

This can be done with 3 simple steps.

    <codelab-breadcrumb i18n>Intro</codelab-breadcrumb>

The 3 steps are:

Create an Angular component

Create an Angular module

Bootstrap the module

    <codelab-breadcrumb i18n>Step 1</codelab-breadcrumb>

      Start by creating an Angular Component. Components in Angular are
      responsible for the visual part of the app

      An Angular component is just a class. Properties and behavior can be added
      inside.

    <codelab-breadcrumb i18n>Decorators</codelab-breadcrumb>

The class is adorned with a @Component decorator

      Decorators attach Angular specific information to the class.

    <codelab-breadcrumb i18n>Decorators</codelab-breadcrumb>

      Decorators are a new feature of TypeScript. They attach metadata to a
      class, function, property or variable

      TypeScript decorators are inspired by a similar feature in the Python
      language.

    <codelab-breadcrumb i18n>Selector</codelab-breadcrumb>

      Selectors define the location of the component. When Angular renders this
      component, it'll find a hello-world HTML element in the document
      and render the component inside of it

    <codelab-breadcrumb i18n>Inline Template</codelab-breadcrumb>

Template defines the HTML code that the component generates

      If the amount of HTML grows out of hand, it's possible (and recommended)
      to use a templateUrl instead and provide a path to the HTML file.

    <codelab-breadcrumb i18n>Exercise</codelab-breadcrumb>

      In the next slide you'll create your first Angular component! We'll
      do all the wiring for you. The result will look like this:

    <codelab-exercise-preview
      column-5
      [exercise]="exercises[0]"
    ></codelab-exercise-preview>

    <codelab-exercise
      [translations]="t"
      testRunner="babel"
      [exercise]="exercises[0]"
      milestone="Bootstrap"
    >

Create first Angular component!

    </codelab-exercise>

    <codelab-breadcrumb i18n>Step 2</codelab-breadcrumb>

Next step is to declare the component in an NgModule.

      NgModule does not have any visual representation and is used
      exclusively for grouping Angular building blocks together

      We will learn more about NgModules in the future milestones

    <codelab-breadcrumb i18n>Module Class</codelab-breadcrumb>

Like a component, Angular module is just a class

    <codelab-breadcrumb i18n>NgModule Decorator</codelab-breadcrumb>

      Like a component, Angular module is adorned with a decorator
      providing metadata

    <codelab-breadcrumb i18n>Browser Module</codelab-breadcrumb>
    <codelab-slides-ng-module-mode></codelab-slides-ng-module-mode>

    <codelab-breadcrumb i18n>Declarations</codelab-breadcrumb>

      The declarations array specifies components belonging to the
      AppModule

    <codelab-breadcrumb i18n>Bootstrap</codelab-breadcrumb>

      The component passed into the bootstrap array will be created and
      displayed in your index.html file

    <codelab-breadcrumb i18n>Exercise</codelab-breadcrumb>

      In the next slide you'll create your first Angular module! We'll
      use the component from the previous exercises and do all the wiring for
      you. The result will look like this:

    <codelab-exercise-preview
      column-5
      [exercise]="exercises[1]"
    ></codelab-exercise-preview>

    <codelab-exercise
      [translations]="t"
      testRunner="babel"
      [exercise]="exercises[1]"
      milestone="Bootstrap2"
    >

Create first NgModule.

    </codelab-exercise>

    <codelab-breadcrumb i18n>Bootstrapping</codelab-breadcrumb>

      We have everything ready, so now it's time to start (bootstrap) the app!

      Passing your AppModule to the bootstrapModule method will
      start up all the components from that module's bootstrap section

      For most simple apps, you can just copy/paste the code above "as is"

    <codelab-breadcrumb i18n>Bootstrapping 1</codelab-breadcrumb>

How does bootstrapping work in Angular?

      1. Kicks off execution environment. platformBrowserDynamic() tells
      Angular that we are operating in the browser

      Read more about root module and bootstrapping in Angular

    <codelab-breadcrumb i18n>Bootstrapping 2</codelab-breadcrumb>

      2. Angular initializes the component from the bootstrap array in
      app.module.ts (HelloWorldComponent in this case)

      Read more about root module and bootstrapping in Angular

    <codelab-breadcrumb i18n>Bootstrapping 3</codelab-breadcrumb>

      3. Angular looks in the document for an element matching the selector
      defined in HelloWorldComponent ('hello-world' in our case)
      and inserts the component inside that element

      Read more about root module and bootstrapping in Angular

    <codelab-breadcrumb i18n>Exercise</codelab-breadcrumb>

      All set! In the next page you'll bootstrap your first Angular app!

    <codelab-exercise-preview
      column-5
      [exercise]="exercises[2]"
    ></codelab-exercise-preview>

    <codelab-exercise
      milestone="Bootstrap3"
      testRunner="babel"
      [translations]="t"
      [exercise]="exercises[2]"
    >

          Now that we've got both NgModule and the component ready, let's
          bootstrap the app!

    </codelab-exercise>

    <codelab-breadcrumb i18n>Review</codelab-breadcrumb>

Loading order: index -> main -> app.module -> app.component

      While Angular is loading, the contents of the element will stay the same
      (Loading...) in this case

    <codelab-closing-slide>

        <codelab-breadcrumb i18n>End of Bootstrap Section</codelab-breadcrumb>

Well done! This is the end of the milestone!

          <ng-container i18n>Next:</ng-container>

            Go to the templates Milestone

        <feedback-rating lesson="FirstAngularApp"></feedback-rating>

    </codelab-closing-slide>

</slide-deck>


text:
layout: page
title: Tech Motors Dinner
date: 2016-05-24
author: Shirley Stanley
tags: weekly links, java
status: published
summary: Morbi varius lorem id elit.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 02/03/2019
  endDate: 02/06/2019
  ctyhocn: BALAMHX
  groupCode: TMD
published: true
---
Aliquam tortor erat, porttitor at ex in, pharetra mattis dolor. Nulla eget est ex. Maecenas tincidunt convallis lectus, non viverra tortor ullamcorper vel. Proin lacinia felis eget porta vulputate. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer condimentum, lacus nec pulvinar accumsan, diam mi egestas velit, congue posuere leo diam nec arcu. Sed ligula nisl, malesuada id ornare ut, venenatis et ex. In hac habitasse platea dictumst.
In hac habitasse platea dictumst. Nulla eu pulvinar libero. Sed ut malesuada tellus, a cursus arcu. Praesent egestas est felis, eget finibus velit viverra vehicula. Integer placerat dolor nisl. Quisque eros ligula, pulvinar ac luctus nec, sodales nec velit. Donec et libero ac felis imperdiet lacinia. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc rhoncus risus eget tortor facilisis convallis.

1 Integer sollicitudin enim eu orci vulputate tempus
1 Quisque sed purus eget metus aliquet aliquet
1 Nunc a justo ut lectus pulvinar placerat tempor sed massa
1 Vestibulum tristique velit eu dolor fermentum efficitur
1 Ut ut nisl vel eros bibendum scelerisque.

Sed massa erat, placerat ac dolor in, condimentum semper lacus. Aliquam laoreet sed quam a viverra. Morbi in eros semper, mollis dolor a, mollis massa. Quisque vel lacus et sem tempor ornare. Sed gravida vulputate massa laoreet convallis. Aliquam suscipit egestas finibus. Praesent tincidunt dolor dolor, et tempus eros finibus non. Quisque id velit libero. Quisque nec arcu sem. Aenean tempor sem sit amet consectetur consectetur. In hac habitasse platea dictumst. Nullam gravida euismod vehicula. Fusce id blandit leo.


text:
// Copyright 2016 ct_common authors. See LICENSE file for details.

#ifndef CT_COMMON_COMMON_EXP_A_CINT_H_
#define CT_COMMON_COMMON_EXP_A_CINT_H_

#include <string>
#include <vector>

#include "ct_common/base/utils.h"
#include "ct_common/common/exp_a_atomic.h"

namespace ct_common {

// Class for constant int arithmetic expressions
class DLL_EXPORT Exp_A_CInt : public Exp_A_Atomic {
 public:
  Exp_A_CInt();
  ~Exp_A_CInt() override;

  void Dump(
      std::ostream& os,
      const std::vector<std::shared_ptr<ParamSpec> >& param_specs)
      const override;

  /** Setting the value */
  void set_value(int value);
  /** Setting the value */
  void set_value(double value);
  /** Setting the string value (preserve a copy of the original string
   * representation) */
  void set_str_value(const std::string& str_value);

  /** Getting the value */
  int get_value() const { return value_; }
  const std::string& get_str_value() const override;

 private:
  optional<double> EvaluateDouble_Impl(
      const std::vector<std::shared_ptr<ParamSpec> >& param_specs,
      const Assignment& assignment) const override;

  optional<int> EvaluateInt_Impl(
      const std::vector<std::shared_ptr<ParamSpec> >& param_specs,
      const Assignment& assignment) const override;

  int value_;
  std::string str_value_; /**< The preserved original string representation */

  DISALLOW_COPY_AND_ASSIGN(Exp_A_CInt);
};

}  // namespace ct_common

#endif  // CT_COMMON_COMMON_EXP_A_CINT_H_


text:
package com.amazonaws.codesamples.lowlevel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.QueryRequest;
import com.amazonaws.services.dynamodbv2.model.QueryResult;

public class LowLevelQuery {

    static AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());
    static String tableName = "Reply";

    public static void main(String[] args) throws Exception {

        String forumName = "Amazon DynamoDB";
        String threadSubject = "DynamoDB Thread 1";

        findRepliesForAThread(forumName, threadSubject);
        findRepliesForAThreadSpecifyOptionalLimit(forumName, threadSubject);
        findRepliesInLast15DaysWithConfig(forumName, threadSubject);
        findRepliesPostedWithinTimePeriod(forumName, threadSubject);
        findRepliesUsingAFilterExpression(forumName, threadSubject);
    }

    private static void findRepliesForAThread(String forumName, String threadSubject) {

        String replyId = forumName + "#" + threadSubject;

        Condition hashKeyCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withS(replyId));

        Map<String, Condition> keyConditions = new HashMap<String, Condition>();
        keyConditions.put("Id", hashKeyCondition);

        QueryRequest queryRequest = new QueryRequest()
            .withTableName(tableName)
            .withKeyConditions(keyConditions);

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }
    }

    private static void findRepliesForAThreadSpecifyOptionalLimit(String forumName, String threadSubject) {

        Map<String, AttributeValue> lastEvaluatedKey = null;
        do {
            QueryRequest queryRequest = new QueryRequest()
                    .withTableName(tableName)
                    .withKeyConditions(makeReplyKeyConditions(forumName, threadSubject))
                    .withLimit(1)
                    .withExclusiveStartKey(lastEvaluatedKey);

            QueryResult result = client.query(queryRequest);
            for (Map<String, AttributeValue> item : result.getItems()) {
                printItem(item);
            }
            lastEvaluatedKey = result.getLastEvaluatedKey();
        } while (lastEvaluatedKey != null);
    }

    private static void findRepliesInLast15DaysWithConfig(String forumName, String threadSubject) {

        long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);

        Condition rangeKeyCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.GT.toString())
            .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr));

        Map<String, Condition> keyConditions = makeReplyKeyConditions(forumName, threadSubject);
        keyConditions.put("ReplyDateTime", rangeKeyCondition);

        QueryRequest queryRequest = new QueryRequest().withTableName(tableName)
            .withKeyConditions(keyConditions)
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }

    }

    private static void findRepliesPostedWithinTimePeriod(String forumName, String threadSubject) {

        long startDateMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
        long endDateMilli = (new Date()).getTime() - (5L*24L*60L*60L*1000L);
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String startDate = df.format(startDateMilli);
        String endDate = df.format(endDateMilli);

        Condition rangeKeyCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.BETWEEN.toString())
            .withAttributeValueList(
                new AttributeValue().withS(startDate),
                new AttributeValue().withS(endDate));

        Map<String, Condition> keyConditions = makeReplyKeyConditions(forumName, threadSubject);
        keyConditions.put("ReplyDateTime", rangeKeyCondition);

        QueryRequest queryRequest = new QueryRequest()
            .withTableName(tableName)
            .withKeyConditions(keyConditions)
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }
    }

    private static void findRepliesUsingAFilterExpression(String forumName, String threadSubject) {

        Map<String, Condition> keyConditions = makeReplyKeyConditions(forumName, threadSubject);

        Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
        expressionAttributeValues.put(":val", new AttributeValue().withS("User B"));

        QueryRequest queryRequest = new QueryRequest()
            .withTableName(tableName)
            .withKeyConditions(keyConditions)
            .withFilterExpression("PostedBy = :val")
            .withExpressionAttributeValues(expressionAttributeValues)
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

         QueryResult result = client.query(queryRequest);
         for (Map<String, AttributeValue> item : result.getItems()) {
             printItem(item);
         }
     }

    private static void printItem(Map<String, AttributeValue> attributeList) {
        for (Map.Entry<String, AttributeValue> item : attributeList.entrySet()) {
            String attributeName = item.getKey();
            AttributeValue value = item.getValue();
            System.out.println(attributeName + " "
                    + (value.getS() == null ? "" : "S=[" + value.getS() + "]")
                    + (value.getN() == null ? "" : "N=[" + value.getN() + "]")
                    + (value.getB() == null ? "" : "B=[" + value.getB() + "]")
                    + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]")
                    + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]")
                    + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n"));
        }
    }

    /**
     * A simple helper function that returns a KeyCondition map filled in with the hash key equality condition
     * for a the Reply example table, given a forumName and threadSubject.
     */
    private static Map<String, Condition> makeReplyKeyConditions(String forumName, String threadSubject) {
        String replyId = forumName + "#" + threadSubject;

        Condition hashKeyCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withS(replyId));

        Map<String, Condition> keyConditions = new HashMap<String, Condition>();
        keyConditions.put("Id", hashKeyCondition);

        return keyConditions;
    }
}


text:
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Lifestyle.Scoped;

namespace Orth.Windsor.Owinlifestyle
{
    internal class OwinWebRequestScopeAccessor : IScopeAccessor
    {
        public void Dispose()
        {
            var scope = PerWebRequestLifestyleOwinMiddleware.YieldScope();
            if (scope != null)
            {
                scope.Dispose();
            }
        }

        public ILifetimeScope GetScope(CreationContext context)
        {
            return PerWebRequestLifestyleOwinMiddleware.GetScope();
        }
    }
}