text:
package cn.newcapec.function.ecardcity.om.dao;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import cn.newcapec.framework.core.utils.pagesUtils.Page;
import cn.newcapec.function.ecardcity.om.dao.base.BaseDao;
import cn.newcapec.function.ecardcity.om.model.TermMainMenu;
import cn.newcapec.function.ecardcity.om.utils.Constant;

/**
 * @author wj
 * @category 终端自定义菜单DAO
 * @version 1.0
 * @date 2014年4月22日 上午11:47:40
 */
@Repository
public class TermMainMenuDao extends BaseDao {
    /* (non-Javadoc)
     * @see cn.newcapec.framework.core.dao.hibernate.HibernateEntityDao#getReferenceClass()
     */
    @Override
    protected Class<TermMainMenu> getReferenceClass() {
	return TermMainMenu.class;
    }

    /**
     * 查询指定卡类型
     * @param key		ID
     * @return ParamLib		根据给定的ID返回对象
     */
    public TermMainMenu get(Serializable key) {
	return (TermMainMenu) get(getReferenceClass(), key);
    }

    /**
     * 根据主菜单名称、终端名称删除菜单
     * @param mainMenu	主菜单名称
     * @param termid	终端ID
     */
    public void deleteByMainMenu(String mainMenu,String termid) {
	if (StringUtils.isNotBlank(mainMenu)&&StringUtils.isNotBlank(termid)) {
	    super.bulkUpdate(false,"delete from term_menu_sub where main_id in (select id from term_menu_main where termid=:termid and main_menu=:mainMenu)", new String[]{"termid","mainMenu"},new Object[]{termid,mainMenu});
	    super.bulkUpdate(false,"delete from term_menu_main where termid=:termid and main_menu=:mainMenu", new String[]{"termid","mainMenu"},new Object[]{termid,mainMenu});
	}
    }

    /**
     * 批量删除
     * @param ids	卡ID数组
     */
    public void delete(String[] ids) {
	if (ids != null && ids.length > 0) {
	    bulkUpdate(true,"delete from TermMainMenu where id in (:ids)", new String[]{"ids"},new Object[]{ids});
	}
    }

    /**
     * 根据map,查询指定的菜单分页(包括主、子菜单)
     * @param param	 	参数Map
     * @return Page 		根据给定的map返回列表
     */
    public Page<?> getPageIncludeSubMenu(Map<String, Object> paramMap) {
	Map<String, Object> param = new HashMap<String, Object>();
	StringBuilder sql = new StringBuilder("select a.*,b.sub_id,b.sub_menu,b.sub_trade_type,b.sub_acl_location,b.sub_acl_setting,c.termname,c.siteid from term_menu_main a,term_menu_sub b,term_info c where c.id=a.termid and b.main_id=a.id");
	if (null != paramMap) {
	    //根据商户或终端名称构建子查询
	    if ((paramMap.containsKey("netsiteid") && StringUtils.isNotBlank(paramMap.get("netsiteid").toString()))
		    || (paramMap.containsKey("termName") && StringUtils.isNotBlank(paramMap.get("termName").toString()))) {
		StringBuilder subSql = new StringBuilder("select id from term_info where 1=1");
		if (paramMap.containsKey("netsiteid") && StringUtils.isNotBlank(paramMap.get("netsiteid").toString())) {
		    subSql.append(" and siteid=:siteid");
		    param.put("siteid", paramMap.get("netsiteid"));
		}
		if (paramMap.containsKey("termName") && StringUtils.isNotBlank(paramMap.get("termName").toString())) {
		    subSql.append(" and termname like :termname");
		    param.put("termname",Constant.PERCENT_SIGN + paramMap.get("termName") + Constant.PERCENT_SIGN);
		}
		sql.append(" and a.termid in (");
		sql.append(subSql.toString());
		sql.append(")");
	    }

	    if (paramMap.containsKey("mainMenu") && StringUtils.isNotBlank(paramMap.get("mainMenu").toString())) {
		sql.append(" and a.main_menu like :mainMenu");
		param.put("mainMenu", Constant.PERCENT_SIGN+paramMap.get("mainMenu")+Constant.PERCENT_SIGN);
	    }
	    if (paramMap.containsKey("paramVer") && StringUtils.isNotBlank(paramMap.get("paramVer").toString())) {
		sql.append(" and a.param_ver = :paramVer");
		param.put("paramVer", paramMap.get("paramVer"));
	    }
	    if (paramMap.containsKey("mainId") && StringUtils.isNotBlank(paramMap.get("mainId").toString())) {
		sql.append(" and a.id = :mainId");
		param.put("mainId", paramMap.get("mainId"));
	    }
	}
	sql.append(" order by a.id desc,b.sub_id asc");
	return super.getPageBySQL(sql.toString(), param);
    }

    /**
     * 根据map,查询指定的模板参数分页
     * @param param	 	参数Map
     * @return Page 		根据给定的map返回列表
     */
    public Page<?> getPage(Map<String, Object> paramMap) {
	Map<String, Object> param = new HashMap<String, Object>();
	StringBuilder sql = new StringBuilder("select * from term_menu_main where 1=1");
	if (null != paramMap) {
		if (paramMap.containsKey("termid") && StringUtils.isNotBlank(paramMap.get("termid").toString())) {
		    sql.append(" and termid = :termid");
		    param.put("termid", paramMap.get("termid"));
		}
		if (paramMap.containsKey("main_menu") && StringUtils.isNotBlank(paramMap.get("main_menu").toString())) {
		    sql.append(" and main_menu like :main_menu");
		    param.put("main_menu", Constant.PERCENT_SIGN+paramMap.get("main_menu")+Constant.PERCENT_SIGN);
		}
	}
	sql.append(" order by ver_time desc");
	return super.getPageBySQL(sql.toString(), param);
    }

