text:
using System.Collections.Generic;
using System.Linq;
using AutoQueryable.Core.Aliases;
using AutoQueryable.Core.Clauses.ClauseHandlers;
using AutoQueryable.Core.Enums;
using AutoQueryable.Core.Models;

namespace AutoQueryable.Core.Clauses
{
    public class ClauseMapManager : IClauseMapManager
    {
        private readonly ISelectClauseHandler _selectClauseHandler;
        private readonly IOrderByClauseHandler _orderByClauseHandler;
        private readonly IWrapWithClauseHandler _wrapWithClauseHandler;
        private readonly IAutoQueryableProfile _autoQueryableProfile;
        private readonly ICollection<IClauseQueryFilter> _queryFilters = new List<IClauseQueryFilter>();

        public ClauseMapManager(ISelectClauseHandler selectClauseHandler, IOrderByClauseHandler orderByClauseHandler, IWrapWithClauseHandler wrapWithClauseHandler, IAutoQueryableProfile autoQueryableProfile)
        {
            _selectClauseHandler = selectClauseHandler;
            _orderByClauseHandler = orderByClauseHandler;
            _wrapWithClauseHandler = wrapWithClauseHandler;
            _autoQueryableProfile = autoQueryableProfile;
        }

        public void Init()
        {
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.Select))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.Select, ClauseType.Select, _selectClauseHandler.Handle));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.Top))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.Top, ClauseType.Top, (value, type, profile) => int.Parse(value)));
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.Take, ClauseType.Top, (value, type, profile) => int.Parse(value)));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.Skip))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.Skip, ClauseType.Skip, (value, type, profile) => int.Parse(value)));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.First))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.First, ClauseType.First));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.Last))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.Last, ClauseType.Last));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.OrderBy))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.OrderBy, ClauseType.OrderBy, _orderByClauseHandler.Handle));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.GroupBy))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.GroupBy, ClauseType.GroupBy));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.Page))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.Page, ClauseType.Page, (value, type, profile) => int.Parse(value)));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.PageSize))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.PageSize, ClauseType.PageSize, (value, type, profile) => int.Parse(value)));
            }
            if (_autoQueryableProfile.IsClauseAllowed(ClauseType.WrapWith))
            {
                _queryFilters.Add(new DefaultClauseQueryFilter(ClauseAlias.WrapWith, ClauseType.WrapWith, _wrapWithClauseHandler.Handle));
            }
        }

        public IClauseQueryFilter GetClauseQueryFilter(ClauseType clauseType) => _queryFilters.FirstOrDefault(f => f.ClauseType == clauseType);

        public IClauseQueryFilter FindClauseQueryFilter(string queryParameterKey) => _queryFilters.FirstOrDefault(clause => queryParameterKey.Contains(clause.Alias.ToLowerInvariant()));
    }
}


text:
@interface BSJTopicListDAL : NSObject

//parameters[@"a"] = typeA;
//parameters[@"c"] = @"data";
//parameters[@"type"] = @(topicType);
//parameters[@"maxtime"] = isMore ? self.maxtime : nil;
//parameters[@"per"] = @10;

+ (void)queryTopicListFromDiskWithAreaType:(NSString *)areaType topicType:(NSString *)topicType maxTime:(NSString *)maxTime per:(NSInteger)per completion:(void(^)(NSMutableArray<NSMutableDictionary *> *dictArrayM))completion;

+ (void)cachesTopicList:(NSMutableArray<NSMutableDictionary *> *)topics areaType:(NSString *)areaType;

+ (void)clearOutTimeCashes;

@end

redpajama_set_name: RedPajamaGithub


text: GnomePackage ('intltool', version_major = '0.40', version_minor = '6')


text:
package com.drew.lang;

import org.junit.Test;

/**
 * @author Drew Noakes https://drewnoakes.com
 */
public class ByteArrayReaderTest extends RandomAccessTestBase
{
    @Override
    protected RandomAccessReader createReader(byte[] bytes)
    {
        return new ByteArrayReader(bytes);
    }

    @SuppressWarnings({ "ConstantConditions" })
    @Test(expected = NullPointerException.class)
    public void testConstructWithNullBufferThrows()
    {
        new ByteArrayReader(null);
    }
}


text:
package org.copperengine.core.tranzient;

import java.util.Queue;

import org.copperengine.core.Interrupt;
import org.copperengine.core.ProcessingEngine;
import org.copperengine.core.ProcessingState;
import org.copperengine.core.Workflow;
import org.copperengine.core.common.Processor;
import org.copperengine.core.internal.WorkflowAccessor;

/**
 * Internally used class.
 *
 * @author austermann
 */
class TransientProcessor extends Processor {

    private TransientScottyEngine engine;

    public TransientProcessor(String name, Queue<Workflow<?>> queue, int prio, ProcessingEngine engine) {
        super(name, queue, prio, engine);
        this.engine = (TransientScottyEngine) engine;
    }

    @Override
    protected void process(Workflow<?> wf) {
        logger.trace("before - stack.size()={}", wf.get__stack().size());
        logger.trace("before - stack={}", wf.get__stack());
        synchronized (wf) {
            try {
                WorkflowAccessor.setProcessingState(wf, ProcessingState.RUNNING);
                wf.__beforeProcess();
                wf.main();
                logger.trace("after 'main' - stack={}", wf.get__stack());
                engine.removeWorkflow(wf.getId());
                assert wf.get__stack().isEmpty() : "Stack must be empty \n" + wf.get__stack();
            } catch (Interrupt e) {
                logger.trace("interrupt - stack={}", wf.get__stack());
                assert wf.get__stack().size() > 0;
            } catch (Exception e) {
                engine.removeWorkflow(wf.getId());
                logger.error("Execution of wf " + wf.getId() + " failed", e);
                assert wf.get__stack().isEmpty() : "Stack must be empty \n" + wf.get__stack();
            }
        }
    }
}


text:
@class ComGoodowRealtimeOperationUndoUndoManagerImpl_Checkpointer;
@class ComGoodowRealtimeOperationUndoUndoStack;
@class ComGoodowRealtimeOperationUtilPair;
@protocol ComGoodowRealtimeJsonJsonArray;
@protocol ComGoodowRealtimeOperationOperation;
@protocol ComGoodowRealtimeOperationTransformer;

#include "J2ObjC_header.h"
#include "com/goodow/realtime/operation/undo/UndoManagerPlus.h"

@interface ComGoodowRealtimeOperationUndoUndoManagerImpl : NSObject < ComGoodowRealtimeOperationUndoUndoManagerPlus > {
}

- (instancetype)initWithComGoodowRealtimeOperationTransformer:(id<ComGoodowRealtimeOperationTransformer>)algorithms;

- (jboolean)canRedo;

- (jboolean)canUndo;

- (void)checkpoint;

- (void)nonUndoableOpWithId:(id<ComGoodowRealtimeOperationOperation>)op;

- (id)redo;

- (ComGoodowRealtimeOperationUtilPair *)redoPlus;

- (id)undo;

- (void)undoableOpWithId:(id<ComGoodowRealtimeOperationOperation>)op;

- (ComGoodowRealtimeOperationUtilPair *)undoPlus;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeOperationUndoUndoManagerImpl)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeOperationUndoUndoManagerImpl)

@interface ComGoodowRealtimeOperationUndoUndoManagerImpl_Checkpointer : NSObject {
}

- (void)checkpoint;

- (void)increment;

- (jint)releaseCheckpoint;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeOperationUndoUndoManagerImpl_Checkpointer)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeOperationUndoUndoManagerImpl_Checkpointer)

#endif // _ComGoodowRealtimeOperationUndoUndoManagerImpl_H_


text:
@implementation PKAddressZip

+ (instancetype)addressZipWithString:(NSString *)string
{
    return [[self alloc] initWithString:string];
}

- (instancetype)initWithString:(NSString *)string
{
    if (self = [super init]) {
        _zip = [string copy];
    }
    return self;
}

- (NSString *)string
{
    return _zip;
}

- (BOOL)isValid
{
    NSString *stripped = [_zip stringByReplacingOccurrencesOfString:@"\\s"
                                                         withString:@""
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, _zip.length)];

    return stripped.length > 2;
}

- (BOOL)isPartiallyValid
{
    return _zip.length < 10;
}

@end


text:
package com.vikingbrain.nmt.client.modules.impl;

import com.vikingbrain.nmt.client.modules.ModuleSystem;
import com.vikingbrain.nmt.operations.TheDavidboxOperationFactory;
import com.vikingbrain.nmt.operations.system.CheckNmtExistOperation;
import com.vikingbrain.nmt.operations.system.GetDeviceInfoOperation;
import com.vikingbrain.nmt.operations.system.GetFirmwareVersionOperation;
import com.vikingbrain.nmt.operations.system.GetMacAddressOperation;
import com.vikingbrain.nmt.operations.system.GetNmtServiceStatusOperation;
import com.vikingbrain.nmt.operations.system.GetNmtVersionOperation;
import com.vikingbrain.nmt.operations.system.ListDevicesOperation;
import com.vikingbrain.nmt.operations.system.ListNmtServicesOperation;
import com.vikingbrain.nmt.operations.system.SendKeyOperation;
import com.vikingbrain.nmt.operations.system.SetNmtServiceStatusOperation;

/**
 * It allows to create the operations related to the system module.
 *
 * @author vikingBrain
 */
public class ModuleSystemImpl extends AbstractModule implements ModuleSystem {

	/**
	 * Constructor.
	 * @param operationFactory the operation factory
	 */
	public ModuleSystemImpl(TheDavidboxOperationFactory operationFactory) {
		super(operationFactory);
	}

	/** {@inheritDoc} */
	public GetMacAddressOperation buildGetMacAddressOperation(){
		return new GetMacAddressOperation(getOperationFactory());
	}

	/** {@inheritDoc} */
	public GetFirmwareVersionOperation buildGetFirmwareVersionOperation(){
		return new GetFirmwareVersionOperation(getOperationFactory());
	}

	/** {@inheritDoc} */
	public GetNmtVersionOperation buildGetNmtVersionOperation(){
		return new GetNmtVersionOperation(getOperationFactory());
	}

	/** {@inheritDoc} */
	public CheckNmtExistOperation buildCheckNmtExistOperation(){
		return new CheckNmtExistOperation(getOperationFactory());
	}

	/** {@inheritDoc} */
	public ListNmtServicesOperation buildListNmtServicesOperation(){
		return new ListNmtServicesOperation(getOperationFactory());
	}

	/** {@inheritDoc} */
	public SetNmtServiceStatusOperation buildSetNmtServiceStatusOperation(String serviceName, boolean status){
		return new SetNmtServiceStatusOperation(getOperationFactory(), serviceName, status);
	}

	/** {@inheritDoc} */
	public GetNmtServiceStatusOperation buildGetNmtServiceStatusOperation(String serviceName){
		return new GetNmtServiceStatusOperation(getOperationFactory(), serviceName);
	}

	//TODO set_nmt_device_name

	//TODO get_nmt_device_name

	//TODO set_nmt_samba_workgroup

	//TODO get_nmt_samba_workgroup

	//TODO set_nmt_ftp_password

	//TODO set_nmt_media_destination

	//TODO install_nmt

	/** {@inheritDoc} */
	public ListDevicesOperation buildListDevicesOperation(){
		return new ListDevicesOperation(getOperationFactory());
	}

	//TODO list_drives

