text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace App\Controller;
use App\Model\Table;
use App\DTO\UploadDTO;
use Cake\Log\Log;
use App\DTO\DownloadDTO;
/**
 * Description of RecipeItemMasterController
 *
 * @author niteen
 */
class RecipeItemMasterController extends ApiController{

    private function getTableObj() {
        return new Table\RecipeItemMasterTable();
    }

    public function AddNewRecipeItem() {
          if(!$this->isLogin()){
            $this->redirect('login');
        }
        $data = $this->request->data;
        $restaurantId = parent::readCookie('cri');
       if ($this->request->is('post') and isset($data['add-m'])) {

            $file = $data['file-upload']['tmp_name'];
            $filename = $data['file-upload']['name'];
            $extenstion = $this->getExtension($filename);
            if(empty($file)) {
                $this->set(['suc_msg' => SELECT_FILE_MESSAGE,'color' => 'red']);
            } elseif ($extenstion != CSV_EXT) {
                $this->set(['suc_msg' => INCORRECT_FILE_MESSAGE, 'color' => 'red']);
            } else {
                if (($handle = fopen($file, "r")) !== FALSE) {
                    $counter = 0;
                    $allItems= null;
                    $fileCount = count(fgetcsv($handle));
                    while (($filesop = fgetcsv($handle, 1000, ",")) !== false) {
                        $allItems[$counter++] = new UploadDTO\RecipeItemMaterInsertDto(
                                $filesop[0],
                                $filesop[1],
                                $filesop[2],
                                $filesop[3],
                                $filesop[4]);
                    }
                    fclose($handle);
                    $result = $this->getTableObj()->insert($allItems);
                    if ($result) {
                        $this->set(['suc_msg' => 'You database has imported successfully. You have inserted ' . count($result) . ' records','color' => 'green']);
                    } else {
                        $this->set(['suc_msg' => DB_FILE_ERROR,'color' => 'red']);
                    }
                }
            }
        }
    }

    public function stockUpdate(UploadDTO\OpenStockUploadDto $updateRequest) {
        return $this->getTableObj()->update($updateRequest->itemId, $updateRequest->restaurantId, $updateRequest->stock);
    }
    public function inventory() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }
        $data = $this->request->data;
        $restaurantId = $this->readCookie('cri');
//        if($this->request->is('post') and isset($data['os'])){
//              $this->redirect('inventory');
//        }elseif ($this->request->is('post') and isset($data['cs'])) {
//              $this->redirect('inventory');
//
//        }elseif ($this->request->is('post') and isset($data['su'])) {
//              $this->redirect('inventory/stockupload');
//        }

       $allRecipeitems = $this->getTableObj()->getStock($restaurantId);

       $this->set([
                'items' => $allRecipeitems
       ]);

    }

    public function stockUpload() {
        $data = $this->request->data;
        if($this->request->is('post') and isset($data['add-m'])){
            parent::writeCookie('msu-message', 'Material Stock Updated');
            $this->redirect('inventory/stockupload');

        }elseif ($this->request->is('post') and isset($data['add-mb'])) {
            parent::writeCookie('mbsu-message', 'Material Brand Stock Updated');
            $this->redirect('inventory/stockupload');

        }elseif ($this->request->is('post') and isset($data['su'])) {
              $this->redirect('inventory/stockupload');
        }
        $message = parent::readCookie('msu-message');
        parent::deleteCookie('msu-message');
        $message1 = parent::readCookie('mbsu-message');
        parent::deleteCookie('mbsu-message');
        if($message){
            \Cake\Log\Log::debug('message:- '.$message);
            $this->set(['message',$message]);
        }  else {
            \Cake\Log\Log::debug('message:- '.$message1);
            $this->set(['message',$message1]);
        }
    }

    public function getItemInfo() {
        $this->autoRender = FALSE;
        Log::debug('Ajax request hitted to get items');
        if($this->request->is('get') and $this->isLogin()){
            $restaurantId = parent::readCookie('cri');
            $response =  $this->getTableObj()->getItems($restaurantId);
            Log::debug($response);
            $this->response->body(json_encode($response));
        }else{
            $this->response->body(FALSE);
        }
    }

    public function getMaterialRequisitionReport() {
        $this->autoRender = FALSE;
        if($this->request->is('ajax') and $this->isLogin()){
            $type = $this->request->query('type');
            Log::debug('Type of Map: '.$type);
            $restaurantId = parent::readCookie('cri');
            $rows = $this->getTableObj()->getRecipeItems($restaurantId,$type);

            $this->response->body(json_encode($rows));
        }else{
            $this->response->body(false);
        }

    }

    public function materialStockUpload() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }
         $data = $this->request->data;
        $restaurantId = parent::readCookie('cri');
        $allow = 5;
       if ($this->request->is('post') and isset($data['upload'])) {

            $file = $data['file-upload']['tmp_name'];
            $filename = $data['file-upload']['name'];
            $extenstion = $this->getExtension($filename);
            if(empty($file)) {
                $this->set(['suc_msg' => SELECT_FILE_MESSAGE,'color' => 'red']);
            } elseif ($extenstion != CSV_EXT) {
                $this->set(['suc_msg' => INCORRECT_FILE_MESSAGE, 'color' => 'red']);
            } else {
                if (($handle = fopen($file, "r")) !== FALSE) {
                    $counter = 0;
                    $allItems= null;
                    $fileCount = count(fgetcsv($handle));
                    Log::debug('File COunt:'.$fileCount);
                    if($fileCount != $allow){
                         $this->set(['suc_msg' => 'Please verify file data and try again..! ','color' => 'red']);
                        fclose($handle);
                        return;
                    }
                    while (($filesop = fgetcsv($handle, 1000, ",")) !== false) {
                        $allItems[$counter++] = new UploadDTO\RecipeItemMaterInsertDto(
                                $filesop[0],
                                $filesop[1],
                                $filesop[2],
                                $filesop[3],
                                $filesop[4]);
                    }
                    fclose($handle);
                    $result = $this->getTableObj()->insert($allItems);
                    if ($result) {
                        $this->set(['suc_msg' => 'You database has imported successfully. You have inserted ' . count($result) . ' recoreds','color' => 'green']);
                    } else {
                        $this->set(['suc_msg' => DB_FILE_ERROR,'color' => 'red']);
                    }
                }
            }
        }

    }
    public function materialBrandStockUpload() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }

    }

    public function materialStockModification() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }
        $restaurantId = $this->readCookie('cri');
        $allRecipeitems = $this->getTableObj()->getStock($restaurantId);
       $this->set([
                'items' => $allRecipeitems
       ]);

    }

    public function materialBrandStockModification() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }

    }

    public function stockInventoryReport() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }

    }

    public function materialRequisitionReport() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }
        if($this->request->is('get')){
            $this->set(['limit' => 'set']);
        }

    }

    public function materialBrandwiseRequisitionReport() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }
         if($this->request->is('get')){
            $this->set(['limit' => 1]);
        }
    }

    public function stockAvailability() {
         if(!$this->isLogin()){
            $this->redirect('login');
        }
        if($this->request->is('get')){
            $this->set(['limit' => 1]);
        }
    }
   /*
    private function paginatedItem($restaurantId, $page = 1) {
        $recipeItemTable = $this->getTableObj();
        $count = $recipeItemTable->connect()->find()->count();
        Log::debug('Number of menu available in list is :- '.$count);
        if(!$count){
            return Null;
        }
        $conditions = array('RestaurantId =' => $restaurantId);
        $limit = PAGE_LIMIT;
         $joins = [
                    'a' => [
                            'table' => 'unit_master',
                            'type' => 'INNER',
                            'conditions' => 'a.UnitId = recipe_item_master.UnitId '
                        ]

                 ];

        $fields = [
            'ItemId' => 'recipe_item_master.ItemId',
            'ItemName' => 'recipe_item_master.ItemName',
            'UnitId' => 'recipe_item_master.UnitId',
            'SLevel' => 'recipe_item_master.SafetyLevel',
            'RLevel' => 'recipe_item_master.RorderLevel',
            'Qty' => 'recipe_item_master.QtyInHand',
            'Unit' => 'a.UnitTitle',
        ];
        $allRecipItems = $this->paginate($recipeItemTable->connect()->find('all',array('fields' => $fields,'condition' => $conditions))
                    ->join($joins),['limit' => $limit, 'page' => $page]);
        $allItems = null;
        $itemCounter = 0;

        foreach ($allRecipItems as $recipeItems){
                $allItems[$itemCounter++] = new UploadDTO\RecipeItemMaterInsertDto(
                        $recipeItems->ItemName,
                        $recipeItems->UnitId,
                        $recipeItems->SLevel,
                        $recipeItems->RLevel,
                        $recipeItems->Qty,
                        $recipeItems->ItemId,
                        $recipeItems->Unit);
            }
            return $allItems;
    }
    *
    */

   public function getItemUnit($itemId) {
       return $this->getTableObj()->getUnit($itemId);
   }

   public function restoreItemQty($itemDetails) {
       return $this->getTableObj()->restoreQty($itemDetails);
   }

}


text:
package com.packtpub.felix.bookshelf.service.tui;

import java.util.HashSet;
import java.util.Set;

import org.apache.felix.service.command.Descriptor;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import com.packtpub.felix.bookshelf.inventory.api.Book;
import com.packtpub.felix.bookshelf.inventory.api.BookAlreadyExistsException;
import com.packtpub.felix.bookshelf.inventory.api.BookNotFoundException;
import com.packtpub.felix.bookshelf.inventory.api.InvalidBookException;
import com.packtpub.felix.bookshelf.service.api.BookshelfService;
import com.packtpub.felix.bookshelf.service.api.InvalidCredentialsException;

public class BookshelfServiceProxy {
	public static final String SCOPE = "book";
	public static final String[] FUNCTIONS = new String[] { "search", "add" };
	private BundleContext context;

	public BookshelfServiceProxy(BundleContext context) {
		this.context = context;
	}

	@Descriptor("Search books by author, title, or category")
	public Set<Book> search(
			@Descriptor("username") String username,
			@Descriptor("password") String password,
			@Descriptor("search on attribute: author, title, or category") String attribute,
			@Descriptor("match like (use % at the beginning or end of <like> for wild-card)") String filter)
			throws InvalidCredentialsException {
		BookshelfService service = lookupService();
		String sessionId = service.login(username, password.toCharArray());
		Set<String> results;
		if ("title".equals(attribute)) {
			results = service.searchBooksByTitle(sessionId, filter);
		} else if ("author".equals(attribute)) {
			results = service.searchBooksByAuthor(sessionId, filter);
		} else if ("category".equals(attribute)) {
			results = service.searchBooksByCategory(sessionId, filter);
		} else {
			throw new RuntimeException(
					"Invalid attribute, expecting one of { 'title', "
							+ "'author', 'category' } got '" + attribute + "'");
		}
		return getBooks(sessionId, service, results);
	}