    /**
     * 根据termid,查询已用的二级菜单权限位置
     * @param termid	 	终端ID
     * @return List 		已用的权限列表位置
     */
    public List<?> getPermLocListByTerm(String termid) {
	if (StringUtils.isNotBlank(termid)) {
	    Map<String, Object> param = new HashMap<String, Object>();
	    param.put("startLoc",Constant.TERM_MENU_PERMISSION_START_LOC);
	    param.put("termid", termid);
	    String sql = "select a.p_value,a.title_name from base_param a where a.allow_visible='1' and a.p_group='6'"
		+ " and to_number(a.p_value)>=:startLoc"
	    	+ " and instr((select b.used_business from term_info b where b.id=:termid)||',',a.p_value||',')>0"
	    	+ " and a.p_value not in (select c.sub_acl_location from term_menu_sub c where main_id in (select id from term_menu_main where termid=:termid))";
	    return super.getPageBySQL(sql, param).getItems();
	}else{
	    return null;
	}
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "base/logging.hh"
#include "systemc/ext/dt/sc_mempool.hh"

namespace sc_core
{

void *
sc_mempool::allocate(std::size_t sz)
{
    return ::operator new(sz);
}
void
sc_mempool::release(void *p, std::size_t sz)
{
    ::operator delete(p);
}
void
sc_mempool::display_statistics()
{
    warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}

};


text:
package com.frdfsnlght.transporter;

import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;

/**
 *
 * @author frdfsnlght <frdfsnlght@gmail.com>
 */
public final class Economy {

    private static net.milkbowl.vault.economy.Economy vaultPlugin = null;

    public static boolean isAvailable() {
        return vaultAvailable();
    }

    public static boolean vaultAvailable() {
        if (! Config.getUseVaultEconomy()) return false;
        Plugin p = Global.plugin.getServer().getPluginManager().getPlugin("Vault");
        if ((p == null) || (! p.isEnabled())) return false;
        if (vaultPlugin != null) return true;
        RegisteredServiceProvider<net.milkbowl.vault.economy.Economy> rsp =
                Global.plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
        if (rsp == null) return false;
        vaultPlugin = rsp.getProvider();
        if (vaultPlugin == null) return false;
        Utils.info("Initialized Vault for Economy");
        return true;
    }

    public static String format(double funds) {
        if (vaultAvailable())
            return vaultPlugin.format(funds);

        return String.format("$%1.2f", funds);
    }

    public static boolean requireFunds(Player player, double amount) throws EconomyException {
        if (player == null) return false;
        return requireFunds(player.getName(), amount);
    }

    public static boolean requireFunds(String accountName, double amount) throws EconomyException {
        if (accountName == null) return false;
        if (amount <= 0) return false;
        if (vaultAvailable()) {
            double balance = vaultPlugin.getBalance(accountName);
            if (balance < amount)
                throw new EconomyException("insufficient funds");
            return true;
        }

        // default
        return false;
    }

    public static boolean deductFunds(Player player, double amount) throws EconomyException {
        if (player == null) return false;
        return deductFunds(player.getName(), amount);
    }

    public static boolean deductFunds(String accountName, double amount) throws EconomyException {
        if (accountName == null) return false;
        if (amount <= 0) return false;

        if (vaultAvailable()) {
            double balance = vaultPlugin.getBalance(accountName);
            if (balance < amount)
                throw new EconomyException("insufficient funds");
            EconomyResponse r = vaultPlugin.withdrawPlayer(accountName, amount);
            if (r.transactionSuccess()) return true;
            throw new EconomyException("economy error: %s", r.errorMessage);
        }

        // default
        return false;
    }

}


text:
@interface CRTKeychainCredentialStorage : NSObject <CRTCredentialStorage>

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBitcoin.BitcoinCore
{
	public class Coins : IBitcoinSerializable
	{
		// whether transaction is a coinbase
		bool fCoinBase;
		public bool Coinbase
		{
			get
			{
				return fCoinBase;
			}
			set
			{
				fCoinBase = value;
			}
		}

		// unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
		List<TxOut> vout = new List<TxOut>();

		// at which height this transaction was included in the active block chain
		uint nHeight;
		public uint Height
		{
			get
			{
				return nHeight;
			}
			set
			{
				nHeight = value;
			}
		}

		// version of the CTransaction; accesses to this value should probably check for nHeight as well,
		// as new tx version will probably only be introduced at certain heights
		uint nVersion;
		public uint Version
		{
			get
			{
				return nVersion;
			}
			set
			{
				nVersion = value;
			}
		}

		public List<TxOut> Outputs
		{
			get
			{
				return vout;
			}
		}

		Money _Value;
		public Money Value
		{
			get
			{
				return _Value;
			}
		}

		public Coins()
		{

		}
		public Coins(Transaction tx, int height)
			: this(tx, null, height)
		{
		}
		public Coins(Transaction tx, Func<TxOut, bool> belongsToCoins, int height)
		{
			if(belongsToCoins == null)
				belongsToCoins = o => !o.ScriptPubKey.IsUnspendable;
			fCoinBase = tx.IsCoinBase;
			vout = tx.Outputs.ToList();
			nVersion = tx.Version;
			nHeight = (uint)height;
			ClearUnused(belongsToCoins);
			UpdateValue();
		}

		private void UpdateValue()
		{
			_Value = Outputs.Where(o => !o.IsNull).Select(o => o.Value).Sum();
		}

		public bool IsEmpty
		{
			get
			{
				return vout.Count == 0;
			}
		}

		private void ClearUnused(Func<TxOut, bool> belongsToCoins)
		{
			for(int i = 0; i < vout.Count; i++)
			{
				var o = vout[i];
				if(o.ScriptPubKey.IsUnspendable || !belongsToCoins(o))
				{
					vout[i] = new TxOut();
				}
			}
			Cleanup();
		}

		private void Cleanup()
		{
			var count = vout.Count;
			// remove spent outputs at the end of vout
			for(int i = count - 1; i >= 0; i--)
			{
				if(vout[i].IsNull)
					vout.RemoveAt(i);
				else
					break;
			}
		}

		public bool Spend(int position, out TxInUndo undo)
		{
			undo = null;
			if(position >= vout.Count)
				return false;
			if(vout[position].IsNull)
				return false;
			undo = new TxInUndo(vout[position].Clone());
			vout[position].SetNull();
			Cleanup();
			if(vout.Count == 0)
			{
				undo.Height = nHeight;
				undo.CoinBase = fCoinBase;
				undo.Version = nVersion;
			}
			return true;
		}

		public bool Spend(int position)
		{
			TxInUndo undo;
			return Spend(position, out undo);
		}

		#region IBitcoinSerializable Members

		public void ReadWrite(BitcoinStream stream)
		{
			if(stream.Serializing)
			{
				uint nMaskSize = 0, nMaskCode = 0;
				CalcMaskSize(ref nMaskSize, ref nMaskCode);
				bool fFirst = vout.Count > 0 && !vout[0].IsNull;
				bool fSecond = vout.Count > 1 && !vout[1].IsNull;
				uint nCode = unchecked((uint)(8 * (nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0)));
				// version
				stream.ReadWriteAsVarInt(ref nVersion);
				// size of header code
				stream.ReadWriteAsVarInt(ref nCode);
				// spentness bitmask
				for(uint b = 0; b < nMaskSize; b++)
				{
					byte chAvail = 0;
					for(uint i = 0; i < 8 && 2 + b * 8 + i < vout.Count; i++)
						if(!vout[2 + (int)b * 8 + (int)i].IsNull)
							chAvail |= (byte)(1 << (int)i);
					stream.ReadWrite(ref chAvail);
				}

				// txouts themself
				for(uint i = 0; i < vout.Count; i++)
				{
					if(!vout[(int)i].IsNull)
					{
						var compressedTx = new TxOutCompressor(vout[(int)i]);
						stream.ReadWrite(ref compressedTx);
					}
				}
				// coinbase height
				stream.ReadWriteAsVarInt(ref nHeight);
			}
			else
			{
				uint nCode = 0;
				// version
				stream.ReadWriteAsVarInt(ref nVersion);
				//// header code
				stream.ReadWriteAsVarInt(ref nCode);
				fCoinBase = (nCode & 1) != 0;
				List<bool> vAvail = new List<bool>() { false, false };
				vAvail[0] = (nCode & 2) != 0;
				vAvail[1] = (nCode & 4) != 0;
				uint nMaskCode = unchecked((uint)((nCode / 8) + ((nCode & 6) != 0 ? 0 : 1)));
				//// spentness bitmask
				while(nMaskCode > 0)
				{
					byte chAvail = 0;
					stream.ReadWrite(ref chAvail);
					for(uint p = 0; p < 8; p++)
					{
						bool f = (chAvail & (1 << (int)p)) != 0;
						vAvail.Add(f);
					}
					if(chAvail != 0)
						nMaskCode--;
				}
				// txouts themself
				vout = Enumerable.Range(0, vAvail.Count).Select(_ => new TxOut()).ToList();
				for(uint i = 0; i < vAvail.Count; i++)
				{
					if(vAvail[(int)i])
					{
						TxOutCompressor compressed = new TxOutCompressor();
						stream.ReadWrite(ref compressed);
						vout[(int)i] = compressed.TxOut;
					}
				}
				//// coinbase height
				stream.ReadWriteAsVarInt(ref nHeight);
				Cleanup();
				UpdateValue();
			}
		}

		// calculate number of bytes for the bitmask, and its number of non-zero bytes
		// each bit in the bitmask represents the availability of one output, but the
		// availabilities of the first two outputs are encoded separately
		private void CalcMaskSize(ref uint nBytes, ref uint nNonzeroBytes)
		{
			uint nLastUsedByte = 0;
			for(uint b = 0; 2 + b * 8 < vout.Count; b++)
			{
				bool fZero = true;
				for(uint i = 0; i < 8 && 2 + b * 8 + i < vout.Count; i++)
				{
					if(!vout[2 + (int)b * 8 + (int)i].IsNull)
					{
						fZero = false;
						continue;
					}
				}
				if(!fZero)
				{
					nLastUsedByte = b + 1;
					nNonzeroBytes++;
				}
			}
			nBytes += nLastUsedByte;
		}

		// check whether a particular output is still available
		public bool IsAvailable(uint position)
		{
			return (position < vout.Count && !vout[(int)position].IsNull);
		}

		// check whether the entire CCoins is spent
		// note that only !IsPruned() CCoins can be serialized
		public bool IsPruned
		{
			get
			{
				return vout.All(v => v.IsNull);
			}
		}

		#endregion

		public void ClearUnspendable()
		{
			ClearUnused(o => !o.ScriptPubKey.IsUnspendable);
		}

		public void MergeFrom(Coins otherCoin)
		{
			var diff = otherCoin.Outputs.Count - this.Outputs.Count;
			if(diff > 0)
			{
				Outputs.Resize(otherCoin.Outputs.Count);
				for(int i = 0; i < Outputs.Count; i++)
				{
					if(Outputs[i] == null)
						Outputs[i] = new TxOut();
				}
			}
			for(int i = 0; i < otherCoin.Outputs.Count; i++)
			{
				if(!otherCoin.Outputs[i].IsNull)
					Outputs[i] = otherCoin.Outputs[i];
			}
			UpdateValue();
		}
	}
}


text:
class X {
  static method(): void -> 1
}


text:
require 'chefspec'
require 'chefspec/berkshelf'

RSpec.configure do |config|
  config.color = true
  config.log_level = :error
end

at_exit { ChefSpec::Coverage.report! }


text:
package org.hawkular.alerts.engine.impl;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import org.hawkular.alerts.api.model.condition.CompareCondition;
import org.hawkular.alerts.api.model.condition.Condition;
import org.hawkular.alerts.api.model.data.Data;
import org.hawkular.alerts.api.model.trigger.Trigger;
import org.hawkular.alerts.api.model.trigger.TriggerType;
import org.hawkular.alerts.api.services.DefinitionsEvent;
import org.hawkular.alerts.api.services.DefinitionsListener;
import org.hawkular.alerts.api.services.DefinitionsService;
import org.jboss.logging.Logger;

/**
 * A helper class to keep track of DataDrivenGroup
 *
 * @author Jay Shaughnessy
 * @author Lucas Ponce
 */
@Singleton
@TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED)
public class DataDrivenGroupCacheManager {
    private final Logger log = Logger.getLogger(DataDrivenGroupCacheManager.class);

    // The sources with member triggers for the dataId.
    // - null if dataId is not used in a group trigger condition
    // - EmptySet if no source members are yet defined
    Map<CacheKey, Set<String>> sourcesMap = new HashMap<>();
    // The group triggerIds relevant to the dataId, null if none
    Map<CacheKey, Set<String>> triggersMap = new HashMap<>();

    @EJB
    DefinitionsService definitions;

    @PostConstruct
    public void init() {
        updateCache();

        definitions.registerListener(new DefinitionsListener() {
            @Override
            public void onChange(DefinitionsEvent event) {
                updateCache();
            }
        }, DefinitionsEvent.Type.CONDITION_CHANGE);
    }

    private synchronized void updateCache() {

        try {
            Collection<Trigger> allTriggers = definitions.getAllTriggers();
            Set<Trigger> ddGroupTriggers = new HashSet<>();
            for (Trigger t : allTriggers) {
                if (TriggerType.DATA_DRIVEN_GROUP == t.getType()) {
                    ddGroupTriggers.add(t);
                }
            }
            Collection<Condition> conditions = new HashSet<>();
            for (Trigger groupTrigger : ddGroupTriggers) {
                String tenantId = groupTrigger.getTenantId();
                Set<String> sources = new HashSet<>();
                for (Trigger memberTrigger : definitions.getMemberTriggers(tenantId, groupTrigger.getId(), false)) {
                    sources.add(memberTrigger.getSource());
                }
                for (Condition c : definitions.getTriggerConditions(tenantId, groupTrigger.getId(), null)) {
                    CacheKey key = new CacheKey(tenantId, c.getDataId());
                    sourcesMap.put(key, sources);
                    Set<String> triggers = triggersMap.get(key);
                    if (null == triggers) {
                        triggers = new HashSet<>();
                    }
                    triggers.add(groupTrigger.getId());
                    triggersMap.put(key, triggers);

                    if (c instanceof CompareCondition) {
                        key = new CacheKey(tenantId, ((CompareCondition) c).getData2Id());
                        sourcesMap.put(key, sources);

                        triggers = triggersMap.get(key);
                        if (null == triggers) {
                            triggers = new HashSet<>();
                        }
                        triggers.add(groupTrigger.getId());
                        triggersMap.put(key, triggers);
                    }
                }
            }
        } catch (Exception e) {
            log.error("FAILED to updateCache. Unable to generate data-driven member triggers!", e);
            sourcesMap = new HashMap<>();
        }

        if (log.isDebugEnabled()) {
            log.debug("Updated sourceMap! " + sourcesMap);
        }
    }

    public boolean isCacheActive() {
        return !sourcesMap.isEmpty();
    }

    public Set<String> needsSourceMember(String tenantId, String dataId, String source) {
        if (isEmpty(source, dataId, tenantId) || Data.SOURCE_NONE.equals(source)) {
            return Collections.EMPTY_SET;
        }

        CacheKey key = new CacheKey(tenantId, dataId);

        // if the dataId is not relevant to any group triggers just return empty set
        if (null == triggersMap.get(key)) {
            return Collections.EMPTY_SET;
        }

        // if the dataId is relevant to group triggers but the source is already known just return empty set
        Set<String> sources = sourcesMap.get(key);
        if (sources.contains(source)) {
            return Collections.EMPTY_SET;
        }

        // otherwise, return the triggers that need a member for this source
        return triggersMap.get(key);
    }

    private boolean isEmpty(String... strings) {
        for (String s : strings) {
            if (null == s || s.trim().isEmpty()) {
                return true;
            }
        }

        return false;
    }