	/** {@inheritDoc} */
	public GetDeviceInfoOperation buildGetDeviceInfoOperation(String deviceName){
		return new GetDeviceInfoOperation(getOperationFactory(), deviceName);
	}

	//TODO list_all_active_apps

	//TODO get_current_app

	//TODO get_mute_status

	//TODO set_mute_status

	//TODO get_system_volume

	//TODO set_system_volume

	//TODO list_key

	/** {@inheritDoc} */
	public SendKeyOperation buildSendKeyOperation(String keyName){
		return new SendKeyOperation(getOperationFactory(), keyName);
	}

	//TODO load_page

	//TODO get_connection_status

	//TODO get_linkup_status

	//TODO suspend_screensaver

	//TODO get_board_id

	//TODO get_time

	//TODO load_appcenter

	//TODO load_launcher

	//TODO load_phf

	//TODO load_widget

	//TODO list_webservices_option

	//TODO update_firmware

	//TODO set_system_led

	//TODO capture_screen

}


text:
#include "merkletx.h"

#include "block.h"
#include "blockindexlrucache.h"
#include "init.h"
#include "main.h"
#include "txdb.h"
#include "txmempool.h"

const uint256
    CMerkleTx::ABANDON_HASH(uint256("0000000000000000000000000000000000000000000000000000000000000001"));

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

thread_local std::pair<uint256, int> cachedBestHeight = std::make_pair(0, 0);

static int GetBestBlockHeight(const ITxDB& txdb, const uint256& bestBlockHash)
{
    // to minimize database calls, we cache the best height vs its block hash
    int bestHeight = 0;
    if (cachedBestHeight.first == bestBlockHash) {
        return cachedBestHeight.second;
    } else {
        const boost::optional<CBlockIndex> bestBlockIndex = txdb.ReadBlockIndex(bestBlockHash);
        if (!bestBlockIndex) {
            bestHeight = 0;
        } else {
            bestHeight       = bestBlockIndex->nHeight;
            cachedBestHeight = std::make_pair(bestBlockHash, bestHeight);
        }
    }
    return bestHeight;
}

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

using BlockIndexHeightIfMainChainCacheType = BlockIndexLRUCache<boost::optional<int>>;

struct ExtractorFunctor
{
    const uint256 bestBlockHash;

    ExtractorFunctor(const uint256& bestBlockHashIn) : bestBlockHash(bestBlockHashIn) {}

    boost::optional<int> operator()(const CBlockIndex& bi)
    {
        return bi.IsInMainChain(bestBlockHash) ? boost::make_optional(bi.nHeight) : boost::none;
    }
};

static thread_local BlockIndexHeightIfMainChainCacheType
    blockIndexMainChainCache(2 * pwalletMain->getWalletTxsCount(), ExtractorFunctor(0));

thread_local uint256 cachedBestHash = 0;
/**
 * @brief GetBlockHeightIfMainChain
 * The BlockIndexLRUCache class is designed to only store values that are constants of blocks. However,
 * we abuse it here and store the "IsMainChain" status. This is valid because we reset the cache
 * whenever the bestBlockHash changed
 *
 * To avoid resetting the cache often, we abuse the system further by checking whether the new
 * bestBlockhash is next block right after the previous block. If that's the case, that just means the
 * IsMainChain state hasn't chained, so we skip resetting the cache.
 */
static boost::optional<int> GetBlockHeightIfMainChain(const ITxDB& txdb, const uint256& blockHash,
                                                      const uint256& bestBlockHash)
{
    if (cachedBestHash != bestBlockHash) {
        // read the current best to update the cache
        const auto bi = txdb.ReadBlockIndex(bestBlockHash);
        if (!bi) {
            NLog.write(b_sev::critical,
                       "CRITICAL ERROR: Failed to read best block index indicated with hash: {}!",
                       bestBlockHash.ToString());
            return boost::none;
        }

        // if the next block is just built upon the last best, then the state of "mainchain" is
        // unchanged in the cache
        if (bi->hashPrev != cachedBestHash) {
            // we clear the cache
            blockIndexMainChainCache.clear();
            blockIndexMainChainCache.updateCacheSize(2 * pwalletMain->getWalletTxsCount());
        }
        // we just the new best height in the extractor
        blockIndexMainChainCache.setExtractor(ExtractorFunctor(bestBlockHash));
        cachedBestHash = bestBlockHash;
    }
    const boost::optional<BlockIndexHeightIfMainChainCacheType::BICacheEntry> entry =
        blockIndexMainChainCache.get(txdb, blockHash);
    if (!entry) {
        NLog.write(b_sev::critical, "CRITICAL ERROR: A WalletTx pointed to a non-existing block: {}!",
                   blockHash.ToString());
        return boost::none;
    }
    return entry->value;
}

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

CMerkleTx::CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); }

int CMerkleTx::GetDepthInMainChain(boost::optional<CBlockIndex>& pindexRet, const ITxDB& txdb,
                                   const uint256& bestBlockHash) const
{
    if (hashBlock == 0 || hashBlock == ABANDON_HASH)
        return 0;
    int nResult = 0;

    // Find the block it claims to be in
    const auto bi = txdb.ReadBlockIndex(hashBlock);
    if (!bi || !bi->IsInMainChain(txdb)) {
        nResult   = 0;
        pindexRet = boost::none;
    } else {
        const int bestHeight = GetBestBlockHeight(txdb, bestBlockHash);
        nResult              = ((nIndex == -1) ? (-1) : 1) * (bestHeight - bi->nHeight + 1);
        pindexRet            = std::move(bi);
    }

    return nResult;
}

int CMerkleTx::GetDepthInMainChain(const ITxDB& txdb, const uint256& bestBlockHash) const
{
    if (hashBlock == 0 || hashBlock == ABANDON_HASH)
        return 0;
    int nResult = 0;

    const boost::optional<int> blockHeight = GetBlockHeightIfMainChain(txdb, hashBlock, bestBlockHash);
    if (blockHeight) {
        const int bestHeight = GetBestBlockHeight(txdb, bestBlockHash);
        nResult              = ((nIndex == -1) ? (-1) : 1) * (bestHeight - *blockHeight + 1);
    }

    return nResult;
}

bool CMerkleTx::IsInMainChain(const ITxDB& txdb, const uint256& bestBlockHash) const
{
    return GetDepthInMainChain(txdb, bestBlockHash) > 0;
}

int CMerkleTx::GetBlocksToMaturity(const ITxDB& txdb, const uint256& bestBlockHash) const
{
    if (!(IsCoinBase() || IsCoinStake()))
        return 0;
    int nCbM = Params().CoinbaseMaturity(txdb);
    return std::max(0, (nCbM + 1) - GetDepthInMainChain(txdb, bestBlockHash));
}

Result<void, TxValidationState> CMerkleTx::AcceptToMemoryPool() const
{
    return ::AcceptToMemoryPool(mempool, *this);
}

bool CMerkleTx::hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }

bool CMerkleTx::isAbandoned() const { return (hashBlock == ABANDON_HASH); }

void CMerkleTx::setAbandoned() { hashBlock = ABANDON_HASH; }

int CMerkleTx::SetMerkleBranch(const ITxDB& txdb, const CBlock* pblock)
{
    AssertLockHeld(cs_main);

    CBlock blockTmp;
    if (pblock == nullptr) {
        // Load the block this tx is in
        CTxIndex txindex;
        if (!txdb.ReadTxIndex(GetHash(), txindex))
            return 0;
        if (!blockTmp.ReadFromDisk(txindex.pos.nBlockPos, txdb))
            return 0;
        pblock = &blockTmp;
    }

    // Update the tx's hashBlock
    hashBlock = pblock->GetHash();

    // Locate the transaction
    for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
        if (pblock->vtx[nIndex] == *(CTransaction*)this)
            break;
    if (nIndex == (int)pblock->vtx.size()) {
        vMerkleBranch.clear();
        nIndex = -1;
        NLog.write(b_sev::err, "ERROR: SetMerkleBranch() : couldn't find tx in block");
        return 0;
    }

    // Fill in merkle branch
    vMerkleBranch = pblock->GetMerkleBranch(nIndex);

    // Is the tx in a block that's in the main chain
    const auto bi = txdb.ReadBlockIndex(hashBlock);
    if (!bi)
        return 0;
    const boost::optional<CBlockIndex> pindex = bi;
    if (!pindex || !pindex->IsInMainChain(txdb))
        return 0;

    return txdb.GetBestBlockIndex()->nHeight - pindex->nHeight + 1;
}


text:
<?php
  session_start();
//PUT THIS HEADER ON TOP OF EACH UNIQUE PAGE
  if(!isset($_SESSION['username'])){
    header("location:../login/main_login.php");
  }
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="css/bootstrap.css" rel="stylesheet" media="screen">
    <link href="css/main.css" rel="stylesheet" media="screen">

You have been successfully logged in.

        Logout


