text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.GenerateFromMembers
{
    internal abstract class AbstractGenerateFromMembersService<TMemberDeclarationSyntax>
        where TMemberDeclarationSyntax : SyntaxNode
    {
        protected AbstractGenerateFromMembersService()
        {
        }

        protected abstract Task<IList<TMemberDeclarationSyntax>> GetSelectedMembersAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
        protected abstract IEnumerable<ISymbol> GetDeclaredSymbols(SemanticModel semanticModel, TMemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken);

        protected class SelectedMemberInfo
        {
            public INamedTypeSymbol ContainingType;
            public IList<TMemberDeclarationSyntax> SelectedDeclarations;
            public IList<ISymbol> SelectedMembers;
        }

        protected async Task<SelectedMemberInfo> GetSelectedMemberInfoAsync(
            Document document, TextSpan textSpan, CancellationToken cancellationToken)
        {
            var selectedDeclarations = await this.GetSelectedMembersAsync(document, textSpan, cancellationToken).ConfigureAwait(false);

            if (selectedDeclarations.Count > 0)
            {
                var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                var selectedMembers = selectedDeclarations.SelectMany(
                    d => this.GetDeclaredSymbols(semanticModel, d, cancellationToken)).WhereNotNull().ToList();
                if (selectedMembers.Count > 0)
                {
                    var containingType = selectedMembers.First().ContainingType;
                    if (containingType != null)
                    {
                        return new SelectedMemberInfo { ContainingType = containingType, SelectedDeclarations = selectedDeclarations, SelectedMembers = selectedMembers };
                    }
                }
            }

            return null;
        }

        protected static bool IsWritableInstanceFieldOrProperty(ISymbol symbol)
        {
            // Can use non const fields and properties with setters in them.
            return
                IsInstanceFieldOrProperty(symbol) &&
                IsWritableFieldOrProperty(symbol);
        }

        private static bool IsWritableFieldOrProperty(ISymbol symbol)
        {
            return symbol.TypeSwitch(
                (IFieldSymbol field) => !field.IsConst,
                (IPropertySymbol property) => property.SetMethod != null);
        }

        protected static bool IsInstanceFieldOrProperty(ISymbol symbol)
        {
            return !symbol.IsStatic && (IsField(symbol) || IsProperty(symbol));
        }

        private static bool IsProperty(ISymbol symbol)
        {
            return symbol.Kind == SymbolKind.Property;
        }

        private static bool IsField(ISymbol symbol)
        {
            return symbol.Kind == SymbolKind.Field;
        }

        protected CodeRefactoring CreateCodeRefactoring(
            IList<TMemberDeclarationSyntax> selectedDeclarations,
            IEnumerable<CodeAction> actions)
        {
#if false
            var lastDeclaration = selectedDeclarations.Last();
            var endSpan = new TextSpan(lastDeclaration.Span.End - 1, 1);
            return new CodeRefactoring(actions, endSpan);
#endif
            return new CodeRefactoring(null, actions);
        }

        protected List<IParameterSymbol> DetermineParameters(
            IList<ISymbol> selectedMembers)
        {
            var parameters = new List<IParameterSymbol>();

            foreach (var symbol in selectedMembers)
            {
                var type = symbol is IFieldSymbol
                    ? ((IFieldSymbol)symbol).Type
                    : ((IPropertySymbol)symbol).Type;

                parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
                    attributes: null,
                    refKind: RefKind.None,
                    isParams: false,
                    type: type,
                    name: symbol.Name.ToCamelCase()));
            }

            return parameters;
        }

        protected IMethodSymbol GetDelegatedConstructor(
            INamedTypeSymbol containingType,
            List<IParameterSymbol> parameters)
        {
            var q =
                from c in containingType.InstanceConstructors
                orderby c.Parameters.Length descending
                where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Count
                where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams)
                let constructorTypes = c.Parameters.Select(p => p.Type)
                let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type)
                where constructorTypes.SequenceEqual(symbolTypes)
                select c;

            return q.FirstOrDefault();
        }

        protected bool HasMatchingConstructor(
            INamedTypeSymbol containingType,
            List<IParameterSymbol> parameters)
        {
            return containingType.InstanceConstructors.Any(c => MatchesConstructor(c, parameters));
        }

        private bool MatchesConstructor(
            IMethodSymbol constructor,
            List<IParameterSymbol> parameters)
        {
            return parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type));
        }

        protected static readonly SymbolDisplayFormat SimpleFormat =
            new SymbolDisplayFormat(
                typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
                genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
                parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType,
                miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
    }
}


text:
package org.fusesource.hawtdispatch;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.fusesource.hawtdispatch.internal.DispatcherConfig;
import org.fusesource.hawtdispatch.internal.util.RunnableCountDownLatch;
import org.junit.Test;

import static java.util.concurrent.TimeUnit.*;
import static junit.framework.Assert.*;

/**
 *
 * @author Hiram Chirino
 */
public class DispatchSourceTest {

    @Test
    public void connect() throws IOException, InterruptedException {

        // Create the nio server socket...
        final ServerSocketChannel channel = ServerSocketChannel.open();
        channel.configureBlocking(false);
        channel.socket().bind(address("0.0.0.0", 0), 10);

        // Get a DISPATCHER and queue..
        Dispatcher dispatcher = new DispatcherConfig().createDispatcher();

        Thread.sleep(1000);
        DispatchQueue accepts = dispatcher.createQueue("test");

        // Create a source attached to the server socket to deal with new connectins..
        DispatchSource source = dispatcher.createSource(channel, SelectionKey.OP_ACCEPT, accepts);
        RunnableCountDownLatch accepted;

        // Events should not be seen until the source is resumed.
        accepted = acceptor(channel);
        source.setEventHandler(accepted);
        connect(channel);
        assertFalse(accepted.await(1, SECONDS));
        source.resume();
        assertTrue(accepted.await(1, SECONDS));

        // Since we are resumed we should get the next connect quickly..
        System.out.println("start....");
        accepted = acceptor(channel);
        source.setEventHandler(accepted);
        connect(channel);
        System.out.println("waiting....");
        assertTrue(accepted.await(2, SECONDS));

        // Now test that events don't get fired
        // once the source is canceled.
        accepted = acceptor(channel);
        source.setEventHandler(accepted);
        source.cancel();
        connect(channel);
        assertFalse(accepted.await(2, SECONDS));

    }