    private static class CacheKey {
        private String tenantId;
        private String dataId;

        public CacheKey(String tenantId, String dataId) {
            super();
            this.tenantId = tenantId;
            this.dataId = dataId;
        }

        public String getTenantId() {
            return tenantId;
        }

        public String getDataId() {
            return dataId;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((dataId == null) ? 0 : dataId.hashCode());
            result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            CacheKey other = (CacheKey) obj;
            if (dataId == null) {
                if (other.dataId != null)
                    return false;
            } else if (!dataId.equals(other.dataId))
                return false;
            if (tenantId == null) {
                if (other.tenantId != null)
                    return false;
            } else if (!tenantId.equals(other.tenantId))
                return false;
            return true;
        }

        @Override
        public String toString() {
            return "CacheKey [" + tenantId + ":" + dataId + "]";
        }

    }
}


text:
package request

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestLocation_Valid(t *testing.T) {
	var loc Location
	assert.Error(t, loc.Valid())
	loc.Region = "CA"
	assert.NoError(t, loc.Valid())
	loc.Page = -1
	assert.Error(t, loc.Valid())
}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Origin.apikey'
        db.add_column(u'server_origin', 'apikey',
                      self.gf('django.db.models.fields.CharField')(default=u'', max_length=256),
                      keep_default=False)

        # Adding unique constraint on 'Backup', fields ['name', 'origin', 'destination', 'date']
        #db.create_unique(u'server_backup', ['name', 'origin_id', 'destination_id', 'date'])

    def backwards(self, orm):
        # Removing unique constraint on 'Backup', fields ['name', 'origin', 'destination', 'date']
        #db.delete_unique(u'server_backup', ['name', 'origin_id', 'destination_id', 'date'])

        # Deleting field 'Origin.apikey'
        db.delete_column(u'server_origin', 'apikey')

    models = {
        'server.apidestination': {
            'Meta': {'object_name': 'APIDestination', '_ormbases': ['server.BaseDestination']},
            'base_uri': ('django.db.models.fields.CharField', [], {'max_length': '1024'}),
            u'basedestination_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['server.BaseDestination']", 'unique': 'True', 'primary_key': 'True'}),
            'get_uri': ('django.db.models.fields.CharField', [], {'default': "'/get/'", 'max_length': '1024'}),
            'pubkey': ('django.db.models.fields.TextField', [], {}),
            'set_uri': ('django.db.models.fields.CharField', [], {'default': "'/set/'", 'max_length': '1024'})
        },
        'server.backup': {
            #'Meta': {'unique_together': "(('name', 'origin', 'destination', 'date'),)", 'object_name': 'Backup'},
						'Meta': {'object_name': 'Backup'},
            'after_restore': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'before_restore': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'date': ('django.db.models.fields.DateTimeField', [], {}),
            'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'}),
            'destination': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['server.BaseDestination']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '1024'}),
            'obs': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'origin': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['server.Origin']"}),
            'related_to': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['server.Backup']", 'null': 'True', 'blank': 'True'}),
            'restore_dt': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'success': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
        },
        'server.basedestination': {
            'Meta': {'object_name': 'BaseDestination'},
            'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'}),
            'directory': ('django.db.models.fields.CharField', [], {'default': "u'~'", 'max_length': '1024', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '1024'})
        },
        'server.localdestination': {
            'Meta': {'object_name': 'LocalDestination', '_ormbases': ['server.BaseDestination']},
            u'basedestination_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['server.BaseDestination']", 'unique': 'True', 'primary_key': 'True'})
        },
        u'server.origin': {
            'Meta': {'object_name': 'Origin'},
            'apikey': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
            'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '1024'}),
            'plan': ('django.db.models.fields.TextField', [], {})
        },
        'server.sftpdestination': {
            'Meta': {'object_name': 'SFTPDestination', '_ormbases': ['server.BaseDestination']},
            u'basedestination_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['server.BaseDestination']", 'unique': 'True', 'primary_key': 'True'}),
            'hostname': ('django.db.models.fields.CharField', [], {'max_length': '1024'}),
            'key_filename': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
            'port': ('django.db.models.fields.CharField', [], {'max_length': '5', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'default': "u'tbackup'", 'max_length': '80'})
        }
    }

    complete_apps = ['server']


text:
<?php

declare(strict_types=1);

namespace Cortex\Foundation\Verifiers;

use Illuminate\Validation\DatabasePresenceVerifier;

class EloquentPresenceVerifier extends DatabasePresenceVerifier
{
    /**
     * Count the number of objects in a collection having the given value.
     *
     * @param string      $model
     * @param string      $column
     * @param string      $value
     * @param int|null    $excludeId
     * @param string|null $idColumn
     * @param array       $extra
     *
     * @return int
     */
    public function getCount($model, $column, $value, $excludeId = null, $idColumn = null, array $extra = [])
    {
        $query = $this->model($model)->where($column, '=', $value);

        if (! is_null($excludeId) && $excludeId !== 'NULL') {
            $query->where($idColumn ?: 'id', '<>', $excludeId);
        }

        return $this->addConditions($query, $extra)->count();
    }

    /**
     * Count the number of objects in a collection with the given values.
     *
     * @param string $model
     * @param string $column
     * @param array  $values
     * @param array  $extra
     *
     * @return int
     */
    public function getMultiCount($model, $column, array $values, array $extra = [])
    {
        $query = $this->model($model)->whereIn($column, $values);

        return $this->addConditions($query, $extra)->distinct()->count($column);
    }

    /**
     * Get model eloquent builder.
     *
     * @param $model
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    private function model($model)
    {
        return $model->setConnection($this->connection)->useWritePdo();
    }
}


text:
@interface ToolCell : UICollectionViewCell

//加载图片
@property (nonatomic, retain) UIImageView *imageView;
//创建一个lable用于显示装备的标题
@property (nonatomic, retain) UILabel *titleLabel;

@end


text:
package org.apache.camel.component.mina2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

public class Mina2UdpConcurrentTest extends BaseMina2Test {

    protected int messageCount = 3;

    public Mina2UdpConcurrentTest() {
    }

    @Test
    public void testMinaRoute() throws Exception {
        MockEndpoint endpoint = getMockEndpoint("mock:result");
        endpoint.expectedBodiesReceivedInAnyOrder("Hello Message: 0", "Hello Message: 1", "Hello Message: 2");

        sendUdpMessages();

        assertMockEndpointsSatisfied();
    }

    protected void sendUdpMessages() throws Exception {
        DatagramSocket socket = new DatagramSocket();
        try {
            InetAddress address = InetAddress.getByName("127.0.0.1");
            for (int i = 0; i < messageCount; i++) {
                String text = "Hello Message: " + Integer.toString(i);
                byte[] data = text.getBytes();

                DatagramPacket packet = new DatagramPacket(data, data.length, address, getPort());
                socket.send(packet);
            }
            Thread.sleep(2000);
        } finally {
            socket.close();
        }
    }

    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                // we use un-ordered to allow processing the UDP messages in any order from same client
                from("mina2:udp://127.0.0.1:" + getPort() + "?sync=false&minaLogger=true&orderedThreadPoolExecutor=false")
                        .delay(1000)
                        .to("mock:result");
            }
        };
    }
}


text:
<?php

namespace TD\CinemaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Personne
 *
 * @ORM\Table(name="personne")
 * @ORM\Entity(repositoryClass="TD\CinemaBundle\Repository\PersonneRepository")
 */
class Personne
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     */
    private $nom;

    /**
     * @var string
     *
     * @ORM\Column(name="prenom", type="string", length=255)
     */
    private $prenom;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date_de_naissance", type="date")
     */
    private $dateDeNaissance;

    /**
     * @var string
     *
     * @ORM\Column(name="biographie", type="text")
     */
    private $biographie;

    /**
     * @ORM\OneToMany(targetEntity="Film",mappedBy="personne")
     */
    private $films ;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nom
     *
     * @param string $nom
     *
     * @return Personne
     */
    public function setNom($nom)
    {
        $this->nom = $nom;

        return $this;
    }

    /**
     * Get nom
     *
     * @return string
     */
    public function getNom()
    {
        return $this->nom;
    }

    /**
     * Set prenom
     *
     * @param string $prenom
     *
     * @return Personne
     */
    public function setPrenom($prenom)
    {
        $this->prenom = $prenom;

        return $this;
    }
 public function setBiographie($biographie)
    {
        $this->biographie = $biographie;

        return $this;
    }

    /**
     * Get prenom
     *
     * @return string
     */
    public function getPrenom()
    {
        return $this->prenom;
    }
public function getBiographie()
    {
        return $this->biographie;
    }

    /**
     * Set dateDeNaissance
     *
     * @param \DateTime $dateDeNaissance
     *
     * @return Personne
     */
    public function setDateDeNaissance($dateDeNaissance)
    {
        $this->dateDeNaissance = $dateDeNaissance;

        return $this;
    }

    /**
     * Get dateDeNaissance
     *
     * @return \DateTime
     */
    public function getDateDeNaissance()
    {
        return $this->dateDeNaissance;
    }

   public function getFilm()
    {
        return $this->films;
    }
}


text:
from __future__ import unicode_literals
import logging
import os.path
import babelfish
import charade
import pysrt
from .video import Episode, Movie

logger = logging.getLogger(__name__)

class Subtitle(object):
    """Base class for subtitle

    :param language: language of the subtitle
    :type language: :class:`babelfish.Language`
    :param bool hearing_impaired: `True` if the subtitle is hearing impaired, `False` otherwise
    :param page_link: link to the web page from which the subtitle can be downloaded, if any
    :type page_link: string or None

    """
    def __init__(self, language, hearing_impaired=False, page_link=None):
        self.language = language
        self.hearing_impaired = hearing_impaired
        self.page_link = page_link

        #: Subtitle's content once downloaded with :meth:`~subliminal.providers.Provider.download_subtitle`
        self.content = None

    def compute_matches(self, video):
        """Compute the matches of the subtitle against the `video`

        :param video: the video to compute the matches against
        :type video: :class:`~subliminal.video.Video`
        :return: matches of the subtitle
        :rtype: set

        """
        raise NotImplementedError

    def compute_score(self, video):
        """Compute the score of the subtitle against the `video`

        There are equivalent matches so that a provider can match one element or its equivalent. This is
        to give all provider a chance to have a score in the same range without hurting quality.

        * Matching :class:`~subliminal.video.Video`'s `hashes` is equivalent to matching everything else
        * Matching :class:`~subliminal.video.Episode`'s `season` and `episode`
          is equivalent to matching :class:`~subliminal.video.Episode`'s `title`
        * Matching :class:`~subliminal.video.Episode`'s `tvdb_id` is equivalent to matching
          :class:`~subliminal.video.Episode`'s `series`

        :param video: the video to compute the score against
        :type video: :class:`~subliminal.video.Video`
        :return: score of the subtitle
        :rtype: int

        """
        score = 0
        # compute matches
        initial_matches = self.compute_matches(video)
        matches = initial_matches.copy()
        # hash is the perfect match
        if 'hash' in matches:
            score = video.scores['hash']
        else:
            # remove equivalences
            if isinstance(video, Episode):
                if 'imdb_id' in matches:
                    matches -= {'series', 'tvdb_id', 'season', 'episode', 'title', 'year'}
                if 'tvdb_id' in matches:
                    matches -= {'series', 'year'}
                if 'title' in matches:
                    matches -= {'season', 'episode'}
            # add other scores
            score += sum((video.scores[match] for match in matches))
        logger.info('Computed score %d with matches %r', score, initial_matches)
        return score

    def __repr__(self):
        return '<%s [%s]>' % (self.__class__.__name__, self.language)