text:
// WARNING
//
// This file has been generated automatically by Visual Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace ScalesApp
{
    [Register ("ModesTabPage")]
    partial class ModesTabPage
    {
        void ReleaseDesignerOutlets ()
        {
        }
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources>
  <string name="ErrorTooManyRequests">Liian monta käsiteltävää pyyntöä. Yritä myöhemmin uudelleen.</string>
  <string name="a2dp_sink_mbs_label">Bluetooth Ääni</string>
  <string name="ack_record">Hyv. tiedot</string>
  <string name="airplane_error_msg">Et voi käyttää Bluetoothia lentokonetilassa.</string>
  <string name="airplane_error_title">Lentokonetila</string>
  <string name="app_name">Bluetooth</string>
  <string name="auth_notif_message">Kirjoita kohteen %1$s käyttökerran avain</string>
  <string name="auth_notif_ticker">Obex-todennuspyyntö</string>
  <string name="auth_notif_title">Käyttökerran avain</string>
  <string name="bluetooth_connected">Bluetooth ääni yhdistetty</string>
  <string name="bluetooth_disconnected">Bluetooth ääni katkaistu</string>
  <string name="bluetooth_map_settings_app_icon">Sovelluskuvake</string>
  <string name="bluetooth_map_settings_cancel">Peruuta</string>
  <string name="bluetooth_map_settings_count">Paikkoja jäljellä:</string>
  <string name="bluetooth_map_settings_intro">Valitse tilit, jotka haluat jakaa Bluetoothin kautta. Tilien käyttöoikeus pitää silti hyväksyä yhdistettäessä.</string>
  <string name="bluetooth_map_settings_no_account_slots_left">Tilin valinta epäonnistui. 0 paikkaa jäljellä</string>
  <string name="bluetooth_map_settings_save">Tallenna</string>
  <string name="bluetooth_map_settings_title">Bluetoothin viestinjakoasetukset</string>
  <string name="bluetooth_sap_notif_disconnect_button">Katkaise yhteys</string>
  <string name="bluetooth_sap_notif_disconnecting">Odotetaan, että asiakassovellus katkaisee yhteyden.</string>
  <string name="bluetooth_sap_notif_force_disconnect_button">Pakota yhteyden katkaiseminen</string>
  <string name="bluetooth_sap_notif_message">Pyydetäänkö asiakassovellusta katkaisemaan yhteys?</string>
  <string name="bluetooth_sap_notif_ticker">Bluetooth SIM -käyttö</string>
  <string name="bluetooth_sap_notif_title">Bluetooth SIM -käyttö</string>
  <string name="bluetooth_share_file_name">bluetooth_content_share</string>
  <string name="bt_enable_cancel">Peruuta</string>
  <string name="bt_enable_line1">Jos haluat käyttää Bluetooth-palveluita, ota Bluetooth käyttöön.</string>
  <string name="bt_enable_line2">Otetaanko Bluetooth käyttöön nyt?</string>
  <string name="bt_enable_ok">Ota käyttöön</string>
  <string name="bt_enable_title"/>
  <string name="bt_error_btn_ok">OK</string>
  <string name="bt_share_picker_label">Bluetooth</string>
  <string name="bt_sm_2_1">USB-tallennustilassa ei ole tarpeeksi tilaa. Tiedostoa lähettäjältä %1$s ei voi tallentaa.</string>
  <string name="bt_sm_2_2">Tilaa tarvitaan: %1$s</string>
  <string name="bt_toast_1">Tiedosto otetaan vastaan. Näet siirron tilan Ilmoitukset-paneelissa.</string>
  <string name="bt_toast_2">Tiedostoa ei voi vastaanottaa.</string>
  <string name="bt_toast_3">Pysäytettiin tiedoston vastaanotto lähettäjältä %1$s</string>
  <string name="bt_toast_4">Lähetetään tiedosto vastaanottajalle %1$s</string>
  <string name="bt_toast_5">Lähetetään %1$s tiedostoa vastaanottajalle %2$s</string>
  <string name="bt_toast_6">Tiedoston lähettäminen vastaanottajalle %1$s pysäytetty</string>
  <string name="btopp_live_folder">Bluetooth, vastaanotettu</string>
  <string name="defaultname">Autosarja</string>
  <string name="deleteAll_record">Poista kaikki tiedot</string>
  <string name="delete_record">Poista tiedot</string>
  <string name="download_cancel">Lopeta</string>
  <string name="download_fail_line1">Tiedostoa ei vastaanotettu</string>
  <string name="download_fail_line2">Tiedosto: %1$s</string>
  <string name="download_fail_line3">Syy: %1$s</string>
  <string name="download_fail_ok">OK</string>
  <string name="download_line1">Lähettäjä: %1$s</string>
  <string name="download_line2">Tiedosto: %1$s</string>
  <string name="download_line3">Tiedostokoko: %1$s</string>
  <string name="download_line4"/>
  <string name="download_line5">Vastaanotetaan tiedostoa…</string>
  <string name="download_ok">Piilota</string>
  <string name="download_succ_line5">Tiedosto vastaanotettu</string>
  <string name="download_succ_ok">Avaa</string>
  <string name="download_success">%1$s vastaanotto valmis.</string>
  <string name="download_title">Tiedostonsiirto</string>
  <string name="enabling_progress_content">Otetaan Bluetooth käyttöön...</string>
  <string name="enabling_progress_title">Odota…</string>
  <string name="inbound_history_title">Saapuvat siirrot</string>
  <string name="inbound_noti_title">Bluetooth-jako: Vastaanotetut tiedostot</string>
  <string name="incoming_file_confirm_Notification_content">%1$s on valmis lähettämään kohteen %2$s.</string>
  <string name="incoming_file_confirm_Notification_title">Saapuva tiedosto</string>
  <string name="incoming_file_confirm_cancel">Hylkää</string>
  <string name="incoming_file_confirm_content">Hyväksytäänkö saapuva tiedosto?</string>
  <string name="incoming_file_confirm_ok">Hyväksy</string>
  <string name="incoming_file_confirm_timeout_content">Yhteys aikakatkaistiin vastaanotettaessa tiedostoa lähettäjältä %1$s</string>
  <string name="incoming_file_confirm_timeout_ok">OK</string>
  <string name="incoming_file_confirm_title">Tiedostonsiirto</string>
  <string name="incoming_file_toast_msg">Toinen laite lähettää tiedostoa. Vahvista, että haluat vastaanottaa tämän tiedoston.</string>
  <string name="incoming_line1">Lähettäjä</string>
  <string name="incoming_line2">Tiedostonimi</string>
  <string name="incoming_line3">Koko</string>
  <string name="insert_record">Lisää tiedot</string>
  <string name="localPhoneName">Oma nimeni</string>
  <string name="miui_transfer_history_title">Bluetooth siirrot</string>
  <string name="miui_transfer_inbound_title">Sisääntuleva</string>
  <string name="miui_transfer_outbound_title">Ulosmenevä</string>
  <string name="no_transfers">Lähetyshistoria on tyhjä.</string>
  <string name="not_exist_file">Ei tiedostoa</string>
  <string name="not_exist_file_desc">"Tiedostoa ei ole olemassa.
"</string>
  <string name="notification_received">Bluetooth-jako: %1$s vastaanotettu</string>
  <string name="notification_received_fail">Bluetooth-jako: tiedostoa %1$s ei vastaanotettu</string>
  <string name="notification_receiving">Bluetooth-jako: vastaanotetaan tiedostoa %1$s</string>
  <string name="notification_sending">Bluetooth-jako: lähetetään tiedostoa %1$s</string>
  <string name="notification_sent">Bluetooth-jako: lähetä %1$s</string>
  <string name="notification_sent_complete">100 % valmis</string>
  <string name="notification_sent_fail">Bluetooth-jako: tiedostoa %1$s ei lähetetty</string>
  <string name="notify_server">Ilmoita TCP-palvelin</string>
  <string name="ok_button">OK</string>
  <string name="opp_notification_group">Bluetooth Jako</string>
  <string name="outbound_history_title">Lähtevät siirrot</string>
  <string name="outbound_noti_title">Bluetooth-jako: Lähetetyt tiedostot</string>
  <string name="pbap_acceptance_timeout_message">Kohteen %1$s yhteyspyyntö aikakatkaistiin</string>
  <string name="pbap_authentication_timeout_message">Kohteen %1$s käyttökerran avaimen syöttö aikakatkaistiin</string>
  <string name="pbap_notification_group">Bluetooth Yhteystietojen jakaminen</string>
  <string name="pbap_session_key_dialog_header">Bluetooth-käyttökerran avain vaaditaan</string>
  <string name="pbap_session_key_dialog_title">Kirjoita kohteen %1$s käyttökerran avain</string>
  <string name="permdesc_bluetoothShareManager">Antaa sovelluksen käyttää BluetoothShare-hallintaa tiedostojen siirtoon.</string>
  <string name="permdesc_bluetoothWhitelist">Mahdollistaa tilapäisten käyttöoikeuksien antamisen Bluetooth-laitteelle, jolloin tiedostojen lähettäminen laitteesta tähän laitteeseen ei vaadi käyttäjän hyväksyntää.</string>
  <string name="permdesc_handoverStatus">Sallii handover siirron tilatietojen vastaanoton Bluetoothilta.</string>
  <string name="permlab_bluetoothShareManager">Lataustenhallinnan käyttö.</string>
  <string name="permlab_bluetoothWhitelist">Käyttö Bluetooth-laitteella, jolla on tilapäinen käyttöoikeus.</string>
  <string name="permlab_handoverStatus">Vastaanota BT handover siirron tilatiedot.</string>
  <string name="process"/>
  <string name="sharedUserId"/>
  <string name="start_server">Käynnistä TCP-palvelin</string>
  <string name="status_canceled">Käyttäjä peruutti tiedonsiirron.</string>
  <string name="status_connection_error">Yhteys epäonnistui.</string>
  <string name="status_file_error">Tallennusongelma.</string>
  <string name="status_forbidden">Kohdelaite kieltää siirron.</string>
  <string name="status_no_sd_card">Ei USB-tallennustilaa.</string>
  <string name="status_not_accept">Sisältöä ei tueta.</string>
  <string name="status_pending">Tiedostonsiirto ei ole vielä alkanut.</string>
  <string name="status_protocol_error">Pyyntö ei ole käsiteltävissä.</string>
  <string name="status_running">Tiedostonsiirto on käynnissä.</string>
  <string name="status_success">Tiedostonsiirto onnistui.</string>
  <string name="status_unknown_error">Tuntematon virhe.</string>
  <string name="transfer_clear_dlg_msg">Koko luettelo tyhjennetään.</string>
  <string name="transfer_clear_dlg_title">Poista</string>
  <string name="transfer_menu_clear">Poista luettelosta</string>
  <string name="transfer_menu_clear_all">Tyhjennä luettelo</string>
  <string name="transfer_menu_open">Avaa</string>
  <string name="unknownName">Tuntematon nimi</string>
  <string name="unknownNumber">Tuntematon</string>
  <string name="unknown_device">Tuntematon laite</string>
  <string name="unknown_file">Tuntematon tiedosto</string>
  <string name="unknown_file_desc">"Tämän tyyppisten tiedostojen käsittelyyn sopivaa sovellusta ei ole asennettu.
"</string>
  <string name="update_record">Vahvista tiedot</string>
  <string name="upload_fail_cancel">Sulje</string>
  <string name="upload_fail_line1">Tiedostoa ei lähetetty vastaanottajalle %1$s.</string>
  <string name="upload_fail_line1_2">Tiedosto: %1$s</string>
  <string name="upload_fail_ok">Yritä uudelleen</string>
  <string name="upload_fail_waiting">Tiedostonlähetyksen valmistelu on meneillään, automaattinen uudelleenlähetys myöhemmin</string>
  <string name="upload_line1">Vastaanottaja: %1$s</string>
  <string name="upload_line3">Tiedostotyyppi: %1$s (%2$s)</string>
  <string name="upload_line5">Lähetetään tiedostoa…</string>
  <string name="upload_succ_line5">Tiedosto lähetetty</string>
  <string name="upload_succ_ok">OK</string>
  <string name="upload_success">%1$s lähetys valmis.</string>
</resources>


text:
package com.invariantproperties.projecteuler.figurate;

import org.junit.Assert;
import org.junit.Test;

import com.invariantproperties.projecteuler.figurate.HeptagonalNumber;

import java.util.Arrays;

public class HeptagonalNumberTest extends AbstractFigurateTest<Long> {
    /**
     * Constructor.
     */
    public HeptagonalNumberTest() throws NoSuchMethodException {
        super(HeptagonalNumber.class);
    }

    /**
     * Verify the definition is properly implemented.
     *
     * @return
     */
    @Test
    @Override
    public void verifyDefinition() {
        for (int n = 0; n < getMaxTests(); n++) {
            long x = (long) ((n * ((5 * n) - 3)) / 2);
            Assert.assertEquals(x, seq.get(n).longValue());
        }
    }

    /**
     * Verify initial terms.
     */
    @Test
    @Override
    public void verifyInitialTerms() {
        verifyInitialTerms(Arrays.asList(0L, 1L, 7L, 18L, 34L, 55L, 81L, 112L,
                148L, 189L, 235L, 286L));
    }
}


text:
tagm-open
=========

Command tool to open files based on it's tagm tags.


text:
<?php

class f_v_helper_formInvisibleRecaptcha extends f_v_helper_formElementAbstract
{

    public function helper($sName = 'button', $mVal = null, $aAttr = array())
    {
        $key = f::$c->config->googleApi['reCAPTCHA_Site_key'];
        return ""
//                . "

";
        .''
        .'

'
        .'<input type="submit" name="send" value="Submit" id="recaptcha-submit" />'
//        .'<input type="submit" name="send" value="Submit" class="g-recaptcha" data-badge="inline" data-sitekey="'.$key.'" data-callback="onSubmit">'

        ;
    }

}


text:
snd-hda-intel-objs := hda_intel.o

snd-hda-codec-y := hda_codec.o
snd-hda-codec-$(CONFIG_SND_HDA_GENERIC) += hda_generic.o
snd-hda-codec-$(CONFIG_PROC_FS) += hda_proc.o
snd-hda-codec-$(CONFIG_SND_HDA_HWDEP) += hda_hwdep.o
snd-hda-codec-$(CONFIG_SND_HDA_INPUT_BEEP) += hda_beep.o

# for trace-points
CFLAGS_hda_codec.o := -I$(src)

snd-hda-codec-realtek-objs :=	patch_realtek.o
snd-hda-codec-cmedia-objs :=	patch_cmedia.o
snd-hda-codec-analog-objs :=	patch_analog.o
snd-hda-codec-idt-objs :=	patch_sigmatel.o
snd-hda-codec-si3054-objs :=	patch_si3054.o
snd-hda-codec-cirrus-objs :=	patch_cirrus.o
snd-hda-codec-ca0110-objs :=	patch_ca0110.o
snd-hda-codec-ca0132-objs :=	patch_ca0132.o
snd-hda-codec-conexant-objs :=	patch_conexant.o
snd-hda-codec-via-objs :=	patch_via.o
snd-hda-codec-hdmi-objs :=	patch_hdmi.o hda_eld.o

# common driver
obj-$(CONFIG_SND_HDA_INTEL) := snd-hda-codec.o

# codec drivers (note: CONFIG_SND_HDA_CODEC_XXX are booleans)
ifdef CONFIG_SND_HDA_CODEC_REALTEK
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-realtek.o
endif
ifdef CONFIG_SND_HDA_CODEC_CMEDIA
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-cmedia.o
endif
ifdef CONFIG_SND_HDA_CODEC_ANALOG
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-analog.o
endif
ifdef CONFIG_SND_HDA_CODEC_SIGMATEL
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-idt.o
endif
ifdef CONFIG_SND_HDA_CODEC_SI3054
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-si3054.o
endif
ifdef CONFIG_SND_HDA_CODEC_CIRRUS
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-cirrus.o
endif
ifdef CONFIG_SND_HDA_CODEC_CA0110
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-ca0110.o
endif
ifdef CONFIG_SND_HDA_CODEC_CA0132
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-ca0132.o
endif
ifdef CONFIG_SND_HDA_CODEC_CONEXANT
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-conexant.o
endif
ifdef CONFIG_SND_HDA_CODEC_VIA
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-via.o
endif
ifdef CONFIG_SND_HDA_CODEC_HDMI
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-codec-hdmi.o
endif

# this must be the last entry after codec drivers;
# otherwise the codec patches won't be hooked before the PCI probe
# when built in kernel
obj-$(CONFIG_SND_HDA_INTEL) += snd-hda-intel.o


text:
module.exports = {
	elements: {
		noItemsFoundNoText:'.BlankState__heading',
		singleItemDeleteIcon: '.ItemList__control--delete',
		firstItemDeleteIcon: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[1]/td[contains(concat(" ", normalize-space(@class), " "), "ItemList__col--control ItemList__col--delete")][1]',
		},
		secondItemDeleteIcon: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[2]/td[contains(concat(" ", normalize-space(@class), " "), "ItemList__col--control ItemList__col--delete")][1]',
		},
		itemDeleteIcon: '.Table.ItemList .ItemList__col--control.ItemList__col--delete',
		searchInputField: '.ListHeader__searchbar-input',
		searchInputFieldClearIcon: '.ListHeader__search__icon',
		filterDropdown: '#listHeaderFilterButton',
		columnDropdown: '#listHeaderColumnButton',
		downloadDropdown: '#listHeaderDownloadButton',
		expandTableIcon: 'div.InputGroup_section:nth-child(5) > button:nth-child(1)',
		createFirstItemButton: '.Button',
		createMoreItemsButton: '.Button--success',
		paginationCount: '.Pagination__count',
		firstColumnHeader: {
			locateStrategy: 'xpath',
			selector: '//thead/tr[1]/th[2]/button[contains(@class, "ItemList__sort-button th-sort")]',
		},
		secondColumnHeader: {
			locateStrategy: 'xpath',
			selector: '//thead/tr[1]/th[3]/button[contains(@class, "ItemList__sort-button th-sort")]',
		},
		thirdColumnHeader: {
			locateStrategy: 'xpath',
			selector: '//thead/tr[1]/th[4]/button[contains(@class, "ItemList__sort-button th-sort")]',
		},
		firstItemFirstColumnValue: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[1]/td[2]',
		},
		firstItemSecondColumnValue: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[1]/td[3]',
		},
		firstItemThirdColumnValue: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[1]/td[4]',
		},
		secondItemFirstColumnValue: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[2]/td[2]',
		},
		secondItemSecondColumnValue: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[2]/td[3]',
		},
		secondItemThirdColumnValue: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[2]/td[4]',
		},
		firstUserItemIsNotAdmin: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[1]/td[4]/div/span[contains(@class, "octicon-x")]',
		},
		firstUserItemIsMember: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[1]/td[5]/div/span[contains(@class, "octicon-check")]',
		},
		secondUserItemIsAdmin: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[2]/td[4]/div/span[contains(@class, "octicon-check")]',
		},
		secondUserItemIsNotMember: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[2]/td[5]/div/span[contains(@class, "octicon-x")]',
		},
		firstItemLink: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[1]/td[2]/a',
		},
		secondItemLink: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[2]/td[2]/a',
		},
		thirdItemLink: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[3]/td[2]/a',
		},
		firstItemNameValue: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[1]/td/a[contains(@class, "ItemList__value ItemList__value--text")][1]',
		},
		secondItemNameValue: {
			locateStrategy: 'xpath',
			selector: '//tbody/tr[2]/td/a[contains(@class, "ItemList__value ItemList__value--text")][1]',
		},
	},
	commands: [{
		deleteItem: function (selector) {
			return this
				.click(selector);
		},
		createFirstItem: function() {
			return this
				.click('@createFirstItemButton');
		},
		navigateToFirstItem: function() {
			return this
				.click('@firstItemLink');
		}
	}],
};


