text:
<?php

namespace app\controllers;

use app\models\UserAccounts;
use Yii;
use app\models\Warehouse;
use app\models\WarehouseSearch;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * WarehouseController implements the CRUD actions for Warehouse model.
 */
class WarehouseController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' =>[
                'class' => AccessControl::className(),
                'rules'=> [
                    [
                        'allow'=>true,
                        'matchCallback' => function ($rule, $action) {
                            if(!Yii::$app->user->isGuest) {
                                if(Yii::$app->user->identity->category_id == UserAccounts::SUPER_ADMIN) {
                                    return true;
                                }
                            }
                            return false;
                        }
                    ]
                ]
            ]
        ];
    }

    /**
     * Lists all Warehouse models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new WarehouseSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Warehouse model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Warehouse model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Warehouse();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Warehouse model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Warehouse model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Warehouse model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Warehouse the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Warehouse::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System;

namespace Microsoft.CodeAnalysis
{
    internal static class Boxes
    {
        public static readonly object BoxedTrue = true;
        public static readonly object BoxedFalse = false;
        public static readonly object BoxedByteZero = (byte)0;
        public static readonly object BoxedSByteZero = (sbyte)0;
        public static readonly object BoxedInt16Zero = (short)0;
        public static readonly object BoxedUInt16Zero = (ushort)0;
        public static readonly object BoxedInt32Zero = 0;
        public static readonly object BoxedInt32One = 1;
        public static readonly object BoxedUInt32Zero = 0U;
        public static readonly object BoxedInt64Zero = 0L;
        public static readonly object BoxedUInt64Zero = 0UL;
        public static readonly object BoxedSingleZero = 0.0f;
        public static readonly object BoxedDoubleZero = 0.0;
        public static readonly object BoxedDecimalZero = 0m;

        private static readonly object?[] s_boxedAsciiChars = new object?[128];

        public static object Box(bool b)
        {
            return b ? BoxedTrue : BoxedFalse;
        }

        public static object Box(byte b)
        {
            return b == 0 ? BoxedByteZero : b;
        }

        public static object Box(sbyte sb)
        {
            return sb == 0 ? BoxedSByteZero : sb;
        }

        public static object Box(short s)
        {
            return s == 0 ? BoxedInt16Zero : s;
        }

        public static object Box(ushort us)
        {
            return us == 0 ? BoxedUInt16Zero : us;
        }

        public static object Box(int i)
        {
            switch (i)
            {
                case 0: return BoxedInt32Zero;
                case 1: return BoxedInt32One;
                default: return i;
            }
        }

        public static object Box(uint u)
        {
            return u == 0 ? BoxedUInt32Zero : u;
        }

        public static object Box(long l)
        {
            return l == 0 ? BoxedInt64Zero : l;
        }

        public static object Box(ulong ul)
        {
            return ul == 0 ? BoxedUInt64Zero : ul;
        }

        public static unsafe object Box(float f)
        {
            // There are many representations of zero in floating point.
            // Use the boxed value only if the bit pattern is all zeros.
            return *(int*)(&f) == 0 ? BoxedSingleZero : f;
        }

        public static object Box(double d)
        {
            // There are many representations of zero in floating point.
            // Use the boxed value only if the bit pattern is all zeros.
            return BitConverter.DoubleToInt64Bits(d) == 0 ? BoxedDoubleZero : d;
        }

        public static object Box(char c)
        {
            return c < 128
                ? s_boxedAsciiChars[c] ?? (s_boxedAsciiChars[c] = c)
                : c;
        }

        public static unsafe object Box(decimal d)
        {
            // There are many representation of zero in System.Decimal
            // Use the boxed value only if the bit pattern is all zeros.
            ulong* ptr = (ulong*)&d;
            return ptr[0] == 0 && ptr[1] == 0 ? BoxedDecimalZero : d;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
efcalendar_click = function (control_source, id) {
	var node = ef.getNodeById(id);
	efcalendar(control_source, node, 'yyyy-mm-dd', true);
};

efform_onload = function ()
{
	ef.get("inqu_status-0-startDate").value = today;
	ef.get("inqu_status-0-endDate").value = today;
	var eiInfo =  _getEi();
	if(eiInfo.get("uploadComplete") == "true"){
		var filePath = eiInfo.get("filePath");
		efform.setStatus(1, "提取数据中...");
		var info = new EiInfo();
		info.set("filePath",filePath);
		EiCommunicator.send("STXS1401","doImport",info,{
			onSuccess :
				function(eiInfo){
					alert(eiInfo.getMsg());
					if(eiInfo.getStatus() != -1){
						self.location = "DispatchAction.do?efFormEname=STXS1401";
					}
				},
			onFail:
				function(eMsg){alert("Error occured on call service: "+eMsg);}
		});
	}
};

button_query_onclick = function()
{
	efgrid.submitInqu("ef_grid_result","STXS","STXS1401","query");
};

efcascadeselect_ensure_onclick = function(id)
{
	var grid_id = efcascadeselect.getDivWindowSubNodeId("_efselect_divwindow");
	var grid = efgrid.getGridObject(grid_id);
	var index = grid.getCurrentRowIndex();
	if(id == 'inqu_status-0-customerId')
	{
		var cellValue = grid.getCellValue(index, 0, TYPE_DATA);
		var cellValue1 = grid.getCellValue(index, 1, TYPE_DATA);
		ef.get("inqu_status-0-customerId").value = cellValue;
		ef.get("inqu_status-0-custName").value = cellValue1;
	}
};

efgrid_onRowCheckboxClicked = function( grid_id, row_index,div_node ){  //checkBox单选
	if(grid_id == 'ef_grid_result'){
		var grid_result = efgrid.getGridObject("ef_grid_result");

			var row_num = grid_result.getRowCount();
			var settleIdChecked = grid_result.blockData.getCell(row_index,'settleId');
			if(grid_result.isRowChecked(row_index)==false){
					for(j=0;j<row_num;j++){
						var settleId = grid_result.blockData.getCell(j,'settleId');
						if (settleIdChecked == settleId){
							grid_result.setRowChecked ( j , true );
							grid_result.refresh();
						}
					}
					grid_result.setRowChecked ( row_index , true );
			}else{
						for(j=0;j<row_num;j++){
						var settleId = grid_result.blockData.getCell(j,'settleId');
						if (settleIdChecked == settleId){
							grid_result.setRowChecked ( j , false );
							grid_result.refresh();
						}
					}
					grid_result.setRowChecked ( row_index , false );
					}
	}
};

button_export_onclick = function()
{
	var grid = efgrid.getGridObject("ef_grid_result");
	if(grid.getCheckedRowCount() == 0){alert("没有数据被选中!");return;}

	var uploadFileKeepedDir = document.getElementById("uploadFileKeepedDir").value;
	var ajax_callback = {
	onSuccess :
		function(eiInfo){
			if (eiInfo.get('exportComplete') == 'true') {
//				efform.setStatus(0, eiInfo.getMsg());
//				alert(eiInfo.getMsg());
//				efform.getGrid("ef_grid_result").ajax=false;
//				efgrid.submitForm("ef_grid_result","STXS","STXS1401","query");
//				efform.getGrid("ef_grid_result").ajax=true;

	            document.forms["STXS1401"].action = "./STXS/download.jsp?path="+uploadFileKeepedDir;
	            document.forms["STXS1401"].submit();
			}else if (eiInfo.get('ifSuccess') == 'false') {
				alert(eiInfo.getMsg());
			}
		},
		onFail:
		function(eMsg) {}
	}
	var info = new EiInfo();
	info.set("uploadFileKeepedDir",uploadFileKeepedDir)
	var block_result = new EiBlock(grid.getBlockData().getBlockMeta());
	info.setByNodeObject( document.forms[0] );
	efgrid._addSelectedData(block_result, grid);
	info.addBlock(block_result);
	EiCommunicator.send("STXS1401","export",info,ajax_callback );
};

button_import_onclick = function()
{
	var file_id_callback = {
	onSuccess :
		function(eiInfo){
			var fileId = eiInfo.get("fileId");
			document.forms["STXS1401"].action = "./STXT/upload.jsp?uploadfiles=uploadfiles-xs/"+fileId+"&efFormEname=STXS1401";
			document.forms["STXS1401"].submit();
		},
 	 onFail    :
   		 function(eMsg) {
      	 alert("failure");
    	}
	}
	if(document.getElementById("filedir").value == ""){
		alert("请先选择文件路径!");
		return;
	}
	var info = new EiInfo();
	EiCommunicator.send("STXS1401","getFileId",info,file_id_callback );
};

fun=function(currentIndex,index){
		if(index == '0'){
				var button_export = document.getElementById('button_export');
				button_export.disabled = '';
				var button_import = document.getElementById('button_import');
				button_import.disabled = 'disabled';

		}else{
				var button_import = document.getElementById('button_import');
				button_import.disabled = '';
				var button_export = document.getElementById('button_export');
				button_export.disabled = 'disabled';
		}
};

//function  downTxt(){
//window.open ('${pageContext.request.contextPath}/business/magazineAction.do?method=downFile&filename=magazinePub.txt', '文件下载', 'height=300, width=400, top='+(screen.availHeight-300)/2+', left='+(screen.availWidth-400)/2+', toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
//};


text:
from key import Key

def _object_getattr(obj, field):
  '''Attribute getter for the objects to operate on.

  This function can be overridden in classes or instances of Query, Filter, and
  Order. Thus, a custom function to extract values to attributes can be
  specified, and the system can remain agnostic to the client's data model,
  without loosing query power.

  For example, the default implementation works with attributes and items::

    def _object_getattr(obj, field):
      # check whether this key is an attribute
      if hasattr(obj, field):
        value = getattr(obj, field)

      # if not, perhaps it is an item (raw dicts, etc)
      elif field in obj:
        value = obj[field]

      # return whatever we've got.
      return value

  Or consider a more complex, application-specific structure::

    def _object_getattr(version, field):

      if field in ['key', 'committed', 'created', 'hash']:
        return getattr(version, field)

      else:
        return version.attributes[field]['value']

  '''

  # TODO: consider changing this to raise an exception if no value is found.
  value = None

  # check whether this key is an attribute
  if hasattr(obj, field):
    value = getattr(obj, field)

  # if not, perhaps it is an item (raw dicts, etc)
  elif field in obj:
    value = obj[field]

  # return whatever we've got.
  return value

def limit_gen(limit, iterable):
  '''A generator that applies a count `limit`.'''
  limit = int(limit)
  assert limit >= 0, 'negative limit'

  for item in iterable:
    if limit <= 0:
      break
    yield item
    limit -= 1

def offset_gen(offset, iterable, skip_signal=None):
  '''A generator that applies an `offset`, skipping `offset` elements from
  `iterable`. If skip_signal is a callable, it will be called with every
  skipped element.
  '''
  offset = int(offset)
  assert offset >= 0, 'negative offset'

  for item in iterable:
    if offset > 0:
      offset -= 1
      if callable(skip_signal):
        skip_signal(item)
    else:
      yield item

def chain_gen(iterables):
  '''A generator that chains `iterables`.'''
  for iterable in iterables:
    for item in iterable:
      yield item

class Filter(object):
  '''Represents a Filter for a specific field and its value.

  Filters are used on queries to narrow down the set of matching objects.

  Args:
    field: the attribute name (string) on which to apply the filter.

    op: the conditional operator to apply (one of
        ['<', '<=', '=', '!=', '>=', '>']).

    value: the attribute value to compare against.

  Examples::

    Filter('name', '=', 'John Cleese')
    Filter('age', '>=', 18)

  '''

  conditional_operators = ['<', '<=', '=', '!=', '>=', '>']
  '''Conditional operators that Filters support.'''

  _conditional_cmp = {
    "<"  : lambda a, b: a < b,
    "<=" : lambda a, b: a <= b,
    "="  : lambda a, b: a == b,
    "!=" : lambda a, b: a != b,
    ">=" : lambda a, b: a >= b,
    ">"  : lambda a, b: a > b
  }

  object_getattr = staticmethod(_object_getattr)
  '''Object attribute getter. Can be overridden to match client data model.
  See :py:meth:`datastore.query._object_getattr`.
  '''

  def __init__(self, field, op, value):
    if op not in self.conditional_operators:
      raise ValueError('"%s" is not a valid filter Conditional Operator' % op)

    self.field = field
    self.op = op
    self.value = value

  def __call__(self, obj):
    '''Returns whether this object passes this filter.
    This method aggressively tries to find the appropriate value.
    '''
    value = self.object_getattr(obj, self.field)

    # TODO: which way should the direction go here? it may make more sense to
    #       convert the passed-in value instead. Or try both? Or not at all?
    if not isinstance(value, self.value.__class__):
      value = self.value.__class__(value)

    return self.valuePasses(value)

  def valuePasses(self, value):
    '''Returns whether this value passes this filter'''
    return self._conditional_cmp[self.op](value, self.value)

  def __str__(self):
    return '%s %s %s' % (self.field, self.op, self.value)

  def __repr__(self):
    return "Filter('%s', '%s', %s)" % (self.field, self.op, repr(self.value))

  def __eq__(self, o):
    return self.field == o.field and self.op == o.op and self.value == o.value

  def __ne__(self, other):
    return not self.__eq__(other)

  def __hash__(self):
    return hash(repr(self))

  def generator(self, iterable):
    '''Generator function that iteratively filters given `items`.'''
    for item in iterable:
      if self(item):
        yield item

  @classmethod
  def filter(cls, filters, iterable):
    '''Returns the elements in `iterable` that pass given `filters`'''
    if isinstance(filters, Filter):
      filters = [filters]

    for filter in filters:
      iterable = filter.generator(iterable)

    return iterable

class Order(object):
  '''Represents an Order upon a specific field, and a direction.
  Orders are used on queries to define how they operate on objects

  Args:
    order: an order in string form. This follows the format: [+-]name
           where + is ascending, - is descending, and name is the name
           of the field to order by.
           Note: if no ordering operator is specified, + is default.

  Examples::

    Order('+name')   #  ascending order by name
    Order('-age')    # descending order by age
    Order('score')   #  ascending order by score

  '''

  order_operators = ['-', '+']
  '''Ordering operators: + is ascending, - is descending.'''

  object_getattr = staticmethod(_object_getattr)
  '''Object attribute getter. Can be overridden to match client data model.
  See :py:meth:`datastore.query._object_getattr`.
  '''

  def __init__(self, order):
    self.op = '+'

    try:
      if order[0] in self.order_operators:
        self.op = order[0]
        order = order[1:]
    except IndexError:
      raise ValueError('Order input be at least two characters long.')

    self.field = order

    if self.op not in self.order_operators:
      raise ValueError('"%s" is not a valid Order Operator.' % op)

  def __str__(self):
    return '%s%s' % (self.op, self.field)

  def __repr__(self):
    return "Order('%s%s')" % (self.op, self.field)

  def __eq__(self, other):
    return self.field == other.field and self.op == other.op

  def __ne__(self, other):
    return not self.__eq__(other)

  def __hash__(self):
    return hash(repr(self))

  def isAscending(self):
    return self.op == '+'

  def isDescending(self):
    return not self.isAscending()

  def keyfn(self, obj):
    '''A key function to be used in pythonic sort operations.'''
    return self.object_getattr(obj, self.field)

  @classmethod
  def multipleOrderComparison(cls, orders):
    '''Returns a function that will compare two items according to `orders`'''
    comparers = [ (o.keyfn, 1 if o.isAscending() else -1) for o in orders]

    def cmpfn(a, b):
      for keyfn, ascOrDesc in comparers:
        comparison = cmp(keyfn(a), keyfn(b)) * ascOrDesc
        if comparison is not 0:
          return comparison
      return 0

    return cmpfn

  @classmethod
  def sorted(cls, items, orders):
    '''Returns the elements in `items` sorted according to `orders`'''
    return sorted(items, cmp=cls.multipleOrderComparison(orders))

class Query(object):
  '''A Query describes a set of objects.

  Queries are used to retrieve objects and instances matching a set of criteria
  from Datastores. Query objects themselves are simply descriptions,
  the actual Query implementations are left up to the Datastores.
  '''

  '''Object attribute getter. Can be overridden to match client data model.'''
  object_getattr = staticmethod(_object_getattr)

  def __init__(self, key, limit=None, offset=0, object_getattr=None):
    ''' Initialize a query.

    Parameters
      key: a key representing the level of this query. For example, a Query with
           Key('/MontyPython/Actor:') would query objects in that key path, eg:
             Key('/MontyPython/Actor:JohnCleese')
             Key('/MontyPython/Actor:EricIdle')
             Key('/MontyPython/Actor:GrahamChapman')

            It is up to datastores how to implement this namespacing. E.g.,
            some datastores may store values in different tables or collections.

      limit: an integer representing the maximum number of results to return.

      offset: an integer representing a number of results to skip.

      object_getattr: a function to extract attribute values from an object. It
           is used to satisfy query filters and orders. Defining this function
           allows the client to control the data model of the stored values.
           The default function attempts to access values as attributes
           (__getattr__) or items (__getitem__).
    '''
    if not isinstance(key, Key):
      raise TypeError('key must be of type %s' % Key)

    self.key = key

    self.limit = int(limit) if limit is not None else None
    self.offset = int(offset)

    self.filters = []
    self.orders = []

    if object_getattr:
      self.object_getattr = object_getattr

  def __str__(self):
    '''Returns a string describing this query.'''
    return repr(self)

  def __repr__(self):
    '''Returns the representation of this query. Enables eval(repr(.)).'''
    return 'Query.from_dict(%s)' % self.dict()

  def __call__(self, iterable):
    '''Naively apply this query on an iterable of objects.
    Applying a query applies filters, sorts by appropriate orders, and returns
    a limited set.

    WARNING: When orders are applied, this function operates on the entire set
             of entities directly, not just iterators/generators. That means
             the entire result set will be in memory. Datastores with large
             objects and large query results should translate the Query and
             perform their own optimizations.
    '''

    cursor = Cursor(self, iterable)
    cursor.apply_filter()
    cursor.apply_order()
    cursor.apply_offset()
    cursor.apply_limit()
    return cursor

  def order(self, order):
    '''Adds an Order to this query.

    Args:
      see :py:class:`Order <datastore.query.Order>` constructor

    Returns self for JS-like method chaining::

      query.order('+age').order('-home')

    '''
    order = order if isinstance(order, Order) else Order(order)

    # ensure order gets attr values the same way the rest of the query does.
    order.object_getattr = self.object_getattr
    self.orders.append(order)
    return self # for chaining

  def filter(self, *args):
    '''Adds a Filter to this query.

    Args:
      see :py:class:`Filter <datastore.query.Filter>` constructor

    Returns self for JS-like method chaining::

      query.filter('age', '>', 18).filter('sex', '=', 'Female')

    '''
    if len(args) == 1 and isinstance(args[0], Filter):
      filter = args[0]
    else:
      filter = Filter(*args)

    # ensure filter gets attr values the same way the rest of the query does.
    filter.object_getattr = self.object_getattr
    self.filters.append(filter)
    return self # for chaining

  def __cmp__(self, other):
    return cmp(self.dict(), other.dict())

  def __hash__(self):
    return hash(repr(self))

  def copy(self):
    '''Returns a copy of this query.'''
    if self.object_getattr is Query.object_getattr:
      other = Query(self.key)
    else:
      other = Query(self.key, object_getattr=self.object_getattr)
    other.limit = self.limit
    other.offset = self.offset
    other.filters = self.filters
    other.orders = self.orders
    return other

  def dict(self):
    '''Returns a dictionary representing this query.'''
    d = dict()
    d['key'] = str(self.key)

    if self.limit is not None:
      d['limit'] = self.limit
    if self.offset > 0:
      d['offset'] = self.offset
    if len(self.filters) > 0:
      d['filter'] = [[f.field, f.op, f.value] for f in self.filters]
    if len(self.orders) > 0:
      d['order'] = [str(o) for o in self.orders]

    return d

  @classmethod
  def from_dict(cls, dictionary):
    '''Constructs a query from a dictionary.'''
    query = cls(Key(dictionary['key']))

    for key, value in dictionary.items():

      if key == 'order':
        for order in value:
          query.order(order)

      elif key == 'filter':
        for filter in value:
          if not isinstance(filter, Filter):
            filter = Filter(*filter)
          query.filter(filter)

      elif key in ['limit', 'offset']:
        setattr(query, key, value)
    return query

def is_iterable(obj):
  return hasattr(obj, '__iter__') or hasattr(obj, '__getitem__')

class Cursor(object):
  '''Represents a query result generator.'''

  __slots__ = ('query', '_iterable', '_iterator', 'skipped', 'returned', )

  def __init__(self, query, iterable):
    if not isinstance(query, Query):
      raise ValueError('Cursor received invalid query: %s' % query)

    if not is_iterable(iterable):
      raise ValueError('Cursor received invalid iterable: %s' % iterable)

    self.query = query
    self._iterable = iterable
    self._iterator = None
    self.returned = 0
    self.skipped = 0

  def __iter__(self):
    '''The cursor itself is the iterator. Note that it cannot be used twice,
    and once iteration starts, the cursor cannot be modified.
    '''
    if self._iterator:
      raise RuntimeError('Attempt to iterate over Cursor twice.')

    self._iterator = iter(self._iterable)
    return self

  def next(self):
    '''Iterator next. Build up count of returned elements during iteration.'''

    # if iteration has not begun, begin it.
    if not self._iterator:
      self.__iter__()

    next = self._iterator.next()
    if next is not StopIteration:
      self._returned_inc(next)
    return next

  def _skipped_inc(self, item):
    '''A function to increment the skipped count.'''
    self.skipped += 1

  def _returned_inc(self, item):
    '''A function to increment the returned count.'''
    self.returned += 1

  def _ensure_modification_is_safe(self):
    '''Assertions to ensure modification of this Cursor is safe.'''
    assert self.query, 'Cursor must have a Query.'
    assert is_iterable(self._iterable), 'Cursor must have a resultset iterable.'
    assert not self._iterator, 'Cursor must not be modified after iteration.'

  def apply_filter(self):
    '''Naively apply query filters.'''
    self._ensure_modification_is_safe()

    if len(self.query.filters) > 0:
      self._iterable = Filter.filter(self.query.filters, self._iterable)

  def apply_order(self):
    '''Naively apply query orders.'''
    self._ensure_modification_is_safe()

    if len(self.query.orders) > 0:
      self._iterable = Order.sorted(self._iterable, self.query.orders)
      # not a generator :(

  def apply_offset(self):
    '''Naively apply query offset.'''
    self._ensure_modification_is_safe()

    if self.query.offset != 0:
      self._iterable = \
        offset_gen(self.query.offset, self._iterable, self._skipped_inc)
        # _skipped_inc helps keep count of skipped elements

  def apply_limit(self):
    '''Naively apply query limit.'''
    self._ensure_modification_is_safe()

    if self.query.limit is not None:
      self._iterable = limit_gen(self.query.limit, self._iterable)


text:
.. _adafruit_2_8_tft_touch_v2:

Adafruit 2.8" TFT Touch Shield v2
#################################

Overview
********

The Adafruit 2.8" TFT Touch Shield v2 with a
resolution of 320x240 pixels, is based on the ILI9341 controller.
This shield comes with a resistive (STMPE610 controller)
or capacitive (FT6206 controller) touchscreen. While the
Zephyr RTOS supports display output to these screens,
touchscreen input is supported only on Capacitive Touch version.
More information about the shield can be found
at the `Adafruit 2.8" TFT Touch Shield v2 website`_.

Pins Assignment of the Adafruit 2.8" TFT Touch Shield v2
========================================================

+-----------------------+---------------------------------------------+
| Shield Connector Pin  | Function                                    |
+=======================+=============================================+
| D4                    | MicroSD SPI CSn                             |
+-----------------------+---------------------------------------------+
| D7                    | Touch Controller IRQ (see note below)       |
+-----------------------+---------------------------------------------+
| D8                    | STMPE610 SPI CSn (Resistive Touch Version)  |
+-----------------------+---------------------------------------------+
| D9                    | ILI9341 DC       (Data/Command)             |
+-----------------------+---------------------------------------------+
| D10                   | ILI9341 SPI CSn                             |
+-----------------------+---------------------------------------------+
| D11                   | SPI MOSI         (Serial Data Input)        |
+-----------------------+---------------------------------------------+
| D12                   | SPI MISO         (Serial Data Out)          |
+-----------------------+---------------------------------------------+
| D13                   | SPI SCK          (Serial Clock Input)       |
+-----------------------+---------------------------------------------+
| SDA                   | FT6206 SDA       (Capacitive Touch Version) |
+-----------------------+---------------------------------------------+
| SCL                   | FT6206 SCL       (Capacitive Touch Version) |
+-----------------------+---------------------------------------------+

.. note::
   Touch controller IRQ line is not connected by default. You will need to
   solder the ``ICSP_SI1`` jumper to use it. You will also need to adjust
   driver configuration and its Device Tree entry to make use of it.

Requirements
************

This shield can only be used with a board which provides a configuration
for Arduino or Arduino Nano connectors and defines node aliases for SPI and
GPIO interfaces (see :ref:`shields` for more details).

Programming
***********

Set ``-DSHIELD=adafruit_2_8_tft_touch_v2`` when you invoke ``west build``. For example:

.. zephyr-app-commands::
   :zephyr-app: samples/subsys/display/lvgl
   :board: nrf52840dk_nrf52840
   :shield: adafruit_2_8_tft_touch_v2
   :goals: build

If the shield is connected to a board which has Arduino Nano connector,
set ``-DSHIELD=adafruit_2_8_tft_touch_v2_nano`` when you invoke ``west build``.

.. zephyr-app-commands::
   :zephyr-app: samples/subsys/display/lvgl
   :board: arduino_nano_33_ble
   :shield: adafruit_2_8_tft_touch_v2_nano
   :goals: build

References
**********

.. target-notes::

.. _Adafruit 2.8" TFT Touch Shield v2 website:
   https://learn.adafruit.com/adafruit-2-8-tft-touch-shield-v2


text:
package br.com.rf.pdchallenge.domain;

import android.content.Context;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

import br.com.rf.pdchallenge.R;
import br.com.rf.pdchallenge.event.WeatherEvent;
import br.com.rf.pdchallenge.helper.WeatherHelper;
import br.com.rf.pdchallenge.http.RestFacade;
import br.com.rf.pdchallenge.model.FlickrPhoto;
import br.com.rf.pdchallenge.model.Weather;
import br.com.rf.pdchallenge.model.WeatherApiWrapper;

/**
 * Created by rodrigoferreira on 3/6/16.
 */