def get_subtitle_path(video_path, language=None):
    """Create the subtitle path from the given `video_path` and `language`

    :param string video_path: path to the video
    :param language: language of the subtitle to put in the path
    :type language: :class:`babelfish.Language` or None
    :return: path of the subtitle
    :rtype: string

    """
    subtitle_path = os.path.splitext(video_path)[0]
    if language is not None:
        try:
            return subtitle_path + '.%s.%s' % (language.alpha2, 'srt')
        except babelfish.LanguageConvertError:
            return subtitle_path + '.%s.%s' % (language.alpha3, 'srt')
    return subtitle_path + '.srt'

def is_valid_subtitle(subtitle_text):
    """Check if a subtitle text is a valid SubRip format

    :return: `True` if the subtitle is valid, `False` otherwise
    :rtype: bool

    """
    try:
        pysrt.from_string(subtitle_text, error_handling=pysrt.ERROR_RAISE)
        return True
    except pysrt.Error as e:
        if e.args[0] > 80:
            return True
    except:
        logger.exception('Unexpected error when validating subtitle')
    return False

def compute_guess_matches(video, guess):
    """Compute matches between a `video` and a `guess`

    :param video: the video to compute the matches on
    :type video: :class:`~subliminal.video.Video`
    :param guess: the guess to compute the matches on
    :type guess: :class:`guessit.Guess`
    :return: matches of the `guess`
    :rtype: set

    """
    matches = set()
    if isinstance(video, Episode):
        # series
        if video.series and 'series' in guess and guess['series'].lower() == video.series.lower():
            matches.add('series')
        # season
        if video.season and 'seasonNumber' in guess and guess['seasonNumber'] == video.season:
            matches.add('season')
        # episode
        if video.episode and 'episodeNumber' in guess and guess['episodeNumber'] == video.episode:
            matches.add('episode')
        # year
        if video.year == guess.get('year'):  # count "no year" as an information
            matches.add('year')
    elif isinstance(video, Movie):
        # year
        if video.year and 'year' in guess and guess['year'] == video.year:
            matches.add('year')
    # title
    if video.title and 'title' in guess and guess['title'].lower() == video.title.lower():
        matches.add('title')
    # release group
    if video.release_group and 'releaseGroup' in guess and guess['releaseGroup'].lower() == video.release_group.lower():
        matches.add('release_group')
    # screen size
    if video.resolution and 'screenSize' in guess and guess['screenSize'] == video.resolution:
        matches.add('resolution')
    # video codec
    if video.video_codec and 'videoCodec' in guess and guess['videoCodec'] == video.video_codec:
        matches.add('video_codec')
    # audio codec
    if video.audio_codec and 'audioCodec' in guess and guess['audioCodec'] == video.audio_codec:
        matches.add('audio_codec')
    return matches

def decode(content, language):
    """Decode subtitle `content` in a specified `language`

    :param bytes content: content of the subtitle
    :param language: language of the subtitle
    :type language: :class:`babelfish.Language`
    :return: the decoded `content` bytes
    :rtype: string

    """
    # always try utf-8 first
    encodings = ['utf-8']

    # add language-specific encodings
    if language.alpha3 == 'zho':
        encodings.extend(['gb18030', 'big5'])
    elif language.alpha3 == 'jpn':
        encodings.append('shift-jis')
    elif language.alpha3 == 'ara':
        encodings.append('windows-1256')
    else:
        encodings.append('latin-1')

    # try to decode
    for encoding in encodings:
        try:
            print encoding
            return content.decode(encoding)
        except UnicodeDecodeError:
            pass

    # fallback on charade
    logger.warning('Could not decode content with encodings %r', encodings)
    return content.decode(charade.detect(content)['encoding'], 'replace')


text:
#pragma once

#include <modules/meshrenderinggl/meshrenderingglmoduledefine.h>

#include <inviwo/core/datastructures/geometry/mesh.h>

#include <memory>

namespace inviwo {

namespace meshutil {
/**
 * \brief The weighting modes for calculating normals
 */
enum class CalculateMeshNormalsMode {
    /**
     * \brief Pass through, mesh is not changed
     */
    PassThrough,
    /**
     * \brief no weighting of the normals, simple average
     */
    NoWeighting,
    /**
     * \brief Weight = area of the triangle
     */
    WeightArea,
    /**
     * \brief Weight based on the angle.
     * As defined in "Computing vertex normals from polygonal facets" by Grit Thürmer and
     * Charles A. Wüthrich 1998.
     */
    WeightAngle,
    /**
     * \brief Based on "Weights for Computing Vertex Normals from Facet Normals", N. Max, 1999.
     * This gives the best results in most cases.
     */
    WeightNMax
};

IVW_MODULE_MESHRENDERINGGL_API void calculateMeshNormals(
    Mesh& mesh, CalculateMeshNormalsMode mode = CalculateMeshNormalsMode::WeightNMax);

inline std::unique_ptr<Mesh> calculateMeshNormals(
    const Mesh& mesh, CalculateMeshNormalsMode mode = CalculateMeshNormalsMode::WeightNMax) {
    auto cloned = std::unique_ptr<Mesh>(mesh.clone());
    calculateMeshNormals(*cloned, mode);
    return cloned;
}

}  // namespace meshutil

}  // namespace inviwo


text:
from CommonServerPython import *

'''IMPORTS'''

from typing import Dict, Any, List, Union, Optional, Generator
from datetime import timezone
import csv
import gzip
import boto3 as s3
import botocore
import botocore.config as config
import urllib3
import dateparser

# Disable insecure warnings
urllib3.disable_warnings()

'''CONSTANTS'''

BATCH_SIZE = 2000

BUCKETS: Dict[str, str] = {
    'domain': 'sis-new-observations',
    'phish': 'riq-sis-blacklist-phish',
    'malware': 'riq-sis-blacklist-malware',
    'content': 'riq-sis-blacklist-content',
    'scam': 'riq-sis-blacklist-scam'
}

FIELD_NAMES: Dict[str, List[str]] = {
    'domain': ['value', 'Timestamp'],
    'phish': ['value', 'Category', 'MatchType', 'Expiration'],
    'malware': ['value', 'MalwareType', 'MatchType', 'MaliciousExpiration'],
    'content': ['value', 'Category', 'MatchType', 'Expiration'],
    'scam': ['value', 'Category', 'MatchType', 'Expiration']
}

INDICATOR_TYPES: Dict[str, str] = {
    'domain': FeedIndicatorType.Domain,
    'phish': FeedIndicatorType.URL,
    'malware': FeedIndicatorType.URL,
    'content': FeedIndicatorType.URL,
    'scam': FeedIndicatorType.URL
}

REGIONS: Dict[str, str] = {
    'domain': 'us-west-1',
    'phish': 'us-east-1',
    'malware': 'us-west-1',
    'content': 'us-west-1',
    'scam': 'us-west-1',
}

MESSAGES: Dict[str, str] = {
    'BAD_REQUEST_ERROR': 'API call failed: Bad Request. Error: ',
    'AUTHORIZATION_ERROR': 'Unauthorized. S3 Access Key or S3 Secret Key is invalid. Error: ',
    'NOT_FOUND_ERROR': 'Not found. Error: ',
    'SERVER_ERROR': 'API call failed. Server error received. Error: ',
    'PROXY_ERROR': 'Proxy Error - if the \'Use system proxy\' checkbox in the integration\
                    configuration is selected, try clearing the checkbox. Error: ',
    'HTTP_CLIENT_ERROR': 'API call failed. Check the parameters configured. Error: ',
    'ERROR': 'API call failed. Error: ',
    'INVALID_FEED_TYPE_ERROR': 'Invalid feed type.',
    'REQUIRED_FEED_TYPE_ERROR': 'Argument feedType is mandatory.',
    'INVALID_LIMIT_ERROR': 'Argument limit must be a positive integer between 1 to 1000.',
    'BLANK_PROXY_ERROR': 'https proxy value is empty. Check XSOAR server configuration ',
    'Feed_EXTRACT_ERROR': 'Unable to extract feeds. Error: ',
    'INVALID_FIRST_FETCH_INTERVAL_ERROR': 'First fetch time range must be "number time_unit", '
                                          'examples: (10 days, 6 months, 1 year, etc.)',
    'INVALID_FIRST_FETCH_UNIT_ERROR': 'First fetch time range field\'s unit is invalid. Must be in day(s), '
                                      'month(s) or year(s)',
    'INVALID_MAX_INDICATORS_ERROR': 'Max Indicators Per Interval must be a positive integer.',
    'NO_INDICATORS_FOUND': 'No indicators found for the given argument(s).'
}