text:
@interface FTViewController : UIViewController

@end


text:
package org.springframework.web.servlet.view.script;

import org.springframework.web.servlet.view.UrlBasedViewResolver;

/**
 * Convenience subclass of {@link UrlBasedViewResolver} that supports
 * {@link ScriptTemplateView} and custom subclasses of it.
 *
 *
The view class for all views created by this resolver can be specified
 * via the {@link #setViewClass(Class)} property.
 *
 *
Note: When chaining ViewResolvers this resolver will check for the
 * existence of the specified template resources and only return a non-null
 * View object if a template is actually found.
 *
 * @author Sebastien Deleuze
 * @since 4.2
 * @see ScriptTemplateConfigurer
 */
public class ScriptTemplateViewResolver extends UrlBasedViewResolver {

	/**
	 * Sets the default {@link #setViewClass view class} to {@link #requiredViewClass}:
	 * by default {@link ScriptTemplateView}.
	 */
	public ScriptTemplateViewResolver() {
		setViewClass(requiredViewClass());
	}

	/**
	 * A convenience constructor that allows for specifying {@link #setPrefix prefix}
	 * and {@link #setSuffix suffix} as constructor arguments.
	 * @param prefix the prefix that gets prepended to view names when building a URL
	 * @param suffix the suffix that gets appended to view names when building a URL
	 * @since 4.3
	 */
	public ScriptTemplateViewResolver(String prefix, String suffix) {
		this();
		setPrefix(prefix);
		setSuffix(suffix);
	}

	@Override
	protected Class<?> requiredViewClass() {
		return ScriptTemplateView.class;
	}

}


text:
<?php

namespace yariksav\actives\behaviors;

use Yii;
use yii\base\Behavior;
use yii\db\Expression;
use yii\db\ActiveRecord;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * TreeLinkBehavior automatically creates tree links
 *
 * To use UserActivityBehavior, insert the following code to your ActiveRecord class:
 *
 * ```php
 * use yariksav\actives\behaviors\UserActivityBehavior;
 *
 * public function behaviors()
 * {
 *     return [
 *         [
 *            'class' => TreeLinkBehavior::className(),
 *            'model' => TreeLink::className(),
 *            'key' => 'id',
 *            'parentKey' => 'parentId',
 *         ],
 *     ];
 * }
 * ```
 *
 * @author Savaryn Yaroslav <yaiksav@gmail.com>
 */

class TreeLinkBehavior extends Behavior
{

    /**
     * @var array list of attributes that are to be automatically changed attributes.
     * The array keys are the ActiveRecord events upon which the attributes are to be updated,
     * and the array values are the corresponding attribute(s) to be updated. You can use a string to represent
     * a single attribute, or an array to represent a list of attributes. For example,
     *
     * ```php
     * [
     *     ActiveRecord::EVENT_AFTER_INSERT => [] // log all attributes
     *     ActiveRecord::EVENT_BEFORE_UPDATE => ['attribute1', 'attribute2'], // log specific attributes
     * ]
     * ```
     */
    public $attributes = [];
    /**
     * @var boolean whether to skip this behavior when the `$owner` has not been
     * modified
     */
    public $skipUpdateOnClean = true;
    /**
     * @var string model for saving action
     */
    public $model;

    /**
     * @inheritdoc
     */

    public function onSave()
    {

    }

    public function onDelete() {
        call_user_func($this->delete, $this->owner, $this->getValue());
    }

    /**
     * @inheritdoc
     */
    public function events()
    {
        return [
            BaseActiveRecord::EVENT_AFTER_INSERT => [$this, 'onSave'],
            BaseActiveRecord::EVENT_AFTER_UPDATE => [$this, 'onSave'],
            BaseActiveRecord::EVENT_BEFORE_DELETE => [$this, 'onDelete'],
        ];
    }

    public static function removeLinks($table, $id){
        self::deleteAll(['table'=>$table, 'id'=>$id]);
    }

    public static function addLinks($table, $id, $parents)
    {
        self::removeLinks($table, $id);
        foreach($parents as $key=>$parent){
            $link = new TreeLink(['table'=>$table, 'id'=>$id, 'level'=>$key, 'parent_id'=>$parent]);
            $link->save();
        }
    }