	protected BookshelfService lookupService() {
		ServiceReference reference = context
				.getServiceReference(BookshelfService.class.getName());
		if (reference == null) {
			throw new RuntimeException(
					"BookshelfService not registered, cannot invoke "
							+ "operation");
		}
		BookshelfService service = (BookshelfService) this.context
				.getService(reference);
		if (service == null) {
			throw new RuntimeException(
					"BookshelfService not registered, cannot invoke "
							+ "operation");
		}
		return service;
	}

	private Set<Book> getBooks(String sessionId, BookshelfService service,
			Set<String> results) {
		Set<Book> books = new HashSet<Book>();
		for (String isbn : results) {
			Book book;
			try {
				book = service.getBook(sessionId, isbn);
				books.add(book);
			} catch (BookNotFoundException e) {
				System.err
						.println("ISBN " + isbn + " referenced but not found");
			}
		}
		return books;
	}

	@Descriptor("Search books by rating")
	public Set<Book> search(@Descriptor("username") String username,
			@Descriptor("password") String password,
			@Descriptor("search on attribute: rating") String attribute,
			@Descriptor("lower rating limit (inclusive)") int lower,
			@Descriptor("upper rating limit (inclusive)") int upper)
			throws InvalidCredentialsException {
		if (!"rating".equals(attribute)) {
			throw new RuntimeException(
					"Invalid attribute, expecting 'rating' got '" + attribute
							+ "'");
		}
		BookshelfService service = lookupService();
		String sessionId = service.login(username, password.toCharArray());
		Set<String> results = service.searchBooksByRating(sessionId, lower,
				upper);
		return getBooks(sessionId, service, results);
	}

	public String add(@Descriptor("username") String username,
			@Descriptor("password") String password,
			@Descriptor("ISBN") String isbn, @Descriptor("Title") String title,
			@Descriptor("Author") String author,
			@Descriptor("Category") String category,
			@Descriptor("Rating (0..10)") int rating)
			throws InvalidCredentialsException, BookAlreadyExistsException,
			InvalidBookException {
		BookshelfService service = lookupService();
		String sessionId = service.login(username, password.toCharArray());
		service.addBook(sessionId, isbn, title, author, category, rating);
		return isbn;
	}
}

redpajama_set_name: RedPajamaGithub


text:
import os
from urllib import parse as urlparse

from oslo_log import log as logging
from zvmconnector import connector

from oslo_utils import fileutils

from nova.api.metadata import base as instance_metadata
from nova import conf
from nova import exception
from nova.virt import configdrive

CONF = conf.CONF
LOG = logging.getLogger(__name__)

class ConnectorClient(object):
    """Request handler to zVM cloud connector"""

    def __init__(self, zcc_url, ca_file=None):
        _url = urlparse.urlparse(zcc_url)

        _ssl_enabled = False

        if _url.scheme == 'https':
            _ssl_enabled = True
        elif ca_file:
            LOG.warning("url is %(url)s which is not https "
                        "but ca_file is configured to %(ca_file)s",
                        {'url': zcc_url, 'ca_file': ca_file})

        if _ssl_enabled and ca_file:
            self._conn = connector.ZVMConnector(_url.hostname, _url.port,
                                                ssl_enabled=_ssl_enabled,
                                                verify=ca_file)
        else:
            self._conn = connector.ZVMConnector(_url.hostname, _url.port,
                                                ssl_enabled=_ssl_enabled,
                                                verify=False)

    def call(self, func_name, *args, **kwargs):
        results = self._conn.send_request(func_name, *args, **kwargs)

        if results['overallRC'] != 0:
            LOG.error("zVM Cloud Connector request %(api)s failed with "
               "parameters: %(args)s %(kwargs)s .  Results: %(results)s",
               {'api': func_name, 'args': str(args),
                'kwargs': str(kwargs),
                'results': str(results)})
            raise exception.ZVMConnectorError(results=results)

        return results['output']

def _get_instance_path(instance_uuid):
    instance_folder = os.path.join(os.path.normpath(CONF.instances_path),
                                   instance_uuid)
    fileutils.ensure_tree(instance_folder)
    return instance_folder

def _create_config_drive(context, instance_path, instance,
                         injected_files, network_info, admin_password):
    if CONF.config_drive_format != 'iso9660':
        raise exception.ConfigDriveUnsupportedFormat(
                        format=CONF.config_drive_format)

    LOG.debug('Using config drive', instance=instance)

    extra_md = {}
    if admin_password:
        extra_md['admin_pass'] = admin_password

    inst_md = instance_metadata.InstanceMetadata(instance,
                                                 content=injected_files,
                                                 extra_md=extra_md,
                                                 network_info=network_info)

    configdrive_iso = os.path.join(instance_path, 'cfgdrive.iso')
    LOG.debug('Creating config drive at %s', configdrive_iso,
              instance=instance)
    with configdrive.ConfigDriveBuilder(instance_md=inst_md) as cdb:
        cdb.make_drive(configdrive_iso)

    return configdrive_iso

# Prepare and create configdrive for instance
def generate_configdrive(context, instance, injected_files,
                         network_info, admin_password):
    # Create network configuration files
    LOG.debug('Creating config drive configuration files '
              'for instance: %s', instance.name, instance=instance)

    instance_path = _get_instance_path(instance.uuid)

    transportfiles = None
    if configdrive.required_by(instance):
        transportfiles = _create_config_drive(context, instance_path,
                                              instance,
                                              injected_files,
                                              network_info,
                                              admin_password)
    return transportfiles

def clean_up_file(filepath):
    if os.path.exists(filepath):
        os.remove(filepath)


text:
package eu.openanalytics.rsb.rservi;

import org.eclipse.statet.rj.servi.RServi;

/**
 * @author "Open Analytics <rsb.development@openanalytics.eu>"
 */
public interface ErrorableRServi extends RServi
{
    void resetError();

    void markError();

    boolean hasError();
}


text:
package base

import (
   "math/rand"
   "reflect"
   "runtime"
   "time"

   "github.com/eriq-augustine/goml/util"
)

var random *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()));
var maxProcs = runtime.GOMAXPROCS(0);
var machineMaxProcs = maxProcs;

func Seed(seed int64) {
   random = rand.New(rand.NewSource(seed));
}

func GetMaxProcs() int {
   return maxProcs;
}

// Set the maximum number of concurent goroutines a call to goml will use.
// Return the value that was actually used.
func SetMaxProcs(max int) int {
   maxProcs = util.MinInt(util.MaxInt(max, 0), machineMaxProcs);
   return maxProcs;
}

func TupleEquals(a Tuple, b Tuple) bool {
   return reflect.DeepEqual(a, b);
}

// Return a new tuple with the given type and data.
func NewTypedTuple(tupleType reflect.Type, data []interface{}, class interface{}) Tuple {
   var newTuple Tuple;

   if (tupleType == reflect.TypeOf(IntegerTuple{}) || tupleType == reflect.TypeOf(&IntegerTuple{})) {
      newTuple = NewIntTuple(data, class);
   } else if (tupleType == reflect.TypeOf(FloatTuple{}) || tupleType == reflect.TypeOf(&FloatTuple{})) {
      newTuple = NewNumericTuple(data, class);
   } else {
      newTuple = NewTuple(data, class);
   }

   return newTuple;
}

// Fisher–Yates (Sattolo variant).
func ShuffleTuples(slice []Tuple) {
   for i, _ := range(slice) {
      var j int = random.Intn(i + 1);
      slice[i], slice[j] = slice[j], slice[i];
   }
}

// Pull out tuples that match the given indexes.
func SelectTuples(tuples []Tuple, indexes []int) []Tuple {
   var rtn []Tuple = make([]Tuple, len(indexes));
   for i, chosenIndex := range(indexes) {
      rtn[i] = tuples[chosenIndex];
   }
   return rtn;
}

// Pull out tuples that match the given indexes.
func SelectNumericTuples(tuples []NumericTuple, indexes []int) []NumericTuple {
   var rtn []NumericTuple = make([]NumericTuple, len(indexes));
   for i, chosenIndex := range(indexes) {
      rtn[i] = tuples[chosenIndex];
   }
   return rtn;
}

// Shallow wrappers for util.FakeData().
// Wraps the output in NumericTuple.

func FakeDataDefault() []Tuple {
   data, classes := util.FakeDataDefault();

   var rtn []Tuple = make([]Tuple, len(data));
   for i, _ := range(data) {
      rtn[i] = NewFloatTuple(data[i], classes[i]);
   }

   return rtn;
}

func FakeData(numPoints int, numClasses int, numFeatures int, maxDistanceToCenter float64,
              rangeMin []float64, rangeMax []float64, seed int64) []Tuple {
   data, classes := util.FakeData(numPoints, numClasses, numFeatures, maxDistanceToCenter, rangeMin, rangeMax, seed);

   var rtn []Tuple = make([]Tuple, len(data));
   for i, _ := range(data) {
      rtn[i] = NewFloatTuple(data[i], classes[i]);
   }

   return rtn;
}

// Remove the classes from the tuples and return both the tuples and classes.
func StripClasses(tuples []Tuple) ([]Tuple, []Feature) {
   var rtnTuples []Tuple = make([]Tuple, len(tuples));
   var rtnClasses []Feature = make([]Feature, len(tuples));

   copy(rtnTuples, tuples);

   for i, _ := range(tuples) {
      rtnClasses[i] = rtnTuples[i].GetClass();
      rtnTuples[i].SetClass(nil);
   }

   return rtnTuples, rtnClasses;
}


text:
require 'hamlit/concerns/included'
require 'hamlit/concerns/registerable'
require 'hamlit/filters/coffee'
require 'hamlit/filters/css'
require 'hamlit/filters/erb'
require 'hamlit/filters/escaped'
require 'hamlit/filters/javascript'
require 'hamlit/filters/less'
require 'hamlit/filters/plain'
require 'hamlit/filters/preserve'
require 'hamlit/filters/ruby'
require 'hamlit/filters/sass'
require 'hamlit/filters/markdown'
require 'hamlit/filters/scss'

module Hamlit
  module Compilers
    module Filter
      extend Concerns::Included

      included do
        extend Concerns::Registerable

        define_options :format

        register :coffee,       Filters::Coffee
        register :coffeescript, Filters::Coffee
        register :css,          Filters::Css
        register :erb,          Filters::Erb
        register :escaped,      Filters::Escaped
        register :javascript,   Filters::Javascript
        register :less,         Filters::Less
        register :markdown,     Filters::Markdown
        register :plain,        Filters::Plain
        register :preserve,     Filters::Preserve
        register :ruby,         Filters::Ruby
        register :sass,         Filters::Sass
        register :scss,         Filters::Scss
      end

      def on_haml_filter(name, lines)
        ast = compile_filter(name, lines)
        compile(ast)
      end

      private

      def compile_filter(name, exp)
        self.class.find(name).new(options).compile(exp)
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Symfony2PluginSettings">
    <option name="directoryToWeb" value="public_html" />
    <option name="pluginEnabled" value="true" />
  </component>