class Client:
    """
    Client to use in integration to fetch data from Amazon S3.
    Creates instance of botot3 client and Handles exceptions.
    """

    def __init__(self, access_key: str, secret_key: str, verify: bool, proxy: bool):
        self.access_key = access_key
        self.secret_key = secret_key
        self.verify = verify

        # Set proxy
        if proxy:
            proxies = handle_proxy()

            # Throws a ValueError if Proxy is empty in configuration.
            if not proxies.get('https', True):
                raise ValueError(MESSAGES['BLANK_PROXY_ERROR'] + str(proxies))

            self.config = config.Config(proxies=proxies)
        else:
            self.config = config.Config(proxies={})

        self.s3_client: Any = None

    def set_s3_client(self, region_name: Optional[str]) -> None:
        """
        Create S3 Client instance specific to region.

        :param region_name: Name of the S3 supported region.
        :return: None
        """
        self.s3_client = s3.client('s3', aws_access_key_id=self.access_key,
                                   region_name=region_name,
                                   aws_secret_access_key=self.secret_key, verify=self.verify,
                                   config=self.config)

    def return_error_based_on_status_code(self, status_code: int, error_message: str) -> Optional[None]:
        """
        Return error message based on status code.
        Throws a ValueError based on respected status code.

        :param status_code: HTTP response code.
        :param error_message: Error message.
        :return: return_error
        """
        if status_code == 400:
            raise ValueError(MESSAGES['BAD_REQUEST_ERROR'] + error_message)
        elif status_code == 401 or status_code == 403:
            raise ValueError(MESSAGES['AUTHORIZATION_ERROR'] + error_message)
        elif status_code == 404:
            raise ValueError(MESSAGES['NOT_FOUND_ERROR'] + error_message)
        elif status_code >= 500:
            raise ValueError(MESSAGES['SERVER_ERROR'] + error_message)

    def request_list_objects(self, feed_type: str, max_keys: int = 1000, start_after: str = '', prefix: str = '') -> \
            List[Dict[str, Any]]:
        """
        Makes the API call to Amazon S3 using the boto3 list_objects method to retrieve the keys of objects.

        :param feed_type: Type of the feed. That is map with bucket.
        :param max_keys: Sets the maximum number of keys returned in the response.
        :param start_after: Start_after is where you want Amazon S3 to start listing from. Amazon S3 starts listing
        after this specified key.
        :param prefix: Limits the response to keys that begin with the specified prefix.
        :return: list of keys.
        """
        response = self.s3_client.list_objects_v2(Bucket=BUCKETS.get(feed_type, ''),
                                                  MaxKeys=max_keys,
                                                  StartAfter=start_after,
                                                  Prefix=prefix)
        return response.get('Contents', [])

    def request_select_object_content(self, feed_type: str, key: str, limit: str = None,
                                      search: str = None, delimiter: str = '\t') -> csv.DictReader:
        """
         Makes the API call to Amazon S3 using the boto3 select_objecy_content method to retrieve the feeds.
         Method will execute search and limit records using SQL query provided.
         Used in get-indicators command.

        :param feed_type: Type of the feed. That is map with bucket.
        :param key: Return data of specified key.
        :param limit: Number of records to fetch.
        :param search: To search specific feeds from S3.
        :param delimiter: character to split feed from.
        :return: String of records.
        """
        query = "Select * from S3Object s where s._1 LIKE '%{0}%' ESCAPE '\\' LIMIT {1}" if search \
            else "Select * from S3Object s LIMIT {}"
        response = self.s3_client.select_object_content(
            Bucket=BUCKETS.get(feed_type, ''),
            Key=key,
            ExpressionType='SQL',
            Expression=query.format(search, limit) if search else query.format(limit),
            InputSerialization={
                'CompressionType': 'GZIP',
                'CSV': {
                    'FileHeaderInfo': 'NONE',
                    'RecordDelimiter': '\n',
                    'FieldDelimiter': '\t',
                    'QuoteCharacter': '\t',
                    'AllowQuotedRecordDelimiter': True
                }
            },
            OutputSerialization={
                'CSV': {
                    'RecordDelimiter': '\n',
                    'FieldDelimiter': '\t',
                }
            }
        )
        records: List[bytes] = []
        for event in response.get('Payload', ''):
            if 'Records' in event:
                records.append(event['Records']['Payload'])
            elif 'end' in event:
                return csv.DictReader('')

        response_string = ''.join(r.decode('utf-8') for r in records)
        return csv.DictReader(response_string.splitlines(),
                              fieldnames=FIELD_NAMES.get(feed_type),
                              delimiter=delimiter, quoting=csv.QUOTE_NONE)

    def build_iterator(self, feed_type: str, key: str, limit: str = None, search: str = None, batch_size: int = 2000,
                       **kwargs) -> Any:
        """
        Retrieves all entries from the streaming response batch wise
        and prepares dictionaries of feeds.
        If any parameter required to get response from S3 is invalid then throws a ValueError.

        :param feed_type: Type of the feed. That is map with bucket.
        :param key: Return data of specified key.
        :param start_from: Integer line number to start reading file from.
        :param limit: Number of records to fetch.
        :param search: To search specific feeds from S3.
        :param delimiter: character to split feed from.
        :param batch_size: size of feeds batch to return.
        :return: list of feed dictionaries.
        """
        try:

            if kwargs.get('is_get_indicators', False):
                # Request for get-indicators
                yield self.request_select_object_content(feed_type, key, limit, search, kwargs.get('delimiter', '\t'))
            else:
                if not os.path.exists(feed_type):
                    self.s3_client.download_file(Bucket=BUCKETS.get(feed_type, ''), Key=key, Filename=feed_type)

                file_stream = gzip.open(feed_type, 'rt')

                while True:
                    # Creating feeds batch
                    feed_batch = [feed for _, feed in zip(range(batch_size), file_stream) if feed]

                    if not feed_batch:
                        file_stream.close()
                        os.remove(feed_type)
                        return

                    yield csv.DictReader(feed_batch, fieldnames=FIELD_NAMES.get(feed_type),
                                         delimiter=kwargs.get('delimiter', '\t'),
                                         quoting=csv.QUOTE_NONE)

        except botocore.exceptions.ClientError as exception:
            status_code = exception.response.get('ResponseMetadata', {}).get('HTTPStatusCode', '')
            error_message = exception.response.get('Error', {}).get('Message', '')
            self.return_error_based_on_status_code(status_code, error_message)

        except botocore.exceptions.ProxyConnectionError as exception:
            raise ValueError(MESSAGES['PROXY_ERROR'] + str(exception))

        except botocore.exceptions.HTTPClientError as exception:
            raise ValueError(MESSAGES['HTTP_CLIENT_ERROR'] + str(exception))

        except Exception as exception:
            raise ValueError(MESSAGES['ERROR'] + str(exception))

''' HELPER FUNCTIONS '''

def validate_feeds(feed_types: List[str]) -> None:
    """
    Checks that given feeds are exist or not.
    If feed_types is empty then throws a ValueError.
    If any feed_type is not exist in BUCKET throws a ValueError.

    :param feed_types: Feed types provided.
    :return: True if feeds exist else return error.
    """
    if not feed_types:
        raise ValueError(MESSAGES['REQUIRED_FEED_TYPE_ERROR'])
    for feed in feed_types:
        if feed not in BUCKETS:
            raise ValueError(MESSAGES['INVALID_FEED_TYPE_ERROR'])

def get_last_key_from_integration_context_dict(feed_type: str, integration_context: List[Any] = []) -> \
        str:
    """
    To get last fetched key of feed from integration context.

    :param feed_type: Type of feed to get last fetched key.
    :param integration_context: Integration context.
    :return: list of S3 object keys.
    """
    feed_context = integration_context
    for cached_feed in feed_context:
        cached_key = cached_feed.get(feed_type, '')
        if cached_key:
            return cached_key
    return ''

def set_last_key_to_integration_context_dict(feed_type: str, key: str,
                                             integration_context: List[Any]) -> None:
    """
    To set last fetched key of feed to integration context.

    :param feed_type: Type of feed to set.
    :param integration_context: context retrieved from integration context.
    :param key: Key to set.
    :return: None
    """
    for f_type_dict in integration_context:
        if f_type_dict.get(feed_type, ''):
            f_type_dict[feed_type] = key
            return
    integration_context.append({feed_type: key})

def validate_limit(limit: str) -> None:
    """
    Validates the limit argument.
    If the limit is 0 >= limit > 1000 or not an integer then throws a ValueError.

    :param limit: Number of feeds to fetch .
    :return: None
    """
    try:
        val = int(limit)
        if val <= 0 or val > 1000:
            raise ValueError
    except ValueError:
        raise ValueError(MESSAGES['INVALID_LIMIT_ERROR'])

def prepare_date_string_for_custom_fields(date_string: str) -> str:
    """
    Prepares date string in iso format and adds timezone if not exist.

    :param date_string: string represent date.
    :return: formatted date string.
    """
    parsed_dt = dateparser.parse(date_string)
    if parsed_dt:
        if parsed_dt.tzinfo is None:
            parsed_dt = parsed_dt.replace(tzinfo=timezone.utc)
        return parsed_dt.isoformat()
    return ''

def indicator_field_mapping(feed_type: str, indicator: Dict[str, Any], tags: List[str],
                            tlp_color: Optional[str]) -> Dict[str, Any]:
    """
    Maps the indicator fields.

    :param feed_type: Type of feed.
    :param indicator: Indicator dictionary.
    :param tags: Tags specified in configuration.
    :param tlp_color: Traffic Light Protocol color.
    :return: Dict of fields.
    """
    fields: Dict[str, Any] = {
        'service': 'Passive Total',
        'tags': tags
    }
    if tlp_color:
        fields['trafficlightprotocol'] = tlp_color

    if feed_type == 'domain':
        if indicator.get('Timestamp'):
            fields['firstseenbysource'] = datetime.fromtimestamp(int(indicator.get('Timestamp')),  # type: ignore
                                                                 timezone.utc).isoformat()
    else:
        fields['threattypes'] = [{'threatcategory': feed_type.capitalize() if feed_type != 'phish' else 'Phishing'}]
        if indicator.get('MatchType'):
            fields['sismatchtype'] = indicator['MatchType']

        if feed_type == 'malware':
            if indicator.get('MalwareType'):
                fields['sismalwaretype'] = indicator['MalwareType']

            if indicator.get('MaliciousExpiration'):
                fields['sisexpiration'] = prepare_date_string_for_custom_fields(
                    indicator['MaliciousExpiration'])
        else:
            if indicator.get('Category'):
                fields['siscategory'] = indicator['Category']

            if indicator.get('Expiration'):
                fields['sisexpiration'] = prepare_date_string_for_custom_fields(indicator['Expiration'])
    remove_nulls_from_dictionary(fields)
    return fields

def validate_first_fetch_interval(first_fetch_interval):
    """
    Validating first fetch interval. it should be in form of (<number> <time unit>, e.g., 12 hours, 7 days,
    3 months, 1 year)
    raise value error if validation fails.

    :param first_fetch_interval: first fetch interval
    :return: None
    """
    range_split = first_fetch_interval.split(' ')
    if len(range_split) != 2:
        raise ValueError(MESSAGES['INVALID_FIRST_FETCH_INTERVAL_ERROR'])
    if not range_split[0].isdigit():
        raise ValueError(MESSAGES['INVALID_FIRST_FETCH_INTERVAL_ERROR'])
    if not range_split[1] in ['minute', 'minutes', 'hours', 'hour', 'day', 'days', 'month', 'months', 'year', 'years']:
        raise ValueError(MESSAGES['INVALID_FIRST_FETCH_UNIT_ERROR'])