    public static function getChildren($table, $id, $fields = null)
    {
        $idField = ArrayHelper::getValue($fields, 0, 'id');
        $parentField = ArrayHelper::getValue($fields, 1, 'parent_id');
        $nameField = ArrayHelper::getValue($fields, 2, 'name');
        $query = new yii\db\Query();
        $query->select("t2.$idField, t2.$parentField, t2.$nameField, tlink.level")
            ->from($table.' t1, '.self::tableName().' tlink, '.$table.' t2')
            ->where('
                    t1.'.$idField.' = tlink.parent_id
                AND tlink.id = t2.'.$idField.'
                AND t2.'.$idField.' != t2.'.$parentField.'
                AND t1.'.$idField.' = :id

                AND tlink.table = :table
            ')->params([':id'=>$id, ':table'=>$table]);
        return $query->all();
    }

    public static function getParents($table, $id, $fields = null)
    {
        $idField = ArrayHelper::getValue($fields, 0, 'id');
        $parentField = ArrayHelper::getValue($fields, 1, 'parent_id');
        $nameField = ArrayHelper::getValue($fields, 2, 'name');
        $query = new yii\db\Query();
        $query->select("t2.$idField, t2.$parentField, t2.$nameField, tlink.level")
            ->from($table.' t1, '.self::tableName().' tlink, '.$table.' t2')
            ->where('
                    t1.'.$idField.' = tlink.id
                AND tlink.parent_id = t2.'.$idField.'
                AND t1.'.$idField.' = :id

                AND tlink.table = :table
            ')->params([':id'=>$id, ':table'=>$table]);
        return $query->all();
    }
}


text:
package org.sagebionetworks.repo.model.ar;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.repo.model.NodeConstants;
import org.sagebionetworks.repo.model.RestrictableObjectType;
import org.sagebionetworks.repo.model.dbo.DDLUtilsImpl;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class AccessRestrictionStatusDaoImpl implements AccessRestrictionStatusDao {

	public static final String GET_ENTITY_ACCESS_RESTRICTIONS_SQL = DDLUtilsImpl
			.loadSQLFromClasspath("sql/GetEntityAccessRestrictions.sql");
	public static final String GET_NON_ENTITY_ACCESS_RESTRICTIONS_SQL = DDLUtilsImpl
			.loadSQLFromClasspath("sql/GetNonEntityAccessRestrictions.sql");

	private static final String CREATED_BY = "CREATED_BY";
	private static final String NODE_TYPE = "NODE_TYPE";
	private static final String ENTITY_ID = "ENTITY_ID";
	private static final String REQUIREMENT_TYPE = "REQUIREMENT_TYPE";
	private static final String APPROVED2 = "APPROVED";
	private static final String REQUIREMENT_ID = "REQUIREMENT_ID";
	private static final String SUBJECT_ID = "SUBJECT_ID";
	@Autowired
	private NamedParameterJdbcTemplate namedJdbcTemplate;

	@Override
	public List<UsersRestrictionStatus> getSubjectStatus(List<Long> subjectIds, RestrictableObjectType subjectType,
			Long userId) {
		ValidateArgument.required(subjectIds, "subjectIds");
		ValidateArgument.required(subjectType, "subjectType");
		ValidateArgument.required(userId, "userId");
		if (RestrictableObjectType.ENTITY.equals(subjectType)) {
			return getEntityStatus(subjectIds, userId);
		} else {
			return getNonEntityStatus(subjectIds, subjectType, userId);
		}
	}

	@Override
	public Map<Long, UsersRestrictionStatus> getEntityStatusAsMap(List<Long> entityIds, Long userId) {
		ValidateArgument.required(entityIds, "entityIds");
		ValidateArgument.required(userId, "userId");
		if (entityIds.isEmpty()) {
			return Collections.emptyMap();
		}
		final Map<Long, UsersRestrictionStatus> statusMap = new LinkedHashMap<Long, UsersRestrictionStatus>(entityIds.size());
		for (Long entityId : entityIds) {
			UsersRestrictionStatus status = new UsersRestrictionStatus(entityId, userId);
			statusMap.put(entityId, status);
		}
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("entityIds", entityIds);
		params.addValue("userId", userId);
		params.addValue("depth", NodeConstants.MAX_PATH_DEPTH_PLUS_ONE);
		namedJdbcTemplate.query(GET_ENTITY_ACCESS_RESTRICTIONS_SQL, params, (ResultSet rs) -> {
			Long entityId = rs.getLong(ENTITY_ID);
			EntityType entityType = EntityType.valueOf(rs.getString(NODE_TYPE));
			Long createdBy = rs.getLong(CREATED_BY);
			Long requirementId = rs.getLong(REQUIREMENT_ID);
			if (rs.wasNull()) {
				requirementId = null;
			}
			Boolean approved = rs.getBoolean(APPROVED2);
			if (rs.wasNull()) {
				approved = null;
			}
			String requirementTypeString = rs.getString(REQUIREMENT_TYPE);
			AccessRequirementType requirementType = null;
			if(requirementTypeString != null) {
				requirementType = AccessRequirementType.lookupClassName(requirementTypeString);
			}
			// The user is automatically approved for any requirement on files they create.
			if (EntityType.file.equals(entityType) && userId.equals(createdBy)) {
				approved = true;
			}
			UsersRestrictionStatus status = statusMap.get(entityId);
			if (approved != null && !approved) {
				status.setHasUnmet(true);
			}
			if (requirementId != null) {
				status.addRestrictionStatus(new UsersRequirementStatus().withRequirementId(requirementId)
						.withRequirementType(requirementType).withIsUnmet(!approved));
			}
		});
		return statusMap;
	}

	@Override
	public List<UsersRestrictionStatus> getEntityStatus(List<Long> entityIds, Long userId) {
		Map<Long, UsersRestrictionStatus> statusMap = getEntityStatusAsMap(entityIds, userId);
		return new ArrayList<UsersRestrictionStatus>(statusMap.values());
	}

	@Override
	public List<UsersRestrictionStatus> getNonEntityStatus(List<Long> subjectIds, RestrictableObjectType subjectType,
			Long userId) {
		ValidateArgument.required(subjectIds, "subjectIds");
		ValidateArgument.required(subjectType, "subjectType");
		ValidateArgument.required(userId, "userId");
		if (RestrictableObjectType.ENTITY.equals(subjectType)) {
			throw new IllegalArgumentException("This method can only be used for non-entity subject types.");
		}
		if (subjectIds.isEmpty()) {
			return Collections.emptyList();
		}
		final Map<Long, UsersRestrictionStatus> statusMap = new LinkedHashMap<Long, UsersRestrictionStatus>(subjectIds.size());
		for (Long subjectId : subjectIds) {
			UsersRestrictionStatus status = new UsersRestrictionStatus(subjectId, userId);
			statusMap.put(subjectId, status);
		}
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("subjectIds", subjectIds);
		params.addValue("subjectType", subjectType.name());
		params.addValue("userId", userId);
		namedJdbcTemplate.query(GET_NON_ENTITY_ACCESS_RESTRICTIONS_SQL, params, (ResultSet rs) -> {
			Long subjectId = rs.getLong(SUBJECT_ID);
			Long requirementId = rs.getLong(REQUIREMENT_ID);
			if (rs.wasNull()) {
				requirementId = null;
			}
			Boolean approved = rs.getBoolean(APPROVED2);
			if (rs.wasNull()) {
				approved = null;
			}
			String requirementTypeString = rs.getString(REQUIREMENT_TYPE);
			AccessRequirementType requirementType = null;
			if(requirementTypeString != null) {
				requirementType = AccessRequirementType.lookupClassName(requirementTypeString);
			}
			UsersRestrictionStatus status = statusMap.get(subjectId);
			if (!approved) {
				status.setHasUnmet(true);
			}
			if (requirementId != null) {
				status.addRestrictionStatus(new UsersRequirementStatus().withRequirementId(requirementId)
						.withRequirementType(requirementType).withIsUnmet(!approved));
			}
		});
		return new ArrayList<UsersRestrictionStatus>(statusMap.values());
	}

}


text:
require 'rails_helper'

module MnoEnterprise
  describe Jpi::V1::TeamsController, type: :controller do
    include MnoEnterprise::TestingSupport::JpiV1TestHelper

    render_views
    routes { MnoEnterprise::Engine.routes }
    before { request.env["HTTP_ACCEPT"] = 'application/json' }

    def users_for_team(team)
      team.users.map do |user|
        {
            'id' => user.id,
            'name' => user.name,
            'surname' => user.surname,
            'email' => user.email,
            'role' => nil
        }
      end
    end

    def apps_for_team(team)
      team.app_instances.map do |app_instance|
        {
            'id' => app_instance.id,
            'name' => app_instance.name,
            'logo' => app_instance.app.logo
        }
      end
    end

    def hash_for_team(team)
      {
          'team' => {
              id: team.id,
              name: team.name,
              users: users_for_team(team),
              app_instances: apps_for_team(team)
          }
      }
    end

    #===============================================
    # Assignments
    #===============================================
    # Stub controller ability
    let!(:ability) { stub_ability }
    before { allow(ability).to receive(:can?).with(any_args).and_return(true) }

    # Stub user and user call
    let!(:app) { build(:app) }
    let(:user) { build(:user, :with_organizations) }
    let(:user2) { build(:user, :with_organizations, name: "Joe") }
    let(:organization) { build(:organization) }
    let(:team) { build(:team, organization: organization) }
    let(:app_instance) { build(:app_instance, app: app, app_id: app.id) }
    before do
      api_stub_for(get: '/apps', response: from_api([app]))
      api_stub_for(get: "/apps/#{app.id}", response: from_api(app))
      api_stub_for(get: "/users/#{user.id}", response: from_api(user))
      api_stub_for(get: "/users/#{user.id}/organizations", response: from_api(organization))
      api_stub_for(post: "/organizations", response: from_api(organization))
      api_stub_for(get: "/organizations/#{organization.id}/users", response: from_api([user]))
      api_stub_for(post: "/organizations/#{organization.id}/users", response: from_api(user))
      api_stub_for(get: "/organizations/#{organization.id}/teams", response: from_api([team]))
      api_stub_for(get: "/teams/#{team.id}", response: from_api(team))
      api_stub_for(get: "/teams/#{team.id}/app_instances", response: from_api([app_instance]))
      api_stub_for(get: "/teams/#{team.id}/users", response: from_api([user, user2]))
      sign_in user
    end

    #===============================================
    # Specs
    #===============================================
    describe 'PUT #add_users' do
      subject { put :add_users, id: team.id }

      context 'success' do
        before { subject }

        it 'returns a list of teams' do
          expect(response).to be_success
          expect(JSON.parse(response.body)).to eq(JSON.parse(hash_for_team(team).to_json))
        end
      end
    end
  end
end


text:
require 'replay'
require "replay/rails/version"

module Replay
  module Rails
    class ActiveRecordEventStore
      class Event < ActiveRecord::Base
        self.table_name = "domain_events"

        def readonly?
          persisted?
        end

        def destroy
          raise ActiveRecord::ReadOnlyRecord.new
        end
        def delete
          raise ActiveRecord::ReadOnlyRecord.new
        end

        def self.delete_all(*args)
          raise ActiveRecord::ReadOnlyRecord.new
        end

        def self.delete(*args)
          raise ActiveRecord::ReadOnlyRecord.new
        end

        def event
          if data.is_a? String
            event_type.constantize.new(JSON.parse(data))
          else
            event_type.constantize.new(data)
          end
        end

        def metadata
          if envelope_data.is_a? String
            JSON.parse(envelope_data)
          else
            envelope_data
          end
        end

        def envelope
          @envelope ||= Replay::EventEnvelope.new(
            stream_id,
            event,
            envelope_data
          )
        end

        def self.events_for(stream_id)
          where(:stream_id => stream_id).order('created_at asc')
        end

        def self.event_stream(stream_id)
          events_for(stream_id).to_a.map(&:envelope)
        end
      end

      def self.archive(stream_id)
        live_events = Arel::Table.new(:domain_events)
      end

      def self.published(envelope)
        Event.create(stream_id: envelope.stream_id, event_type: envelope.type, data: envelope.event.to_json, envelope_data: envelope.metadata.to_json)
      end

      def self.event_stream(stream_id)
        Event.event_stream(stream_id)
      end
    end
  end
end

Replay::Backends.register(:active_record, Replay::Rails::ActiveRecordEventStore)


text:
#include <string.h>

#include "GL/glew.h"
#include "GL/glfw.h"

#include "chipmunk/chipmunk_private.h"
#include "ChipmunkDemo.h"
#include "ChipmunkDemoShaderSupport.h"
#include "ChipmunkDemoTextSupport.h"

#include "VeraMoBd.ttf_sdf.h"

//#define Scale 3.0f
#define Scale 0.70f
#define LineHeight (18.0f*Scale)

static GLuint program;
static GLuint texture;

struct v2f {GLfloat x, y;};
typedef struct Vertex {struct v2f vertex, tex_coord; cpSpaceDebugColor color;} Vertex;
typedef struct Triangle {Vertex a, b, c;} Triangle;

static GLuint vao = 0;
static GLuint vbo = 0;

// char -> glyph indexes generated by the lonesock tool.
static int glyph_indexes[256];

void
ChipmunkDemoTextInit(void)
{
	GLint vshader = CompileShader(GL_VERTEX_SHADER, GLSL(
		attribute vec2 vertex;
		attribute vec2 tex_coord;
		attribute vec4 color;

		varying vec2 v_tex_coord;
		varying vec4 v_color;

		void main(void){
			// TODO: get rid of the GL 2.x matrix bit eventually?
			gl_Position = gl_ModelViewProjectionMatrix*vec4(vertex, 0.0, 1.0);

			v_color = color;
			v_tex_coord = tex_coord;
		}
	));

	GLint fshader = CompileShader(GL_FRAGMENT_SHADER, GLSL(
		uniform sampler2D u_texture;

		varying vec2 v_tex_coord;
		varying vec4 v_color;

		float aa_step(float t1, float t2, float f)
		{
			//return step(t2, f);
			return smoothstep(t1, t2, f);
		}

		void main(void)
		{
			float sdf = texture2D(u_texture, v_tex_coord).a;

			//float fw = fwidth(sdf)*0.5;
			float fw = length(vec2(dFdx(sdf), dFdy(sdf)))*0.5;

			float alpha = aa_step(0.5 - fw, 0.5 + fw, sdf);
			gl_FragColor = v_color*(v_color.a*alpha);
//			gl_FragColor = vec4(1, 0, 0, 1);
		}
	));

	program = LinkProgram(vshader, fshader);
	CHECK_GL_ERRORS();

//	GLint index = -1;//glGetUniformLocation(program, "u_texture");
//	glUniform1i(index, 0);
//	CHECK_GL_ERRORS();

	// Setu VBO and VAO.
#if __APPLE__
	glGenVertexArraysAPPLE(1, &vao);
	glBindVertexArrayAPPLE(vao);
#else
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
#endif

	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);

	SET_ATTRIBUTE(program, struct Vertex, vertex, GL_FLOAT);
	SET_ATTRIBUTE(program, struct Vertex, tex_coord, GL_FLOAT);
	SET_ATTRIBUTE(program, struct Vertex, color, GL_FLOAT);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
#if __APPLE__
	glBindVertexArrayAPPLE(0);
#else
	glBindVertexArray(0);
#endif
	CHECK_GL_ERRORS();

	// Load the SDF font texture.
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, sdf_tex_width, sdf_tex_height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, sdf_data);
	glGenerateMipmap(GL_TEXTURE_2D);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	CHECK_GL_ERRORS();