</project>


text:
package com.intel.analytics.bigdl.nn.ops

import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.utils.Table
import com.intel.analytics.bigdl.nn.{Sum => SumLayer}

import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

class Sum[T: ClassTag, D: ClassTag](val keepDims: Boolean, val startFromZero: Boolean = false)
  (implicit ev: TensorNumeric[T], ev2: TensorNumeric[D])
  extends Operation[Table, Tensor[D], T] {

  private val sum: SumLayer[D] = SumLayer[D](squeeze = !keepDims)

  output = Tensor[D]()

  override def updateOutput(input: Table): Tensor[D] = {
    val data = input[Tensor[D]](1)
    val dims = input[Tensor[Int]](2)

    output.resizeAs(data).copy(data)

    val sumDims = if (dims.isEmpty) {
      return output
    } else if (dims.isScalar) {
      Array(if (startFromZero) dims.value() + 1 else dims.value())
    } else {
      require(dims.nDimension() == 1, s"Only accept 1D as dims, but now is ${dims.nDimension()}")
      val buffer = new ArrayBuffer[Int]()
      dims.apply1(a => {
        buffer.append(if (startFromZero) a + 1 else a)
        a
      })
      buffer.toArray.sortWith(_ > _)
    }

    var i = 0
    while(i < sumDims.length) {
      sum.changeSumDims(sumDims(i))
      val tmp = sum.updateOutput(output)
      output.resizeAs(tmp).copy(tmp)
      i += 1
    }

    output
  }

  override def getClassTagNumerics() : (Array[ClassTag[_]], Array[TensorNumeric[_]]) = {
    (Array[ClassTag[_]](scala.reflect.classTag[T], scala.reflect.classTag[D]),
      Array[TensorNumeric[_]](ev, ev2))
  }
}

object Sum {
  def apply[T: ClassTag, D: ClassTag](keepDims: Boolean = false, startFromZero: Boolean = false)
    (implicit ev: TensorNumeric[T], ev2: TensorNumeric[D]): Sum[T, D] =
    new Sum(keepDims, startFromZero)
}


text:
<?php

namespace common\modules\cms\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\modules\cms\models\Text;

/**
 * TextSearch represents the model behind the search form about `common\modules\cms\models\Text`.
 */
class TextSearch extends Text
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['name', 'text'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Text::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'text', $this->text]);

        return $dataProvider;
    }
}


text:
CRICTL User Guide
=================
This document presumes you already have `containerd` and `cri-containerd`
installed and running.

This document is for developers who wish to debug, inspect, and manage their pods,
containers, and container images.

Before generating issues against this document, `containerd`, `cri-containerd`,
or `crictl` please make sure the issue has not already been submitted.

## Install crictl
If you have not already installed crictl please install the version compatible
with the `cri-containerd` you are using. If you are a user, your deployment
should have installed crictl for you. If not, get it from your release tarball.
If you are a developer the current version of crictl is specified [here](../hack/utils.sh).
A helper command has been included to install the dependencies at the right version:
```console
$ make install.deps
```
* Note: The file named `/etc/crictl.yaml` is used to configure crictl
so you don't have to repeatedly specify the runtime sock used to connect crictl
to the container runtime:
```console
$ cat /etc/crictl.yaml
runtime-endpoint: /var/run/cri-containerd.sock
image-endpoint: /var/run/cri-containerd.sock
timeout: 10
debug: true
```

## Download and Inspect a Container Image
The pull command tells the container runtime to download a container image from
a container registry.
```console
$ crictl pull busybox
  ...
$ crictl inspecti busybox
  ... displays information about the image.
```

## Directly Load a Container Image
Another way to load an image into the container runtime is with the load
command. With the load command you inject a container image into the container
runtime from a file. First you need to create a container image tarball. For
example to create an image tarball for a pause container using Docker:
```console
$ docker pull k8s.gcr.io/pause-amd64:3.1
  3.1: Pulling from pause-amd64
  67ddbfb20a22: Pull complete
  Digest: sha256:59eec8837a4d942cc19a52b8c09ea75121acc38114a2c68b98983ce9356b8610
  Status: Downloaded newer image for k8s.gcr.io/pause-amd64:3.1
$ docker save k8s.gcr.io/pause-amd64:3.1 -o pause.tar
```
Then load the container image into the container runtime:
```console
$ sudo ctrcri load pause.tar
  Loaded image: k8s.gcr.io/pause-amd64:3.1
```
List images and inspect the pause image:
```console
$ sudo crictl images
IMAGE                       TAG                 IMAGE ID            SIZE
docker.io/library/busybox   latest              f6e427c148a76       728kB
k8s.gcr.io/pause-amd64      3.1                 da86e6ba6ca19       746kB
$ sudo crictl inspecti da86e6ba6ca19
  ... displays information about the pause image.
$ sudo crictl inspecti k8s.gcr.io/pause-amd64:3.1
  ... displays information about the pause image.
```

## Run a pod sandbox (using a config file)
```console
$ cat sandbox-config.json
{
    "metadata": {
        "name": "nginx-sandbox",
        "namespace": "default",
        "attempt": 1,
        "uid": "hdishd83djaidwnduwk28bcsb"
    },
    "linux": {
    }
}

$ crictl runp sandbox-config.json
e1c83b0b8d481d4af8ba98d5f7812577fc175a37b10dc824335951f52addbb4e
$ crictl pods
PODSANDBOX ID       CREATED             STATE               NAME               NAMESPACE          ATTEMPT
e1c83b0b8d481       2 hours ago         SANDBOX_READY       nginx-sandbox      default            1
$ crictl inspectp e1c8
  ... displays information about the pod and the pod sandbox pause container.
```
* Note: As shown above, you may use truncated IDs if they are unique.
* Other commands to manage the pod include `stops ID` to stop a running pod and
`rmp ID` to remove a pod sandbox.