def get_latest_key(client: Client, feed_type: str, first_fetch_interval: str,
                   is_get_indicators: bool = False, integration_context: List[Any] = []) -> str:
    """
    Get latest key from bucket of specified feed type.

    :param first_fetch_interval: first fetch interval.
    :param client: Client object.
    :param feed_type: Type of feed.
    :param is_get_indicators: True if get-indicators command is called.
    :param integration_context: Retrieved integration context.
    :return:
    """
    # Retrieving cached key from integration context.
    cached_key = get_last_key_from_integration_context_dict(feed_type, integration_context)
    object_key_list = client.request_list_objects(feed_type=feed_type, start_after=cached_key,
                                                  prefix=feed_type.lower())
    object_key_list = [object_key for object_key in object_key_list if '.gz' in object_key.get('Key', '')]
    object_key_list.sort(key=lambda key_dict: key_dict['LastModified'])

    if is_get_indicators:
        return object_key_list[-1].get('Key', '') if object_key_list else cached_key

    # Parsing first fetch time.
    date_from, now = dateparser.parse(f'{first_fetch_interval} UTC'), datetime.now(timezone.utc)

    # Fetching latest object keys.
    latest_key_list: List[str] = [key_dict.get('Key', '') for key_dict in
                                  object_key_list if
                                  key_dict.get('LastModified', now) >= date_from]

    return latest_key_list[0] if latest_key_list else cached_key

''' REQUESTS FUNCTIONS '''

@logger
def test_module(client: Client, feed_type: str) -> Optional[str]:
    """
    Performs test connectivity by valid response.
    If any parameter required to get response from S3 is invalid then throws a ValueError.

    :param client: boto3 client
    :param feed_type: Type of feed to test.
    :return: 'ok' if test passed, anything else will fail the test.
    """
    try:
        client.set_s3_client(REGIONS[feed_type])
        client.request_list_objects(feed_type=feed_type, max_keys=1)
    except botocore.exceptions.ClientError as exception:
        status_code = exception.response.get('ResponseMetadata', {}).get('HTTPStatusCode', '')
        error_message = exception.response.get('Error', {}).get('Message', '')
        client.return_error_based_on_status_code(status_code, error_message)

    except botocore.exceptions.ProxyConnectionError as exception:
        raise ValueError(MESSAGES['PROXY_ERROR'] + str(exception))

    except botocore.exceptions.HTTPClientError as exception:
        raise ValueError(MESSAGES['HTTP_CLIENT_ERROR'] + str(exception))
    except Exception as exception:
        raise ValueError(MESSAGES['ERROR'] + str(exception))
    return 'ok'

@logger
def fetch_indicators_command(client: Client, feed_types: List[str], first_fetch_interval: str = '7 day',
                             limit: str = None, search: str = None, batch_size: int = 2000,
                             **kwargs) -> Generator:
    """
    Fetches indicators from the S3 to the indicators tab.

    :param client: client object.
    :param feed_types: Types of feeds to fetch.
    :param first_fetch_interval: Interval to look back first time to fetch indicators.
    :param search: To search specific feeds from S3.
    :param limit: Number of records to fetch.
    :param batch_size: Size of the batch to create indicators.
    :param is_get_indicators: return true if get-indicators command called.
    :return: list of indicators.
    """

    for feed in feed_types:
        client.set_s3_client(region_name=REGIONS[feed])

        latest_key = get_latest_key(client, feed, first_fetch_interval,
                                    kwargs.get('is_get_indicators', False),
                                    kwargs.get('integration_context', []))

        if latest_key:
            feed_batches = client.build_iterator(feed_type=feed, key=latest_key, limit=limit, search=search,
                                                 batch_size=batch_size,
                                                 is_get_indicators=kwargs.get('is_get_indicators', False))
            for feed_dicts in feed_batches:
                indicators = []
                # Iterating trough each feed dictionary and creating indicators.
                for feed_dict in feed_dicts:
                    value = feed_dict.get('value', '')
                    if value:
                        indicator_type = INDICATOR_TYPES.get(feed)
                        feed_dict['type'] = indicator_type
                        remove_nulls_from_dictionary(feed_dict)
                        indicators.append({
                            'value': value,
                            'type': indicator_type,
                            'rawJSON': feed_dict,
                            'fields': indicator_field_mapping(feed, indicator=feed_dict, tags=kwargs.get('tags', []),
                                                              tlp_color=kwargs.get('tlp_color'))
                        })

                yield indicators

            # Setting last key to context.
            if not kwargs.get('is_get_indicators', False):
                set_last_key_to_integration_context_dict(feed_type=feed, key=latest_key,
                                                         integration_context=kwargs.get('integration_context', []))

@logger
def get_indicators_command(client: Client, args: Dict[str, str]) -> Union[CommandResults, str]:
    """
    Wrapper for retrieving indicators from the feed to the war-room.

    :param client: Client object.
    :param args: demisto arguments.
    :return: CommandResult instance.
    """
    # Retrieving command arguments.
    feed_type = args.get('feed_type', 'domain').lower()
    feed_type = feed_type if feed_type != 'phishing' else 'phish'
    limit = args.get('limit', '50')
    search = args.get('search', '')

    # Validate the provided limit
    validate_limit(limit)

    # Validate the provided feed type.
    validate_feeds([feed_type])

    # Retrieving indicators from fetch indicators command.
    indicators_list: List[Dict] = []
    for indicators in fetch_indicators_command(client, [feed_type], limit=limit, search=search,
                                               is_get_indicators=True):
        indicators_list.extend(indicators)

    # Generating human-readable.
    if not indicators_list:
        return MESSAGES['NO_INDICATORS_FOUND']

    human_readable = '### Total indicators fetched: {}\n'.format(len(indicators_list))
    human_readable += tableToMarkdown('Indicators from Security Intelligence Services feed',
                                      indicators_list, ['value', 'type'], removeNull=True,
                                      headerTransform=lambda header: header.capitalize())

    # Returning command result.
    return CommandResults(readable_output=human_readable, raw_response=indicators_list)

''' COMMANDS MANAGER / SWITCH PANEL '''

def main() -> None:
    """
    PARSE AND VALIDATE INTEGRATION PARAMS
    """
    # Retrieving parameters.
    params = demisto.params()
    access_key = params.get('accessKey', '')
    secret_key = params.get('secretKey', '')
    verify_certificate = not params.get('insecure', False)
    use_proxy = params.get('proxy', False)
    feed_types = params.get('feedType', [])
    first_fetch_interval = params.get('firstFetchInterval', '1 day')

    try:
        # Prepare tags and tlp
        tags = list(set(argToList(params.get('feedTags', ''))))
        tlp_color = params.get('tlp_color')

        # validate first_fetch_time_interval parameter
        validate_first_fetch_interval(first_fetch_interval)

        # Validate the provided feed types.
        feed_types_lower = [feed_type.lower() if 'phish' not in feed_type.lower() else 'phish' for feed_type in
                            feed_types]
        validate_feeds(feed_types_lower)

        client = Client(
            verify=verify_certificate,
            access_key=access_key,
            secret_key=secret_key,
            proxy=use_proxy
        )

        if demisto.command() == 'test-module':
            demisto.results(test_module(client, feed_types_lower[0]))

        elif demisto.command() == 'fetch-indicators':

            integration_context = demisto.getIntegrationContext().get('SISContext', [])

            indicators_generator = fetch_indicators_command(client, feed_types=feed_types_lower,
                                                            first_fetch_interval=first_fetch_interval,
                                                            batch_size=BATCH_SIZE,
                                                            integration_context=integration_context,
                                                            tags=tags,
                                                            tlp_color=tlp_color)
            for indicators in indicators_generator:
                demisto.createIndicators(indicators)  # type: ignore

            demisto.setIntegrationContext({'SISContext': integration_context})

        elif demisto.command() == 'sis-get-indicators':
            return_results(get_indicators_command(client, demisto.args()))
    # Log exceptions
    except Exception as e:
        demisto.error(traceback.format_exc())
        return_error('Failed to execute {0} command. Error: {1}'.format(demisto.command(), str(e)))

if __name__ in ('__main__', '__builtin__', 'builtins'):
    main()


text:
#if !defined(SERIALPORT_MAC_H_INCLUDED) && defined (__APPLE__)
#define SERIALPORT_MAC_H_INCLUDED

#include "serialport_posix.h"

class SerialPortMac : public SerialPortPosix
{
public:
    wxArrayString GetSerialPortList() override;
};

#endif  // SERIALPORT_MAC_H_INCLUDED


text:
#ifndef TENSORFLOW_KERNELS_OPS_TESTUTIL_H_
#define TENSORFLOW_KERNELS_OPS_TESTUTIL_H_

#include <memory>
#include <vector>

#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/gtl/stl_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/tensor_slice_reader_cache.h"

namespace tensorflow {

namespace test {

// Return a NodeDef with the specified name/op/inputs.
NodeDef Node(const string& name, const string& op,
             const std::vector<string>& inputs);

inline void SetOutputAttrs(OpKernelContext::Params* params,
                           std::vector<AllocatorAttributes>* attrs) {
  attrs->clear();
  for (int index = 0; index < params->op_kernel->num_outputs(); index++) {
    AllocatorAttributes attr;
    const bool on_host =
        (params->op_kernel->output_memory_types()[index] == HOST_MEMORY);
    attr.set_on_host(on_host);
    attrs->push_back(attr);
  }
  params->output_attr_array = gtl::vector_as_array(attrs);
}

}  // namespace test

// Helpful functions to test operators.
//
// This class will eventually be replaced / heavily modified
// to use the BrainClient interface.
class OpsTestBase : public ::testing::Test {
 public:
  OpsTestBase() : device_type_(DEVICE_CPU) {
    device_.reset(
        DeviceFactory::NewDevice("CPU", {}, "/job:a/replica:0/task:0"));
    CHECK(device_.get()) << "Could not create CPU device";
  }

  ~OpsTestBase() override {
    gtl::STLDeleteElements(&tensors_);
    context_.reset(nullptr);
    params_.reset(nullptr);
  }

  void set_node_def(const NodeDef& node_def) { node_def_.CopyFrom(node_def); }

  // Clients can manipulate the underlying NodeDef via this accessor.
  NodeDef* node_def() { return &node_def_; }

  // Initializes an operator that takes in 'input_types' as input
  // and output types as output.
  //
  // Returns the status of initialization.
  Status InitOp() { return InitOpWithGraphVersion(TF_GRAPH_DEF_VERSION); }

  // Only use this directly if you have a deprecated op that you need to test.
  Status InitOpWithGraphVersion(int graph_def_version) {
    Status status;
    kernel_ = CreateOpKernel(device_type_, device_.get(), allocator(),
                             node_def_, graph_def_version, &status);
    if (kernel_ != nullptr) input_types_ = kernel_->input_types();
    return status;
  }