	// Fill in the glyph index array.
	for(int i=0; i<sdf_num_chars; i++){
		int char_index = sdf_spacing[i*8];
		glyph_indexes[char_index] = i;
	}
}

#undef MAX
#define MAX(__a__, __b__) (__a__ > __b__ ? __a__ : __b__)

static GLsizei triangle_capacity = 0;
static GLsizei triangle_count = 0;
static Triangle *triangle_buffer = NULL;

static Triangle *PushTriangles(GLsizei count)
{
	if(triangle_count + count > triangle_capacity){
		triangle_capacity += MAX(triangle_capacity, count);
		triangle_buffer = (Triangle *)realloc(triangle_buffer, triangle_capacity*sizeof(Triangle));
	}

	Triangle *buffer = triangle_buffer + triangle_count;
	triangle_count += count;
	return buffer;
}

static GLfloat
PushChar(int character, GLfloat x, GLfloat y, cpSpaceDebugColor color)
{
	int i = glyph_indexes[character];
	GLfloat w = (GLfloat)sdf_tex_width;
	GLfloat h = (GLfloat)sdf_tex_height;

	GLfloat gw = (GLfloat)sdf_spacing[i*8 + 3];
	GLfloat gh = (GLfloat)sdf_spacing[i*8 + 4];

	GLfloat txmin = sdf_spacing[i*8 + 1]/w;
	GLfloat tymin = sdf_spacing[i*8 + 2]/h;
	GLfloat txmax = txmin + gw/w;
	GLfloat tymax = tymin + gh/h;

	GLfloat s = Scale/scale_factor;
	GLfloat xmin = x + sdf_spacing[i*8 + 5]/scale_factor*Scale;
	GLfloat ymin = y + (sdf_spacing[i*8 + 6]/scale_factor - gh)*Scale;
	GLfloat xmax = xmin + gw*Scale;
	GLfloat ymax = ymin + gh*Scale;

	Vertex a = {{xmin, ymin}, {txmin, tymax}, color};
	Vertex b = {{xmin, ymax}, {txmin, tymin}, color};
	Vertex c = {{xmax, ymax}, {txmax, tymin}, color};
	Vertex d = {{xmax, ymin}, {txmax, tymax}, color};

	Triangle *triangles = PushTriangles(2);
	Triangle t0 = {a, b, c}; triangles[0] = t0;
	Triangle t1 = {a, c, d}; triangles[1] = t1;

	return sdf_spacing[i*8 + 7]*s;
}

#undef ChipmunkDemoTextDrawString

void
ChipmunkDemoTextDrawString(cpVect pos, char *str)
{
	cpSpaceDebugColor c = LAColor(1.0f, 1.0f);
	GLfloat x = (GLfloat)pos.x, y = (GLfloat)pos.y;

	for(size_t i=0, len=strlen(str); i<len; i++){
		if(str[i] == '\n'){
			y -= LineHeight;
			x = (GLfloat)pos.x;
//		} else if(str[i] == '*'){ // print out the last demo key
//			glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, 'A' + demoCount - 1);
		} else {
			x += (GLfloat)PushChar(str[i], x, y, c);
		}
	}
}

void
ChipmunkDemoTextFlushRenderer(void)
{
//	triangle_count = 0;
//	ChipmunkDemoTextDrawString(cpv(-300, 0), "0.:,'");

	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(Triangle)*triangle_count, triangle_buffer, GL_STREAM_DRAW);

	glUseProgram(program);

#if __APPLE__
	glBindVertexArrayAPPLE(vao);
#else
	glBindVertexArray(vao);
#endif
	glDrawArrays(GL_TRIANGLES, 0, triangle_count*3);

	CHECK_GL_ERRORS();
}

void
ChipmunkDemoTextClearRenderer(void)
{
	triangle_count = 0;
}

static int pushed_triangle_count = 0;
void
ChipmunkDemoTextPushRenderer(void)
{
	pushed_triangle_count = triangle_count;
}

void
ChipmunkDemoTextPopRenderer(void)
{
	triangle_count = pushed_triangle_count;
}


text:
package com.android.dexgen.dex.code.form;

import com.android.dexgen.dex.code.DalvInsn;
import com.android.dexgen.dex.code.InsnFormat;
import com.android.dexgen.dex.code.TargetInsn;
import com.android.dexgen.util.AnnotatedOutput;

/**
 * Instruction format {@code 20t}. See the instruction format spec
 * for details.
 */
public final class Form20t extends InsnFormat {
    /** {@code non-null;} unique instance of this class */
    public static final InsnFormat THE_ONE = new Form20t();

    /**
     * Constructs an instance. This class is not publicly
     * instantiable. Use {@link #THE_ONE}.
     */
    private Form20t() {
        // This space intentionally left blank.
    }

    /** {@inheritDoc} */
    @Override
    public String insnArgString(DalvInsn insn) {
        return branchString(insn);
    }

    /** {@inheritDoc} */
    @Override
    public String insnCommentString(DalvInsn insn, boolean noteIndices) {
        return branchComment(insn);
    }

    /** {@inheritDoc} */
    @Override
    public int codeSize() {
        return 2;
    }

    /** {@inheritDoc} */
    @Override
    public boolean isCompatible(DalvInsn insn) {
        if (!((insn instanceof TargetInsn) &&
              (insn.getRegisters().size() == 0))) {
            return false;
        }

        TargetInsn ti = (TargetInsn) insn;
        return ti.hasTargetOffset() ? branchFits(ti) : true;
    }

    /** {@inheritDoc} */
    @Override
    public boolean branchFits(TargetInsn insn) {
        int offset = insn.getTargetOffset();

        // Note: A zero offset would fit, but it is prohibited by the spec.
        return (offset != 0) && signedFitsInShort(offset);
    }

    /** {@inheritDoc} */
    @Override
    public InsnFormat nextUp() {
        return Form30t.THE_ONE;
    }

    /** {@inheritDoc} */
    @Override
    public void writeTo(AnnotatedOutput out, DalvInsn insn) {
        int offset = ((TargetInsn) insn).getTargetOffset();

        write(out, opcodeUnit(insn, 0), (short) offset);
    }
}


text:
substor
=======

Node.js promise based utility to subscribe to one or more Redis channels at a time and store all messages received on subscribed channels. Messages can then be inspected.

Background
----------

I created substor for a project where we were testing a web application whose Java backend had to communicate with other systems. These included SOAP, JMS and JSON messages. As part of our testing we wanted the ability to check the contents of these outgoing messages. This was because on our local machines and on CI we did not connect to these other systems, an activity which would not happen until the System Integration Testing (SIT) phase of the project. We did not want to wait until SIT before being able to test integration messages and we also wanted to continually test integration messages to ensure any breaking changes would be detected before releasing into the SIT environment.

There is a missing piece in this set up that is key to being able to test integration messages with substor and that is a utility that was also created as part of the project (known internally as the 'simulator'). The simulator provides the ability to mock other systems and put any integration request messages on Redis channels. Hopefully the 'simulator' project will be published on GitHub in the future.