## Create and Run a Container in a Pod Sandbox (using a config file)
```console
$ cat sandbox-config.json
{
    "metadata": {
        "name": "nginx-sandbox",
        "namespace": "default",
        "attempt": 1,
        "uid": "hdishd83djaidwnduwk28bcsb"
    },
    "linux": {
    }
}

$ cat container-config.json
{
  "metadata": {
      "name": "busybox"
  },
  "image":{
      "image": "busybox"
  },
  "command": [
      "top"
  ],
  "linux": {
  }
}

$ crictl create e1c83 container-config.json sandbox-config.json
0a2c761303163f2acaaeaee07d2ba143ee4cea7e3bde3d32190e2a36525c8a05
$ crictl ps
CONTAINER ID        IMAGE               CREATED             STATE               NAME                ATTEMPT
0a2c761303163       docker.io/busybox   2 hours ago         CONTAINER_CREATED   busybox             0
$ crictl start 0a2c
0a2c761303163f2acaaeaee07d2ba143ee4cea7e3bde3d32190e2a36525c8a05
$ crictl ps
CONTAINER ID        IMAGE               CREATED             STATE               NAME                ATTEMPT
0a2c761303163       docker.io/busybox   2 hours ago         CONTAINER_RUNNING   busybox             0
$ crictl inspect 0a2c7
  ... show detailed information about the container
```
## Exec a Command in the Container
```console
$ crictl exec -i -t 0a2c ls
bin   dev   etc   home  proc  root  sys   tmp   usr   var
```
## Display Stats for the Container
```console
$ crictl stats
CONTAINER           CPU %               MEM                 DISK                INODES
0a2c761303163f      0.00                991.2kB             16.38kB             6
```
* Other commands to manage the container include `stop ID` to stop a running
container and `rm ID` to remove a container.
## Display Version Information
```console
$ crictl version
Version:  0.1.0
RuntimeName:  cri-containerd
RuntimeVersion:  1.0.0-alpha.1-167-g737efe7-dirty
RuntimeApiVersion:  0.0.0
```
## Display Status & Configuration Information about Containerd & CRI-Containerd
```console
$ crictl info
{
  "status": {
    "conditions": [
      {
        "type": "RuntimeReady",
        "status": true,
        "reason": "",
        "message": ""
      },
      {
        "type": "NetworkReady",
        "status": true,
        "reason": "",
        "message": ""
      }
    ]
  },
  "config": {
    "containerd": {
      "rootDir": "/var/lib/containerd",
      "snapshotter": "overlayfs",
      "endpoint": "/run/containerd/containerd.sock",
      "runtime": "io.containerd.runtime.v1.linux"
    },
    "cni": {
      "binDir": "/opt/cni/bin",
      "confDir": "/etc/cni/net.d"
    },
    "socketPath": "/var/run/cri-containerd.sock",
    "rootDir": "/var/lib/cri-containerd",
    "streamServerPort": "10010",
    "sandboxImage": "gcr.io/google_containers/pause:3.0",
    "statsCollectPeriod": 10,
    "oomScore": -999,
    "enableProfiling": true,
    "profilingPort": "10011",
    "profilingAddress": "127.0.0.1"
  }
}
```
## More Information
See [here](https://github.com/kubernetes-incubator/cri-tools/blob/master/docs/crictl.md)
for information about crictl.


text:
#ifndef ELFIO_ARRAY_HPP
#define ELFIO_ARRAY_HPP

#include <algorithm>

namespace ELFIO {

//------------------------------------------------------------------------------
template <class S, typename T> class array_section_accessor_template
{
  public:
    //------------------------------------------------------------------------------
    explicit array_section_accessor_template( const elfio& elf_file,
                                              S*           section )
        : elf_file( elf_file ), array_section( section )
    {
    }

    //------------------------------------------------------------------------------
    Elf_Xword get_entries_num() const
    {
        Elf_Xword entry_size = sizeof( T );
        return array_section->get_size() / entry_size;
    }

    //------------------------------------------------------------------------------
    bool get_entry( Elf_Xword index, Elf64_Addr& address ) const
    {
        if ( index >= get_entries_num() ) { // Is index valid
            return false;
        }

        const endianess_convertor& convertor = elf_file.get_convertor();

        const T temp = *reinterpret_cast<const T*>( array_section->get_data() +
                                                    index * sizeof( T ) );
        address      = convertor( temp );

        return true;
    }

    //------------------------------------------------------------------------------
    void add_entry( Elf64_Addr address )
    {
        const endianess_convertor& convertor = elf_file.get_convertor();

        T temp = convertor( (T)address );
        array_section->append_data( reinterpret_cast<char*>( &temp ),
                                    sizeof( temp ) );
    }

  private:
    //------------------------------------------------------------------------------
    const elfio& elf_file;
    S*           array_section;
};

template <typename T = Elf32_Word>
using array_section_accessor = array_section_accessor_template<section, T>;
template <typename T = Elf32_Word>
using const_array_section_accessor =
    array_section_accessor_template<const section, T>;

} // namespace ELFIO

#endif // ELFIO_ARRAY_HPP


text:
require "spec_helper"
require "support/shared/integration/integration_helper"
require "chef/mixin/shell_out"

describe "notifications" do
  include IntegrationSupport
  include Chef::Mixin::ShellOut

  let(:chef_dir) { File.expand_path("../../..", __dir__) }
  let(:chef_client) { "bundle exec chef-client --minimal-ohai" }

  when_the_repository "notifies a nameless resource" do
    before do
      directory "cookbooks/x" do
        file "recipes/default.rb", <<-EOM
          apt_update do
            action :nothing
          end
          notify_group "foo" do
            notifies :nothing, 'apt_update', :delayed
            action :run
          end
          notify_group "bar" do
            notifies :nothing, 'apt_update[]', :delayed
            action :run
          end
        EOM
      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      # our delayed notification should run at the end of the parent run_context after the baz resource
      expect(result.stdout).to match(/\* apt_update\[\] action nothing \(skipped due to action :nothing\)\s+\* notify_group\[foo\] action run\s+\* notify_group\[bar\] action run\s+\* apt_update\[\] action nothing \(skipped due to action :nothing\)/)
      result.error!
    end
  end

  when_the_repository "notifies delayed one" do
    before do
      directory "cookbooks/x" do

        file "resources/notifying_test.rb", <<~EOM
          unified_mode true

          default_action :run
          provides :notifying_test
          resource_name :notifying_test

          action :run do
            notify_group "bar" do
              notifies :write, 'log[foo]', :delayed
              action :run
            end
          end
        EOM

        file "recipes/default.rb", <<~EOM
          log "foo" do
            action :nothing
          end
          notifying_test "whatever"
          log "baz"
        EOM

      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      # our delayed notification should run at the end of the parent run_context after the baz resource
      expect(result.stdout).to match(/\* notify_group\[bar\] action run\s+\* log\[baz\] action write\s+\* log\[foo\] action write/)
      result.error!
    end
  end

  when_the_repository "notifies delayed two" do
    before do
      directory "cookbooks/x" do

        file "resources/notifying_test.rb", <<~EOM
          unified_mode true

          default_action :run
          provides :notifying_test
          resource_name :notifying_test

          action :run do
            notify_group "bar" do
              notifies :write, 'log[foo]', :delayed
              action :run
            end
          end
        EOM

        file "recipes/default.rb", <<~EOM
          log "foo" do
            action :nothing
          end
          notifying_test "whatever"
          notify_group "baz" do
            notifies :write, 'log[foo]', :delayed
            action :run
          end
        EOM

      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      # our delayed notification should run at the end of the parent run_context after the baz resource
      expect(result.stdout).to match(/\* notify_group\[bar\] action run\s+\* notify_group\[baz\] action run\s+\* log\[foo\] action write/)
      # and only run once
      expect(result.stdout).not_to match(/\* log\[foo\] action write.*\* log\[foo\] action write/)
      result.error!
    end
  end

  when_the_repository "notifies delayed three" do
    before do
      directory "cookbooks/x" do

        file "resources/notifying_test.rb", <<~EOM
          unified_mode true

          default_action :run
          provides :notifying_test
          resource_name :notifying_test

          action :run do
            notify_group "bar" do
              notifies :write, 'log[foo]', :delayed
              action :run
            end
          end
        EOM

        file "recipes/default.rb", <<~EOM
          log "foo" do
            action :nothing
          end
          notify_group "quux" do
            notifies :write, 'log[foo]', :delayed
            notifies :write, 'log[baz]', :delayed
            action :run
          end
          notifying_test "whatever"
          log "baz"
        EOM

      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      # the delayed notification from the sub-resource is de-duplicated by the notification already in the parent run_context
      expect(result.stdout).to match(/\* notify_group\[quux\] action run\s+\* notifying_test\[whatever\] action run\s+\* notify_group\[bar\] action run\s+\* log\[baz\] action write\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
      # and only run once
      expect(result.stdout).not_to match(/\* log\[foo\] action write.*\* log\[foo\] action write/)
      result.error!
    end
  end

  when_the_repository "notifies delayed four" do
    before do
      directory "cookbooks/x" do
        file "recipes/default.rb", <<~EOM
          log "foo" do
            action :nothing
          end
          notify_group "bar" do
            notifies :write, 'log[foo]', :delayed
            action :run
          end
          notify_group "baz" do
            notifies :write, 'log[foo]', :delayed
            action :run
          end
        EOM

      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      # the delayed notification from the sub-resource is de-duplicated by the notification already in the parent run_context
      expect(result.stdout).to match(/\* notify_group\[bar\] action run\s+\* notify_group\[baz\] action run\s+\* log\[foo\] action write/)
      # and only run once
      expect(result.stdout).not_to match(/\* log\[foo\] action write.*\* log\[foo\] action write/)
      result.error!
    end
  end

  when_the_repository "notifies immediately" do
    before do
      directory "cookbooks/x" do

        file "resources/notifying_test.rb", <<~EOM
          unified_mode true

          default_action :run
          provides :notifying_test
          resource_name :notifying_test

          action :run do
            notify_group "bar" do
              notifies :write, 'log[foo]', :immediately
              action :run
            end
          end
        EOM

        file "recipes/default.rb", <<~EOM
          log "foo" do
            action :nothing
          end
          notifying_test "whatever"
          log "baz"
        EOM

      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      expect(result.stdout).to match(/\* notify_group\[bar\] action run\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
      result.error!
    end
  end

  when_the_repository "uses old notifies syntax" do
    before do
      directory "cookbooks/x" do

        file "resources/notifying_test.rb", <<~EOM
          unified_mode true

          default_action :run
          provides :notifying_test
          resource_name :notifying_test

          action :run do
            notify_group "bar" do
              notifies :write, resources(log: "foo"), :immediately
              action :run
            end
          end
        EOM

        file "recipes/default.rb", <<~EOM
          log "foo" do
            action :nothing
          end
          notifying_test "whatever"
          log "baz"
        EOM

      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      expect(result.stdout).to match(/\* notify_group\[bar\] action run\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
      result.error!
    end
  end

  when_the_repository "does not have a matching resource" do
    before do
      directory "cookbooks/x" do

        file "resources/notifying_test.rb", <<~EOM
          unified_mode true

          default_action :run
          provides :notifying_test
          resource_name :notifying_test

          action :run do
            notify_group "bar" do
              notifies :write, "log[foo]"
              action :run
            end
          end
        EOM

        file "recipes/default.rb", <<~EOM
          notifying_test "whatever"
          log "baz"
        EOM

      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      expect(result.stdout).to match(/Chef::Exceptions::ResourceNotFound/)
      expect(result.exitstatus).not_to eql(0)
    end
  end

  when_the_repository "encounters identical resources in parent and child resource collections" do
    before do
      directory "cookbooks/x" do

        file "resources/cloning_test.rb", <<~EOM
          unified_mode true

          default_action :run
          provides :cloning_test
          resource_name :cloning_test

          action :run do
            log "bar" do
              level :info
            end
          end
        EOM

        file "recipes/default.rb", <<~EOM
          log "bar" do
            level :warn
          end

          cloning_test "whatever"
        EOM

      end
    end

    it "should complete with success" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      expect(result.stdout).not_to match(/CHEF-3694/)
      result.error!
    end
  end

  when_the_repository "has resources that have arrays as the name" do
    before do
      directory "cookbooks/x" do
        file "recipes/default.rb", <<-EOM
          log [ "a", "b" ] do
            action :nothing
          end

          notify_group "doit" do
            notifies :write, "log[a, b]"
            action :run
          end
        EOM
      end
    end

    it "notifying the resource should work" do
      file "config/client.rb", <<~EOM
        local_mode true
        cookbook_path "#{path_to("cookbooks")}"
        log_level :warn
      EOM

      result = shell_out("#{chef_client} -c \"#{path_to("config/client.rb")}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
      expect(result.stdout).to match(/\* log\[a, b\] action write/)
      result.error!
    end

  end
end


text:
global.Promise = global.Promise || require('bluebird');

var NetrixServer = require('./lib/server');
var NetrixClient = require('./lib/client')

module.exports = {
  NetrixServer: NetrixServer,
  NetrixClient: NetrixClient,
  createServer: function(opts) {
    var server = new NetrixServer(opts);
    return server.start();
  }
}


text:
var Client = require("./../lib/index");

var gh = new Client({
  Promise: require('bluebird')
});

function getAllOrgRepos(orgName) {
  var repos = [];

  function pager(res) {
    repos = repos.concat(res);
    if (gh.hasNextPage(res)) {
      return gh.getNextPage(res)
        .then(pager);
    }
    return repos;
  }

  return gh.repos.getForOrg({ org: orgName })
    .then(pager);
}

getAllOrgRepos('organization')
  .then(function(orgRepos) {
    console.log(orgRepos);
  });


text:
namespace Dike.Core.Application.Features
{
    using Conditions;
    using Dike.Core.Collections.Extensions;
    using System;
    using System.Collections.Generic;
    using System.Collections.Immutable;

    /// <summary>
    /// Defines a feature of the application. A feature can be used in a multi-tenant application to enable disable some application features depending on editions and tenants.
    /// </summary>
    public class Feature
    {
        #region Fields

        private readonly List<Feature> _children;
        private Feature _parent;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Feature"/> class.
        /// </summary>
        /// <param name="name">The name of the feature.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <param name="displayName">The display name of the feature.</param>
        /// <param name="description">The description of the feature.</param>
        /// <param name="scope">The scope of the feature.</param>
        /// <param name="inputType">The input type.</param>
        /// <exception cref="ArgumentNullException"><paramref name="name"/> can not be <c>null</c>.</exception>
        /// <exception cref="ArgumentException"><paramref name="name"/> can not be empty or contain only whitespace.</exception>
        public Feature(
            string name,
            string defaultValue,
            Localization.ILocalizableString displayName = null,
            Localization.ILocalizableString description = null,
            FeatureScopes scope = FeatureScopes.All,
            UI.Inputs.IInputType inputType = null)
        {
            name.Requires(nameof(name)).IsNotNullOrWhiteSpace();

            Name = name;
            DisplayName = displayName;
            Description = description;
            Scope = scope;
            DefaultValue = defaultValue;
            InputType = inputType ?? new UI.Inputs.CheckboxInputType();

            _children = new List<Feature>();
            Attributes = new Dictionary<string, object>();
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// Gets the attributes objects related to this feature.
        /// </summary>
        /// <value>The attributes objects related to this feature.</value>
        public IDictionary<string, object> Attributes
        {
            get;
        }

        /// <summary>
        /// Gets the child features.
        /// </summary>
        /// <value>A read only list of child features.</value>
        public IReadOnlyList<Feature> Children
            => _children.ToImmutableList();

        /// <summary>
        /// Gets or sets the default value of the feature. This value is used if feature's value is not defined for current edition or tenant.
        /// </summary>
        /// <value>The default value of the feature.</value>
        public string DefaultValue
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the description for this feature.
        /// </summary>
        /// <value>The description for this feature.</value>
        public Localization.ILocalizableString Description
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the display name. This can be used to show the feature to the user.
        /// </summary>
        /// <value>The display name.</value>
        public Localization.ILocalizableString DisplayName
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the input type. This can be used to prepare an input for changing this feature's value.
        /// </summary>
        /// <value>The input type.</value>
        public UI.Inputs.IInputType InputType
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the unique feature name.
        /// </summary>
        /// <value>The unique feature name.</value>
        public string Name
        {
            get;
        }

        /// <summary>
        /// Gets the parent of this feature if one exists. If set, this feature can be enabled only if parent is enabled.
        /// </summary>
        /// <value>The parent of this feature if one exists.</value>
        public Feature Parent
            => _parent;

        /// <summary>
        /// Gets or sets the scope.
        /// </summary>
        /// <value>The scope.</value>
        public FeatureScopes Scope
        {
            get;
            set;
        }

        #endregion Properties

        #region Indexers

        /// <summary>
        /// Gets or sets the <see cref="object"/> with the specified key. Gets null if given key does not exists. This is a shortcut for <see cref="Attributes"/> dictionary.
        /// </summary>
        /// <param name="key">The key value of the object.</param>
        /// <returns>The object related to the key value.</returns>
        public object this[string key]
        {
            get
                => Attributes.GetOrDefault(key);

            set
                => Attributes[key] = value;
        }

        #endregion Indexers

        #region Methods

        /// <summary>
        /// Creates and add the child feature.
        /// </summary>
        /// <param name="name">The name of the feature.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <param name="displayName">The display name of the feature.</param>
        /// <param name="description">The description of the feature.</param>
        /// <param name="scope">The scope of the feature.</param>
        /// <param name="inputType">The input type.</param>
        /// <returns>The added child feature.</returns>
        public Feature CreateChildFeature(
            string name,
            string defaultValue,
            Localization.ILocalizableString displayName = null,
            Localization.ILocalizableString description = null,
            FeatureScopes scope = FeatureScopes.All,
            UI.Inputs.IInputType inputType = null)
        {
            Feature feature = new Feature(name, defaultValue, displayName, description, scope, inputType)
            {
                _parent = this,
            };
            _children.Add(feature);
            return feature;
        }

        /// <summary>
        /// Returns a <see cref="string" /> that represents this instance.
        /// </summary>
        /// <returns>A <see cref="string" /> that represents this instance.</returns>
        public override string ToString()
            => $"[Feature: {Name}]";

        #endregion Methods
    }
}


text:
package org.apache.wiki.api.exceptions;

/**
 *  A generic PageFilter exception.
 *
 *  @since 2.1.112
 */
public class FilterException extends WikiException {

    private static final long serialVersionUID = -490652869936406653L;

    /**
     *  Constructs an exception.
     *
     *  @param msg exception message.
     */
    public FilterException( final String msg ) {
        super( msg );
    }

}


text:
#include <util/testing_utils.hpp>

namespace graphlab {

////////////////////////////////////////////////////////////////////////////////

static std::vector<std::string> __list_of_directories_to_clean_up;
static mutex __list_of_directories_lock;
static bool archive_directory_deleter_added = false;

void _archive_directory_deleter() {

  std::lock_guard<mutex> lgaurd(__list_of_directories_lock);

  for(const std::string& dir : __list_of_directories_to_clean_up) {
    try {
      boost::filesystem::remove_all(dir);
    } catch(...) {
      // Ignore it.
    }
  }
}

/** The directories we use for our temporary archives should be unique
 *  and everything, but we don't want hundreds of these lying around.
 *  Thus add them to a list with which we delete when the program
 *  exits; this function does that.
 */
void _add_directory_to_deleter(const std::string& name) {

  __list_of_directories_lock.lock();

  if(!archive_directory_deleter_added) {
    std::atexit(_archive_directory_deleter);
    archive_directory_deleter_added = true;
  }

  __list_of_directories_to_clean_up.push_back(name);

  __list_of_directories_lock.unlock();
}

/** Make a unique directory name.
 */
std::string _get_unique_directory(const std::string& file, size_t line) {

  std::ostringstream ss;

  ss << "./archive_" << getpid() << "_";

  ss  << "t" << thread::thread_id() << "__";

  ss << random::fast_uniform<size_t>(0, size_t(-1));

  return ss.str();
}

}


text:
package org.apache.camel.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.camel.Exchange;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.util.ExchangeHelper;

/**
 * The text based data format supporting
 * charset encoding.
 *
 * @version
 */
public class StringDataFormat implements DataFormat {

    private final String charset;

    public StringDataFormat(String charset) {
        this.charset = charset;
    }

    public void marshal(Exchange exchange, Object graph, OutputStream stream) throws IOException {
        String text = ExchangeHelper.convertToType(exchange, String.class, graph);

        byte[] bytes;
        if (charset != null) {
            bytes = text.getBytes(charset);
        } else {
            bytes = text.getBytes();
        }
        stream.write(bytes);
    }

    public Object unmarshal(Exchange exchange, InputStream stream) throws IOException {
        byte[] bytes = ExchangeHelper.convertToType(exchange, byte[].class, stream);

        String answer;
        if (charset != null) {
            answer = new String(bytes, charset);
        } else {
            answer = new String(bytes);
        }

        return answer;
    }

}


text:
require 'pathname'
require 'logger'
require 'rack/utils'

require 'stringio'
require 'open3'

# require 'nokogiri'

module Repertoire
  module Assets

    #
    # Rack middleware to construct, interpolate, and cache js + css manifests
    #
    class Manifest

      COMPRESSOR_PATH = Pathname.new(__FILE__).dirname + '../../vendor/yuicompressor-2.4.2.jar'
      COMPRESSOR_CMD  = "java -jar #{COMPRESSOR_PATH} --type %s --charset utf-8"

      # regular expression for HTML 4.0 DTD through the HTML & HEAD elements
      HTML_HEAD       = %r{^(\s*<\s*!DOCTYPE[^>]*>)?\s*<\s*HTML[^>]*>\s*<\s*HEAD[^>]*>.*?(?=</\s*HEAD[^>]*>)}im
      HEADER_BUFFER   = 1000                  # upper length limit for HTML_HEAD

      # Initialize the rack manifest middleware.
      #
      # === Parameters
      # :delegate::
      #    The next rack app in the filter chain
      # :processor::
      #    The Repertoire Assets processor singleton
      # :options::
      #    Hash of configuration options
      # :logger::
      #    Framework's logger - defaults to STDERR
      #
      # ---
      def initialize(delegate, processor, options, logger=nil)
        @delegate  = delegate
        @processor = processor
        @options   = options
        @logger    = logger || Logger.new(STDERR)
      end

      # The core rack call to filter an http request. If the wrapped application
      # returns an html page, the manifest is converted to <script> and <link>
      # tags and interpolated into the <head>.
      #
      # For the middleware's purposes, an "html page" is
      #
      # (1) mime-type "text/html"
      # (2) contains a <head> element (i.e. not an ajax html fragment)
      #
      # Currently, html manipulation is done using a basic HTML 4.0-compliant
      # filter parser.  It is simple and quite efficient.
      #
      # ---
      def call(env)
        dup._call(env)
      end

      def _call(env)
        # get application's response
        status, headers, body = @delegate.call(env)

        # only reference manifest in html files
        if /^text\/html/ === headers["Content-Type"]
          # for html & html fragments, attempt to interpolate manifest
          @path_info = Rack::Utils.unescape(env["PATH_INFO"])
          @body, body = body, self
        end

        [status, headers, body]
      end

      # Apply a simple stream-based html 'filter parser' that conforms to the
      # HTML 4.0 DTD to the client application's output, interpolating the html
      # manifest into ^<doctype...>?<html...><head> (if it occurs within the first
      # HEADER_BUFFER characters).
      #
      # HTML fragments are passed through unchanged.
      #
      # ---
      def each(&block)
        #
        # N.B. Processing HTML using regular expressions is notoriously error-prone.
        #      However, after much consideration I decided that conforming to the
        #      HTML 4.0 DTD through <html><head> was sufficiently simple, and the
        #      alternatives of SAX and DOM too heavy weight for use server-side on
        #      every outgoing HTML page.  For posterity, however, here is the code
        #      written in nokogiri and DOM:
        #
        #      dom  = Nokogiri::HTML(body.to_s)
        #      head = dom.css('head').children
        #      unless head.empty?
        #        head.before(html_manifest)
        #        body = dom.to_html
        #      end
        #
        prefix = ""
        @body.each do |chunk|
          if prefix == nil                       # already interpolated manifest
            yield chunk
          elsif prefix.size < HEADER_BUFFER      # collecting enough data to interpolate manifest
            prefix << chunk
          else                                   # attempt to interpolate one time only
            # regular expression will match only "complete" html 4.0 documents
            # fragments and all others will pass through unchanged
            prefix << chunk
            yield interpolate(prefix)
            prefix = nil                         # done interpolating
          end
        end

        # process single chunks
        yield interpolate(prefix) unless prefix == nil
      end

      # If the manifest can be interpolated, then do so
      #
      def interpolate(text)
        text.gsub(HTML_HEAD) do |head|
          @logger.debug "Interpolating manifest into #{@path_info}"
          "#{head}#{html_manifest}"
        end
      end

      # Construct an HTML fragment containing <script> and <link> tags corresponding
      # to the asset files in the manifest.
      #
      # To speed loading, css files are listed at the top.  Javascript files are listed
      # in order of their dependency requirements.  Because browsers block javascript
      # execution during the evaluation of a <script> element, the files will load in
      # appropriate order.
      #
      # If the :precache option is selected, javascript and css will already
      # exist in a digest at the application public root.  In this case, we only
      # generate a single <script> and <link> for each digest file.
      #
      # ---- Returns
      #    A string containing the HTML fragment.
      #
      # ---
      def html_manifest
        html = []
        path_prefix = @options[:path_prefix] || ''

        # reference digest files when caching
        if @options[:precache]
          digest_uri = "#{path_prefix}/#{@options[:digest_basename]}"
          html << "<link rel='stylesheet' type='text/css' href='#{digest_uri}.css'/>"
          html << "<script language='javascript' type='text/javascript' src='#{digest_uri}.js'></script>"
        else
          manifest = @processor.manifest

          # output css links first since they load asynchronously
          manifest.grep(/\.css$/).each do |uri|
            html << "<link rel='stylesheet' type='text/css' href='#{path_prefix}#{cache_bust uri}'/>"
          end

          # script requires load synchronously, in order of dependencies
          manifest.grep(/\.js$/).each do |uri|
            html << "<script language='javascript' type='text/javascript' src='#{path_prefix}#{cache_bust uri}'></script>"
          end
        end

        html.join("\n")
      end

      # Generate a URL with the file's modification time appended.  This makes browsers reload when a
      # static asset changes.
      #
      # ---- Returns
      #    A string containing the complete uri
      #
      # ---
      def cache_bust(uri)
        mtime = @processor.provided[uri].mtime.to_i
        "#{uri}?#{mtime}"
      end

      # Collect all of the required js and css files from their current locations
      # in gems and bundle them together into digest files stored at the application
      # public root.  Thereafter, the web server will serve them directly.
      #
      # If the :compress option is on, the YUI compressor is run on the
      # digest files.
      #
      # Urls in CSS files are rewritten to account for the file's new URI.
      #
      # ---
      def precache!
        root     = Pathname.new( @options[:cache_root] ).realpath
        rewrites = {}

        precache_by_type(root, 'css') do |uri, code|
          # rewrite urls in css files from digest's uri at root
          # see http://www.w3.org/TR/CSS21/syndata.html#uri
          code.gsub(/url\(\s*['"]?(.*?)['"]?\s*\)/) do
            (rewrites[uri] ||= []) << $1
            "url(%s%s)" % [ @options[:path_prefix], (Pathname.new(uri).dirname + $1).cleanpath ]
          end
        end
        precache_by_type(root, 'js')

        rewrites.each { |uri, rewritten| @logger.info "Rewrote #{ rewritten.size } urls in #{ uri }" }
      end

      private

      def precache_by_type(root, type, &block)
        digest   = Pathname.new(root) + "#{@options[:digest_basename]}.#{type}"
        uris     = @processor.manifest.grep(/\.#{type}$/)
        provided = @processor.provided

        # N.B. application servers often start many processes simultaneously
        #      only first process will write the digests since it keeps files open
        return if digest.exist? && !digest.zero? && !@processor.stale?(digest.mtime)

        File.open(digest, 'w') do |f|
          bundled = Manifest.bundle(uris, provided) do |*args|
            yield(*args) if block_given?
          end
          bundled = Manifest.compress(bundled, type, @logger) if @options[:compress]
          f.write(bundled)
          @logger.info "Cached #{digest}"
        end
      end

      class << self

        # Bundle all of the provided files of a given type into a single
        # string.  If a block is given, file contents are yielded to it.
        #
        # In the future, this will return a stream.
        #
        # ==== Parameters
        # ::uris:
        #    The processor's manifest of uris for a given type, in order
        # ::provided:
        #    The processor's hash of provided uri -> path pairs
        #
        # ==== Returns
        #  The bundled files, as a string.
        # ---
        def bundle(uris, provided, &block)
          result = ""
          uris.map do |uri|
            path     = provided[uri]
            contents = File.read(path)
            contents = yield(uri, contents) || contents if block_given?

            result << "/* File: #{path} */\n"
            result << contents
            result << "\n\n"
          end

          result
        end

        # Utility compress files using YUI compressor.
        #
        # ==== Parameters
        # ::source:
        #    The code to be compressed
        # ::type:
        #    The type - js or css
        #
        # ==== Returns
        #  The compressed code, or source if compression failed
        # ---
        def compress(source, type, logger)
          stream = StringIO.new(source)
          Open3.popen3(COMPRESSOR_CMD % type) do |stdin, stdout, stderr|
            begin
              while buffer = stream.read(4096)
                stdin.write(buffer)
              end
              stdin.close
              compressed = stdout.read

              if !source.empty?
                raise "No result" if compressed.empty?
                ratio = 100.0 * (source.length - compressed.length) / source.length
              end
              logger.info "Digest #{type} compression %i%% to (%ik)" %
                                     [ratio || 0, compressed.length / 1024 ]

              return compressed
            rescue Exception => e
              logger.warn("Could not compress: #{e.message} (using #{COMPRESSOR_CMD % type})")
# CWY 13/11/2010.  Obscure errors with OS X new Java install hanging here...
#              logger.warn(stderr.read)
              logger.warn("Reverting to uncompressed digest")
              return source
            end
          end
        end
      end
    end
  end
end


text:
title:  Putovanje duže od hiljadu milja
date:   07/09/2018
---

**Istraživanje (Dela 18,23)**

**Zaključak**

Dugo putovanje počinje jednim korakom. Hristos je lično otpočeo hrišćansko putovanje i prepustio ga svojim sledbenicima kad se vazneo na nebo. Apostoli su bili prvi Hristovi sledbenici i preuzeli su odgovornost da odnesu evanđelje do različitih mesta i naroda. Pavle je proputovao skoro 2.500 kilometara (1.500 milja) da bi objavio evanđelje u Efesu, Korintu, Jerusalimu, i na mnogim drugim mestima. Šta ti i ja činimo da bismo dovršili misionsko delo?

**Razmotrite**

Prihvatite izazov da se pridružite kratkom misionskom putovanju tokom raspusta ili odmora. Kao mladi misionar, razmislite šta biste mogli da učinite za Isusa u roku od dve, četiri, ili šest sedmica.

Izgrađujte svoju veru tako što ćete istraživati druge delove Biblije koji govore o ostalim apostolima uključenim u misionski rad. Primenite njihove principe i osobine da biste vi danas postali bolji misionar.

Napravite akronim od reči MISIONAR. Za svako slovo pronađite neku reč koja opisuje poniznog vođu. Na primer, slovo S – kao Sluga.

Potražite na internetu imena današnjih misionara i čitajte o njihovim dostignućima. Šta možete naučiti od tih ljudi, a što će vam pomoći da postanete bolji vođa?

Intervjuišite više ljudi postavljajući im pitanje šta misle o misionskom radu lokalno i u inostranstvu. Na osnovu njihovih mišljenja, donesite odluku da li da pođete na neko lokalno misionsko putovanje ili u inostranstvo.

Upotrebite savremenu tehnologiju u misionskom radu. Razmislite kako biste mogli da iskoristite društvene mreže kao što su Fejsbuk, Instagram, Votsap i druge da biste postigli misionske ciljeve, kako lokalno, tako i na internacionalnom planu.

**POVEŽITE**

Matej 28,16-20 u nekom savremenom prevodu.

Elen G. Vajt, Apostolska crkva – Hristovim tragom, 27. poglavlje, "Efes".

Gorden R. Doss, The Challenges of Adventist Discipleship  (https://bit.ly/2M4pLvl)

*Semjuel Očieng, Ndiva, Kenija*


text:
#include "login-common.h"
#include "array.h"
#include "ioloop.h"
#include "istream.h"
#include "ostream.h"
#include "base64.h"
#include "str.h"
#include "str-sanitize.h"
#include "safe-memset.h"
#include "client.h"
#include "client-authenticate.h"
#include "imap-resp-code.h"
#include "imap-quote.h"
#include "imap-proxy.h"

#include <stdlib.h>

enum imap_proxy_state {
	IMAP_PROXY_STATE_NONE,
	IMAP_PROXY_STATE_BANNER,
	IMAP_PROXY_STATE_ID,
	IMAP_PROXY_STATE_STARTTLS,
	IMAP_PROXY_STATE_CAPABILITY,
	IMAP_PROXY_STATE_AUTH_CONTINUE,
	IMAP_PROXY_STATE_LOGIN
};

static void proxy_write_id(struct imap_client *client, string_t *str)
{
	i_assert(client->common.proxy_ttl > 1);

	str_printfa(str, "I ID ("
		    "\"x-session-id\" \"%s\" "
		    "\"x-originating-ip\" \"%s\" "
		    "\"x-originating-port\" \"%u\" "
		    "\"x-connected-ip\" \"%s\" "
		    "\"x-connected-port\" \"%u\" "
		    "\"x-proxy-ttl\" \"%u\")\r\n",
		    client_get_session_id(&client->common),
		    net_ip2addr(&client->common.ip),
		    client->common.remote_port,
		    net_ip2addr(&client->common.local_ip),
		    client->common.local_port,
		    client->common.proxy_ttl - 1);
}

static void proxy_free_password(struct client *client)
{
	if (client->proxy_password == NULL)
		return;

	safe_memset(client->proxy_password, 0, strlen(client->proxy_password));
	i_free_and_null(client->proxy_password);
}

static void get_plain_auth(struct client *client, string_t *dest)
{
	string_t *str;

	str = t_str_new(128);
	str_append(str, client->proxy_user);
	str_append_c(str, '\0');
	str_append(str, client->proxy_master_user);
	str_append_c(str, '\0');
	str_append(str, client->proxy_password);
	base64_encode(str_data(str), str_len(str), dest);
}

static void proxy_write_login(struct imap_client *client, string_t *str)
{
	str_append(str, "C CAPABILITY\r\n");

	if (client->common.proxy_master_user == NULL) {
		/* logging in normally - use LOGIN command */
		str_append(str, "L LOGIN ");
		imap_append_string(str, client->common.proxy_user);
		str_append_c(str, ' ');
		imap_append_string(str, client->common.proxy_password);

		proxy_free_password(&client->common);
	} else if (client->proxy_sasl_ir) {
		/* master user login with SASL initial response support */
		str_append(str, "L AUTHENTICATE PLAIN ");
		get_plain_auth(&client->common, str);
		proxy_free_password(&client->common);
	} else {
		/* master user login without SASL initial response */
		str_append(str, "L AUTHENTICATE PLAIN");
		client->proxy_wait_auth_continue = TRUE;
	}
	str_append(str, "\r\n");
}

static int proxy_input_banner(struct imap_client *client,
			      struct ostream *output, const char *line)
{
	enum login_proxy_ssl_flags ssl_flags;
	const char *const *capabilities = NULL;
	string_t *str;

	if (strncmp(line, "* OK ", 5) != 0) {
		client_log_err(&client->common, t_strdup_printf(
			"proxy: Remote returned invalid banner: %s",
			str_sanitize(line, 160)));
		return -1;
	}

	str = t_str_new(128);
	if (strncmp(line + 5, "[CAPABILITY ", 12) == 0) {
		capabilities = t_strsplit(t_strcut(line + 5 + 12, ']'), " ");
		if (str_array_icase_find(capabilities, "ID"))
			proxy_write_id(client, str);
		if (str_array_icase_find(capabilities, "SASL-IR"))
			client->proxy_sasl_ir = TRUE;
	}

	ssl_flags = login_proxy_get_ssl_flags(client->common.login_proxy);
	if ((ssl_flags & PROXY_SSL_FLAG_STARTTLS) != 0) {
		if (capabilities != NULL &&
		    !str_array_icase_find(capabilities, "STARTTLS")) {
			client_log_err(&client->common,
				"proxy: Remote doesn't support STARTTLS");
			return -1;
		}
		str_append(str, "S STARTTLS\r\n");
	} else {
		proxy_write_login(client, str);
	}

	o_stream_nsend(output, str_data(str), str_len(str));
	return 0;
}

static void
client_send_login_reply(struct imap_client *client, string_t *str,
			const char *line)
{
	const char *capability;
	bool tagged_capability;

	capability = client->proxy_backend_capability;
	tagged_capability = strncasecmp(line, "[CAPABILITY ", 12) == 0;
	if (tagged_capability)
		capability = t_strcut(line + 12, ']');

	if (client->client_ignores_capability_resp_code && capability != NULL) {
		/* client has used CAPABILITY command, so it didn't understand
		   the capabilities in the banner. send the backend's untagged
		   CAPABILITY reply and hope that the client understands it */
		str_printfa(str, "* CAPABILITY %s\r\n", capability);
	}
	str_append(str, client->cmd_tag);
	str_append(str, " OK ");
	if (!client->client_ignores_capability_resp_code &&
	    !tagged_capability && capability != NULL) {
		str_printfa(str, "[CAPABILITY %s] ", capability);
		if (*line == '[') {
			/* we need to send the capability.
			   skip over this resp-code */
			while (*line != ']' && *line != '\0')
				line++;
			if (*line == ' ') line++;
		}
	}
	str_append(str, line);
	str_append(str, "\r\n");
}

int imap_proxy_parse_line(struct client *client, const char *line)
{
	struct imap_client *imap_client = (struct imap_client *)client;
	struct ostream *output;
	string_t *str;

	i_assert(!client->destroyed);

	output = login_proxy_get_ostream(client->login_proxy);
	if (!imap_client->proxy_seen_banner) {
		/* this is a banner */
		client->proxy_state = IMAP_PROXY_STATE_BANNER;
		imap_client->proxy_seen_banner = TRUE;
		if (proxy_input_banner(imap_client, output, line) < 0) {
			client_proxy_failed(client, TRUE);
			return -1;
		}
		return 0;
	} else if (*line == '+') {
		/* AUTHENTICATE started. finish it. */
		if (!imap_client->proxy_wait_auth_continue) {
			/* used literals with LOGIN command, just ignore. */
			return 0;
		}
		client->proxy_state = IMAP_PROXY_STATE_AUTH_CONTINUE;
		imap_client->proxy_wait_auth_continue = FALSE;

		str = t_str_new(128);
		get_plain_auth(client, str);
		str_append(str, "\r\n");
		proxy_free_password(client);

		o_stream_nsend(output, str_data(str), str_len(str));
		return 0;
	} else if (strncmp(line, "S ", 2) == 0) {
		if (strncmp(line, "S OK ", 5) != 0) {
			/* STARTTLS failed */
			client_log_err(client, t_strdup_printf(
				"proxy: Remote STARTTLS failed: %s",
				str_sanitize(line + 5, 160)));
			client_proxy_failed(client, TRUE);
			return -1;
		}
		/* STARTTLS successful, begin TLS negotiation. */
		client->proxy_state = IMAP_PROXY_STATE_STARTTLS;
		if (login_proxy_starttls(client->login_proxy) < 0) {
			client_proxy_failed(client, TRUE);
			return -1;
		}
		/* i/ostreams changed. */
		output = login_proxy_get_ostream(client->login_proxy);
		str = t_str_new(128);
		proxy_write_login(imap_client, str);
		o_stream_nsend(output, str_data(str), str_len(str));
		return 1;
	} else if (strncmp(line, "L OK ", 5) == 0) {
		/* Login successful. Send this line to client. */
		client->proxy_state = IMAP_PROXY_STATE_LOGIN;
		str = t_str_new(128);
		client_send_login_reply(imap_client, str, line + 5);
		o_stream_nsend(client->output, str_data(str), str_len(str));

		(void)client_skip_line(imap_client);
		client_proxy_finish_destroy_client(client);
		return 1;
	} else if (strncmp(line, "L ", 2) == 0) {
		line += 2;
		if (client->set->auth_verbose) {
			const char *log_line = line;

			if (strncasecmp(log_line, "NO ", 3) == 0)
				log_line += 3;
			client_proxy_log_failure(client, log_line);
		}
#define STR_NO_IMAP_RESP_CODE_AUTHFAILED "NO ["IMAP_RESP_CODE_AUTHFAILED"]"
		if (strncmp(line, STR_NO_IMAP_RESP_CODE_AUTHFAILED,
			    strlen(STR_NO_IMAP_RESP_CODE_AUTHFAILED)) == 0) {
			/* the remote sent a generic "authentication failed"
			   error. replace it with our one, so that in case
			   the remote is sending a different error message
			   an attacker can't find out what users exist in
			   the system. */
			client_send_reply_code(client, IMAP_CMD_REPLY_NO,
					       IMAP_RESP_CODE_AUTHFAILED,
					       AUTH_FAILED_MSG);
		} else if (strncmp(line, "NO [", 4) == 0) {
			/* remote sent some other resp-code. forward it. */
			client_send_raw(client, t_strconcat(
				imap_client->cmd_tag, " ", line, "\r\n", NULL));
		} else {
			/* there was no [resp-code], so remote isn't Dovecot
			   v1.2+. we could either forward the line as-is and
			   leak information about what users exist in this
			   system, or we could hide other errors than password
			   failures. since other errors are pretty rare,
			   it's safer to just hide them. they're still
			   available in logs though. */
			client_send_reply_code(client, IMAP_CMD_REPLY_NO,
					       IMAP_RESP_CODE_AUTHFAILED,
					       AUTH_FAILED_MSG);
		}

		client->proxy_auth_failed = TRUE;
		client_proxy_failed(client, FALSE);
		return -1;
	} else if (strncasecmp(line, "* CAPABILITY ", 13) == 0) {
		i_free(imap_client->proxy_backend_capability);
		imap_client->proxy_backend_capability = i_strdup(line + 13);
		return 0;
	} else if (strncmp(line, "C ", 2) == 0) {
		/* Reply to CAPABILITY command we sent, ignore it */
		client->proxy_state = IMAP_PROXY_STATE_CAPABILITY;
		return 0;
	} else if (strncasecmp(line, "I ", 2) == 0 ||
		   strncasecmp(line, "* ID ", 5) == 0) {
		/* Reply to ID command we sent, ignore it */
		client->proxy_state = IMAP_PROXY_STATE_ID;
		return 0;
	} else if (strncmp(line, "* ", 2) == 0) {
		/* untagged reply. just foward it. */
		client_send_raw(client, t_strconcat(line, "\r\n", NULL));
		return 0;
	} else {
		/* tagged reply, shouldn't happen. */
		client_log_err(client, t_strdup_printf(
			"proxy: Unexpected input, ignoring: %s",
			str_sanitize(line, 160)));
		return 0;
	}
}

void imap_proxy_reset(struct client *client)
{
	struct imap_client *imap_client = (struct imap_client *)client;

	imap_client->proxy_sasl_ir = FALSE;
	imap_client->proxy_seen_banner = FALSE;
	imap_client->proxy_wait_auth_continue = FALSE;
	client->proxy_state = IMAP_PROXY_STATE_NONE;
}

void imap_proxy_error(struct client *client, const char *text)
{
	client_send_reply_code(client, IMAP_CMD_REPLY_NO,
			       IMAP_RESP_CODE_UNAVAILABLE, text);
}


text:
"use strict";

module.exports = exportFn;

function exportFn(ErrorsBase){
    ErrorsBase.captureStackTrace = captureStackTrace;
}

function captureStackTrace(inst, constructor){
    Error.captureStackTrace(inst, constructor);
}


text:
/*
 * Circlr Public Controller
 * Handles the display of public photos
 */
appControllers.controller('CirclrPublicCtrl', ['$scope', '$http', '$stateParams', 'PhotoService', 'Options',
	function CirclrPublicCtrl($scope, $http, $stateParams, PhotoService, Options) {

		$scope.photos = [];
		$scope.urlPhotoPrefix = Options.urlPhotoPrefix;

		PhotoService.getPublicPhotos().then(function(data) {
			$scope.photos = data;
		});

		$scope.loadMorePhoto = function(offset) {
			return PhotoService.getPublicPhotos(offset);
		}
	}
]);


text:
All URIs are relative to *https://www.saltedge.com/api/v5*

Method | HTTP request | Description
------------- | ------------- | -------------
[**connect_sessions_create_post**](ConnectSessionsApi.md#connect_sessions_create_post) | **POST** /connect_sessions/create | Create Connect session
[**connect_sessions_reconnect_post**](ConnectSessionsApi.md#connect_sessions_reconnect_post) | **POST** /connect_sessions/reconnect | Create Connect session to reconnect
[**connect_sessions_refresh_post**](ConnectSessionsApi.md#connect_sessions_refresh_post) | **POST** /connect_sessions/refresh | Create Connect session to refresh

# **connect_sessions_create_post**
> ConnectSessionResponse connect_sessions_create_post(body=body)

Create Connect session

Allows you to create a connect session, which will be used to access Salt Edge Connect for connection creation.

### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint

# Configure API key authorization: app_id
configuration = swagger_client.Configuration()
configuration.api_key['App-id'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['App-id'] = 'Bearer'
# Configure API key authorization: secret
configuration = swagger_client.Configuration()
configuration.api_key['Secret'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Secret'] = 'Bearer'

# create an instance of the API class
api_instance = swagger_client.ConnectSessionsApi(swagger_client.ApiClient(configuration))
body = swagger_client.ConnectSessionRequestBody() # ConnectSessionRequestBody |  (optional)

try:
    # Create Connect session
    api_response = api_instance.connect_sessions_create_post(body=body)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ConnectSessionsApi->connect_sessions_create_post: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **body** | [**ConnectSessionRequestBody**](ConnectSessionRequestBody.md)|  | [optional]

### Return type

[**ConnectSessionResponse**](ConnectSessionResponse.md)

### Authorization

[app_id](../README.md#app_id), [secret](../README.md#secret)

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **connect_sessions_reconnect_post**
> ConnectSessionResponse connect_sessions_reconnect_post(body=body)

Create Connect session to reconnect

Allows you to create a connect session, which will be used to access Salt Edge Connect to reconnect a connection.

### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint

# Configure API key authorization: app_id
configuration = swagger_client.Configuration()
configuration.api_key['App-id'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['App-id'] = 'Bearer'
# Configure API key authorization: secret
configuration = swagger_client.Configuration()
configuration.api_key['Secret'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Secret'] = 'Bearer'

# create an instance of the API class
api_instance = swagger_client.ConnectSessionsApi(swagger_client.ApiClient(configuration))
body = swagger_client.ReconnectSessionRequestBody() # ReconnectSessionRequestBody |  (optional)

try:
    # Create Connect session to reconnect
    api_response = api_instance.connect_sessions_reconnect_post(body=body)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ConnectSessionsApi->connect_sessions_reconnect_post: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **body** | [**ReconnectSessionRequestBody**](ReconnectSessionRequestBody.md)|  | [optional]

### Return type

[**ConnectSessionResponse**](ConnectSessionResponse.md)

### Authorization

[app_id](../README.md#app_id), [secret](../README.md#secret)

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **connect_sessions_refresh_post**
> ConnectSessionResponse connect_sessions_refresh_post(body=body)

Create Connect session to refresh

Allows you to create a connect session, which will be used to access Salt Edge Connect to refresh a connection.

### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint

# Configure API key authorization: app_id
configuration = swagger_client.Configuration()
configuration.api_key['App-id'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['App-id'] = 'Bearer'
# Configure API key authorization: secret
configuration = swagger_client.Configuration()
configuration.api_key['Secret'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Secret'] = 'Bearer'

# create an instance of the API class
api_instance = swagger_client.ConnectSessionsApi(swagger_client.ApiClient(configuration))
body = swagger_client.RefreshSessionRequestBody() # RefreshSessionRequestBody |  (optional)

try:
    # Create Connect session to refresh
    api_response = api_instance.connect_sessions_refresh_post(body=body)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ConnectSessionsApi->connect_sessions_refresh_post: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **body** | [**RefreshSessionRequestBody**](RefreshSessionRequestBody.md)|  | [optional]

### Return type

[**ConnectSessionResponse**](ConnectSessionResponse.md)

### Authorization

[app_id](../README.md#app_id), [secret](../README.md#secret)

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)


text:
class Tables(object):

    def __init__(self, dataset, source_schema, table_name, columns):
        self.dataset = dataset
        self.source_schema = source_schema
        self.table_name = table_name
        self.columns = columns
        self.output_table = self.dataset+"."+self.table_name+"_test_copy"


text:
import * as lolex from 'lolex';
import * as mode from '../../../../src/mode';
import {AccessClientAdapter} from '../amp-access-client';

describes.realWin(
  'AccessClientAdapter',
  {
    amp: true,
  },
  (env) => {
    let ampdoc;
    let clock;
    let validConfig;
    let context;
    let contextMock;

    beforeEach(() => {
      ampdoc = env.ampdoc;
      clock = lolex.install({target: ampdoc.win});

      validConfig = {
        'authorization': 'https://acme.com/a?rid=READER_ID',
        'pingback': 'https://acme.com/p?rid=READER_ID',
      };

      context = {
        buildUrl: () => {},
      };
      contextMock = env.sandbox.mock(context);
    });

    afterEach(() => {
      contextMock.verify();
      clock.uninstall();
    });

    describe('config', () => {
      it('should load valid config', () => {
        const adapter = new AccessClientAdapter(ampdoc, validConfig, context);
        expect(adapter.authorizationUrl_).to.equal(
          'https://acme.com/a?rid=READER_ID'
        );
        expect(adapter.pingbackUrl_).to.equal(
          'https://acme.com/p?rid=READER_ID'
        );
        expect(adapter.authorizationTimeout_).to.equal(3000);
        expect(adapter.getConfig()).to.deep.equal({
          authorizationUrl: 'https://acme.com/a?rid=READER_ID',
          pingbackEnabled: true,
          pingbackUrl: 'https://acme.com/p?rid=READER_ID',
          authorizationTimeout: 3000,
        });
        expect(adapter.isAuthorizationEnabled()).to.be.true;
        expect(adapter.isPingbackEnabled()).to.be.true;
      });

      it('should set authorization timeout if provided', () => {
        validConfig['authorizationTimeout'] = 5000;
        const adapter = new AccessClientAdapter(ampdoc, validConfig, context);
        expect(adapter.authorizationTimeout_).to.equal(5000);
      });

      it('should allow only lower-than-default timeout in production', () => {
        env.sandbox.stub(mode, 'getMode').callsFake(() => {
          return {development: false, localDev: false};
        });

        let adapter;

        validConfig['authorizationTimeout'] = 1000;
        adapter = new AccessClientAdapter(ampdoc, validConfig, context);
        expect(adapter.authorizationTimeout_).to.equal(1000);

        validConfig['authorizationTimeout'] = 5000;
        adapter = new AccessClientAdapter(ampdoc, validConfig, context);
        expect(adapter.authorizationTimeout_).to.equal(3000);
      });

      it('should fail when authorization timeout is malformed', () => {
        validConfig['authorizationTimeout'] = 'someString';
        allowConsoleError(() => {
          expect(() => {
            new AccessClientAdapter(ampdoc, validConfig, context);
          }).to.throw(/"authorizationTimeout" must be a number/);
        });
      });

      it('should fail if config authorization is missing or malformed', () => {
        delete validConfig['authorization'];
        allowConsoleError(() => {
          expect(() => {
            new AccessClientAdapter(ampdoc, validConfig, context);
          }).to.throw(/"authorization" URL must be specified/);
        });

        validConfig['authorization'] = 'http://acme.com/a';
        allowConsoleError(() => {
          expect(() => {
            new AccessClientAdapter(ampdoc, validConfig, context);
          }).to.throw(/"authorization".*https\:/);
        });
      });

      it('should fail if config pingback is missing or malformed', () => {
        delete validConfig['pingback'];
        allowConsoleError(() => {
          expect(() => {
            new AccessClientAdapter(ampdoc, validConfig, context);
          }).to.throw(/"pingback" URL must be specified/);
        });

        validConfig['pingback'] = 'http://acme.com/p';
        allowConsoleError(() => {
          expect(() => {
            new AccessClientAdapter(ampdoc, validConfig, context);
          }).to.throw(/"pingback".*https\:/);
        });
      });

      it('should allow missing pingback when noPingback=true', () => {
        delete validConfig['pingback'];
        validConfig['noPingback'] = true;
        const adapter = new AccessClientAdapter(ampdoc, validConfig, context);
        expect(adapter.isPingbackEnabled()).to.be.false;
        expect(adapter.pingbackUrl_).to.not.exist;
      });
    });

    describe('runtime', () => {
      let adapter;
      let xhrMock;

      beforeEach(() => {
        adapter = new AccessClientAdapter(ampdoc, validConfig, context);
        xhrMock = env.sandbox.mock(adapter.xhr_);
      });

      afterEach(() => {
        xhrMock.verify();
      });

      describe('authorize', () => {
        it('should issue XHR fetch', () => {
          contextMock
            .expects('buildUrl')
            .withExactArgs(
              'https://acme.com/a?rid=READER_ID',
              /* useAuthData */ false
            )
            .returns(Promise.resolve('https://acme.com/a?rid=reader1'))
            .once();
          xhrMock
            .expects('fetchJson')
            .withExactArgs('https://acme.com/a?rid=reader1', {
              credentials: 'include',
            })
            .returns(
              Promise.resolve({
                json() {
                  return Promise.resolve({access: 'A'});
                },
              })
            )
            .once();
          return adapter.authorize().then((response) => {
            expect(response).to.exist;
            expect(response.access).to.equal('A');
          });
        });

        it('should fail when XHR fails', () => {
          contextMock
            .expects('buildUrl')
            .withExactArgs(
              'https://acme.com/a?rid=READER_ID',
              /* useAuthData */ false
            )
            .returns(Promise.resolve('https://acme.com/a?rid=reader1'))
            .once();
          xhrMock
            .expects('fetchJson')
            .withExactArgs('https://acme.com/a?rid=reader1', {
              credentials: 'include',
            })
            .returns(Promise.reject('intentional'))
            .once();
          return adapter.authorize().then(
            () => {
              throw new Error('must never happen');
            },
            (error) => {
              expect(error).to.match(/intentional/);
            }
          );
        });

        it('should time out XHR fetch', () => {
          contextMock
            .expects('buildUrl')
            .withExactArgs(
              'https://acme.com/a?rid=READER_ID',
              /* useAuthData */ false
            )
            .returns(Promise.resolve('https://acme.com/a?rid=reader1'))
            .once();
          xhrMock
            .expects('fetchJson')
            .withExactArgs('https://acme.com/a?rid=reader1', {
              credentials: 'include',
            })
            .returns(new Promise(() => {})) // Never resolved.
            .once();
          const promise = adapter.authorize();
          return Promise.resolve()
            .then(() => {
              clock.tick(3001);
              return promise;
            })
            .then(
              () => {
                throw new Error('must never happen');
              },
              (error) => {
                expect(error).to.match(/timeout/);
              }
            );
        });
      });

      describe('pingback', () => {
        it('should send POST pingback', () => {
          contextMock
            .expects('buildUrl')
            .withExactArgs(
              'https://acme.com/p?rid=READER_ID',
              /* useAuthData */ true
            )
            .returns(Promise.resolve('https://acme.com/p?rid=reader1'))
            .once();
          xhrMock
            .expects('sendSignal')
            .withExactArgs(
              'https://acme.com/p?rid=reader1',
              env.sandbox.match((init) => {
                return (
                  init.method == 'POST' &&
                  init.credentials == 'include' &&
                  init.body == '' &&
                  init.headers['Content-Type'] ==
                    'application/x-www-form-urlencoded'
                );
              })
            )
            .returns(Promise.resolve())
            .once();
          return adapter.pingback();
        });

        it('should fail when POST fails', () => {
          contextMock
            .expects('buildUrl')
            .withExactArgs(
              'https://acme.com/p?rid=READER_ID',
              /* useAuthData */ true
            )
            .returns(Promise.resolve('https://acme.com/p?rid=reader1'))
            .once();
          xhrMock
            .expects('sendSignal')
            .withExactArgs(
              'https://acme.com/p?rid=reader1',
              env.sandbox.match((init) => {
                return (
                  init.method == 'POST' &&
                  init.credentials == 'include' &&
                  init.body == '' &&
                  init.headers['Content-Type'] ==
                    'application/x-www-form-urlencoded'
                );
              })
            )
            .returns(Promise.reject('intentional'))
            .once();
          return adapter.pingback().then(
            () => {
              throw new Error('must never happen');
            },
            (error) => {
              expect(error).to.match(/intentional/);
            }
          );
        });
      });
    });
  }
);