  // Adds an input for every element described by the shape.
  // 'input_mapping' maps an index (0...NumElements(shape)) to a
  // value.
  //
  // TODO(vrv): Replace with something like a BrainClient Feed.
  template <typename T>
  void AddInput(const TensorShape& shape, std::function<T(int)> input_mapping) {
    CHECK_GT(input_types_.size(), inputs_.size())
        << "Adding more inputs than types; perhaps you need to call MakeOp";
    bool is_ref = IsRefType(input_types_[inputs_.size()]);
    Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
                               DataTypeToEnum<T>::v(), shape);
    test::FillFn(input, input_mapping);
    tensors_.push_back(input);
    if (is_ref) {
      CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]),
               DataTypeToEnum<T>::v());
      inputs_.push_back({&lock_for_refs_, input});
    } else {
      CHECK_EQ(input_types_[inputs_.size()], DataTypeToEnum<T>::v());
      inputs_.push_back({nullptr, input});
    }
  }

  // Like AddInput but takes in an explicit arrayslice of data.
  template <typename T>
  void AddInputFromArray(const TensorShape& shape,
                         const gtl::ArraySlice<T>& data) {
    CHECK_GT(input_types_.size(), inputs_.size())
        << "Adding more inputs than types; perhaps you need to call MakeOp";
    bool is_ref = IsRefType(input_types_[inputs_.size()]);
    Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
                               DataTypeToEnum<T>::v(), shape);
    test::FillValues<T>(input, data);
    tensors_.push_back(input);
    if (is_ref) {
      CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]),
               DataTypeToEnum<T>::v());
      inputs_.push_back({&lock_for_refs_, input});
    } else {
      CHECK_EQ(input_types_[inputs_.size()], DataTypeToEnum<T>::v());
      inputs_.push_back({nullptr, input});
    }
  }

  // Convenience function to add an input and populate it with the elements from
  // an initializer list converting the types as needed.
  template <typename T, typename SrcType>
  void AddInputFromList(const TensorShape& shape,
                        std::initializer_list<SrcType> data) {
    CHECK_GT(input_types_.size(), inputs_.size())
        << "Adding more inputs than types; perhaps you need to call MakeOp";
    bool is_ref = IsRefType(input_types_[inputs_.size()]);
    Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
                               DataTypeToEnum<T>::v(), shape);
    test::FillValues<T>(input, data);
    tensors_.push_back(input);
    if (is_ref) {
      CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]),
               DataTypeToEnum<T>::v());
      inputs_.push_back({&lock_for_refs_, input});
    } else {
      CHECK_EQ(input_types_[inputs_.size()], DataTypeToEnum<T>::v());
      inputs_.push_back({nullptr, input});
    }
  }

  // Runs an operation producing 'num_outputs' outputs.
  //
  // Returns the context's status after running the operation.
  Status RunOpKernel() {
    // Make sure the old OpKernelContext is deleted before the Params
    // it was using.
    context_.reset(nullptr);

    params_.reset(new OpKernelContext::Params);
    params_.get()->device = device_.get();
    params_.get()->frame_iter = FrameAndIter(0, 0);
    params_.get()->inputs = &inputs_;
    params_.get()->op_kernel = kernel_.get();
    std::vector<AllocatorAttributes> attrs;
    test::SetOutputAttrs(params_.get(), &attrs);
    checkpoint::TensorSliceReaderCacheWrapper slice_reader_cache_wrapper;
    params_.get()->slice_reader_cache = &slice_reader_cache_wrapper;

    context_.reset(new OpKernelContext(params_.get()));
    device_->Compute(kernel_.get(), context_.get());
    return context_->status();
  }

  // Returns the tensor input for 'input_index'.
  //
  // REQUIRES: 0 <= input_index < context_->num_inputs()
  const Tensor& GetInput(int input_index) const {
    CHECK_LT(input_index, context_->num_inputs());
    CHECK(!IsRefType(context_->input_dtype(input_index)));
    return context_->input(input_index);
  }

  TensorValue mutable_input(int input_index) {
    CHECK_LT(input_index, inputs_.size());
    return inputs_[input_index];
  }
  // Returns the tensor output for 'output_index'.
  //
  // REQUIRES: 0 <= output_index < context_->num_outputs()
  Tensor* GetOutput(int output_index) {
    CHECK_LT(output_index, context_->num_outputs());
    return context_->mutable_output(output_index);
  }

  Allocator* allocator() {
    return device_->GetAllocator(AllocatorAttributes());
  }

  const DataTypeVector& output_types() const { return kernel_->output_types(); }

 protected:
  std::unique_ptr<Device> device_;

  std::unique_ptr<OpKernel> kernel_;
  NodeDef node_def_;
  DataTypeVector input_types_;
  DeviceType device_type_;

  mutex lock_for_refs_;  // Used as the Mutex for inputs added as refs

  gtl::InlinedVector<TensorValue, 4> inputs_;
  // Owns Tensors.
  std::vector<Tensor*> tensors_;

  std::unique_ptr<OpKernelContext::Params> params_;
  std::unique_ptr<OpKernelContext> context_;

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(OpsTestBase);
};

}  // namespace tensorflow

#endif  // TENSORFLOW_KERNELS_OPS_TESTUTIL_H_


text:
.om-resizable { position: relative;}
.om-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block; }
.om-resizable-disabled .om-resizable-handle, .om-resizable-autohide .om-resizable-handle { display: none; }
.om-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; }
.om-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; }
.om-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; }
.om-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; }
.om-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
.om-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
.om-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
.om-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}


text:
from anima.env.fusion.model.projectPath import *
from anima.env.fusion.model.fusion import *
from anima.env.fusion.view.view import form

class controller(object):
	def __init__(self):
		#path
		self.path = project()
		self.path.projectList()

		#view
		self.projectForm = form()
		self.shotForm = form()
		self.sequenceForm= form()
		self.fusion = fusion()

	def projectSelect(self):
		form1 = self.projectForm.AskUser("Select Project", self.path.projectdict, 1)
		if form1 == None:
			print "Canceled by User"
			return None
		else:
			self.project = self.path.projectChoose(int(form1["project"]))
			self.sequence()

	def sequence(self):
		self.path.sequencesList()
		self.path.sequenceDict()
		form2 = self.sequenceForm.AskUser(self.project, self.path.sequencedict, 2)
		if form2 == None:
			print "Canceled by User"
			return None
		else:
			self.path.sequenceSelect(form2["sequence"])
			self.shotLoop()
			#path.sequence(0)

	def shotLoop(self):
		self.plateloop = self.path.plateLoop()
		#Loader Loop sokuluyor
		for i in range(0,len(self.plateloop), 1):
			shot = self.path.selectShot(i)
			f = self.shotForm.AskUser(shot, self.plateloop[i], 0)
			if f == None:
				print "Canceled by User"
				break
			if self.path.fileCheck(f["Path"])== True:
				self.fusion.loader(self.path.shot, f["Path"], i, 0)
				print str(i+1)+" / "+str(len(self.plateloop)) + " Shots Completed " + f["Path"]
			else:
				print "Wrong yol: " + f["Path"]
				break

	def cStartEnd(self):
		self.fusion.compStartEnd()


text:
package org.python.util.install.driver;

import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.python.util.install.ConsoleInstaller;
import org.python.util.install.Installation;
import org.python.util.install.InstallerCommandLine;
import org.python.util.install.JavaHomeHandler;

public class InstallationDriver {
    private SilentAutotest[] _silentTests;
    private ConsoleAutotest[] _consoleTests;
    private GuiAutotest[] _guiTests;
    private InstallerCommandLine _commandLine;

    /**
     * construct the driver
     *
     * @param commandLine the console arguments
     *
     * @throws IOException
     * @throws DriverException
     */
    public InstallationDriver(InstallerCommandLine commandLine) throws DriverException {
        _commandLine = commandLine;
        try {
            buildSilentTests();
            buildConsoleTests();
            buildGuiTests();
        } catch (IOException ioe) {
            throw new DriverException(ioe);
        }
    }

    /**
     * execute all the automatic tests
     *
     * @throws DriverException
     */
    public void drive() throws DriverException {
        try {
            // silent tests
            for (int i = 0; i < _silentTests.length; i++) {
                driveSilentTest(_silentTests[i]);
            }
            // console tests
            for (int i = 0; i < _consoleTests.length; i++) {
                driveConsoleTest(_consoleTests[i]);
            }
            // gui tests
            for (int i = 0; i < _guiTests.length; i++) {
                driveGuiTest(_guiTests[i]);
            }
        } catch (IOException ioe) {
            throw new DriverException(ioe);
        }
    }

    /**
     * execute a single console test
     *
     * @param consoleTest
     * @throws DriverException
     * @throws IOException
     * @throws IOException
     */
    private void driveConsoleTest(ConsoleAutotest consoleTest) throws DriverException, IOException {
        Tunnel _tunnel;
        _tunnel = new Tunnel();
        // have to fork off the driver thread first
        ConsoleDriver driver = new ConsoleDriver(_tunnel, consoleTest.getAnswers());
        driver.start();
        // now do the installation
        Installation.driverMain(consoleTest.getCommandLineArgs(), consoleTest, _tunnel);
        _tunnel.close();
        validate(consoleTest);
    }

    /**
     * execute a single silent test
     *
     * @param silentTest
     * @throws DriverException
     */
    private void driveSilentTest(SilentAutotest silentTest) throws DriverException {
        Installation.driverMain(silentTest.getCommandLineArgs(), silentTest, null); // only a thin wrapper
        validate(silentTest);
    }

    /**
     * execute a single gui test
     *
     * @param guiTest
     * @throws DriverException
     */
    private void driveGuiTest(GuiAutotest guiTest) throws DriverException {
        Installation.driverMain(guiTest.getCommandLineArgs(), guiTest, null); // only a thin wrapper
        guiTest.execute();
        validate(guiTest);
    }

    /**
     * perform validations after the test was run
     *
     * @param autoTest
     * @throws DriverException
     */
    private void validate(Autotest autoTest) throws DriverException {
        autoTest.assertTargetDirNotEmpty();
        if (autoTest.getVerifier() != null) {
            System.out.println("verifying installation - this can take a while ...");
            autoTest.getVerifier().verify();
            System.out.println("... installation ok.\n");
        }
    }

    /**
     * @return the command line the autotest session was started with
     */
    private InstallerCommandLine getOriginalCommandLine() {
        return _commandLine;
    }

    /**
     * build all the silent tests
     *
     * @throws IOException
     * @throws DriverException
     */
    private void buildSilentTests() throws IOException, DriverException {
        List<SilentAutotest> silentTests = new ArrayList<SilentAutotest>(50);

        SilentAutotest test1 = new SilentAutotest(getOriginalCommandLine());
        String[] arguments = new String[] { "-s" };
        test1.setCommandLineArgs(arguments);
        test1.addAdditionalArguments(); // this also adds target directory
        test1.setVerifier(new NormalVerifier());
        silentTests.add(test1);

        SilentAutotest test2 = new SilentAutotest(getOriginalCommandLine());
        arguments = new String[] { "-s", "-t", "minimum" };
        test2.setCommandLineArgs(arguments);
        test2.addAdditionalArguments();
        test2.setVerifier(new NormalVerifier());
        silentTests.add(test2);

        SilentAutotest test3 = new SilentAutotest(getOriginalCommandLine());
        arguments = new String[] { "-s", "-t", "standalone" };
        test3.setCommandLineArgs(arguments);
        test3.addAdditionalArguments();
        test3.setVerifier(new StandaloneVerifier());
        silentTests.add(test3);

        // build array
        int size = silentTests.size();
        _silentTests = new SilentAutotest[size];
        Iterator<SilentAutotest> silentIterator = silentTests.iterator();
        for (int i = 0; i < size; i++) {
            _silentTests[i] = silentIterator.next();
        }
    }