public class WeatherUseCase extends BaseUseCase {
    public WeatherUseCase(Context context) {
        super(context);
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void retrieveWeatherList(final WeatherEvent.RetrieveList event) {
        List<Weather> weatherList = new ArrayList<>();
        Exception exception = null;
        for (String city : WeatherHelper.getMySavedCities(mContext)) {
            try {
                WeatherApiWrapper apiWrapper = RestFacade.getWeatherByCity(city.toUpperCase());
                apiWrapper.timeZoneId = RestFacade.getTimeZoneByLatLong(apiWrapper.getLocation()).timeZoneId;
                Weather weather = new Weather(apiWrapper);
                FlickrPhoto flickrPhoto = RestFacade.searchPhotoByTag(weather.city);
                if ("ok".equals(flickrPhoto.stat) && flickrPhoto.photos.photo.size() > 0) {
                    FlickrPhoto.Photo photo = flickrPhoto.photos.photo.get(0);
                    String photoUrl = mContext.getString(R.string.url_flikr_photo, photo.farm, photo.server, photo.id, photo.secret);
                    Log.d("photoUrl", photoUrl);
                    weather.photoUrl = photoUrl;
                }
                weatherList.add(weather);
            } catch (Exception e) {
                exception = e;
            }
        }

        if (exception != null) {
            weatherList = new ArrayList<>();
        }
        EventBus.getDefault().post(new WeatherEvent().new SuccessRetrieveList(weatherList));
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void AddCityToList(final WeatherEvent.AddCity event) {
        try {
            WeatherApiWrapper apiWrapper = RestFacade.getWeatherByCity(event.city.toUpperCase());
            EventBus.getDefault().post(new WeatherEvent().new ShowLoading());
            if (apiWrapper != null && event.city.toLowerCase().equals(apiWrapper.getCity().toLowerCase())) {
                apiWrapper.timeZoneId = RestFacade.getTimeZoneByLatLong(apiWrapper.getLocation()).timeZoneId;
                Weather weather = new Weather(apiWrapper);
                FlickrPhoto flickrPhoto = RestFacade.searchPhotoByTag(weather.city);
                if ("ok".equals(flickrPhoto.stat) && flickrPhoto.photos.photo.size() > 0) {
                    FlickrPhoto.Photo photo = flickrPhoto.photos.photo.get(0);
                    String photoUrl = mContext.getString(R.string.url_flikr_photo, photo.farm, photo.server, photo.id, photo.secret);
                    Log.d("photoUrl", photoUrl);
                    weather.photoUrl = photoUrl;
                }
                EventBus.getDefault().post(new WeatherEvent().new SuccessCityAdded(weather));
            } else {
                EventBus.getDefault().post(new WeatherEvent().new ErrorCityAdded(mContext.getString(R.string.msg_error_search_city)));
            }
        } catch (Exception e) {
            EventBus.getDefault().post(new WeatherEvent().new ErrorCityAdded(mContext.getString(R.string.msg_error_generic)));
        }

    }

}