    private void connect(final ServerSocketChannel channel) {
        new Thread("connect") {
            public void run() {
                try {
                    Socket socket = new Socket();
                    socket.connect(channel.socket().getLocalSocketAddress());
                    socket.close();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private RunnableCountDownLatch acceptor(final ServerSocketChannel channel) {
        return new RunnableCountDownLatch(1) {
            @Override
            public void run() {
                try {
                    SocketChannel socket = channel.accept();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                super.run();
            }
        };
    }

    static public InetSocketAddress address(String host, int port) throws UnknownHostException {
        return new InetSocketAddress(ip(host), port);
    }

    static public InetAddress ip(String host) throws UnknownHostException {
        return InetAddress.getByName(host);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.taobao.taokeeper.monitor.core.task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import common.toolkit.java.entity.DateFormat;
import common.toolkit.java.util.DateUtil;

/**
 * Description: Check if alive one node(ip).
 *
 * @author 银时 yinshi.nc@taobao.com
 * @Date 2011-10-28
 */
public class CheckerJob implements Runnable {

	private static final Logger LOG = LoggerFactory.getLogger( CheckerJob.class );
	private static final Logger LOG_checkData = LoggerFactory.getLogger( "checkData" );

	private Map< String, ZkClient > zkClientList = new HashMap< String, ZkClient >();

	private String[] paths = { "/jingwei-v2/tasks/IC-DATA-DB2/locks", "/jingwei-v2/tasks/IC-DATA-DB3/locks", "/jingwei-v2/tasks/IC-DATA-DB4/locks",
			"/jingwei-v2/tasks/IC-DATA-DB5/locks", "/jingwei-v2/tasks/IC-DATA-DB6/locks", "/jingwei-v2/tasks/IC-DATA-DB7/locks", };

	@Override
	public void run() {

		String[] serlist = { "172.24.113.124", "172.24.113.125", "172.24.113.126" };
		// String[] serlist={ "10.232.102.188:2181", "10.232.102.189:2181" };
		try {

			for ( String server : serlist ) {
				ZkClient zkClient = new ZkClient( server, 50000 );
				zkClientList.put( server, zkClient );
			}
		} catch ( Throwable e1 ) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		while ( true ) {
			try {

				for ( String path : paths ) {

					LOG_checkData.warn( "Path: " + path );
					// System.err.println( "Path: " + path );
					for ( String server : zkClientList.keySet() ) {
						StringBuffer sb = new StringBuffer( DateUtil.getNowTime( DateFormat.DateTime ) );
						sb.append( "  [server: " + server ).append( "] ,data: " );
						List< String > lsit = new ArrayList< String >();
						try {
							lsit = zkClientList.get( server ).getChildren( path );
						} catch ( Throwable e ) {
							LOG.error( e.getMessage(), e );
						}
						for ( String str : lsit ) {
							sb.append( str );
						}
						LOG_checkData.warn( sb.toString() );
						// System.err.println( sb.toString() );
					}
					LOG.warn( "-------------------" );
					// System.err.println("------------------");
					Thread.sleep( 1 * 1000 );
				}
				Thread.sleep( 10 * 1000 );
			} catch ( Throwable e ) {
				LOG.error( e.getMessage(), e );
			}
		}
	}

	public static void main( String[] args ) {
		Thread thread = new Thread( new CheckerJob() );
		thread.start();
	}
}


text: Mamble Javascript Development Kit


text:
module VmrInterviewsHelper
  def pretty_duration(seconds)
   seconds = seconds.to_i
   total_minutes = seconds / 1.minutes
   seconds_in_last_minute = seconds - total_minutes.minutes.seconds
   "#{total_minutes}:#{"%02d" % seconds_in_last_minute}"
  end
end


text:
using System;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.WebSites.Models;

namespace Microsoft.WindowsAzure.Management.WebSites.Models
{
    /// <summary>
    /// The Create Web Hosting Plan operation response.
    /// </summary>
    public partial class WebHostingPlanUpdateResponse : OperationResponse
    {
        private WebHostingPlan _webHostingPlan;

        /// <summary>
        /// Optional. Details of the updated Web Hosting Plan.
        /// </summary>
        public WebHostingPlan WebHostingPlan
        {
            get { return this._webHostingPlan; }
            set { this._webHostingPlan = value; }
        }

        /// <summary>
        /// Initializes a new instance of the WebHostingPlanUpdateResponse
        /// class.
        /// </summary>
        public WebHostingPlanUpdateResponse()
        {
        }
    }
}


text:
var navigationListener = (function(){
	//create listener to transfer active class to nav items
	//requires jquery
	function create($selector){
		$selector = $($selector);
		function clearAllActive(){
			$selector.removeClass('active');
			console.log('remove' + $(this).find("a").text());
		}

		$selector.find('a').on("mousedown", function mousedownCb(){
			clearAllActive();
			var that = $(this);
			console.log('add' + that.text());
			that.parent("li").addClass("active");
		});
	}

	return {
		create: create
	};

}());
	navigationListener.create("#navbar li");


text:
Login to

EASILY USING

FACEBOOK

GOOGLE

- OR USING EMAIL/MOBILENO -

      <form class="register-form">
        <fieldset class="register-input-container">

            <input type="text" class="register-user-input register-user-input-email" placeholder="Your Email Address / Mobile" name="userid" ng-model="userid" autocomplete="off"/>

            <input type="number" class="register-user-input register-user-input-email" placeholder="OTP sent to Mobile Number" name="otp" ng-model="otp" autocomplete="off"/>

            <input type="password" class="register-user-input register-user-input-password" placeholder="Your Password" name="password" ng-model="password"
            style="border-bottom-left-radius:5px;border-bottom-right-radius:5px;" autocomplete="off"/>

        </fieldset>

            {{LoginService.ErrorField}}

        <fieldset class="register-button-container" ng-if="!loginwithotp" ng-click="secureLogin()">
          <button class="register-button-new">LOGIN</button>
        </fieldset>
        <fieldset class="register-button-container" ng-if="loginwithotp && !LoginService.OtpGenerated" ng-click="secureLoginwithOtp()">
          <button class="register-button-new">GET OTP</button>
        </fieldset>
        <fieldset class="register-button-container" ng-if="loginwithotp && LoginService.OtpGenerated" ng-click="verifyLoginwithOtp()">
          <button class="register-button-new">VERIFY OTP</button>
        </fieldset>

            Login with OTP

            Login with Password

            New to Zigfo?
            Create Account

      </form>


text:
import "base";
import "../toolbar/button"
import "../utils/icons"

mpld3.BoxZoomPlugin = mpld3_BoxZoomPlugin;
mpld3.register_plugin("boxzoom", mpld3_BoxZoomPlugin);
mpld3_BoxZoomPlugin.prototype = Object.create(mpld3_Plugin.prototype);
mpld3_BoxZoomPlugin.prototype.constructor = mpld3_BoxZoomPlugin;
mpld3_BoxZoomPlugin.prototype.requiredProps = [];
mpld3_BoxZoomPlugin.prototype.defaultProps = {
    button: true,
    enabled: null
};

function mpld3_BoxZoomPlugin(fig, props) {
    mpld3_Plugin.call(this, fig, props);
    if (this.props.enabled === null){
        this.props.enabled = !(this.props.button);
    }

    var enabled = this.props.enabled;
    if (this.props.button){
	// add a button to enable/disable box zoom
	var BoxZoomButton = mpld3.ButtonFactory({
	    buttonID: "boxzoom",
            sticky: true,
            actions: ["drag"],
	    onActivate: this.activate.bind(this),
	    onDeactivate: this.deactivate.bind(this),
            onDraw: function(){this.setState(enabled);},
	    icon: function(){return mpld3.icons["zoom"];},
	});
	this.fig.buttons.push(BoxZoomButton);
    }
    this.extentClass = "boxzoombrush";
}

mpld3_BoxZoomPlugin.prototype.activate = function(){
    if(this.enable) this.enable();
};

mpld3_BoxZoomPlugin.prototype.deactivate = function(){
    if(this.disable) this.disable();
};

mpld3_BoxZoomPlugin.prototype.draw = function(){
    mpld3.insert_css("#" + this.fig.figid + " rect.extent." + this.extentClass,
		     {"fill": "#fff",
                      "fill-opacity": 0,
                      "stroke": "#999"});

    // getBrush is a d3.svg.brush() object, set up for use on the figure.
    var brush = this.fig.getBrush();

    this.enable = function(){
        this.fig.showBrush(this.extentClass);
        brush.on("brushend", brushend.bind(this));
        this.enabled = true;
    }

    this.disable = function(){
        this.fig.hideBrush(this.extentClass);
        this.enabled = false;
    }

    this.toggle = function(){
	this.enabled ? this.disable() : this.enable();
    }

    function brushend(d){
	if(this.enabled){
	    var extent = brush.extent();
            if(!brush.empty()){
		d.set_axlim([extent[0][0], extent[1][0]],
		            [extent[0][1], extent[1][1]]);
            }
	}
	d.axes.call(brush.clear());
    }
    this.disable();
}


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

namespace _01.DefiningClasses
{
    class DefiningClasses
    {
        static void Main(string[] args)
        {
        }
    }
}


text:
<?php

namespace Tests\Http\Controllers;

use App\Http\Controllers\PageController;
use App\Http\JsonApi;
use App\Page;
use App\Repositories\CacheRepository;
use App\Repositories\PageRepository;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\Support\MessageBag;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Mockery;
use Mockery\Mock;
use Psr\Log\LoggerInterface;
use Tests\TestCase;

class PageControllerTest extends TestCase
{
    /**
     * @var PageController
     */
    private $pageController;
    /**
     * @var PageRepository | Mock
     */
    private $pageRepositoryMock;
    /**
     * @var Gate | Mock
     */
    private $gateMock;
    /**
     * @var Guard | Mock
     */
    private $guardMock;
    /**
     * @var Response | Mock
     */
    private $responseMock;
    /**
     * @var Request | Mock
     */
    private $requestMock;
    /**
     * @var LoggerInterface | Mock
     */
    private $loggerMock;
    /**
     * @var Page | Mock
     */
    private $pageMock;
    /**
     * @var CacheRepository | Mock
     */
    private $cacheRepositoryMock;
    /**
     * @var ValidationFactory | Mock
     */
    private $validationFactoryMock;
    /**
     * @var Validator | Mock
     */
    private $validatorMock;
    /**
     * @var MessageBag
     */
    private $messageBagMock;
    /**
     * @var LengthAwarePaginator | Mock
     */
    private $paginatorMock;
    /**
     * @var JsonApi | Mock
     */
    private $jsonApiMock;

    public function setUp()
    {
        parent::setUp();
        $this->jsonApiMock = Mockery::mock(JsonApi::class);
        $this->pageRepositoryMock = Mockery::mock(PageRepository::class);
        $this->gateMock = Mockery::mock(Gate::class);
        $this->guardMock = Mockery::mock(Guard::class);
        $this->loggerMock = Mockery::mock(LoggerInterface::class);
        $this->cacheRepositoryMock = Mockery::mock(CacheRepository::class);
        $this->requestMock = Mockery::mock(Request::class);
        $this->responseMock = Mockery::mock(Response::class);
        $this->validationFactoryMock = Mockery::mock(ValidationFactory::class);
        $this->validatorMock = Mockery::mock(Validator::class);
        $this->messageBagMock = Mockery::mock(MessageBag::class);
        $this->pageMock = Mockery::mock(Page::class);
        $this->paginatorMock = Mockery::mock(LengthAwarePaginator::class);

        $this->pageController = new PageController(
            $this->jsonApiMock,
            $this->loggerMock,
            $this->gateMock,
            $this->guardMock,
            $this->pageRepositoryMock,
            $this->cacheRepositoryMock,
            $this->validationFactoryMock
        );
    }

    public function tearDown()
    {
        parent::tearDown();
    }

//    public function test_index_responds_with_live_pages()
//    {
//        $this->requestMock
//            ->shouldReceive('query')
//            ->once()
//            ->withArgs(['size', 15])
//            ->andReturn(20);
//
//        $this->requestMock
//            ->shouldReceive('query')
//            ->once()
//            ->withArgs(['page', 1])
//            ->andReturn(2);
//
//        $this->gateMock
//            ->shouldReceive('allows')
//            ->once()
//            ->withArgs(['indexAllPages', $this->pageMock])
//            ->andReturn(false);
//
//        $this->cacheRepositoryMock
//            ->shouldReceive('remember')
//            ->once()
//            ->withArgs(['pages.live.page2.size20', 60, Mockery::any()])
//            ->andReturn($this->paginatorMock);
//
//        $this->jsonApiMock
//            ->shouldReceive('respondResourcesFound')
//            ->once()
//            ->withArgs([$this->responseMock, $this->paginatorMock])
//            ->andReturn($this->responseMock);
//
//        $actualResult = $this->pageController->index($this->requestMock, $this->responseMock, $this->pageMock);
//        $expectedResult = $this->responseMock;
//
//        $this->assertThat($actualResult, $this->equalTo($expectedResult));
//    }
//
//    public function test_index_responds_with_all_pages()
//    {
//        $this->requestMock
//            ->shouldReceive('query')
//            ->once()
//            ->withArgs(['size', 15])
//            ->andReturn(15);
//
//        $this->requestMock
//            ->shouldReceive('query')
//            ->once()
//            ->withArgs(['page', 1])
//            ->andReturn(1);
//
//        $this->gateMock
//            ->shouldReceive('allows')
//            ->once()
//            ->withArgs(['indexAllPages', $this->pageMock])
//            ->andReturn(true);
//
//        $this->cacheRepositoryMock
//            ->shouldReceive('remember')
//            ->once()
//            ->withArgs(['pages.all.page1.size15', 60, Mockery::any()])
//            ->andReturn($this->paginatorMock);
//
//        $this->jsonApiMock
//            ->shouldReceive('respondResourcesFound')
//            ->once()
//            ->withArgs([$this->responseMock, $this->paginatorMock])
//            ->andReturn($this->responseMock);
//
//        $actualResult = $this->pageController->index($this->requestMock, $this->responseMock, $this->pageMock);
//        $expectedResult = $this->responseMock;
//
//        $this->assertThat($actualResult, $this->equalTo($expectedResult));
//    }

    public function test_show_responds_not_found_when_no_resource_exists()
    {
        $this->cacheRepositoryMock
            ->shouldReceive('remember')
            ->once()
            ->withArgs(['page.a-slug', 60, Mockery::any()])
            ->andReturn(null);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . ' unable to find page with slug: a-slug']);

        $this->jsonApiMock
            ->shouldReceive('respondResourceNotFound')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->show($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_show_responds_with_the_page_when_the_page_is_live()
    {
        $this->cacheRepositoryMock
            ->shouldReceive('remember')
            ->once()
            ->withArgs(['page.a-slug', 60, Mockery::any()])
            ->andReturn($this->pageMock);

        $this->pageMock
            ->shouldReceive('isLive')
            ->once()
            ->andReturn(true);

        $this->jsonApiMock
            ->shouldReceive('respondResourceFound')
            ->once()
            ->withArgs([$this->responseMock, $this->pageMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->show($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_show_responds_with_unauthorized_when_guest_user_views_non_live_page()
    {
        $this->cacheRepositoryMock
            ->shouldReceive('remember')
            ->once()
            ->withArgs(['page.a-slug', 60, Mockery::any()])
            ->andReturn($this->pageMock);

        $this->pageMock
            ->shouldReceive('isLive')
            ->once()
            ->andReturn(false);

        $this->guardMock
            ->shouldReceive('guest')
            ->once()
            ->andReturn(true);

        $this->jsonApiMock
            ->shouldReceive('respondUnauthorized')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->show($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_show_responds_with_forbidden_for_non_live_pages_and_user_does_not_have_permission()
    {
        $this->cacheRepositoryMock
            ->shouldReceive('remember')
            ->once()
            ->withArgs(['page.a-slug', 60, Mockery::any()])
            ->andReturn($this->pageMock);

        $this->pageMock
            ->shouldReceive('isLive')
            ->once()
            ->andReturn(false);

        $this->guardMock
            ->shouldReceive('guest')
            ->once()
            ->andReturn(false);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['show', $this->pageMock])
            ->andReturn(true);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . " unauthorized to show page with slug: a-slug"]);

        $this->jsonApiMock
            ->shouldReceive('respondForbidden')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->show($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_show_responds_with_a_page_when_it_is_not_live_but_user_has_permission()
    {
        $this->cacheRepositoryMock
            ->shouldReceive('remember')
            ->once()
            ->withArgs(['page.a-slug', 60, Mockery::any()])
            ->andReturn($this->pageMock);

        $this->pageMock
            ->shouldReceive('isLive')
            ->once()
            ->andReturn(false);

        $this->guardMock
            ->shouldReceive('guest')
            ->once()
            ->andReturn(false);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['show', $this->pageMock])
            ->andReturn(false);

        $this->jsonApiMock
            ->shouldReceive('respondResourceFound')
            ->once()
            ->withArgs([$this->responseMock, $this->pageMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->show($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_store_responds_forbidden_when_authorization_fails()
    {
        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['store', $this->pageMock])
            ->andReturn(true);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . ' unauthorized to create page']);

        $this->jsonApiMock
            ->shouldReceive('respondForbidden')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->store($this->requestMock, $this->responseMock, $this->pageMock);
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_store_responds_validation_failed_when_validation_fails()
    {
        $this->setUpValidationMock(true);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['store', $this->pageMock])
            ->andReturn(false);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . ' validation failed, unable to create page']);

        $this->jsonApiMock
            ->shouldReceive('respondValidationFailed')
            ->once()
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->store($this->requestMock, $this->responseMock, $this->pageMock);
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_store_responds_with_server_error_on_create_exception()
    {
        $this->setUpValidationMock(false);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['store', $this->pageMock])
            ->andReturn(false);

        $this->pageRepositoryMock
            ->shouldReceive('create')
            ->once()
            ->andThrow(new \Exception('an error happened'));

        $this->loggerMock
            ->shouldReceive('error')
            ->once()
            ->withArgs([PageController::class . ' failed to create a page with exception: an error happened']);

        $this->jsonApiMock
            ->shouldReceive('respondServerError')
            ->once()
            ->withArgs([$this->responseMock, 'Unable to create the page.'])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->store($this->requestMock, $this->responseMock, $this->pageMock);
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_store_responds_with_resource_on_successful_creation()
    {
        $this->setUpValidationMock(false);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['store', $this->pageMock])
            ->andReturn(false);

        $this->pageRepositoryMock
            ->shouldReceive('create')
            ->once()
            ->andReturn($this->pageMock);

        $this->cacheRepositoryMock
            ->shouldReceive('keys')
            ->once()
            ->withArgs(['pages*'])
            ->andReturn(['laravel:pages.page1.size5']);

        $this->cacheRepositoryMock
            ->shouldReceive('deleteMultiple')
            ->once()
            ->withArgs([['laravel:pages.page1.size5']]);

        $this->jsonApiMock
            ->shouldReceive('respondResourceCreated')
            ->once()
            ->withArgs([$this->responseMock, $this->pageMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->store($this->requestMock, $this->responseMock, $this->pageMock);
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_update_responds_not_found_when_no_resource_exists()
    {
        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn(null);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . ' unable to find page to update with slug: a-slug']);

        $this->jsonApiMock
            ->shouldReceive('respondResourceNotFound')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->update($this->requestMock, $this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_update_responds_forbidden_when_authorization_fails()
    {
        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn($this->pageMock);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['update', $this->pageMock])
            ->andReturn(true);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . ' unauthorized to update page with slug: a-slug']);

        $this->jsonApiMock
            ->shouldReceive('respondForbidden')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->update($this->requestMock, $this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_update_responds_validation_failed_when_validation_fails()
    {
        $this->setUpValidationMock(true);

        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn($this->pageMock);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['update', $this->pageMock])
            ->andReturn(false);

        $this->requestMock
            ->shouldReceive('input')
            ->times(2);

        $this->pageMock
            ->shouldReceive('getAttribute')
            ->times(2);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . ' validation failed, unable to update page']);

        $this->jsonApiMock
            ->shouldReceive('respondValidationFailed')
            ->once()
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->update($this->requestMock, $this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_update_responds_with_server_error_on_update_exception()
    {
        $this->setUpValidationMock(false);

        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn($this->pageMock);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['update', $this->pageMock])
            ->andReturn(false);

        $this->requestMock
            ->shouldReceive('input')
            ->times(2);

        $this->pageMock
            ->shouldReceive('getAttribute')
            ->times(2);

        $this->loggerMock
            ->shouldReceive('error')
            ->once()
            ->withArgs([PageController::class . ' failed to update a page with exception: an error happened']);

        $this->jsonApiMock
            ->shouldReceive('respondServerError')
            ->once()
            ->withArgs([$this->responseMock, 'Unable to update page'])
            ->andReturn($this->responseMock);

        $this->pageRepositoryMock
            ->shouldReceive('update')
            ->once()
            ->andThrow(new \Exception('an error happened'));

        $actualResult = $this->pageController->update($this->requestMock, $this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_update_responds_with_resource_on_successful_update()
    {
        $this->setUpValidationMock(false);

        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn($this->pageMock);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['update', $this->pageMock])
            ->andReturn(false);

        $this->requestMock
            ->shouldReceive('input')
            ->times(2);

        $this->pageMock
            ->shouldReceive('getAttribute')
            ->times(2);

        $this->pageRepositoryMock
            ->shouldReceive('update')
            ->once()
            ->andReturn($this->pageMock);

        $this->cacheRepositoryMock
            ->shouldReceive('forget')
            ->once()
            ->withArgs(['page.a-slug']);

        $this->cacheRepositoryMock
            ->shouldReceive('keys')
            ->once()
            ->withArgs(['pages*'])
            ->andReturn(['laravel:pages.page1.size5']);

        $this->cacheRepositoryMock
            ->shouldReceive('deleteMultiple')
            ->once()
            ->withArgs([['laravel:pages.page1.size5']]);

        $this->jsonApiMock
            ->shouldReceive('respondResourceUpdated')
            ->once()
            ->withArgs([$this->responseMock, $this->pageMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->update($this->requestMock, $this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_delete_responds_not_found_when_page_does_not_exist()
    {
        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn(null);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . ' unable to find page to delete with slug: a-slug']);

        $this->jsonApiMock
            ->shouldReceive('respondResourceNotFound')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->delete($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_delete_responds_forbidden_when_authorization_fails()
    {
        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn($this->pageMock);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['delete', $this->pageMock])
            ->andReturn(true);

        $this->loggerMock
            ->shouldReceive('debug')
            ->once()
            ->withArgs([PageController::class . ' unauthorized to update page with slug: a-slug']);

        $this->jsonApiMock
            ->shouldReceive('respondForbidden')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->delete($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_delete_responds_with_server_error_on_delete_failure()
    {
        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn($this->pageMock);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['delete', $this->pageMock])
            ->andReturn(false);

        $this->pageMock
            ->shouldReceive('delete')
            ->once()
            ->andThrow(new \Exception('an error happened'));

        $this->loggerMock
            ->shouldReceive('error')
            ->once()
            ->withArgs([PageController::class . ' failed to delete a page with exception: an error happened']);

        $this->jsonApiMock
            ->shouldReceive('respondServerError')
            ->once()
            ->withArgs([$this->responseMock, 'Unable to delete page'])
            ->andReturn($this->responseMock);

        $actualResult = $this->pageController->delete($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    public function test_delete_responds_that_page_was_deleted()
    {
        $this->pageRepositoryMock
            ->shouldReceive('findBySlug')
            ->once()
            ->withArgs(['a-slug'])
            ->andReturn($this->pageMock);

        $this->gateMock
            ->shouldReceive('denies')
            ->once()
            ->withArgs(['delete', $this->pageMock])
            ->andReturn(false);

        $this->pageMock
            ->shouldReceive('delete')
            ->once();

        $this->jsonApiMock
            ->shouldReceive('respondResourceDeleted')
            ->once()
            ->withArgs([$this->responseMock])
            ->andReturn($this->responseMock);

        $this->cacheRepositoryMock
            ->shouldReceive('forget')
            ->once()
            ->withArgs(['page.a-slug']);

        $this->cacheRepositoryMock
            ->shouldReceive('keys')
            ->once()
            ->withArgs(['pages*'])
            ->andReturn(['laravel:pages.page1.size5']);

        $this->cacheRepositoryMock
            ->shouldReceive('deleteMultiple')
            ->once()
            ->withArgs([['laravel:pages.page1.size5']]);

        $actualResult = $this->pageController->delete($this->responseMock, 'a-slug');
        $expectedResult = $this->responseMock;

        $this->assertThat($actualResult, $this->equalTo($expectedResult));
    }

    /**
     * @param boolean $doesValidationFail
     */
    private function setUpValidationMock($doesValidationFail)
    {
        $this->requestMock
            ->shouldReceive('all')
            ->andReturn([]);

        $this->validationFactoryMock
            ->shouldReceive('make')
            ->once()
            ->andReturn($this->validatorMock);

        $this->validatorMock
            ->shouldReceive('fails')
            ->once()
            ->andReturn($doesValidationFail);

        if ($doesValidationFail) {
            $this->validatorMock
                ->shouldReceive('getMessageBag')
                ->once()
                ->andReturn($this->messageBagMock);
        }
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class DatingSimListExtension {

    private static System.Random rng = new System.Random();

    public static void Shuffle<T>(this IList<T> list) {
        int n = list.Count;
        while (n > 1) {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}


text:
namespace TellySorter.Commands
{

    using ManyConsole;
    using Mono.Data.Sqlite;
    using NLog;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text.RegularExpressions;
    using TellySorter.Models;

    public class SetCommand : AbstractConsoleCommand
    {

        readonly static Logger logger = LogManager.GetCurrentClassLogger();

        readonly string[] validVariables = {
            "ApiKey",
            "DefaultLanguage",
            "DefaultTargetPath",
            "EpisodeFileFormat",
            "SeasonFolderFormat",
            "SeriesFolderFormat",
            "ShowId",
        };

        public SetCommand() : base()
        {

            this.IsCommand("set", "Sets a config variable");

            this.AllowsAnyAdditionalArguments(string.Format("<{0}> <value>", string.Join("|", validVariables)));

        }

        public override int Run(string[] remainingArguments)
        {

            Initialise();

            if (remainingArguments.Length < 2) {
                throw new ConsoleHelpAsException("The variable name and value are required");
            }

            Configuration config = Configuration.GetConfig(this);

            // TODO: Optimise / DRY this up
            switch (remainingArguments[0]) {
                case "ShowId":
                    if (remainingArguments.Length != 3) {
                        throw new ConsoleHelpAsException("The id and TVDB id are required");
                    }

                    Regex r = new Regex(@"^\d+$");
                    Match m = r.Match(remainingArguments[1]);
                    if (!m.Success) {
                        throw new ConsoleHelpAsException(string.Format("The id must be a number, `{0}` is not valid", remainingArguments[1]));
                    }

                    m = r.Match(remainingArguments[2]);
                    if (!m.Success) {
                        throw new ConsoleHelpAsException(string.Format("The TV DB id must be a number, `{0}` is not valid", remainingArguments[2]));
                    }

                    if (Simulate) {
                        logger.Info(string.Format("Simulated: Series `{0}` would be assigned TV DB id `{1}`", remainingArguments[1], remainingArguments[2]));
                    } else {
                        SqliteManager.SetSeriesTvDbId(remainingArguments[1], remainingArguments[2]);

                        logger.Info(string.Format("Series `{0}` assigned TV DB id `{1}`", remainingArguments[1], remainingArguments[2]));

                        Series series = SqliteManager.FindSeries(int.Parse(remainingArguments[1]));
                        TVDBSharp.TVDB tvdb = new TVDBSharp.TVDB(config.ApiKey);
                        TVDBSharp.Models.Show show = tvdb.GetShow(int.Parse(remainingArguments[2]));
                        series.CompleteWith(show);
                    }

                    break;

                case "DefaultTargetPath":
                    if (!Directory.Exists(remainingArguments[1])) {
                        throw new ConsoleHelpAsException(string.Format("The directory `{0}` does not exist", remainingArguments[1]));
                    }

                    if (Simulate) {
                        logger.Info(string.Format("Simulated: `{0}` would be set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    } else {
                        SqliteManager.SetConfigValue(remainingArguments[0], remainingArguments[1]);
                        config.DefaultTargetPath = remainingArguments[1];

                        logger.Info(string.Format("`{0}` set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    }

                    break;

                case "EpisodeFileFormat":
                    if (Simulate) {
                        logger.Info(string.Format("Simulated: `{0}` would be set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    } else {
                        SqliteManager.SetConfigValue(remainingArguments[0], remainingArguments[1]);
                        config.EpisodeFileFormat = remainingArguments[1];

                        logger.Info(string.Format("`{0}` set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    }

                    break;

                case "DefaultLanguage":
                    if (remainingArguments[1].Length != 2) {
                        throw new ConsoleHelpAsException(string.Format("The value `{0}` is not a valid 2-letter language code, eg: en, es, fr, de, nl", remainingArguments[1]));
                    }

                    if (Simulate) {
                        logger.Info(string.Format("Simulated: `{0}` would be set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    } else {
                        SqliteManager.SetConfigValue(remainingArguments[0], remainingArguments[1]);
                        config.DefaultLanguage = remainingArguments[1];

                        logger.Info(string.Format("`{0}` set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    }

                    break;

                case "SeasonFolderFormat":
                    if (Simulate) {
                        logger.Info(string.Format("Simulated: `{0}` would be set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    } else {
                        SqliteManager.SetConfigValue(remainingArguments[0], remainingArguments[1]);
                        config.SeasonFolderFormat = remainingArguments[1];

                        logger.Info(string.Format("`{0}` set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    }

                    break;

                case "SeriesFolderFormat":
                    if (Simulate) {
                        logger.Info(string.Format("Simulated: `{0}` would be set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    } else {
                        SqliteManager.SetConfigValue(remainingArguments[0], remainingArguments[1]);
                        config.SeasonFolderFormat = remainingArguments[1];

                        logger.Info(string.Format("`{0}` set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    }

                    break;

                case "ApiKey":
                    if (Simulate) {
                        logger.Info(string.Format("Simulated: `{0}` would be set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    } else {
                        SqliteManager.SetConfigValue(remainingArguments[0], remainingArguments[1]);
                        config.ApiKey = remainingArguments[1];

                        logger.Info(string.Format("`{0}` set to `{1}`", remainingArguments[0], remainingArguments[1]));
                    }

                    break;

                default:
                    throw new ConsoleHelpAsException(string.Format("Unknown variable `{0}`. Valid variables: {1}", remainingArguments[0], string.Join(",", validVariables)));
            }

            return 0;

        }

    }

}


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

namespace dexih.functions
{
    [DataContract]
    public class TableColumns : IList<TableColumn>
    {
        private readonly List<TableColumn> _tableColumns;
        private readonly Dictionary<string, int> _columnOrdinals;
        private readonly Dictionary<EDeltaType, List<int>> _deltaOrdinals;

        public TableColumns()
        {
            _tableColumns = new List<TableColumn>();
            _columnOrdinals = new Dictionary<string, int>();
            _deltaOrdinals = new Dictionary<EDeltaType, List<int>>();
        }

        public TableColumns(IEnumerable<TableColumn> tableColumns)
        {
            _tableColumns = new List<TableColumn>();
            _columnOrdinals = new Dictionary<string, int>();
            _deltaOrdinals = new Dictionary<EDeltaType, List<int>>();

            foreach (var column in tableColumns)
                Add(column);
        }

        public TableColumn this[int index]
        {
            get => _tableColumns[index];
            set => _tableColumns[index] = value;
        }

        public TableColumn this[string columnName]
        {
            get
            {
                if (_columnOrdinals.TryGetValue(columnName, out var ordinal))
                    return _tableColumns[ordinal];
                return null;
            }

            set => _tableColumns[_columnOrdinals[columnName]] = value;
        }

//        public TableColumn this[string columnName, string columnGroup]
//        {
//            get
//            {
//                var name = (string.IsNullOrWhiteSpace(columnGroup) ? "" : columnGroup + ".") + columnName;
//                if (_columnOrdinals.TryGetValue(name, out var ordinal))
//                    return _tableColumns[ordinal];
//                return null;
//            }
//            set
//            {
//                var name = (string.IsNullOrWhiteSpace(columnGroup) ? "" : columnGroup + ".") + columnName;
//                _tableColumns[_columnOrdinals[name]] = value;
//            }
//        }

        public TableColumn this[TableColumn column]
        {
            get
            {
                if (_columnOrdinals.TryGetValue(column.TableColumnName(), out var ordinal))
					return _tableColumns[ordinal];

				if (_columnOrdinals.TryGetValue(column.Name, out var ordinal1))
					return _tableColumns[ordinal1];

                return null;
            }

            set => _tableColumns[_columnOrdinals[column.TableColumnName()]] = value;
        }

        public bool TryGetColumn(string columnName, out TableColumn column)
        {
            column = this[columnName];
            return column != null;
        }

        public bool TryGetColumn(TableColumn inColumn, out TableColumn column)
        {
            column = this[inColumn];
            return column != null;
        }

        public bool TryGetColumn(EDeltaType deltaType, out TableColumn column)
        {
            column = GetColumn(deltaType);
            return column != null;
        }

        public int GetOrdinal(TableColumn column, bool groupMustMatch = false)
        {
            var ordinal = GetOrdinal(column.TableColumnName());
            if(ordinal < 0 && !groupMustMatch)
            {
                ordinal = GetOrdinal(column.Name);
            }

            return ordinal;
        }

        public int GetOrdinal(string columnName)
        {
            if (_columnOrdinals.TryGetValue(columnName, out var ordinal))
                return ordinal;
            return -1;
        }

        public int GetOrdinal(string columnName, string referenceTable)
        {
            if (_columnOrdinals.TryGetValue(columnName + "." + referenceTable, out var ordinal))
                return ordinal;
            return -1;
        }

//        public int GetOrdinal(string columnName, string columnGroup)
//        {
//            var name = (string.IsNullOrWhiteSpace(columnGroup) ? "" : columnGroup + ".") + columnName;
//            if (_columnOrdinals.TryGetValue(name, out var ordinal))
//                return ordinal;
//            return -1;
//        }

        public int GetOrdinal(EDeltaType deltaType)
        {
            if(_deltaOrdinals.TryGetValue(deltaType, out var value))
            {
                if (value.Count == 1)
                {
                    return value[0];
                }

                throw new TableException($"There are multiple columns with the delta type {deltaType}.");
            }

            return -1;
        }

        public IEnumerable<int> GetOrdinals(EDeltaType deltaType)
        {
            if(_deltaOrdinals.TryGetValue(deltaType, out var value))
            {
                return value;
            }

            return null;
        }

        public TableColumn GetColumn(EDeltaType deltaType)
        {
            var ordinal = GetOrdinal(deltaType);
            if (ordinal == -1) return null;
            return this[ordinal];
        }

        public TableColumn GetAutoIncrementColumn()
        {
            return GetColumn(EDeltaType.DbAutoIncrement) ??
                   GetColumn(EDeltaType.AutoIncrement);
        }

        public int GetAutoIncrementOrdinal()
        {
            var ordinal = GetOrdinal(EDeltaType.AutoIncrement);
            if (ordinal >= 0)
            {
                return ordinal;
            }

            return GetOrdinal(EDeltaType.DbAutoIncrement);
        }

        public TableColumn[] GetColumns(EDeltaType deltaType)
        {
            var ordinals = GetOrdinals(deltaType);
            if (ordinals == null)
            {
                return new TableColumn[] { };
            }
            var columns = ordinals.Select(ordinal => this[ordinal]).ToArray();
            return columns;
        }

        public int Count => _tableColumns.Count;

        public bool IsReadOnly => false;

        public void Add(TableColumn item)
        {
            _tableColumns.Add(item);
            var tableColumnName = item.TableColumnName();
            var ordinal = _tableColumns.Count - 1;

            if (tableColumnName == item.Name)
            {
                if (!_columnOrdinals.ContainsKey(item.Name))
                {
                    _columnOrdinals.Add(item.Name, ordinal);
                }
            }
            else
            {
                if (!_columnOrdinals.ContainsKey(tableColumnName))
                {
                    _columnOrdinals.Add(tableColumnName, ordinal);
                }

                if (!_columnOrdinals.ContainsKey(item.Name))
                {
                    _columnOrdinals.Add(item.Name, ordinal);
                }
            }

            if (_deltaOrdinals.TryGetValue(item.DeltaType, out var ordinals))
            {
                ordinals.Add(ordinal);
            }
            else
            {
                _deltaOrdinals.Add(item.DeltaType, new List<int>() {ordinal});
            }
        }

        public void Clear()
        {
            _tableColumns.Clear();
            _columnOrdinals.Clear();
            _deltaOrdinals.Clear();
        }

        public bool Contains(TableColumn item)
        {
            return _tableColumns.Contains(item);
        }

        public bool ContainsMatching(TableColumn column)
        {
            if (_tableColumns == null)
                return false;

			return _columnOrdinals.ContainsKey(column.TableColumnName());
        }

        public void CopyTo(TableColumn[] array, int arrayIndex)
        {
            _tableColumns.CopyTo(array, arrayIndex);
        }

        public IEnumerator<TableColumn> GetEnumerator()
        {
            return _tableColumns.GetEnumerator();
        }

        public int IndexOf(TableColumn item)
        {
            return _tableColumns.IndexOf(item);
        }

        public void Insert(int index, TableColumn item)
        {
            _tableColumns.Insert(index, item);
            RebuildOrdinals();
        }

        public bool Remove(TableColumn item)
        {
            var returnValue = _tableColumns.Remove(item);
            RebuildOrdinals();
            return returnValue;
        }

        public bool Remove(EDeltaType deltaType)
        {
            var columns = _tableColumns.Where(c => c.DeltaType == deltaType).ToArray();
            if (columns.Any())
            {
                foreach (var column in columns)
                {
                    if (!_tableColumns.Remove(column))
                    {
                        return false;
                    }
                }
                RebuildOrdinals();
            }

            return true;
        }

        public void RemoveAt(int index)
        {
            _tableColumns.RemoveAt(index);
            RebuildOrdinals();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _tableColumns.GetEnumerator();
        }

        public void RebuildOrdinals()
        {
            _columnOrdinals.Clear();
            _deltaOrdinals.Clear();

            var ordinal = 0;
            foreach (var col in _tableColumns)
            {
                var tableColumnName = col.TableColumnName();
                if (tableColumnName == col.Name)
                {
                    if (_columnOrdinals.ContainsKey(col.Name))
                    {
                        //    _columnOrdinals[item.Name] = _tableColumns.Count - 1;
                    }
                    else
                    {
                        _columnOrdinals.Add(col.Name, ordinal);
                    }
                }
                else
                {
                    if (!_columnOrdinals.ContainsKey(tableColumnName))
                    {
                        _columnOrdinals.Add(tableColumnName, ordinal);
                    }

                    if (!_columnOrdinals.ContainsKey(col.Name))
                    {
                        _columnOrdinals.Add(col.Name, ordinal);
                    }
                }

                if (_deltaOrdinals.TryGetValue(col.DeltaType, out var ordinals))
                {
                    ordinals.Add(ordinal);
                }
                else
                {
                    _deltaOrdinals.Add(col.DeltaType, new List<int>() {ordinal});
                }

                ordinal++;
            }
        }
    }
}


text:
<?php
/**
* author: Bakasa Joshua
* @baksajoshua09@gmail.com
*/
class api_model extends CI_Model
{

	function __construct()
	{
		parent:: __construct();
	}

    function get_county_names()
    {
        foreach ($this->counties() as $key => $value)
            $new_db_counties[] = $value['county_name'];

        return $new_db_counties;
    }

    function get_counties()
    {
        return $this->db->query("SELECT
                                    `county_ID`,
                                    `county_name`
                                FROM `counties`")->result_array();
    }

	function counties($name)
    {
        /*
        *When using this function to compare county names,
        *always use str_replace(" ","",$string) to remove whitespace that comes with the county_name
        */
        return $this->db->query("SELECT
                                    `county_ID`
                                FROM `counties`
                                WHERE `county_name` = '$name'")->result_array();
    }

    function insert_sub_counties($data){
        foreach ($data as $key => $value) {
            $sub_county_name = $value['sub_county_name'];
            $county_ID = $value['county_ID'];
            $insert = $this->db->query('INSERT IGNORE INTO `sub_counties` (`sub_county_name`,`county_ID`) VALUES("$sub_county_name","$county_ID")');
        }
        return $insert;
    }

    //Addition of the missing sub counties
    function insert_missing_sub_counties($data)
    {
        $sub_county_name = $data['sub_county_name'];
        $county_ID = $data['county_ID'];
        $sql = "INSERT IGNORE INTO `sub_counties` (`sub_county_name`,`county_ID`) VALUES('$sub_county_name','$county_ID')";
        // echo $sql;die();
        $insert = $this->db->query($sql);

        return $this->db->insert_id();
    }

    function get_subcounty_by_name($name){
        $this->db->where('sub_county_name', $name);
        return $this->db->get('sub_counties')->result_array();
        // return $this->db->query("SELECT
        //                             `sub_county_ID`,
        //                             `sub_county_name`
        //                         FROM `sub_counties`
        //                         WHERE `sub_county_name` = '$name'")->result_array();
    }

    function subCounties($name)
    {
        $this->db->where('sub_county_name',$name);
        return $this->db->get('sub_counties')->result_array();

    }

    function cascade_insert($data)
    {
        if($this->db->get('cascade')->result_array())
        {
            foreach ($data as $key => $value) {
                $this->db->where('sub_county_ID', $value['sub_county_ID']);
                $this->db->update('cascade', $value);
            }
        }
        $this->db->insert_batch('cascade', $data);

        return TRUE;
    }

    function formatting_eid_data($data,$year,$month){
        $sub_counties = $this->db->get('sub_counties')->result_array();
        // echo "<pre>";print_r($data);die();
        foreach ($data as $key => $value) {
            foreach ($sub_counties as $k => $v) {
                if ($value['SubCounty']==$v['sub_county_name']) {
                    $value['County'] = $v['county_ID'];
                    $value['SubCounty'] = $v['sub_county_ID'];
                    $value['period'] = $year."-".$month."-".$this->config->item('eid_report_day');
                    $new_array[] = $value;
                }
            }
        }

        $facility = $this->add_facility($new_array);

        if ($facility) {
            $facilities = $this->db->get('facilities')->result_array();
            foreach ($new_array as $key => $value) {
                foreach ($facilities as $k => $v) {
                    if ($value['MFL']==$v['MFL_Code']) {
                        $value['Facility'] = $v['facility_ID'];
                        $insert_array[] = $value;
                    }
                }
            }

            $insert = $this->adding_eid_data($insert_array);
        }

        $eid_calc = $this->calculate_eid_data($insert_array,$year,$month);

        return $insert;

    }

    function adding_eid_data($data)
    {
        foreach ($data as $key => $value) {
            $insertion = array(
                        'county_ID' => $value['County'],
                        'sub_county_ID' => $value['SubCounty'],
                        'facility_ID' => $value['Facility'],
                        'MFL' => $value['MFL'],
                        'period' => $value['period'],
                        'test' => $value['Test'],
                        'negative' => $value['Neg'],
                        'positive' => $value['Pos'],
                        'onTx' => $value['OnTx'],
                        'invalid' => $value['Invalid']
                    );
            $insert = $this->db->insert('eid', $insertion);
        }

        return $insert;
    }

    function calculate_eid_data($data,$year,$month)
    {
        //Gets the data already calculated
        $eid_calculated = $this->db->get('eid_calc')->result_array();

        //If this is not the first time running this function,
        //      performs an aggregation from that basis
        if ($eid_calculated) {

            //foreach loop that performs the cumulative addition
                foreach ($data as $key => $value) {
                    //Getting the calculated values from the latest reported month of the year for the current Sub County
                    $sub_county = $value['sub_county_ID'];
                    $aggregates = $this->db->query("SELECT * FROM `eid_calc` WHERE `sub_county_ID` = '$sub_county' AND YEAR(`period`) = '$year' AND `period` = (SELECT MAX(`period`) FROM `eid_calc`)")->result_array();
                }

            $insertion = $this->add_eid_calculatedData($new_aggregate);
        }
        //If it is the first time running this function,
        //      take the values just added and do the aggregation from that basis
        else {
            $eid = $this->db->query("SELECT
                                        `county_ID`,
                                        `sub_county_ID`,
                                        `period`,
                                        SUM(`test`) AS `test`,
                                        SUM(`negative`) AS `negative`,
                                        SUM(`positive`) AS `positive`,
                                        SUM(`onTx`) AS `onTx`,
                                        SUM(`invalid`) AS `invalid`
                                    FROM `eid`
                                    GROUP BY `sub_county_ID`")->result_array();

            $insertion = $this->add_eid_calculatedData($eid);

        }

        return $insertion;

    }

    function add_eid_calculatedData($data)
    {
        foreach ($data as $key => $value) {
                $insert = array(
                                'county_ID' => $value['county_ID'],
                                'sub_county_ID' => $value['sub_county_ID'],
                                'period' => $value['period'],
                                'cumulative_test' => $value['test'],
                                'cumulative_negative' => $value['negative'],
                                'cumulative_positive' => $value['positive'],
                                'cumulative_onTx' => $value['onTx'],
                                'cumulative_invalid' => $value['invalid']);

                $insertion = $this->db->insert('eid_calc', $insert);
            }
        return $insertion;
    }

    function add_facility($data)
    {
        foreach ($data as $key => $value) {
            $mfl = $value['MFL'];
            $facility = $value['Facility'];
            $sub_county_ID = $value['SubCounty'];
            $insert = $this->db->query("INSERT IGNORE INTO `facilities` (`MFL_Code`, `facility_name`, `sub_county_ID`) VALUES ('$mfl', '$facility', '$sub_county_ID')");
        }
        return $insert;
    }

    function dhis_insert_aggregation($data){
    	// echo "<pre>";print_r($data);
    	$tests = $this->tests_insert($data['tests']);
    	$positive = $this->positive_insert($data['positive']);
    	// $enrollment = $this->enrollment_insert($data['enrollment']);
    	// $art = $this->art_insert($data['art']);
     //    $vl = $this->vl_insert($data['vl']);

    	return TRUE;
    }

    function tests_insert($data){

    	$test_cal = $this->db->insert_batch('dhis_calc_tests', $data);

    	return TRUE;
    }

    function positive_insert($data){

    	$pos_cal = $this->db->insert_batch('dhis_calc_positive', $data);

    	return TRUE;
    }

    function enrollment_insert($data){

    	$enroll_cal = $this->db->insert_batch('dhis_calc_enrollment', $data);

    	return TRUE;
    }

    function art_insert($data){

    	$arts_cal = $this->db->insert_batch('dhis_calc_art', $data);

    	return TRUE;
    }

    function vl_insert($data)
    {
        $vl_cal = $this->db->insert_batch('vl', $data);

        return TRUE;
    }
}
?>


text:
#ifndef UBJANSSON_H
#define UBJANSSON_H

#include <stdio.h>
#include <stdlib.h>  /* for size_t */
#include <stdarg.h>

#include <jansson.h>

#ifdef __cplusplus
extern "C" {
#endif

/* version */

#define UBJANSSON_MAJOR_VERSION  0
#define UBJANSSON_MINOR_VERSION  1
#define UBJANSSON_MICRO_VERSION  0

/* Micro version is omitted if it's 0 */
#define UBJANSSON_VERSION  "0.1"

/* Version as a 3-byte hex number, e.g. 0x010201 == 1.2.1. Use this
   for numeric comparisons, e.g. #if UBJANSSON_VERSION_HEX >= ... */
#define UBJANSSON_VERSION_HEX  ((UBJANSSON_MAJOR_VERSION << 16) |   \
                                (UBJANSSON_MINOR_VERSION << 8)  |   \
                                (UBJANSSON_MICRO_VERSION << 0))

/* decoding */

json_t *ubjson_loadb(void *buffer, size_t buflen, size_t flags, json_error_t *error);
json_t *ubjson_loadf(FILE *input, size_t flags, json_error_t *error);

/* encoding */

ssize_t ubjson_dumpb(json_t *json, void *buffer, size_t buflen, size_t flags);
int ubjson_dump_callback(json_t *json, json_dump_callback_t callback, void *data, size_t flags);

#ifdef __cplusplus
}
#endif

#endif


text:
//
//  GBApiOfferTemplate.m
//  GroupBuyingIOS
//
//  Created by Piotr Zawadzki on 29.09.2013.
//  Copyright (c) 2013 Piotr Zawadzki. All rights reserved.
//

#import "GBApiOfferEssentialsTemplate.h"
#import "GBURLRequest.h"

@implementation GBApiOfferEssentialsTemplate

/**
 * Use this class method to obtain the shared instance of the class.
 */
+ (id)sharedInstance
{
    static id _sharedInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}

- (void)getOffersByCategory:(NSString *)category AndPageNumber:(NSInteger)pageNumber WithDelegate:(id<GBApiOfferEssentialsTemplateDelegate>)delegate
{
    NSURL *url = [GBConnectionSettings urlWithFormat:@"/offers/%@?page=%d", category, pageNumber];
    NSMutableURLRequest *request = [[GBURLRequest alloc] initWithURL:url];

    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
	[request setTimeoutInterval:DEFAULT_REQUEST_TIMEOUT];
	DLog(@"%@", request);

#if OFFLINE
    DLog(@"OFFLINE REQUEST: %@", request);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
        GBOfferEssential *offer1 = [[GBOfferEssential alloc] init];
        offer1.offerId = 1;
        offer1.title = @"Offer1";
        offer1.imageUrl = @"http://niuniacat.blox.pl/resource/00033434.jpg";
        GBOfferEssential *offer2 = [[GBOfferEssential alloc] init];
        offer2.offerId = 2;
        offer2.title = @"Offer2";
        offer2.imageUrl = @"http://shadow.pl/tellamarna/galeria/zdjecie_08.jpg";
        GBOfferEssential *offer3 = [[GBOfferEssential alloc] init];
        offer3.offerId = 3;
        offer3.title = @"Offer3";
        offer3.imageUrl = @"http://www.ekoenergia.pl/uploaded/Image/zdjecia_wesele/wielkie_zarcie_2.jpg";
        NSArray *offlineOffers = @[offer1, offer2, offer3];
        [delegate getOfferEssentialsDidSucceedWithResults:offlineOffers];
    });

    return;
#endif

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[[NSOperationQueue alloc] init]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
                               [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                               if (statusCode == 200 && data.length > 0 && error == nil) {
                                   DLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                   NSError *error;
                                   NSArray *offerArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                                   if (!error) {
                                       DLog(@"%@", offerArray);
                                       NSMutableArray *offers = [[NSMutableArray alloc] init];
                                       if (offerArray) {
                                           for(NSDictionary * offerDictionary in offerArray) {
                                               GBOfferEssential *offer = [[GBOfferEssential alloc] initWithDictionary:offerDictionary];
                                               [offers addObject:offer];
                                           }
                                       }
                                       dispatch_sync(dispatch_get_main_queue(), ^{
                                           [delegate getOfferEssentialsDidSucceedWithResults:[NSArray arrayWithArray:offers]];
                                       });
                                   } else {
                                       dispatch_sync(dispatch_get_main_queue(), ^{
                                           [delegate getOfferEssentialsDidFailWithError:error];
                                       });
                                   }

                               } else if (error) {
                                   [self requestDidFailWithError:error];
                                   dispatch_sync(dispatch_get_main_queue(), ^{
                                       [delegate getOfferEssentialsDidFailWithError:error];
                                   });
                               } else if (statusCode != 200) {
                                   [self requestDidNotSucceedWithDefaultMessage:@"A problem occurred while retrieving offers." response:response];
                               }
                           }];
}

@end


text:
<?php

namespace Gostei\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * GosteiRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class GosteiRepository extends EntityRepository
{
    public function getGostei($arrPostId, $intUserId)
    {
        if ($arrPostId) {
            $query = $this->_em->createQuery(
                'SELECT u.postId FROM Gostei\Entity\Gostei u WHERE u.postId IN ('
                . $arrPostId . ') AND u.actionAuthorId = ' . $intUserId);
            return $query->getResult();
        }
        return array();
    }
}


text:
"""
Code to manage the creation and SQL rendering of 'where' constraints.
"""
import datetime

from django.utils import tree
from django.db import connection
from django.db.models.fields import Field
from django.db.models.query_utils import QueryWrapper
from datastructures import EmptyResultSet, FullResultSet

# Connection types
AND = 'AND'
OR = 'OR'

class WhereNode(tree.Node):
    """
    Used to represent the SQL where-clause.

    The class is tied to the Query class that created it (in order to create
    the correct SQL).

    The children in this tree are usually either Q-like objects or lists of
    [table_alias, field_name, db_type, lookup_type, value_annotation,
    params]. However, a child could also be any class with as_sql() and
    relabel_aliases() methods.
    """
    default = AND

    def add(self, data, connector):
        """
        Add a node to the where-tree. If the data is a list or tuple, it is
        expected to be of the form (alias, col_name, field_obj, lookup_type,
        value), which is then slightly munged before being stored (to avoid
        storing any reference to field objects). Otherwise, the 'data' is
        stored unchanged and can be anything with an 'as_sql()' method.
        """
        if not isinstance(data, (list, tuple)):
            super(WhereNode, self).add(data, connector)
            return

        alias, col, field, lookup_type, value = data
        if field:
            params = field.get_db_prep_lookup(lookup_type, value)
            db_type = field.db_type()
        else:
            # This is possible when we add a comparison to NULL sometimes (we
            # don't really need to waste time looking up the associated field
            # object).
            params = Field().get_db_prep_lookup(lookup_type, value)
            db_type = None
        if isinstance(value, datetime.datetime):
            annotation = datetime.datetime
        else:
            annotation = bool(value)
        super(WhereNode, self).add((alias, col, db_type, lookup_type,
                annotation, params), connector)

    def as_sql(self, qn=None):
        """
        Returns the SQL version of the where clause and the value to be
        substituted in. Returns None, None if this node is empty.

        If 'node' is provided, that is the root of the SQL generation
        (generally not needed except by the internal implementation for
        recursion).
        """
        if not qn:
            qn = connection.ops.quote_name
        if not self.children:
            return None, []
        result = []
        result_params = []
        empty = True
        for child in self.children:
            try:
                if hasattr(child, 'as_sql'):
                    sql, params = child.as_sql(qn=qn)
                else:
                    # A leaf node in the tree.
                    sql, params = self.make_atom(child, qn)
            except EmptyResultSet:
                if self.connector == AND and not self.negated:
                    # We can bail out early in this particular case (only).
                    raise
                elif self.negated:
                    empty = False
                continue
            except FullResultSet:
                if self.connector == OR:
                    if self.negated:
                        empty = True
                        break
                    # We match everything. No need for any constraints.
                    return '', []
                if self.negated:
                    empty = True
                continue
            empty = False
            if sql:
                result.append(sql)
                result_params.extend(params)
        if empty:
            raise EmptyResultSet

        conn = ' %s ' % self.connector
        sql_string = conn.join(result)
        if sql_string:
            if self.negated:
                sql_string = 'NOT (%s)' % sql_string
            elif len(self.children) != 1:
                sql_string = '(%s)' % sql_string
        return sql_string, result_params

    def make_atom(self, child, qn):
        """
        Turn a tuple (table_alias, column_name, db_type, lookup_type,
        value_annot, params) into valid SQL.

        Returns the string for the SQL fragment and the parameters to use for
        it.
        """
        table_alias, name, db_type, lookup_type, value_annot, params = child
        if table_alias:
            lhs = '%s.%s' % (qn(table_alias), qn(name))
        else:
            lhs = qn(name)
        field_sql = connection.ops.field_cast_sql(db_type) % lhs

        if value_annot is datetime.datetime:
            cast_sql = connection.ops.datetime_cast_sql()
        else:
            cast_sql = '%s'

        if isinstance(params, QueryWrapper):
            extra, params = params.data
        else:
            extra = ''

        if lookup_type in connection.operators:
            format = "%s %%s %s" % (connection.ops.lookup_cast(lookup_type),
                    extra)
            return (format % (field_sql,
                    connection.operators[lookup_type] % cast_sql), params)

        if lookup_type == 'in':
            if not value_annot:
                raise EmptyResultSet
            if extra:
                return ('%s IN %s' % (field_sql, extra), params)
            return ('%s IN (%s)' % (field_sql, ', '.join(['%s'] * len(params))),
                    params)
        elif lookup_type in ('range', 'year'):
            return ('%s BETWEEN %%s and %%s' % field_sql, params)
        elif lookup_type in ('month', 'day'):
            return ('%s = %%s' % connection.ops.date_extract_sql(lookup_type,
                    field_sql), params)
        elif lookup_type == 'isnull':
            return ('%s IS %sNULL' % (field_sql,
                (not value_annot and 'NOT ' or '')), ())
        elif lookup_type == 'search':
            return (connection.ops.fulltext_search_sql(field_sql), params)
        elif lookup_type in ('regex', 'iregex'):
            return connection.ops.regex_lookup(lookup_type) % (field_sql, cast_sql), params

        raise TypeError('Invalid lookup_type: %r' % lookup_type)

    def relabel_aliases(self, change_map, node=None):
        """
        Relabels the alias values of any children. 'change_map' is a dictionary
        mapping old (current) alias values to the new values.
        """
        if not node:
            node = self
        for pos, child in enumerate(node.children):
            if hasattr(child, 'relabel_aliases'):
                child.relabel_aliases(change_map)
            elif isinstance(child, tree.Node):
                self.relabel_aliases(change_map, child)
            else:
                if child[0] in change_map:
                    node.children[pos] = (change_map[child[0]],) + child[1:]

class EverythingNode(object):
    """
    A node that matches everything.
    """
    def as_sql(self, qn=None):
        raise FullResultSet

    def relabel_aliases(self, change_map, node=None):
        return


text:
package mesosphere.marathon.core.appinfo

import com.google.inject.Inject
import mesosphere.marathon.MarathonSchedulerService
import mesosphere.marathon.core.appinfo.impl.{ AppInfoBaseData, DefaultInfoService }
import mesosphere.marathon.core.base.Clock
import mesosphere.marathon.core.task.tracker.TaskTracker
import mesosphere.marathon.health.HealthCheckManager
import mesosphere.marathon.state.{ AppRepository, GroupManager, TaskFailureRepository }

/**
  * Provides a service to query information related to apps.
  */
class AppInfoModule @Inject() (
    clock: Clock,
    groupManager: GroupManager,
    appRepository: AppRepository,
    taskTracker: TaskTracker,
    healthCheckManager: HealthCheckManager,
    marathonSchedulerService: MarathonSchedulerService,
    taskFailureRepository: TaskFailureRepository) {
  private[this] def appInfoBaseData(): AppInfoBaseData =
    new AppInfoBaseData(clock, taskTracker, healthCheckManager, marathonSchedulerService, taskFailureRepository)

  def appInfoService: AppInfoService = infoService
  def groupInfoService: GroupInfoService = infoService

  private[this] lazy val infoService = new DefaultInfoService(groupManager, appRepository, appInfoBaseData)
}


text:
package armauthorization

import (
	"context"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
)

// GlobalAdministratorClient contains the methods for the GlobalAdministrator group.
// Don't use this type directly, use NewGlobalAdministratorClient() instead.
type GlobalAdministratorClient struct {
	host string
	pl   runtime.Pipeline
}

// NewGlobalAdministratorClient creates a new instance of GlobalAdministratorClient with the specified values.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewGlobalAdministratorClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*GlobalAdministratorClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &GlobalAdministratorClient{
		host: ep,
		pl:   pl,
	}
	return client, nil
}

// ElevateAccess - Elevates access for a Global Administrator.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2015-07-01
// options - GlobalAdministratorClientElevateAccessOptions contains the optional parameters for the GlobalAdministratorClient.ElevateAccess
// method.
func (client *GlobalAdministratorClient) ElevateAccess(ctx context.Context, options *GlobalAdministratorClientElevateAccessOptions) (GlobalAdministratorClientElevateAccessResponse, error) {
	req, err := client.elevateAccessCreateRequest(ctx, options)
	if err != nil {
		return GlobalAdministratorClientElevateAccessResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return GlobalAdministratorClientElevateAccessResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return GlobalAdministratorClientElevateAccessResponse{}, runtime.NewResponseError(resp)
	}
	return GlobalAdministratorClientElevateAccessResponse{}, nil
}

// elevateAccessCreateRequest creates the ElevateAccess request.
func (client *GlobalAdministratorClient) elevateAccessCreateRequest(ctx context.Context, options *GlobalAdministratorClientElevateAccessOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Authorization/elevateAccess"
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2015-07-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel backend\models\search\LoanCarCheckSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', '汽车盘库');
$this->params['breadcrumbs'][] = $this->title;
?>
<?php $this->beginBlock('content-header') ?>
<?= $this->title . ' ' . Html::a(Yii::t('app', '新增汽车盘库 '), ['create'], ['class' => 'btn btn-primary btn-flat btn-xs']) ?>
<?php $this->endBlock() ?>

搜索

<?php echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= GridView::widget([
            'dataProvider' => $dataProvider,
//                'filterModel' => $searchModel,
            'columns' => [
                'id',
//                'loan_id',

                [
                    'attribute' => 'loan_id',
                    'value' => function ($model) {
                        return \common\models\Loan::getLoanNo()[$model->loan_id];
                    }
                ],
           //     'car_id',
                'loanCar.carBrandInfo:text:品牌',
               // 'check_class_id',
                [
                    'attribute' => 'check_class_id',
                    'value' => function ($model) {
                        return \common\models\LoanCarCheck::getCheckClass()[$model->check_class_id];
                    }
                ],

                [
                    'attribute' => 'check_type_id',
                    'value' => function ($model) {
                        return \common\models\LoanCarCheck::getCheckType()[$model->check_type_id];
                    }
                ],
                // 'plan_check_manager_by',
                 'plan_check_time:datetime',
                // 'check_by_id',
                [
                    'attribute' => 'check_result',
                    'value' => function ($model) {
                        return \common\models\LoanCarCheck::getCheckResult()[$model->check_result];
                    }
                ],

                // 'check_time:datetime',
                // 'check_description',
                // 'check_longitude',
                // 'check_latitude',
                // 'audit_status',
                // 'audit_by',
                // 'audit_description:ntext',
                //  'status',
//                  'created_at:datetime',
                // 'updated_at',

                ['class' => 'backend\widgets\grid\ActionColumn'],
            ],
        ]); ?>


text:
using System;
using System.Collections.Generic;

namespace IronText.Algorithm
{
    public class BitSetType : IntSetType
    {
        // Consider 1 Kb as a max memory allowed for bitset
        public const int MaxBits = 8 * 1024;

        private IntSet _all;
        private IntSet _empty;
        private int _bitCount;

        public BitSetType(int bitCount)
        {
            this.BitCount = bitCount;
        }

        public int BitCount
        {
            get { return _bitCount; }
            private set
            {
                if (value > MaxBits)
                {
                    throw new ArgumentOutOfRangeException("bitCount", "bitCount is too big. Maximum is " + MaxBits);
                }

                _bitCount = value;
                this._empty = new BitSet(this, value, false);
                this._all = new BitSet(this, value, true);
            }
        }

        public override int MinValue { get { return 0; } }

        public override int MaxValue { get { return _bitCount - 1; } }

        public override IntSet All{ get { return _all; } }

        public override IntSet Empty { get { return _empty; } }

        public override IntSet Of(int value)
        {
            var result = new MutableBitSet(this, _bitCount, false);
            result.Add(value);
            return result;
        }

        public override IntSet Of(IEnumerable<int> value)
        {
            var result = new MutableBitSet(this, _bitCount, false);
            foreach (var item in value)
            {
                result.Add(item);
            }

            return result;
        }

        public override IntSet Range(int from, int to)
        {
            var result = new MutableBitSet(this, _bitCount, false);
            result.Add(new IntInterval(from, to));
            return result;
        }

        public override IntSet Ranges(IEnumerable<IntInterval> intervals)
        {
            if (intervals == null)
            {
                throw new ArgumentNullException("intervals");
            }

            var result = new MutableBitSet(this, _bitCount, false);
            foreach (var item in intervals)
            {
                result.Add(item);
            }

            return result;
        }

        public override MutableIntSet Mutable()
        {
            return new MutableBitSet(this, _bitCount, false);
        }
    }
}