    /**
     * build all the console tests
     *
     * @throws IOException
     * @throws DriverException
     */
    private void buildConsoleTests() throws IOException, DriverException {
        List<ConsoleAutotest> consoleTests = new ArrayList<ConsoleAutotest>(5);
        final String[] arguments;
        if (getOriginalCommandLine().hasVerboseOption()) {
            arguments = new String[] { "-c", "-v" };
        } else {
            arguments = new String[] { "-c" };
        }
        // do NOT call addAdditionalArguments()

        ConsoleAutotest test1 = new ConsoleAutotest(getOriginalCommandLine());
        test1.setCommandLineArgs(arguments);
        test1.addAnswer("e"); // language
        test1.addAnswer("n"); // no read of license
        test1.addAnswer("y"); // accept license
        test1.addAnswer("3"); // type: minimum
        test1.addAnswer("n"); // include: nothing
        test1.addAnswer(test1.getTargetDir().getAbsolutePath()); // target directory
        addJavaAndOSAnswers(test1);
        test1.addAnswer("y"); // confirm copying
        test1.addAnswer("n"); // no readme
        test1.setVerifier(new NormalVerifier());
        consoleTests.add(test1);

        ConsoleAutotest test2 = new ConsoleAutotest(getOriginalCommandLine());
        test2.setCommandLineArgs(arguments);
        test2.addAnswer("e"); // language
        test2.addAnswer("n"); // no read of license
        test2.addAnswer("y"); // accept license
        test2.addAnswer("3"); // type: minimum
        test2.addAnswer("y"); // include
        test2.addAnswer("mod"); // include
        test2.addAnswer("demo"); // include
        test2.addAnswer("src"); // include
        test2.addAnswer("n"); // no further includes
        test2.addAnswer("y"); // exclude
        test2.addAnswer("demo"); // exclude
        test2.addAnswer("wrongAnswer"); // wrong answer
        test2.addAnswer("n"); // no further excludes
        test2.addAnswer(test2.getTargetDir().getAbsolutePath()); // target directory
        addJavaAndOSAnswers(test2);
        test2.addAnswer("y"); // confirm copying
        test2.addAnswer("n"); // no readme
        test2.setVerifier(new NormalVerifier());
        consoleTests.add(test2);

        ConsoleAutotest test3 = new ConsoleAutotest(getOriginalCommandLine());
        test3.setCommandLineArgs(arguments);
        test3.addAnswer("e"); // language
        test3.addAnswer("n"); // no read of license
        test3.addAnswer("y"); // accept license
        test3.addAnswer("9"); // type: standalone
        test3.addAnswer(test3.getTargetDir().getAbsolutePath()); // target directory
        addJavaAndOSAnswers(test3);
        test3.addAnswer("y"); // confirm copying
        test3.addAnswer("n"); // no readme
        test3.setVerifier(new StandaloneVerifier());
        consoleTests.add(test3);

        // test for bug 1783960
        ConsoleAutotest test4 = new ConsoleAutotest(getOriginalCommandLine());
        test4.setCommandLineArgs(arguments);
        test4.addAnswer("e"); // language
        test4.addAnswer("n"); // no read of license
        test4.addAnswer("y"); // accept license
        test4.addAnswer("2"); // type: standard
        test4.addAnswer("n"); // no includes
        test4.addAnswer("y"); // exclude
        test4.addAnswer("n"); // no further excludes
        test4.addAnswer(test4.getTargetDir().getAbsolutePath()); // target directory
        addJavaAndOSAnswers(test4);
        test4.addAnswer("y"); // confirm copying
        test4.addAnswer("n"); // no readme
        test4.setVerifier(new NormalVerifier());
        consoleTests.add(test4);

        // build array
        int size = consoleTests.size();
        _consoleTests = new ConsoleAutotest[size];
        Iterator<ConsoleAutotest> consoleIterator = consoleTests.iterator();
        for (int i = 0; i < size; i++) {
            _consoleTests[i] = consoleIterator.next();
        }
    }

    private void addJavaAndOSAnswers(ConsoleAutotest test) {
        JavaHomeHandler javaHomeHandler = test.getJavaHomeHandler();
        if (javaHomeHandler.isDeviation() && javaHomeHandler.isValidHome()) {
            test.addAnswer(javaHomeHandler.getHome().getAbsolutePath()); // different jre
        } else {
            test.addAnswer(ConsoleInstaller.CURRENT_JRE);
        }
        if (!Installation.isValidOs()) {
            test.addAnswer(""); // enter to proceed anyway
        }
    }

    /**
     * build all the gui tests
     *
     * @throws IOException
     * @throws DriverException
     */
    private void buildGuiTests() throws IOException, DriverException {
        List<GuiAutotest> guiTests = new ArrayList<GuiAutotest>(50);

        if (Installation.isGuiAllowed()) {
            GuiAutotest guiTest1 = new GuiAutotest(getOriginalCommandLine());
            buildLanguageAndLicensePage(guiTest1);
            // type page - use 'Standard'
            guiTest1.addKeyAction(KeyEvent.VK_TAB);
            guiTest1.addKeyAction(KeyEvent.VK_TAB);
            guiTest1.addKeyAction(KeyEvent.VK_TAB);
            guiTest1.addKeyAction(KeyEvent.VK_TAB);
            guiTest1.addKeyAction(KeyEvent.VK_TAB);
            guiTest1.addKeyAction(KeyEvent.VK_TAB);
            guiTest1.addKeyAction(KeyEvent.VK_SPACE);
            buildRestOfGuiPages(guiTest1);
            guiTest1.setVerifier(new NormalVerifier());
            guiTests.add(guiTest1);

            GuiAutotest guiTest2 = new GuiAutotest(getOriginalCommandLine());
            buildLanguageAndLicensePage(guiTest2);
            // type page - use 'All'
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_SPACE); // select 'All'
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_TAB);
            guiTest2.addKeyAction(KeyEvent.VK_SPACE);
            buildRestOfGuiPages(guiTest2);
            guiTest2.setVerifier(new NormalVerifier());
            guiTests.add(guiTest2);

            GuiAutotest guiTest3 = new GuiAutotest(getOriginalCommandLine());
            buildLanguageAndLicensePage(guiTest3);
            // type page - use 'Custom'
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_SPACE); // select 'Custom'
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_SPACE); // deselect 'Demos and Examples'
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_SPACE); // deselect 'Documentation'
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_SPACE); // select 'Sources'
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_TAB);
            guiTest3.addKeyAction(KeyEvent.VK_SPACE);
            buildRestOfGuiPages(guiTest3);
            guiTest3.setVerifier(new NormalVerifier());
            guiTests.add(guiTest3);

            GuiAutotest guiTest4 = new GuiAutotest(getOriginalCommandLine());
            buildLanguageAndLicensePage(guiTest4);
            // type page - use 'Standalone'
            guiTest4.addKeyAction(KeyEvent.VK_TAB);
            guiTest4.addKeyAction(KeyEvent.VK_TAB);
            guiTest4.addKeyAction(KeyEvent.VK_SPACE); // select 'Standalone'
            guiTest4.addKeyAction(KeyEvent.VK_TAB);
            guiTest4.addKeyAction(KeyEvent.VK_TAB);
            guiTest4.addKeyAction(KeyEvent.VK_TAB);
            guiTest4.addKeyAction(KeyEvent.VK_TAB);
            guiTest4.addKeyAction(KeyEvent.VK_SPACE);
            buildRestOfGuiPages(guiTest4);
            guiTest4.setVerifier(new StandaloneVerifier());
            guiTests.add(guiTest4);
        }

        // build array
        int size = guiTests.size();
        _guiTests = new GuiAutotest[size];
        Iterator<GuiAutotest> guiIterator = guiTests.iterator();
        for (int i = 0; i < size; i++) {
            _guiTests[i] = guiIterator.next();
        }
    }

    private void buildLanguageAndLicensePage(GuiAutotest guiTest) {
        // language page
        guiTest.addKeyAction(KeyEvent.VK_E);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_SPACE);
        // license page
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_SPACE); // select "i accept"
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_SPACE);
    }

    private void buildRestOfGuiPages(GuiAutotest guiTest) {
        // directory page
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_SPACE);
        // java selection page
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        guiTest.addKeyAction(KeyEvent.VK_TAB);
        JavaHomeHandler javaHomeHandler = guiTest.getJavaHomeHandler();
        boolean isValidDeviation = javaHomeHandler.isDeviation() && javaHomeHandler.isValidHome();
        if (isValidDeviation) { // need 2 more tabs
            guiTest.addKeyAction(KeyEvent.VK_TAB);
            guiTest.addKeyAction(KeyEvent.VK_TAB);
        }
        guiTest.addKeyAction(KeyEvent.VK_SPACE);
        // overview page
        if (isValidDeviation) {
            guiTest.addKeyAction(KeyEvent.VK_SPACE, 3000); // enough time to check the java version
        } else {
            guiTest.addKeyAction(KeyEvent.VK_SPACE);
        }
        // installation page (skipped)
        // readme page
        guiTest.addWaitingKeyAction(KeyEvent.VK_TAB); // wait for the installation to finish
        guiTest.addKeyAction(KeyEvent.VK_SPACE);
        // success page
        guiTest.addKeyAction(KeyEvent.VK_SPACE);
    }
}


text:
package io.lettuce.core.cluster.api.sync;

import io.lettuce.core.cluster.api.NodeSelectionSupport;

/**
 * Synchronous and thread-safe Redis API to execute commands on a {@link NodeSelectionSupport}.
 *
 * @author Mark Paluch
 */
public interface NodeSelectionCommands<K, V>
        extends BaseNodeSelectionCommands<K, V>, NodeSelectionGeoCommands<K, V>, NodeSelectionHashCommands<K, V>,
        NodeSelectionHLLCommands<K, V>, NodeSelectionKeyCommands<K, V>, NodeSelectionListCommands<K, V>,
        NodeSelectionScriptingCommands<K, V>, NodeSelectionServerCommands<K, V>, NodeSelectionSetCommands<K, V>,
        NodeSelectionSortedSetCommands<K, V>, NodeSelectionStreamCommands<K, V>, NodeSelectionStringCommands<K, V> {
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace CollectionJson
{
    [DataContract]
    public class WriteDocument : IWriteDocument
    {
        [DataMember(Name = "template")]
        public Template Template { get; set; }
    }
}