I use my other npm module [messageCheckr](https://github.com/mrbenhowl/messageCheckr) with substor to verify JMS / SOAP are correct. substor is used on my projects to verify integration messages from both UI tests using Cucumber/Protractor and API tests using mocha/supertest.

Compatibility
------------

Works with Node.js v0.12.* and higher

Getting Started
---------------

`npm install substor` to install from the [NPM registry](https://www.npmjs.com/package/substor).

Install
-------

```javascript
var substor = require('substor');
```

Usage
-----

The following example is how I have used substor in an API test using mocha.

In hook.js

```javascript
before(function () {
  return substor.connect({host: 'redisHost', port: 'redisPort'});
});
```

In testFile.js

```javascript
it('should do something', function () {

  return substore.subscribeToChannels(['redisChannelName'])
    .then(function(){
      // Do something that results in a message or messages to be placed on Redis channel 'redisChannelName'
    })
    .then(function(){
      return substore.getLatestMessageOnChannel('redisChannelName')
    })
    .then(function(latestMessageOnRedisChannelName){
      // latestMessageOnRedisChannelName is a String
      // Do whatever you want to the message.
      // Once done ensure to unsubscribe from the Redis channel(s)
      return substore.unsubscribeFromAllChannels()
    })
});
```

Methods
-------

All promises returned from methods are Promises/A+ compliant. Underneath the hood [q](https://github.com/kriskowal/q) is used.

###connect(options)
| Param | Type | Description |
|---|---|---|
|options | object | *Attributes*
**host** - (mandatory) Redis host (e.g. host: '127.0.0.1')
**port** - (mandatory) Redis port (e.g. port: '6379')
**defaultTimeOutMilliseconds** - (optional) an integer to override the default of 700 milliseconds. This value is the wait time before getting a message (or message count) from a subscribed channel.
**debug** - (optional) set to true if you need to see more logs.|

**Returns** Promise.

###subscribeToChannels(channels)
| Param | Type | Description |
|---|---|---|
| channels | Array | An array of Redis channels. Each element is a String, e.g. ['channel1', 'channel2'] |

**Returns** Promise.

###unsubscribeFromAllChannels()
**Returns** Promise.

###getQueue()
**Returns** object consisting of all messages received on all channels subscribed to.

###getMessageCount(channel)
| Param | Type | Description |
|---|---|---|
| channel | String | Name of channel |

**Returns** Promise that resolves to the number of messages received on the specified **channel** since it was subscribed to.

###getLatestMessageOnChannel(channel)
| Param | Type | Description |
|---|---|---|
| channel | String | Name of channel |

**Returns** Promise that resolves to the message (String) last received on the specified **channel**.

###getMessageOnChannel(position, channel)
| Param | Type | Description |
|---|---|---|
| position | Integer | Position of message received, 1 being the latest |
| channel | String | Name of channel |

**Returns** Promise that resolves to the the message (String) in **position** on the specified **channel**.


text:
Contoh penggunaan Angular Js + CodeIgniter Rest Server 2.7.1.

Referensi:
- http://blog.pisyek.com/create-todo-app-with-codeigniter-3-angularjs/
- https://github.com/chriskacerguis/codeigniter-restserver
- https://angularjs.org/


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE591_Sensitive_Data_Storage_in_Improperly_Locked_Memory__w32_char_43.cpp
Label Definition File: CWE591_Sensitive_Data_Storage_in_Improperly_Locked_Memory__w32.label.xml
Template File: sources-sink-43.tmpl.cpp
*/
/*
 * @description
 * CWE: 591 Sensitive Data Storage in Improperly Locked Memory
 * BadSource:  Allocate memory for sensitive data without using VirtualLock() to lock the buffer into memory
 * GoodSource: Allocate memory for sensitive data and use VirtualLock() to lock the buffer into memory
 * Sinks:
 *    BadSink : Authenticate the user using LogonUserA()
 * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file
 *
 * */

#include "std_testcase.h"

#include <wchar.h>
#include <windows.h>

#pragma comment(lib, "advapi32.lib")

namespace CWE591_Sensitive_Data_Storage_in_Improperly_Locked_Memory__w32_char_43
{

#ifndef OMITBAD

static void badSource(char * &password)
{
    password = (char *)malloc(100*sizeof(char));
    if (password == NULL)
    {
        printLine("Memory could not be allocated");
        exit(1);
    }
    /* FLAW: Do not lock the memory */
    /* INCIDENTAL FLAW: CWE-259 Hardcoded Password */
    strcpy(password, "Password1234!");
}

void bad()
{
    char * password;
    /* Initialize Data */
    password = "";
    badSource(password);
    {
        HANDLE pHandle;
        char * username = "User";
        char * domain = "Domain";
        /* Use the password in LogonUser() to establish that it is "sensitive" */
        if (LogonUserA(
                    username,
                    domain,
                    password,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
        }
        /* POTENTIAL FLAW: Sensitive data possibly improperly locked */
        free(password);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSource(char * &password)
{
    password = (char *)malloc(100*sizeof(char));
    if (password == NULL)
    {
        printLine("Memory could not be allocated");
        exit(1);
    }
    /* FIX: Use VirtualLock() to lock the buffer into memory */
    if(!VirtualLock(password, 100*sizeof(char)))
    {
        printLine("Memory could not be locked");
        exit(1);
    }
    /* INCIDENTAL FLAW: CWE-259 Hardcoded Password */
    strcpy(password, "Password1234!");
}

static void goodG2B()
{
    char * password;
    /* Initialize Data */
    password = "";
    goodG2BSource(password);
    {
        HANDLE pHandle;
        char * username = "User";
        char * domain = "Domain";
        /* Use the password in LogonUser() to establish that it is "sensitive" */
        if (LogonUserA(
                    username,
                    domain,
                    password,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
        }
        /* POTENTIAL FLAW: Sensitive data possibly improperly locked */
        free(password);
    }
}

void good()
{
    goodG2B();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

using namespace CWE591_Sensitive_Data_Storage_in_Improperly_Locked_Memory__w32_char_43; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
> Most of these will move into Vagrant and get automated

## Create servers

    vagrant up

## Login to servers

    vagrant ssh salt
    vagrant ssh server1
    vagrant ssh server2

## Optional: Install emacs

    [root@salt ~]# yum install emacs -y
    [root@server1 ]# yum install emacs -y
    [root@server2 ]# yum install emacs -y

## Clean firewall rules on Master

    [root@salt ~]# iptables -X
    [root@salt ~]# iptables -F

## Start salt-minion on server1, server2

    [root@server1 ~]# systemctl start salt-minion
    [root@server2 ~]# systemctl start salt-minion

## Accept the keys

### On Master

    [root@salt ~]# salt-key -A
    Unaccepted Keys:
    server2
    server1
    Proceed? [n/Y] Y
    Key for minion server1 accepted.
    Key for minion server2 accepted.

### Modify master configuration.

    [root@salt srv]# emacs /etc/salt/master
    file_roots:
      base:
        - /srv/salt/states
    ...
    ...
    pillar_roots:
      base:
        - /srv/salt/pillar

#### Create folders

    [root@salt srv]# mkdir -p /srv/salt/states
    [root@salt srv]# mkdir -p /srv/salt/pillar

#### Restart salt-master

    [root@salt srv]# systemctl restart salt-master


text:
<!doctype html>

<meta charset="utf-8">
<title>Page Not Found – _personal</title>
<meta name="description" content="Page not found. Your pixels are in another canvas.">
<meta name="keywords" content="">

<meta name="twitter:title" content="Page Not Found">
<meta name="twitter:description" content="Page not found. Your pixels are in another canvas.">
<meta name="twitter:site" content="@gio_bll">
<meta name="twitter:creator" content="@gio_bll">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://giovanni-bb.github.io/images/default-thumb.png">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Page Not Found">
<meta property="og:description" content="Page not found. Your pixels are in another canvas.">
<meta property="og:url" content="http://giovanni-bb.github.io/404.html">
<meta property="og:site_name" content="_personal">

<link rel="canonical" href="http://giovanni-bb.github.io/404.html">
<link href="http://giovanni-bb.github.io/feed.xml" type="application/atom+xml" rel="alternate" title="_personal Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://giovanni-bb.github.io/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700%7CPT+Serif:400,700,400italic' rel='stylesheet' type='text/css'>

<link rel="shortcut icon" href="http://giovanni-bb.github.io/favicon.ico">

<link rel="shortcut icon" href="http://giovanni-bb.github.io/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://giovanni-bb.github.io/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://giovanni-bb.github.io/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://giovanni-bb.github.io/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://giovanni-bb.github.io/images/apple-touch-icon-144x144-precomposed.png">

		_personal

About

Posts

Projects

C.V.

Giovanni Belloni

Software Developer

   Email
   Twitter
   Facebook
   Google+
   LinkedIn

   Github

   Youtube

Page Not Found

Sorry, but the page you were trying to view does not exist — perhaps you can try searching for it below.

Share on

       Twitter

       Facebook

       Google+

© 2015 Giovanni Belloni. Powered by Jekyll using the Minimal Mistakes theme.


text:
import {KernelConfig, KernelFunc, Range, RangeAttrs, TensorInfo} from '@tensorflow/tfjs-core';

import {MathBackendCPU} from '../backend_cpu';
import {rangeImpl} from './Range_impl';

export function range(args: {backend: MathBackendCPU, attrs: RangeAttrs}):
    TensorInfo {
  const {backend, attrs} = args;
  const {start, stop, dtype, step} = attrs;

  const values = rangeImpl(start, stop, step, dtype);
  return backend.makeTensorInfo([values.length], dtype, values);
}

export const rangeConfig: KernelConfig = {
  kernelName: Range,
  backendName: 'cpu',
  kernelFunc: range as {} as KernelFunc
};


text:
using System.Collections.Generic;

namespace CodeOwls.PowerShell.Host.History
{
    internal class HistoryStack : List<string>
    {
    }
}


text:
from neo4j import unit_of_work
# end::transaction-function-import[]
# isort: on

# python -m pytest tests/integration/examples/test_transaction_function_example.py -s -v

# tag::transaction-function[]
@unit_of_work(timeout=5)
def create_person(tx, name):
    return tx.run("CREATE (a:Person {name: $name}) RETURN id(a)", name=name).single().value()

def add_person(driver, name):
    with driver.session() as session:
        return session.execute_write(create_person, name)
# end::transaction-function[]

class TransactionFunctionExample:

    def __init__(self, driver):
        self.driver = driver

    def add_person(self, name):
        return add_person(self.driver, name)

def work(tx, query, **parameters):
    res = tx.run(query, **parameters)
    return [rec.values() for rec in res], res.consume()

def test_example(driver):
    eg = TransactionFunctionExample(driver)
    with eg.driver.session() as session:
        session.execute_write(work, "MATCH (_) DETACH DELETE _")
        eg.add_person("Alice")
        records, _ = session.execute_read(
            work, "MATCH (a:Person) RETURN count(a)"
        )
        assert records == [[1]]


text:
package pagarme.exception;

public class PagarMeException extends Exception {
	private static final long serialVersionUID = -1171690318754877605L;

	public PagarMeException(String message){
		super(message);
	}
}


text:
#include "vice.h"

#include <stdio.h>
#include <string.h>

#include "cmdline.h"
#include "driver-select.h"
#include "drv-ascii.h"
#include "lib.h"
#include "log.h"
#include "resources.h"
#include "translate.h"
#include "types.h"
#include "util.h"

/* #define DEBUG_PRINTER */

static log_t driver_select_log = LOG_ERR;

struct driver_select_list_s {
    driver_select_t driver_select;
    struct driver_select_list_s *next;
};
typedef struct driver_select_list_s driver_select_list_t;

/* Names of currently used printer driver.  To be removed.  */
static char *printer_driver[] = { NULL, NULL, NULL };

/* Currently used printer driver.  */
static driver_select_t driver_select[3];

/* Pointer to registered printer driver.  */
static driver_select_list_t *driver_select_list = NULL;

static int set_printer_driver(const char *name, void *param)
{
    driver_select_list_t *list;

    list = driver_select_list;

    if (list == NULL)
        return -1;

    do {
        if (!strcmp(list->driver_select.drv_name, name)) {
            util_string_set(&printer_driver[vice_ptr_to_int(param)], name);
            memcpy(&driver_select[vice_ptr_to_int(param)], &(list->driver_select),
                   sizeof(driver_select_t));
            return 0;
        }
        list = list->next;
    } while (list != NULL);

    return -1;
}

static const resource_string_t resources_string[] = {
    {"Printer4Driver", "ascii", RES_EVENT_NO, NULL,
      &printer_driver[0], set_printer_driver, (void *)0 },
    {"Printer5Driver", "ascii", RES_EVENT_NO, NULL,
      &printer_driver[1], set_printer_driver, (void *)1 },
    {"PrinterUserportDriver", "ascii", RES_EVENT_NO, NULL,
      &printer_driver[2], set_printer_driver, (void *)2 },
    { NULL }
};

int driver_select_init_resources(void)
{
    return resources_register_string(resources_string);
}

void driver_select_shutdown_resources(void)
{
    lib_free(printer_driver[0]);
    lib_free(printer_driver[1]);
    lib_free(printer_driver[2]);
}

static const cmdline_option_t cmdline_options[] =
{
    { "-pr4drv", SET_RESOURCE, 1,
     NULL, NULL, "Printer4Driver", NULL,
     USE_PARAM_ID, USE_DESCRIPTION_ID,
     IDCLS_P_NAME, IDCLS_SPECIFY_PRT_DRIVER_4_NAME,
     NULL, NULL },
    { "-pr5drv", SET_RESOURCE, 1,
     NULL, NULL, "Printer5Driver", NULL,
     USE_PARAM_ID, USE_DESCRIPTION_ID,
     IDCLS_P_NAME, IDCLS_SPECIFY_PRT_DRIVER_5_NAME,
     NULL, NULL },
    { "-pruserdrv", SET_RESOURCE, 1,
     NULL, NULL, "PrinterUserportDriver", NULL,
     USE_PARAM_ID, USE_DESCRIPTION_ID,
     IDCLS_P_NAME, IDCLS_SPECIFY_PRT_DRIVER_USR_NAME,
     NULL, NULL },
    { NULL }
};

int driver_select_init_cmdline_options(void)
{
    return cmdline_register_options(cmdline_options);
}

void driver_select_init(void)
{
    driver_select_log = log_open("Driver Select");
}

/* ------------------------------------------------------------------------- */

void driver_select_register(driver_select_t *driver_select)
{
    driver_select_list_t *list, *prev;

    prev = driver_select_list;
    while (prev != NULL && prev->next != NULL)
        prev = prev->next;

    list = lib_malloc(sizeof(driver_select_list_t));
    memcpy(&(list->driver_select), driver_select, sizeof(driver_select_t));
    list->next = NULL;

    if (driver_select_list != NULL)
        prev->next = list;
    else
        driver_select_list = list;
}

void driver_select_shutdown(void)
{
    driver_select_list_t *list, *next;

    list = driver_select_list;

    while (list != NULL) {
        next = list->next;
        lib_free(list);
        list = next;
    }
}

/* ------------------------------------------------------------------------- */

int driver_select_open(unsigned int prnr, unsigned int secondary)
{
#ifdef DEBUG_PRINTER
    log_message(driver_select_log, "Open device #%i secondary %i.",
                prnr + 4, secondary);
#endif

    return driver_select[prnr].drv_open(prnr, secondary);
}

void driver_select_close(unsigned int prnr, unsigned int secondary)
{
#ifdef DEBUG_PRINTER
    log_message(driver_select_log, "Close device #%i.", prnr + 4);
#endif

    driver_select[prnr].drv_close(prnr, secondary);
}

int driver_select_putc(unsigned int prnr, unsigned int secondary, BYTE b)
{
    return driver_select[prnr].drv_putc(prnr, secondary, b);
}

int driver_select_getc(unsigned int prnr, unsigned int secondary, BYTE *b)
{
    return driver_select[prnr].drv_getc(prnr, secondary, b);
}

int driver_select_flush(unsigned int prnr, unsigned int secondary)
{
    return driver_select[prnr].drv_flush(prnr, secondary);
}

int driver_select_formfeed(unsigned int prnr)
{
    return driver_select[prnr].drv_formfeed(prnr);
}


text:
<?php

/**
 * Translate
 *
 * @category  Gene
 * @package   Gene_Translate
 * @version   $id$
 * @copyright 2009-2011 Shinya Ohyanagi
 * @author    Shinya Ohyanagi <sohyanagi@gmail.com>
 * @license   New BSD License
 */
class Gene_Translate
{
    /**
     * Application path
     *
     * @var    mixed
     * @access protected
     */
    protected $_appPath = null;

    /**
     * Translate
     *
     * @var    mixed
     * @access protected
     */
    protected $_translate = array();

    /**
     * Path to translates
     *
     * @var    array
     * @access protected
     */
    protected $_translatePath = array(
        'locales'   => null,
        'resources' => null
    );

    /**
     * Path to cache.
     *
     * @var    mixed
     * @access protected
     */
    protected $_cachePath = null;

    /**
     * Constructor.
     *
     * @access public
     * @return void
     */
    public function __construct($appPath = null, $cachePath = null)
    {
        $this->_appPath   = $appPath;
        $this->_cachePath = $cachePath;
    }

    /**
     * Set application directory path.
     *
     * @param  mixed $path Application path
     * @access public
     * @return Gene_Translate Fluent interface
     */
    public function setAppPath($path)
    {
        $this->_appPath = $path;
        return $this;
    }

    /**
     * Get application directory path.
     *
     * @access public
     * @return mixed Application path
     */
    public function getAppPath()
    {
        return $this->_appPath;
    }

    /**
     * Get cache object.
     *
     * @param  mixed $path Path to master files
     * @param  string $name Cache object name
     * @access public
     * @return Zend_Cache Cache object
     */
    public function getCacheFileObject($path, $name = 'translates')
    {
        $cachePath = $this->_cachePath;
        if (is_null($cachePath)) {
            $cachePath = $this->getAppPath();
        }

        $instance  = Gene_Cache_File::getInstance($cachePath);
        $frontend  = array(
            'master_files' => $instance->directorySearch($path)
        );

        $cache = $instance->setFrontend($frontend)->getCache($name);
        return $cache;
    }

    /**
     * Set translate path
     *
     * @param  mixed $path Path to locale file directory
     * @access public
     * @return Gene_Translate Fluent interface
     */
    public function setTranslatePath($path, $key = 'locales')
    {
        $this->_translatePath[$key] = $path;
        return $this;
    }

    /**
     * Get translate path
     *
     * @param  mixed $type
     * @access public
     * @return mixed Locale directory path
     */
    public function getTranslatePath($type = 'locales')
    {
        $path = null;
        if (!isset($this->_translatePath[$type])) {
            $this->_translatePath[$type] = null;
            $appPath = $this->getAppPath();
            if (!is_null($appPath)) {
                $path = rtrim($appPath, '\//') . DIRECTORY_SEPARATOR
                      . $type . DIRECTORY_SEPARATOR;
            }
        }

        if (is_null($this->_translatePath[$type])) {
            return $path;
        }

        return $this->_translatePath[$type];
    }

    /**
     * Get system translate
     *
     * @param  string $value Filename
     * @param  mixed $path Path to resources directory
     * @access public
     * @return Zend_Translate
     */
    public function getValidateTranslate($file = 'Zend_Validate.php', $path = null)
    {
        if (array_key_exists($file, $this->_translate)) {
            return $this->_translate[$file];
        }
        $appPath = $this->getAppPath();
        $locale  = new Zend_Locale();
        $lang    = $locale->getLanguage();
        if (is_null($path)) {
            $path = $appPath . DIRECTORY_SEPARATOR . 'resources'
                  . DIRECTORY_SEPARATOR . 'languages'
                  . DIRECTORY_SEPARATOR . $lang;
        }

        $path      = $this->_getPath($path, $lang, 'resources/languages');
        $scan      = array('scan' => Zend_Translate::LOCALE_DIRECTORY);
        $options   = array(
            'adapter' => 'array',
            'content' => $path,
            'locale'  => $locale,
            'scan'    => $scan,
        );
        $translate = new Zend_Translate($options);
        $this->_translate[$file] = $translate;

        return $translate;
    }

    /**
     * Merge yet antoehr translate file to Zend_Validate.php
     *
     * @param  Zend_Translate $translate
     * @param  mixed $path Merge from
     * @param  string $default Merge to
     * @access public
     * @return Zend_Translate Translate object
     */
    public function mergeTranslate(Zend_Translate $translate, $path, $default = 'Zend_Validate.php')
    {
        $cache = $this->getCacheFileObject($path, 'mergetranslate');
        $cacheId = pathinfo(str_replace('/', '_', $path), PATHINFO_FILENAME);
        if (!$data = $cache->load($cacheId)) {
            $iterator = new DirectoryIterator($path);
            foreach ($iterator as $key => $val) {
                // If another translate file found in same directory,
                // Add to default translate file.
                $file = $val->getFilename();
                if ($val->isFile() && $file !== $default) {
                    $translate->addTranslation($path . DIRECTORY_SEPARATOR . $file);
                }
            }
            $cache->save($translate);
        } else {
            $translate = $data;
        }

        $this->_translate[$default] = $translate;
        return $translate;
    }

    /**
     * Get translate object
     *
     * @param  mixed $value Transelate file name
     * @param  string $type Transelate
     * @access public
     * @return Zend_Translate transelates
     */
    public function getTranslate($value, $type = 'ini')
    {
        if (array_key_exists($value, $this->_translate)) {
            return $this->_translate[$value];
        }

        $path   = $this->getTranslatePath();
        $locale = new Zend_Locale();
        $lang   = $locale->getLanguage();
        $path   = $path . $lang . DIRECTORY_SEPARATOR . $value;
        $info   = pathinfo($path);
        if (!isset($info['extension'])) {
            $path .= '.' . $type;
        }

        $path  = $this->_getPath($path, $lang, 'locales');
        $cache = $this->getCacheFileObject($path);

        /**
         * Zend_Translate::setCache($cache); create cache,
         * but cache Zend_Translate it self.
         */
        $cacheId = pathinfo(str_replace('/', '_', $value), PATHINFO_FILENAME);
        if (!$translate = $cache->load($cacheId)) {
            $options = array(
                'adapter' => $type,
                'content' => $path,
                'locale'  => $locale->getLanguage()
            );
            $translate = new Zend_Translate($options);
            $translate = new Zend_Translate($type, $path, $locale);
            $cache->save($translate);
        }

        $this->_translate[$value] = $translate;

        return $translate;
    }

    /**
     * Get path
     *
     * @param  mixed $path Path to resources
     * @param  mixed $lang Language
     * @param  string $type locale|resources
     * @access private
     * @return mixed Path to direcotry
     */
    private function _getPath($path, $lang, $type = 'locale')
    {
        if (file_exists($path)) {
            return dirname($path);
        } else {
            $translatePath = $this->getTranslatePath($type);
            $iterator = new DirectoryIterator($translatePath);
            foreach ($iterator as $val) {
                // If translate of locale direcotry|file not found,
                // use exsist translate file as default.
                if (!$val->isDot() && $val->getFilename() !== $lang) {
                    $locale = new Zend_Locale($val->getFilename());
                    $lang   = $locale->getLanguage();
                    $path   = $translatePath . $lang . DIRECTORY_SEPARATOR;
                    break;
                }
            }
        }

        return $path;
    }
}


text:
@extends('master')

@section('title', 'Registered Users')

@section('content')

	@if (Session::has('flash_message'))

{{ Session::get('flash_message') }}

	@endif

	@if (Sentry::check())

{{ "Welcome, " . Sentry::getUser()->first_name }}

	@endif

This is for standard users only!

@stop


text:
require 'spec_helper'

describe Notice do
  pending "add some examples to (or delete) #{__FILE__}"
end


text: ./node_modules/.bin/supervisor node bin/www