text:
var CCV = require('../../app');
var Cuboid = CCV.components.cuboid;

describe("Cuboid", function() {
    it("can propagate its dimensions", function() {
        var cube = new Cuboid(5, 6, 16);
        expect(cube.length).toBe(5);
        expect(cube.width).toBe(6);
        expect(cube.height).toBe(16);
    });

    it("can propagate complex information", function() {
        var cube = new Cuboid(5, 6, 16);
        expect(cube.diagonal).toBeCloseTo(17.8, 1);
        expect(cube.base).toBeCloseTo(7.81, 2);
    });
});

redpajama_set_name: RedPajamaGithub


text: Built using Flight and PHPAuth


text:
package es.tid.topologyModuleBase.IETFTopoModel.model;

import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * Contains the information necessary to reference a network,\nfor example an underlay network.
 **/

@ApiModel(description = "Contains the information necessary to reference a network,\nfor example an underlay network.")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-07-18T18:59:38.916+02:00")
public class NetworkRef   {

  private String networkRef = null;

  /**
   * Used to reference a network, for example an underlay\nnetwork.
   **/
  public NetworkRef networkRef(String networkRef) {
    this.networkRef = networkRef;
    return this;
  }

  @ApiModelProperty(value = "Used to reference a network, for example an underlay\nnetwork.")
  @JsonProperty("networkRef")
  public String getNetworkRef() {
    return networkRef;
  }
  public void setNetworkRef(String networkRef) {
    this.networkRef = networkRef;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    NetworkRef networkRef = (NetworkRef) o;
    return Objects.equals(networkRef, networkRef.networkRef);
  }

  @Override
  public int hashCode() {
    return Objects.hash(networkRef);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class NetworkRef {\n");

    sb.append("    networkRef: ").append(toIndentedString(networkRef)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<?php namespace Dollar\Generators\Commands;

use Dollar\Generators\Generators\ViewGenerator;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class BaseGeneratorCommand extends Command {

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $path = $this->getPath();
        $template = $this->option('template');

        $this->printResult($this->generator->make($path, $template), $path);
    }

    /**
     * Provide user feedback, based on success or not.
     *
     * @param  boolean $successful
     * @param  string $path
     * @return void
     */
    protected function printResult($successful, $path)
    {
        if ($successful)
        {
            return $this->info("Created {$path}");
        }

        $this->error("Could not create {$path}");
    }

    /**
     * Get the path to the file that should be generated.
     *
     * @return string
     */
    protected function getPath()
    {
       return $this->option('path') . '/' . strtolower($this->argument('name')) . '.blade.php';
    }

}


text:
import java.util.ArrayList;

class DoubleHashing {
	String[] hashTable;
	int noOfCellsUsedInHashTable;

	//Constructor
	DoubleHashing() {
		hashTable = new String[13];
		noOfCellsUsedInHashTable = 0;
	}// end of method

	// HashFunction to be used on Keys
	public int simpleASCIIHashFunction(String x, int M) {
		char ch[];
		ch = x.toCharArray();
		int i, sum;
		for (sum = 0, i = 0; i < x.length(); i++) {
			sum = sum + ch[i];
		}
		// System.out.println("Index from hashfunction: " + sum % M);
		return sum % M;
	}// end of method

	//2nd HashFunction.
	int secondHashFunction(String x, int M) {
		char ch[];
		ch = x.toCharArray();
		int xlength = x.length();
		int i, sum;
		for (sum = 0, i = 0; i < xlength; i++)
			sum += ch[i];
		while (sum > 13)
			sum = addAllTheDigitsTogether(sum);
		return sum % M;
	}// end of method

	private int addAllTheDigitsTogether(int sum) {
		int value = 0;
		while (sum > 0) {
			value = sum % 10;
			sum = sum / 10;
		}
		return value;
	}// end of method

	public double getLoadFactor() {
		return noOfCellsUsedInHashTable * 1.0 / hashTable.length;
	}// end of method

	public void insertKeyInHashTable(String value) {
		double loadFactor = getLoadFactor();
		if (loadFactor >= 0.75) {
			System.out.println("Load factor of this HashTable has exceeded 0.75, hence we need to Rehash !\n");
			rehashKeys(value);
		} else {
			System.out.println("Inserting \"" + value + "\" in HashTable...");
			int x = simpleASCIIHashFunction(value, hashTable.length);
			int y = secondHashFunction(value, hashTable.length);
			for (int i = 0; i < hashTable.length; i++) {
					int newIndex = (x + i * y) % hashTable.length;
					// If there is a collision then we go to the next index
					// and keep going till we reach starting index.
					if (hashTable[newIndex] == null) {
						hashTable[newIndex] = value;
						System.out.println("Index: " + newIndex + " is blank. Inserting there...");
						System.out.println("Successfully inserted " + "\"" + value + "\"" + " in location: " + newIndex);
						System.out.println("-------------------------------------------\n");
						break;
					}else {
						System.out.println("Index: " + newIndex + " is already occupied. Trying next empty cell...");
					}
			}
		}
		noOfCellsUsedInHashTable++;
	}// end of method

	//Creates a new HashTable and does ReHashing
	public void rehashKeys(String newStringToBeInserted) {
		noOfCellsUsedInHashTable = 0; //need to reset it as we are now dealing with fresh HashTable
		ArrayList<String> data = new ArrayList<String>();
		for (String s : hashTable) { //loop through the HashTable and save all the keys in ArrayList
			if (s != null)
				data.add(s);
		}
		data.add(newStringToBeInserted);
		hashTable = new String[hashTable.length * 2]; // make new table with double size
		for (String s : data) { // push all old data into new table
			insertKeyInHashTable(s);
		}
	}//end of method

	//Search for a given key in hashTable
	public boolean searchKeyInHashTable(String stringToBeSearched) {
		int index = simpleASCIIHashFunction(stringToBeSearched, hashTable.length);
		for (int i = index; i < index + hashTable.length; i++) {
			int newIndex = i % hashTable.length;
			if (hashTable[newIndex]!=null && hashTable[newIndex].equals(stringToBeSearched)) {
				System.out.println("\n" + "\"" + stringToBeSearched + "\"" + " found in HashTable at location: "+newIndex);
				return true;
			}
		}
		System.out.println("\n" + "\"" + stringToBeSearched + "\"" + " not found in HashTable.");
		return false;
	}//end of method

	//Delete key from HashTable
	public void deleteKeyFromHashTable(String stringToBeDeleted) {
		int index = simpleASCIIHashFunction(stringToBeDeleted, hashTable.length);
		for (int i = index; i < index + hashTable.length; i++) {
			int newIndex = i % hashTable.length;
			if (hashTable[newIndex]!=null && hashTable[newIndex].equals(stringToBeDeleted)) {
				hashTable[newIndex] = null;
				System.out.println("\n" + "\"" + stringToBeDeleted + "\"" + " has been found in HashTable." );
				System.out.println("\"" + stringToBeDeleted + "\"" + " has been deleted from HashTable !" );
				return;
			}
		}
		System.out.println("\nCould not find " + "\"" + stringToBeDeleted + "\"" + " in HashTable");
	}//end of method

	// Display the hash table
		public void displayHashTable() {
			if(hashTable == null) {
				System.out.println("\nHashTable does not exits !");
				return;
			}else {
				System.out.println("\n---------- HashTable ---------");
				for (int i = 0; i < hashTable.length; i++) {
					System.out.println("Index:" + i + ".   Key:" + hashTable[i]);
				}
			}
			System.out.println("\n");
		}// end of method

	// deletes entire HashTable
	public void deleteHashTable() {
		System.out.println("Successfully deleted HashTable !");
		hashTable = null;
	}// end of method

}

public class doublehashingtech {

	public static void main(String[] args) {

		// Constructor
		DoubleHashing doubleHashing = new DoubleHashing();

		doubleHashing.insertKeyInHashTable("The");
		doubleHashing.insertKeyInHashTable("quick");
		doubleHashing.insertKeyInHashTable("brown");
		doubleHashing.insertKeyInHashTable("fox");
		doubleHashing.insertKeyInHashTable("over");
		doubleHashing.insertKeyInHashTable("lazy");
		doubleHashing.displayHashTable();

		/*doubleHashing.insertKeyInHashTable("fox"); // use for showing collision
		doubleHashing.displayHashTable();

		doubleHashing.insertKeyInHashTable("fox");
		doubleHashing.displayHashTable();

		doubleHashing.insertKeyInHashTable("fox");
		doubleHashing.displayHashTable();

		doubleHashing.insertKeyInHashTable("fox");
		doubleHashing.displayHashTable();

		doubleHashing.insertKeyInHashTable("fox");
		doubleHashing.displayHashTable();*/

		doubleHashing.searchKeyInHashTable("jump");
		doubleHashing.searchKeyInHashTable("brown");

		doubleHashing.deleteKeyFromHashTable("jump");
		doubleHashing.deleteKeyFromHashTable("quick");
		doubleHashing.displayHashTable();

		doubleHashing.deleteHashTable();
		doubleHashing.displayHashTable();

	}// end of method

}// end of class


text:
package fuse

func localVolume(conf *mountConfig) error {
	conf.options["local"] = ""
	return nil
}

func volumeName(name string) MountOption {
	return func(conf *mountConfig) error {
		conf.options["volname"] = name
		return nil
	}
}

func daemonTimeout(name string) MountOption {
	return func(conf *mountConfig) error {
		conf.options["daemon_timeout"] = name
		return nil
	}
}

func noAppleXattr(conf *mountConfig) error {
	conf.options["noapplexattr"] = ""
	return nil
}

func noAppleDouble(conf *mountConfig) error {
	conf.options["noappledouble"] = ""
	return nil
}


text:
<component name="ArtifactManager">
  <artifact type="war" name="my-firsts:war">
    <output-path>$PROJECT_DIR$/target</output-path>
    <root id="archive" name="my-firsts.war">
      <element id="artifact" artifact-name="my-firsts:war exploded" />
    </root>
  </artifact>
</component>


text:
<?php
$domain = "http://" . $_SERVER['SERVER_NAME'];
Yii::setAlias("domain", $domain);

Yii::setAlias("app_domain", 'http://h5.9939.com');


text:
package com.salesmanager.shop.model.catalog.product.attribute.api;

import java.io.Serializable;

import com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute;

public class ProductAttributeEntity extends ProductAttribute implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private int sortOrder;
	private boolean attributeDefault=false;
	private boolean attributeDisplayOnly = false;

	public void setSortOrder(int sortOrder) {
		this.sortOrder = sortOrder;
	}
	public int getSortOrder() {
		return sortOrder;
	}
	public void setAttributeDefault(boolean attributeDefault) {
		this.attributeDefault = attributeDefault;
	}
	public boolean isAttributeDefault() {
		return attributeDefault;
	}

	public boolean isAttributeDisplayOnly() {
		return attributeDisplayOnly;
	}
	public void setAttributeDisplayOnly(boolean attributeDisplayOnly) {
		this.attributeDisplayOnly = attributeDisplayOnly;
	}

}


text:
package inujini_.hatate.data;

import inujini_.sqlite.meta.ISqlite;
import inujini_.sqlite.meta.annotation.SqliteField;
import inujini_.sqlite.meta.annotation.SqliteTable;

import java.io.Serializable;

import lombok.Data;

/**
 * シリーズデータ.
 * @see MetaSeries
 */
@Data
@SqliteTable("Series")
public class Series implements Serializable, ISqlite, TouhouData {

	private static final long serialVersionUID = -4128311317792759035L;

	@SqliteField(name="Id", type=FIELD_INTEGER, primary=true)
	private long id;

	@SqliteField(name="Name", type=FIELD_TEXT, notNull=true, unique=true)
	private String name;

	private int position;
}


text:
package org.apache.hadoop.hdfs;

import java.io.File;
import java.nio.channels.FileLock;
import java.lang.reflect.*;

import junit.framework.TestCase;
import org.junit.Test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.CachingAvatarZooKeeperClient.ZooKeeperCall;

public class TestCachingAvatarZooKeeperClient {
  final static Log LOG = LogFactory.getLog(TestCachingAvatarZooKeeperClient.class);

  @Test
  public void testTryLock() throws Exception {
    String directoryName = "/tmp/temp" + Long.toString(System.nanoTime());
    try {
      Configuration conf = new Configuration();
      conf.set("fs.ha.zookeeper.cache.dir", directoryName);
      conf.setBoolean("fs.ha.zookeeper.cache", false);
      CachingAvatarZooKeeperClient cazkc = new CachingAvatarZooKeeperClient(conf, null);
      Method m = CachingAvatarZooKeeperClient.class.getDeclaredMethod(
          "tryLock", Boolean.TYPE, ZooKeeperCall.class);
      ZooKeeperCall call = cazkc.new GetStat(null);
      m.setAccessible(true);
      FileLock fl = (FileLock) m.invoke(cazkc, true, call);
      fl.release();
      TestCase.assertNotNull(fl);
      fl = (FileLock) m.invoke(cazkc, true, call);
      TestCase.assertNotNull(fl);
      fl.release();
      new File(directoryName, ".avatar_zk_cache_lock").delete();
      m.invoke(cazkc, true, call);
    } finally {
      new File(directoryName, ".avatar_zk_cache_lock").delete();
      new File(directoryName).delete();
    }
  }

}


text:
package com.github.ambry.server;

import com.github.ambry.server.storagestats.HostPartitionClassStorageStats;

/**
 * A wrapper model object that contains a {@link HostPartitionClassStorageStats} and a {@link StatsHeader} with metadata.
 */
public class HostPartitionClassStorageStatsWrapper {
  private final StatsHeader header;
  private final HostPartitionClassStorageStats stats;

  public HostPartitionClassStorageStatsWrapper(StatsHeader header, HostPartitionClassStorageStats stats) {
    this.header = header;
    this.stats = stats;
  }

  /**
   * Return {@link StatsHeader}.
   * @return
   */
  public StatsHeader getHeader() {
    return header;
  }

  /**
   * Return {@link HostPartitionClassStorageStats}.
   * @return
   */
  public HostPartitionClassStorageStats getStats() {
    return stats;
  }
}


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

using Xunit;

namespace System.Composition.AttributeModel.Tests
{
    public class ImportMetadataConstraintAttributeTests
    {
        [Theory]
        [InlineData(null, null)]
        [InlineData("Name", "Value")]
        public void Ctor_Name_Value(string name, string value)
        {
            var attribute = new ImportMetadataConstraintAttribute(name, value);
            Assert.Equal(name, attribute.Name);
            Assert.Equal(value, attribute.Value);
        }
    }
}


text:
.PHONY: test release test-ci-coverage

MOCHA=node_modules/.bin/mocha
COVERALLS=node_modules/.bin/coveralls
_MOCHA=node_modules/.bin/_mocha
ISTANBUL=node_modules/.bin/istanbul

test:
	npm test

test-ci-coverage:
	npm install coveralls
	npm install istanbul
	@rm -rf coverage
	$(ISTANBUL) cover $(_MOCHA) --report lcovonly -- -R tap

	@echo
	@echo Sending report to coveralls.io...
	@cat ./coverage/lcov.info | $(COVERALLS)
	@rm -rf ./coverage
	@echo Done

release:
ifeq ($(strip $(version)),)
	@echo "\033[31mERROR:\033[0;39m No version provided."
	@echo "\033[1;30mmake release version=1.0.0\033[0;39m"
else
	make test
	sed -i.bak 's/"version": "[^"]*"/"version": "$(version)"/' package.json
	rm *.bak
	git add .
	git commit -a -m "Released $(version)."
	git tag v$(version)
	git push origin master
	git push origin --tags
	npm publish
	@echo "\033[32mv${version} released\033[0;39m"
endif


text:
const randomModule = require('../random-module');

describe('Suite A', function() {
  before(function() {
    console.log('SUITE A BEFORE!')
  })
  it('does assertions', function(done) {
    setTimeout(done, 500)
  })
  it('imports files', function() {
    expect(randomModule).to.be.a('function');
  })
  // it('fails', function() {
  //   expect(1).to.equal(2)
  // })
})


text:
layout: null
sitemap:
  exclude: 'yes'
---
<?xml version="1.0"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  <ShortName>Auth0</ShortName>
  <Description>Auth0</Description>
  <Developer>Auth0</Developer>
  <Url type="text/html" method="get" template="https://auth0.com{{ site.baseurl }}/search/?q={searchTerms}"/>
</OpenSearchDescription>


text:
//
//  MJJBanner.m
//  MJSDK-iOS
//
//  Created by John LXThyme on 16/9/12.
//  Copyright © 2016年 WM. All rights reserved.
//

#import "MJBanner.h"

#import "MJTool.h"
#import "MJFactory.h"
#import "MJError.h"

#import "MJGLBanner.h"
#import "MJIMGBanner.h"

#import "MJGLInline.h"
#import "MJIMGInline.h"

#import "MJGLInterstitial.h"
#import "MJIMGInterstitial.h"

#import "MJDataManager.h"
#import "MJGradientLayer.h"
#import "MJRequestManager.h"
#import "MJExceptionReportManager.h"

#import <ReactiveCocoa.h>
#import <AFNetworkActivityIndicatorManager.h>

@interface MJBanner()<UITableViewDelegate,UITableViewDataSource>
{
    //当前行
    NSIndexPath *_currentSelectedIndexPath;
    //定时器
    //    dispatch_source_t _timer;
    //第一次启动 _timer
    //    BOOL _mjTimerIsFirstStart;
    //父容器
    kMJParentContainer _parentContainer;
    UIView *_parentView;

    kMJTimerStatus _mjTimerStatus;

    NSUInteger _reloadCount;
}
/** UITableView*/
@property (nonatomic,retain)UITableView *table;
/** 关闭按钮*/
@property (nonatomic,retain)UIButton *btnClose;
/** 广告标识*/
@property (nonatomic,retain)UILabel *mjLabADLogo;
//***********
@property (nonatomic,assign)BOOL isShow;
/** 广告类型*/
@property (nonatomic,assign)KMJADType adType;
/** 广告位置*/
@property (nonatomic,assign)KMJADPosition position;
/** 加载数据状态*/
@property (nonatomic,assign)kMJLoadDataState dataState;
/** 定时器*/
@property (nonatomic,strong)dispatch_source_t timer;
@property (nonatomic,copy)kMJLoadDataSuccess loadDataSuccessBlock;
/** 在线曝光*/
@property (nonatomic,copy)kMJGotoExposureBlock mjGotoExposureBlock;
//Developer
/** 广告位ID*/
@property (nonatomic,copy)NSString *adSpaceID;
/** 数据源*/
@property (nonatomic,retain)MJResponse *mjResponse;
/**
 *  @brief Mask
 */
@property (nonatomic, strong) CALayer *backgroundLayer;
@property (assign, nonatomic) LXMJViewMaskType defaultMaskType;
@property (strong, nonatomic) UIColor *backgroundLayerColor;

//*****************************MJView.h
@property (nonatomic, readonly) CGFloat visibleKeyboardHeight;

@end
@implementation MJBanner
- (void)dealloc {
    NSLog(@"------------dealloc-------------");
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self bannerClosed];
}
#pragma mark -
#pragma mark - initial
- (instancetype)init{
    NSAssert(NO, @"必须使用 SDK 提供的初始化方法");
    if (self = [super init]) {
    }
    return self;
}
- (void)baseInitial{
    //启动定位系统
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
//        [LXLocationManager getMyLocation];
    });
    [self initial];
}
- (void)initial{
    [self setBackgroundColor:[UIColor whiteColor]];
    __block CGFloat rowHeight;
    [self doitBanner:^{
        rowHeight = kADBannerHeight;
    } interstitial:^{
        [self setBackgroundColor:[UIColor clearColor]];
        rowHeight = CGRectGetHeight(kMJInterstitialHalfScreenBounds);
        self.defaultMaskType =
        //    LXMJViewMaskTypeNone;
        LXMJViewMaskTypeGradient;
        [self updateMask];
    } inline:^{
        rowHeight = kMJInlineHeight;
    }];
    [self.table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.table setRowHeight:rowHeight];
    [self.table setDelegate:self];
    [self.table setDataSource:self];
    if (kIOSVersion >= 8.f) {
        self.table.estimatedRowHeight = kADBannerHeight;
    }
}
/**
 *  @brief 初始化Banner广告
 *
 *  @param adSpaceID 广告位 ID
 *  @param position 广告位置
 *
 *  @return instancetype
 */
+ (instancetype)registerBannerWithAdSpaceID:(NSString *)adSpaceID position:(KMJADPosition)position {
    return [[self alloc]initWithAdSpaceID:adSpaceID position:position adType:KMJADBannerInternalType];
}
/**
 *  @brief 初始化插屏广告
 *
 *  @param adSpaceID 广告位 ID
 *
 *  @return instancetype
 */
+ (instancetype)registerInterstitialWithAdSpaceID:(NSString *)adSpaceID{
    return [[self alloc]initWithAdSpaceID:adSpaceID position:1 adType:KMJADInterstitialInternalType];
}
/**
 *  @brief 注册内嵌广告
 *
 *  @param adSpaceID 广告位 ID
 *
 *  @return instancetype
 */
+ (instancetype)registerInlineWithAdSpaceID:(NSString *)adSpaceID {
    return [[self alloc]initWithAdSpaceID:adSpaceID position:1 adType:KMJADInlineInternalType];
}

/**
 *  @brief 初始化广告位
 *
 *  @param adSpaceID 广告位ID
 *  @param position  广告位置
 *  @param adType    广告类型
 *
 *  @return instancetype
 */
- (instancetype)initWithAdSpaceID:(NSString *)adSpaceID position:(KMJADPosition)position adType:(KMJADType)adType {
    NSString *classString = NSStringFromClass([self class]);
    NSString *lowString = [classString lowercaseString];
    BOOL has = [lowString rangeOfString:@"banner"].location != NSNotFound;
    NSAssert(has, @"非 banner 类型请调用 - initWithAdSpaceID: 方法");
    NSAssert(adSpaceID.length > 0, @"广告位 ID 不能为空!");
    NSAssert(position == 1 || position == 2, @"position 不合法!");
    if (self = [super init]) {
//        self.layer.masksToBounds = YES;
        _adSpaceID = adSpaceID;
        _position = position;
        _adType = adType;
        [self setUp];
        [self initRAC];
        [self registerNotification];
    }
    return self;
}
- (void)registerNotification {
    //application state notification
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationStateDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationStateDidBecomeInActive:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    //banner closed notification
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(mjDidSIMBannerClosed:) name:kMJSDKDidSIMBannerClosedNotification object:nil];
}
- (void)baseSetUp{
    //
    [self setUp];
    //曝光
    //    [self exposureBlock];
    //网络请求时状态栏网络状态小转轮
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
}
#pragma mark -
#pragma mark - show
/**
 *  @brief 广告展示
 */
- (void)show {
    if (self.isShow) {
        NSLog(@"已经展示,不能重复展示");
        MJNSLog(@"已经展示,不能重复展示");
        return;
    }
    if(self.dataState == kMJLoadDataUnReadyState || (self.dataState == kMJLoadDataReadyState && self.mjResponse.impAds <= 0)) {
        NSLog(@"数据源尚未准备好,重新准备中...");
        self.dataState = kMJLoadDataLoadingState;
        WEAKSELF
        [self loadDataSuccessBlock:^(MJResponse *mjResponse, NSDictionary *responseObject) {
            STRONGSELF
            strongSelf.isShow = YES;
            strongSelf.mjResponse = mjResponse;
        } errorBlock:nil];
    }else if(self.dataState == kMJLoadDataLoadingState) {
        NSLog(@"缓存数据ing, will show...");
        MJNSLog(@"缓存数据ing");
        self.isShow = YES;
    }else if(self.dataState == kMJLoadDataReadyState) {
        NSLog(@"kMJLoadDataReadyState");
        self.isShow = YES;
        self.mjResponse = self.mjResponse;
    } else {
        NSAssert(NO, @"");
    }
}
- (void)mj_showInDefaultWindow {
    //    [self setUserInteractionEnabled:YES];
    //    [self.table setUserInteractionEnabled:YES];
    [self addSubview:self.table];
    [kMJSuperview addSubview:self];
    MASAttachKeys(self.table, self);
    //    [self masonry];
    [self baseInitial];
    _currentSelectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
}
- (void)mj_showInView:(UIView *)view {
    [self addSubview:self.table];
    [self addSubview:self.mjLabADLogo];
    [self addSubview:self.btnClose];
    [view addSubview:self];
    MASAttachKeys(self.table, self);
    //    [self masonry];
    [self baseInitial];
    _currentSelectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
}

//轮播
- (void)afterShow {
    //如果是 banner, 则自动轮播
//    if (self.adType == KMJADBannerInternalType) {
        [self resumed];
//    }
}
#pragma mark - setUp
- (void)setUp{
    //
    [self.table setBackgroundColor:[UIColor clearColor]];
    [self.table setDelegate:self];
    [self initial];
    //曝光
    //    [self exposureBlock];
    //网络请求时状态栏网络状态小转轮
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
}
- (void)applicationStateDidBecomeInActive:(NSNotification *)notification {
    [self suspend];
}
- (void)applicationStateDidBecomeActive:(NSNotification *)notification {
    [self resumed];
}
- (void)mjDidSIMBannerClosed:(NSNotification *)notification {
//    id obj = notification.object;
//    if (!obj) {
//        NSAssert(NO, @"");
//    }
//    if ([obj isEqual:self]) {
        [self bannerClosed];
//    }
}
- (void)bannerClosed {
    //    [self.btnClose setUserInteractionEnabled:NO];
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        [self.btnClose setUserInteractionEnabled:YES];
    //    });
    [self resetStatus];
    [self canceld];
}
- (void)resetStatus {
    if (self.dismissBlock) {
        self.dismissBlock();
    }
    _isShow = NO;
    _dataState = kMJLoadDataUnReadyState;
    _mjResponse = nil;
    [self.table removeFromSuperview];
    _table = nil;
    [self removeFromSuperview];
}
- (void)scrollToNext{
    [self timerEventHandler];
}
#pragma mark -
#pragma mark - RAC
- (void)initRAC {
    [[RACObserve(self, mjResponse) filter:^BOOL(id value) {
        if (!self.mjResponse) {
            return NO;
        }
        if (!self.isShow) {
            NSLog(@"尚未show, 不予处理");
            return NO;
        }
        if (_parentContainer == kMJParentContainerView && !_parentView) {
            NSLog(@"父容器为 view 时,需先设置 parentView");
            return NO;
        }
        return YES;
    }] subscribeNext:^(id x) {
        [self.table reloadData];
        id superView = [self superview];
        if (!superView) {
            [self mj_showInView:[MJTool getTopView]];
            [self masonry];
            [self afterShow];
        }
        NSLog(@"加载成功- All:%ld", _mjResponse.impAds.count);
    }];
}
#pragma mark -
#pragma mark - block
#pragma mark - mjGotoExposureBlock
- (kMJGotoExposureBlock)mjGotoExposureBlock
{
    if(!_mjGotoExposureBlock){
        WEAKSELF
        _mjGotoExposureBlock = ^(MJImpAds *impAds){
            impAds.hasExposured = YES;
            [MJExceptionReportManager uploadOnlineExposureReport:impAds adSpaceID:weakSelf.adSpaceID success:^{
                //
                [MJTool responds:weakSelf.delegate toSelector:@selector(mjADDidExposure:error:) block:^{
                    [weakSelf.delegate mjADDidExposure:weakSelf error:nil];
                }];
            } failure:^(NSURLSessionDataTask * _Nullable dataTask, NSError * _Nonnull error) {
                //
                [MJTool responds:weakSelf.delegate toSelector:@selector(mjADDidExposure:error:) block:^{
                    [weakSelf.delegate mjADDidExposure:weakSelf error:error];
                }];
            }];
        };

    }

    return _mjGotoExposureBlock;
}
/**
 *  @brief 设置 mjResponse 时,自动设置 showURL 和数据源 arrayData
 *
 *  @param mjResponse <#mjResponse description#>
 */
- (void)setMjResponse:(MJResponse *)mjResponse {
    if ([_mjResponse isEqual:mjResponse]) {
        return;
    }
//    _showURL = mjResponse.showUrl;
    _mjResponse = mjResponse;
    for (MJImpAds *impAds in _mjResponse.impAds) {
        impAds.showUrl = _mjResponse.showUrl;
    }
}
#pragma mark -
#pragma mark - 定时器 - timer
- (dispatch_source_t)timer
{
    if(!_timer){
        //需要将dispatch_source_t timer设置为成员变量,不然会立即释放
        //@property (nonatomic, strong) dispatch_source_t timer;
        //定时器开始执行的延时时间
        NSTimeInterval delayTime = kMJSDKScrollInterval;
        //定时器间隔时间
        NSTimeInterval timeInterval = kMJSDKScrollInterval;
        //创建子线程队列
        dispatch_queue_t timerQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //使用之前创建的队列来创建计时器
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerQueue);
        //设置延时执行时间,delayTime为要延时的秒数
        dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
        //设置计时器
        dispatch_source_set_timer(_timer, startDelayTime, timeInterval * NSEC_PER_SEC, 0.1 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(_timer, ^{
            //执行事件
            NSLog(@"[%@][%@]timer resumed...", KNSStringFromMJADType(self.adType), _timer);
            [self timerEventHandler];
        });
        dispatch_source_set_cancel_handler(_timer, ^{
            //stop the timer here.
            NSLog(@"cancel timer...");
            if (_mjTimerStatus == kMJTimerCanceledStatus) {
                [self resetStatus];
                self.timer = nil;
            }
        });
        // 启动计时器
        //        dispatch_resume(_timer);
    }
    return _timer;
}
- (void)resumed {
    if (_mjTimerStatus != kMJTimerResumedStatus) {
        _mjTimerStatus = kMJTimerResumedStatus;
        self.isShow = YES;
        dispatch_resume(self.timer);
    }
}
- (void)suspend {
    if (_timer && _mjTimerStatus == kMJTimerResumedStatus) {
        NSLog(@"timer suspend...");
        self.isShow = NO;
        _mjTimerStatus = kMJTimerSuspendStatus;
        dispatch_suspend(_timer);
    }
}
- (void)canceld {
    if (!_timer || _mjTimerStatus == kMJTimerSuspendStatus) {
        [self resumed];
    }
    self.isShow = NO;
    _mjTimerStatus = kMJTimerCanceledStatus;
    dispatch_source_cancel(self.timer);
    self.timer = nil;
}
- (void)timerEventHandler {
    UIApplicationState applicationState = [UIApplication sharedApplication].applicationState;
    if (applicationState != UIApplicationStateActive) {
        [self suspend];
        return;
    }
    if (!self.mjResponse.impAds || self.mjResponse.impAds.count <= 0) {
        NSLog(@"没有数据!");
        [self bannerClosed];
        return;
    }
//    if (self.mjResponse.impAds.count == 1) {
//        NSLog(@"impAds.count == %ld, then auto suspend.", self.mjResponse.impAds.count);
//        [self timerPrerLoadData];
//        [self suspend];
//        return;
//    }
    NSLog(@"current[%ld] - goto[%ld]",_currentSelectedIndexPath.row, _currentSelectedIndexPath.row + 1);
    //当剩余3条数据时开始缓存数据
    NSInteger count = self.mjResponse.impAds.count;
    if (_currentSelectedIndexPath.row > (count - 2)) {
        [self timerPrerLoadData];
    }//if (_currentSelectedIndexPath.row > self.arrayData.count - 3)
    count = self.mjResponse.impAds.count;
    if (_currentSelectedIndexPath.row <= (count - 2)) {
        _currentSelectedIndexPath = [NSIndexPath indexPathForRow:_currentSelectedIndexPath.row + 1 inSection:_currentSelectedIndexPath.section];
        dispatch_async(dispatch_get_main_queue(), ^{
            //
            [self.table scrollToRowAtIndexPath:_currentSelectedIndexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
            NSLog(@"current - ROW:%ld",_currentSelectedIndexPath.row);
        });
    } else {
        NSLog(@"overloaded");
        dispatch_async(dispatch_get_main_queue(), ^{
            _currentSelectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            if (!self.mjResponse && self.mjResponse.impAds.count <= 0) {
                NSLog(@"**********");
                NSAssert(NO, @"");
                return;
            }
            [self.table scrollToRowAtIndexPath:_currentSelectedIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        });
    }//if (_currentSelectedIndexPath.row <= self.arrayData.count - 1)
}
- (void)timerPrerLoadData {
    //如果 dataState 不是 Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/StoreServices.framework/StoreServiceskMJLoadDataReadyState,则可能已经在缓存,需等待缓存完成.
    NSLog(@"dataState:%ld", kMJLoadDataLoadingState);
    if (self.dataState != kMJLoadDataLoadingState) {
        //重置 dataState
        self.dataState = kMJLoadDataLoadingState;
        NSLog(@"开始预加载...");
        MJNSLog(@"开始预加载...");
        WEAKSELF
        [self loadDataSuccessBlock:^(MJResponse * _Nonnull mjResponse, NSDictionary *responseObject) {
            //
            NSLog(@"开始预加载-success");
            STRONGSELF
            NSMutableArray *muarr = [strongSelf.mjResponse.impAds mutableCopy];
            [muarr addObjectsFromArray:mjResponse.impAds];
            mjResponse.impAds = muarr;
            strongSelf.mjResponse = mjResponse;
            [strongSelf.table reloadData];
        } errorBlock:nil];
    }
}
#pragma mark -
#pragma mark - loadData
/**
 *  @brief 预加载数据
 */
- (void)preloadData:(kMJBaseBlock)successBlock {
    self.dataState = kMJLoadDataLoadingState;
    NSLog(@"start preloadData...");
    WEAKSELF
    self.mjResponse = nil;
    [self loadDataSuccessBlock:^(MJResponse * _Nonnull mjResponse, NSDictionary *responseObject) {
        NSLog(@"preloadData success...");
        self.dataState = kMJLoadDataReadyState;
        weakSelf.mjResponse = mjResponse;
        if (successBlock) {
            successBlock();
        }
    } errorBlock:nil];// preLoaded:YES];
}
//- (void)loadDataSuccessBlock:(kRequestSuccessBlock)successBlock errorBlock:(kRequestErrorBlock)errorBlock {
//    [self baseLoadDataSuccessBlock:^(MJResponse * _Nullable mjResponse, NSDictionary * _Nullable responseObject) {
//        <#code#>
//    } errorBlock:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error) {
//        _reloadCount++;
//        if (_reloadCount >= kMJSDKSIMBannerReloadCount) {
//            weakSelf.isShow = NO;
//            weakSelf.dataState = kMJLoadDataUnReadyState;
//            //请求数据失败的回调
//            [MJTool responds:weakSelf.delegate toSelector:@selector(mjADRequestData:error:) block:^{
//                [weakSelf.delegate mjADRequestData:weakSelf error:error];
//            }];
//            if (errorBlock) {
//                errorBlock(response, error);
//            }
//        } else {
//
//        }
//    }];
//}
- (void)loadDataSuccessBlock:(kRequestSuccessBlock)successBlock errorBlock:(kRequestErrorBlock)errorBlock {
//    [self loadDataReloadTimes:kMJSDKSIMBannerReloadCount successBlock:successBlock errorBlock:errorBlock];
    [self loadDataReloadTimes:kMJSDKSIMBannerReloadCount successBlock:^(MJResponse * _Nullable mjResponse, NSDictionary * _Nullable responseObject) {
//        NSLog(@"success");
        if (successBlock) {
            successBlock(mjResponse, responseObject);
        }
    } errorBlock:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error) {
//        NSLog(@"error");
    }];
}
- (void)loadDataReloadTimes:(NSInteger)reloadTimes successBlock:(kRequestSuccessBlock)successBlock errorBlock:(kRequestErrorBlock)errorBlock {
    if (reloadTimes <= 0) {
        MJError *mjerror = [MJError errorWithDomain:@"" code:kMJSDKERROROverRetryLoadAdDataTimesFailure userInfo:@{}];
        if (errorBlock) {
            errorBlock(nil, mjerror);
        }
        return;
    }
    NSLog(@"reloadCount:%ld", reloadTimes);
    reloadTimes--;
    [self baseLoadDataSuccessBlock:successBlock errorBlock:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error) {
        [self loadDataReloadTimes:reloadTimes successBlock:successBlock errorBlock:errorBlock];
    }];
}
- (void)baseLoadDataSuccessBlock:(kRequestSuccessBlock)successBlock errorBlock:(kRequestErrorBlock)errorBlock {
    MJDataManager *dataManager = [MJDataManager manager];
    [dataManager setEventID:@"4" adlocCode:self.adSpaceID adCount:kMJSDKBannerRequestCount];
    NSDictionary *params = dataManager.requestManager.request;
    WEAKSELF
    [dataManager loadData:params adType:self.adType successBlock:^(MJResponse *mjResponse, NSDictionary *responseObject) {
        weakSelf.dataState = kMJLoadDataReadyState;
        //请求数据成功的回调
        [MJTool responds:weakSelf.delegate toSelector:@selector(mjADRequestData:error:) block:^{
            [weakSelf.delegate mjADRequestData:weakSelf error:nil];
        }];
        if (successBlock) {
            successBlock(mjResponse, responseObject);
        }
    } errorBlock:^(NSURLResponse *response, NSError *error) {
        //重置 dataState
        weakSelf.isShow = NO;
        weakSelf.dataState = kMJLoadDataUnReadyState;
        //请求数据失败的回调
        [MJTool responds:weakSelf.delegate toSelector:@selector(mjADRequestData:error:) block:^{
            [weakSelf.delegate mjADRequestData:weakSelf error:error];
        }];
        if (errorBlock) {
            errorBlock(response, error);
        }
    }];
}
#pragma mark -
#pragma mark - delegate
#pragma mark - TableView Required Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.mjResponse.impAds count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self doitReturnBanner:^id{
        MJImpAds *impAds = self.mjResponse.impAds[indexPath.row];
        MJBannerAds *bannerAds = impAds.bannerAds;
        KMJADType mjAdType = bannerAds.mjAdType;

        if (mjAdType == KMJADBannerIMGType) {
            static NSString *cellBannerIMGIdentifier = @"cellIdentifierBannerIMG";
            MJIMGBanner *cell = [tableView dequeueReusableCellWithIdentifier:cellBannerIMGIdentifier];
            if (!cell)
            {
                cell = [[MJIMGBanner alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellBannerIMGIdentifier];
            }
            //configuration cell...
            cell.superOwner = self;
            [cell fillImpAds:impAds indexPath:indexPath];
            return cell;
        } else if (mjAdType == KMJADBannerGLType) {
            static NSString *cellBannerGLIdentifier = @"cellIdentifierBannerGL";
            MJGLBanner *cell = [tableView dequeueReusableCellWithIdentifier:cellBannerGLIdentifier];
            if (!cell)
            {
                cell = [[MJGLBanner alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellBannerGLIdentifier];
            }
            //configuration cell...
            cell.superOwner = self;
            [cell fillImpAds:impAds indexPath:indexPath];
            return cell;
        } else {
            NSAssert(NO, @"ERROR");
        }
        return nil;
    } interstitial:^id{
        MJImpAds *impAds = self.mjResponse.impAds[indexPath.row];
        MJBannerAds *bannerAds = impAds.bannerAds;
        KMJADType mjAdType = bannerAds.mjAdType;
        //    MJElement *mjEelements = bannerAds.mjElement;
        if (mjAdType == KMJADInterstitialIMGType) {
            static NSString *cellIMGIdentifier = @"cellIdentifierIMG";
            MJIMGInterstitial *cell = [tableView dequeueReusableCellWithIdentifier:cellIMGIdentifier];
            if (!cell)
            {
                cell = [[MJIMGInterstitial alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIMGIdentifier];
            }
            //configuration cell...
            cell.superOwner = self;
            [cell fillImpAds:impAds indexPath:indexPath];
            return cell;
        } else if (mjAdType == KMJADInterstitialGLType) {
            static NSString *cellGLIdentifier = @"cellIdentifierGL";
            MJGLInterstitial *cell = [tableView dequeueReusableCellWithIdentifier:cellGLIdentifier];
            if (!cell)
            {
                cell = [[MJGLInterstitial alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellGLIdentifier];
            }
            //configuration cell...
            cell.superOwner = self;
            [cell fillImpAds:impAds indexPath:indexPath];
            return cell;
        }
        else {
            NSAssert(NO, @"ERROR");
        }
        return nil;
    } inline:^id{
        MJImpAds *impAds = self.mjResponse.impAds[indexPath.row];
        MJBannerAds *bannerAds = impAds.bannerAds;
        KMJADType mjAdType = bannerAds.mjAdType;
        if (mjAdType == KMJADInlineIMGType || mjAdType == KMJADInlineIMGShareType) {
            static NSString *cellIMGInlineIdentifier = @"cellIdentifier_MJIMGInline";
            MJIMGInline *cell = [tableView dequeueReusableCellWithIdentifier:cellIMGInlineIdentifier];
            if (!cell) {
                cell = [[MJIMGInline alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIMGInlineIdentifier];
            }
            //configuration cell...
            cell.superOwner = self;
            [cell fillImpAds:impAds indexPath:indexPath];
            return cell;
        } else if (mjAdType == KMJADInlineGLType) {
            static NSString *cellGLInlineIdentifier = @"cellIdentifier_MJGLInline";
            MJGLInline *cell = [tableView dequeueReusableCellWithIdentifier:cellGLInlineIdentifier];
            if (!cell) {
                cell = [[MJGLInline alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellGLInlineIdentifier];
            }
            //configuration cell...
            cell.superOwner = self;
            [cell fillImpAds:impAds indexPath:indexPath];
            return cell;
        } else {
            NSAssert(NO, @"ERROR");
        }
        return nil;
    }];
}
#pragma mark - TableView Optional Methods
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    [MJTool responds:self.delegate toSelector:@selector(mjADWillShow:error:) block:^{
        [weakSelf.delegate mjADWillShow:weakSelf error:nil];
    }];
//    NSLog(@"willDisplayCell:ROW[%ld]\t", indexPath.row);
    __block MJImpAds *impAds = self.mjResponse.impAds[indexPath.row];
    if (impAds.hasExposured) {
//        NSLog(@"willDisplayCell:ROW[%ld]已经曝光过impressionSeqNo[%ld]", indexPath.row, impAds.impressionSeqNo);
        return;
    }
    NSLog(@"1`开始曝光ROW[%ld] : impressionSeqNo[%ld]",indexPath.row,  impAds.impressionSeqNo);
    impAds.beginShowTime = [MJTool getInternetBJDate];
    //dispatch_after
    double delayInSeconds = kMJSDKExposureTimeInterval;
    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(delayInNanoSeconds, dispatch_get_global_queue(0, 0), ^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            if (!impAds.endShowTime && weakSelf.isShow) {
                //                kMJGotoExposureBlock(impAds);
                self.mjGotoExposureBlock(impAds);
            }
        });
    });

}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"didEndDisplayingCell[%ld]\t", indexPath.row);
    WEAKSELF
    [MJTool responds:weakSelf.delegate toSelector:@selector(mjADDidEndShow:error:) block:^{
        [weakSelf.delegate mjADDidEndShow:weakSelf error:nil];
    }];
    MJImpAds *impAds = self.mjResponse.impAds[indexPath.row];
    impAds.endShowTime = [MJTool getInternetBJDate];

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MJImpAds *impAds = self.mjResponse.impAds[indexPath.row];
    MJBannerAds *bannerAds = impAds.bannerAds;
    kMJSDKTargetType targetType = bannerAds.targetType;
    //普通链接 (跳转)
    if (targetType == kMJSDKTargetType_NORMAL_LINK) {
        NSString *clickURL = bannerAds.clickUrl;
        if ([MJExceptionReportManager validateAndExceptionReport:clickURL]) {
            [MJExceptionReportManager mjGotoLandingPageUrl:clickURL before:^{
                [self suspend];
            } completion:^{
                [self resumed];
            }];
        }
    }else if(targetType == kMJSDKTargetType_BANNER_SHARE_LINK) {//横幅分享型+链接(分享)
        MJBaseInline * cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell shareInformationMethod];
    } else {
        NSLog(@"未知的 targetType");
    }
    WEAKSELF
    [MJTool responds:weakSelf.delegate toSelector:@selector(mjADDidClick:error:) block:^{
        [weakSelf.delegate mjADDidClick:weakSelf error:nil];
    }];
}
#pragma mark -
#pragma mark - components
- (id)doitBanner:(void(^)(void))bannerBlock interstitial:(void(^)(void))interstitialBlock inline:(void(^)(void))inlineBlock {
    if (self.adType == KMJADBannerInternalType) {
        if (bannerBlock) {
            bannerBlock();
        }
    }else if (self.adType == KMJADInterstitialInternalType){
        if (interstitialBlock) {
            interstitialBlock();
        }
    }else if (self.adType == KMJADInlineInternalType){
        if (inlineBlock) {
            inlineBlock();
        }
    } else {
        NSAssert(NO, @"");
    }
    return nil;
}
- (id)doitReturnBanner:(id(^)(void))bannerBlock interstitial:(id(^)(void))interstitialBlock inline:(id(^)(void))inlineBlock {
    if (self.adType == KMJADBannerInternalType) {
        if (bannerBlock) {
            return bannerBlock();
        }
    }else if (self.adType == KMJADInterstitialInternalType){
        if (interstitialBlock) {
            return interstitialBlock();
        }
    }else if (self.adType == KMJADInlineInternalType){
        if (inlineBlock) {
            return inlineBlock();
        }
    } else {
        NSAssert(NO, @"");
    }
    return nil;
}
- (void)updateMask {

    if(self.backgroundLayer) {

        [self.backgroundLayer removeFromSuperlayer];
        self.backgroundLayer = nil;

    }
    switch (self.defaultMaskType) {

        case LXMJViewMaskTypeCustom:
        case LXMJViewMaskTypeBlack:{

            self.backgroundLayer = [CALayer layer];
            self.backgroundLayer.frame = self.bounds;
            self.backgroundLayer.backgroundColor = self.defaultMaskType == LXMJViewMaskTypeCustom ? self.backgroundLayerColor.CGColor : [UIColor colorWithWhite:0 alpha:0.4].CGColor;
            [self.backgroundLayer setNeedsDisplay];

            [self.layer insertSublayer:self.backgroundLayer atIndex:0];
            break;
        }

        case LXMJViewMaskTypeGradient:{
            MJGradientLayer *layer = [MJGradientLayer layer];
            self.backgroundLayer = layer;
            self.backgroundLayer.frame = self.bounds;
            CGPoint gradientCenter = self.center;
            gradientCenter.y = (self.bounds.size.height - 0)/2;//self.visibleKeyboardHeight
            layer.gradientCenter = gradientCenter;
            [self.backgroundLayer setNeedsDisplay];

            [self.layer insertSublayer:self.backgroundLayer atIndex:0];
            break;
        }
        default:{
            [self setUserInteractionEnabled:NO];
            break;
        }
    }
}
#pragma mark -
#pragma mark - masonry
- (void)layoutSubviews {
    [super layoutSubviews];
    CGRect bounds = self.mjLabADLogo.bounds;
    if (bounds.size.width <= 0) {
        bounds = CGRectMake(0, 0, 26, 12);
    }
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerTopLeft cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.mjLabADLogo.bounds;
    maskLayer.path = maskPath.CGPath;
    self.mjLabADLogo.layer.mask = maskLayer;
    //
    [self doitBanner:nil interstitial:^{
        [self updateMask];
    } inline:nil];
}
//- (void)updateConstraints{
//    [super updateConstraints];
//    //
//    [self masonry];
//}
- (void)masonry
{
    [self doitBanner:^{
        UIView *superView = [self superview];
        [self mas_remakeConstraints:^(MASConstraintMaker *make) {
            //
            make.edges.equalTo(superView).priorityLow();
            make.width.lessThanOrEqualTo(@(kMainScreen_suitWidth));
            make.centerX.equalTo(superView);
            make.height.equalTo(@(kADBannerHeight));
            if (self.position == KMJADTopPosition) {
                make.top.equalTo(superView).offset(20.f);
            }else if (self.position == KMJADBottomPosition) {
                make.bottom.equalTo(superView);
            }
        }];
        [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.edges.equalTo(self);
        }];
        [self.btnClose mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.top.equalTo(self).offset(5);
            make.right.equalTo(self).offset(-5);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        [self.mjLabADLogo mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.right.equalTo(self);
            make.bottom.equalTo(self);
        }];
    } interstitial:^{
        UIView *superView = [self superview];
        [self mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.edges.equalTo(superView);
        }];

        [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.center.equalTo(superView);
            make.size.mas_equalTo(CGSizeMake(300.f, 250.f));
        }];
        [self.btnClose mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.top.equalTo(self.table).offset(5);
            make.right.equalTo(self.table).offset(-5);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        [self.mjLabADLogo mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.right.equalTo(self.table);
            make.bottom.equalTo(self.table);
        }];
    } inline:^{
        UIView *superView = [self superview];

        [self mas_remakeConstraints:^(MASConstraintMaker *make) {
            //
            make.edges.equalTo(superView).priorityLow();
            make.top.equalTo(superView).offset(20.f);
            make.width.lessThanOrEqualTo(@(kMainScreen_suitWidth));
            make.centerX.equalTo(superView);
            make.height.equalTo(@(kMJInlineHeight));
        }];
        [self.table mas_remakeConstraints:^(MASConstraintMaker *make) {
            //
            make.edges.equalTo(self);
        }];
        [self.btnClose mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.top.equalTo(self).offset(5);
            make.right.equalTo(self).offset(-5);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        [self.mjLabADLogo mas_makeConstraints:^(MASConstraintMaker *make) {
            //
            make.right.equalTo(self).offset(-5.f);
            make.bottom.equalTo(self).offset(-5.f);
        }];
    }];
}
#pragma mark -
#pragma mark - setter/getter

#pragma mark - closed methods

#pragma mark -
#pragma mark - block

#pragma mark - table
- (UITableView *)table
{
    if(!_table){
        //初始化一个 tableView
        //
        _table = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _table.tableFooterView = [[UIView alloc]init];
        [_table setShowsVerticalScrollIndicator:NO];
        [_table setShowsHorizontalScrollIndicator:NO];
        _table.scrollEnabled = NO;
    }
    return _table;
}
#pragma mark -
#pragma mark - setter|getter
- (void)setAdSpaceID:(NSString *)adSpaceID {
    if ([adSpaceID isEqualToString:_adSpaceID]) {
        return;
    }
    _adSpaceID = adSpaceID;
    [self resetStatus];
    if (kMJPreLoadData) {
        [self preloadData:nil];
    }
}
#pragma mark - btnClose
- (UIButton *)btnClose
{
    if(!_btnClose){

        _btnClose = [MJFactory MJADClose];
        //绑定事件
        [_btnClose addTarget:self action:@selector(btnCloseClick:) forControlEvents:UIControlEventTouchUpInside];
    }

    return _btnClose;
}
- (void)btnCloseClick:(id)sender
{
    //        UIButton *btn = (UIButton *)sender;
    //
    self.isShow = NO;
    [self removeFromSuperview];
    [self mjDidSIMBannerClosed:nil];
    //    [[NSNotificationCenter defaultCenter]postNotificationName:kMJSDKDidBannerClosedNotification object:self];
}
#pragma mark - mjLabADLogo
- (UILabel *)mjLabADLogo
{
    if(!_mjLabADLogo){
        _mjLabADLogo = [MJFactory MJADLogoLab];
    }
    return _mjLabADLogo;
}

@end


text:
package integration.pagefragments;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Before;
import org.junit.Test;

import integration.BaseIntegrationTest;
import utils.events.EventCaptor;

import info.novatec.testit.webtester.events.pagefragments.ClearedEvent;
import info.novatec.testit.webtester.events.pagefragments.EnterPressedEvent;
import info.novatec.testit.webtester.events.pagefragments.TextAppendedEvent;
import info.novatec.testit.webtester.events.pagefragments.TextSetEvent;
import info.novatec.testit.webtester.pagefragments.TextField;
import info.novatec.testit.webtester.pagefragments.annotations.IdentifyUsing;
import info.novatec.testit.webtester.pagefragments.mapping.MappingException;
import info.novatec.testit.webtester.pages.Page;

public class TextFieldIntegrationTest extends BaseIntegrationTest {

    TestPage page;

    @Override
    protected String getHTMLFilePath() {
        return "html/pagefragments/textField.html";
    }

    @Before
    public void initPage() {
        page = create(TestPage.class);
    }

    /* set text */

    @Test
    public void textCanBeSet() {
        TextField textField = page.empty().setText("foo");
        assertThat(textField.getText()).isEqualTo("foo");
    }

    @Test
    public void settingTextFiresEvent() {
        EventCaptor.capture(eventSystem(), TextSetEvent.class)
            .execute(() -> page.empty().setText("foo"))
            .assertEventWasFired()
            .assertEvent(event -> {
                assertThat(event.getBefore()).isEqualTo("");
                assertThat(event.getAfter()).isEqualTo("foo");
            });
    }

    @Test
    public void textOfTextFieldWithMaxLengthMightOnlyBePartiallySet() {
        TextField textField = page.maxLength().setText("1234567890");
        assertThat(textField.getText()).isEqualTo("12");
    }

    /* append text */

    @Test
    public void textCanBeAppended() {
        TextField element = page.withValue().appendText(" with appended text");
        assertThat(element.getText()).isEqualTo("value with appended text");
    }

    @Test
    public void appendingTextFiresEvent() {
        EventCaptor.capture(eventSystem(), TextAppendedEvent.class)
            .execute(() -> page.withValue().appendText(" with appended text"))
            .assertEventWasFired()
            .assertEvent(event -> {
                assertThat(event.getBefore()).isEqualTo("value");
                assertThat(event.getAfter()).isEqualTo("value with appended text");
            });
    }

    @Test
    public void textOfTextFieldWithMaxLengthMightOnlyBePartiallyAppended() {
        TextField textField = page.withValueAndMaxLength().appendText("3456");
        assertThat(textField.getText()).isEqualTo("123");
    }

    /* clear */

    @Test
    public void textCanBeCleared() {
        TextField textField = page.withValue().clear();
        assertThat(textField.getText()).isEmpty();
    }

    @Test
    public void clearingTextFiresEvent() {
        EventCaptor.capture(eventSystem(), ClearedEvent.class)
            .execute(() -> page.withValue().clear())
            .assertEventWasFired();
    }

    /* get text */

    @Test
    public void gettingTextReturnsItAsString() {
        assertThat(page.withValue().getText()).isEqualTo("value");
    }

    @Test
    public void gettingTextOfEmptyFieldReturnsEmptyString() {
        assertThat(page.empty().getText()).isEqualTo("");
    }

    /* get visible text */

    @Test
    public void gettingVisibleTextOfEmptyFieldReturnsEmptyString() {
        assertThat(page.empty().getVisibleText()).isEqualTo("");
    }

    @Test
    public void gettingVisibleTextReturnsString() {
        assertThat(page.withValue().getVisibleText()).isEqualTo("value");
    }

    /* pressing enter */

    @Test
    public void pressingEnterSendsForm(){
        page.enterTextField().pressEnter();
        assertThat(currentPageTitle()).isEqualTo("Target Page");
    }

    @Test
    public void pressingEnterFiresEvent(){
        EventCaptor.capture(eventSystem(), EnterPressedEvent.class)
            .execute(() -> page.enterTextField().pressEnter())
            .assertEventWasFired();
    }

    /* mapping */

    @Test
    public void inputNoTypeIsValidMapping() {
        assertPageFragmentCanBeInitialized(page.inputNone());
    }

    @Test
    public void inputEmptyTypeIsValidMapping() {
        assertPageFragmentCanBeInitialized(page.inputEmpty());
    }

    @Test
    public void inputTextTypeIsValidMapping() {
        assertPageFragmentCanBeInitialized(page.inputText());
    }

    @Test(expected = MappingException.class)
    public void nonTextFieldTypeIsInvalidMapping() {
        assertPageFragmentCanBeInitialized(page.noTextField());
    }

    public interface TestPage extends Page {

        @IdentifyUsing("#maxLength")
        TextField maxLength();

        @IdentifyUsing("#empty")
        TextField empty();
        @IdentifyUsing("#withValue")
        TextField withValue();
        @IdentifyUsing("#withValueAndMaxLength")
        TextField withValueAndMaxLength();

        @IdentifyUsing("#input_none")
        TextField inputNone();
        @IdentifyUsing("#input_empty")
        TextField inputEmpty();
        @IdentifyUsing("#input_text")
        TextField inputText();
        @IdentifyUsing("#noTextField")
        TextField noTextField();

        @IdentifyUsing("#enterTextField")
        TextField enterTextField();

    }

}


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.Emulation
{
	/// <summary>
	/// Sets a specified page scale factor.
	/// </summary>
	[CommandResponse(ProtocolName.Emulation.SetPageScaleFactor)]
	public class SetPageScaleFactorCommandResponse
	{
	}
}


text:
class Admin::Academy::TutorialsController < Admin::ApplicationController
	before_action :set_academy_tutorial, only: [:show, :edit, :update, :destroy]

	def index
		@aproved_tutorials = Academy::Tutorial.aproved_tutorials
		@unaproved_tutorials = Academy::Tutorial.unaproved_tutorials
		@tutorials = Academy::Tutorial.all
		authorize! :read, @aproved_tutorials
	end

	def show

	end

	def edit

	end

	def aprove_tutorial
		tutorial = Academy::Tutorial.find(params[:id_aprove])
		tutorial.aproved = true
		tutorial.save

		#cria notificação
    Notification.create_notification( tutorial.user_id , tutorial.id , 6 , "Tutorial Aprovado")

		redirect_to admin_academy_tutorials_path,:notice => "Tutorial foi aprovado com sucesso"

		owner_user = User.find_by_id(tutorial.user_id)

		owner_user.followers.each do | user|

			feed = Feed.new
			feed.user_id = user.id
			feed.in = 3
			feed.id_content = tutorial.id
			feed.save

		end
	end

  def destroy
    #@academy_tutorial.destroy
    dest = @academy_tutorial.id
    type = 6 #aproved_tutorial_code
    Notification.clear_notifications(type,dest)
    @academy_tutorial.is_deleted = true
    @academy_tutorial.save
    respond_to do |format|
      format.html { redirect_to admin_academy_tutorials_url }
      format.json { head :no_content }
    end
  end

private
	    # Use callbacks to share common setup or constraints between actions.
	    def set_academy_tutorial
	    	@academy_tutorial = Academy::Tutorial.find(params[:id])
	    	@categories = Category.all
	    	authorize! :read, nil
	    end

	    # Never trust parameters from the scary internet, only allow the white list through.
	    def academy_tutorial_params
	    	params.require(:academy_tutorial).permit(:category_id,:rapid_description, :user_id, :aproved, :title, :text, :is_delected)
	    end

	end


text:
#include "postgres.h"

#include "access/multixact.h"
#include "access/twophase_rmgr.h"
#include "commands/async.h"
#include "pgstat.h"
#include "storage/lock.h"
#include "utils/flatfiles.h"
#include "utils/inval.h"

const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID + 1] =
{
	NULL,						/* END ID */
	lock_twophase_recover,		/* Lock */
	NULL,						/* Inval */
	NULL,						/* flat file update */
	NULL,						/* notify/listen */
	NULL,						/* pgstat */
	multixact_twophase_recover	/* MultiXact */
};

const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID + 1] =
{
	NULL,						/* END ID */
	lock_twophase_postcommit,	/* Lock */
	inval_twophase_postcommit,	/* Inval */
	flatfile_twophase_postcommit,		/* flat file update */
	notify_twophase_postcommit, /* notify/listen */
	pgstat_twophase_postcommit,	/* pgstat */
	multixact_twophase_postcommit /* MultiXact */
};

const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID + 1] =
{
	NULL,						/* END ID */
	lock_twophase_postabort,	/* Lock */
	NULL,						/* Inval */
	NULL,						/* flat file update */
	NULL,						/* notify/listen */
	pgstat_twophase_postabort,	/* pgstat */
	multixact_twophase_postabort /* MultiXact */
};


text:
#ifndef UTILITIES_H
#define UTILITIES_H

#ifndef DEBUG
#define OMP_ENABLE
#endif

#if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
	#define OS_WIN
#endif

typedef unsigned short u_short;

inline u_short wrap(int x, u_short d) {

	// One cannot trust result of (x % b) with negative
	// input x for various compilers:
	// http://www.learncpp.com/cpp-tutorial/32-arithmetic-operators/
	// Hence we take abs(x) first

	if(x > 0)
		return x % d;
	else if((-x) % d == 0)
		return 0;
	else
		return d - ((-x) % d);
}

/*
#include <string>
#include <vector>
#include <dirent.h>
#include <sys/types.h>

using namespace std;

vector<string> directoryListing(const char * directory);

vector<string> split(const string &s, char delim, vector<string> &elems);
vector<string> split(const string &s, char delim);
vector<string> split(const char * s, char delim);

template <class T>
vector<T> splitAndConvert(char * s);

template <class T>
T convert(char * s);
*/
#endif // UTILITIES_H


text:
/*
** $Id: lpvm.h,v 1.3 2014/02/21 13:06:41 roberto Exp $
*/

#if !defined(lpvm_h)
#define lpvm_h

#include "lpcap.h"

/* Virtual Machine's instructions */
typedef enum Opcode {
  IAny, /* if no char, fail */
  IChar,  /* if char != aux, fail */
  ISet,  /* if char not in buff, fail */
  ITestAny,  /* in no char, jump to 'offset' */
  ITestChar,  /* if char != aux, jump to 'offset' */
  ITestSet,  /* if char not in buff, jump to 'offset' */
  ISpan,  /* read a span of chars in buff */
  IBehind,  /* walk back 'aux' characters (fail if not possible) */
  IRet,  /* return from a rule */
  IEnd,  /* end of pattern */
  IChoice,  /* stack a choice; next fail will jump to 'offset' */
  IJmp,  /* jump to 'offset' */
  ICall,  /* call rule at 'offset' */
  IOpenCall,  /* call rule number 'key' (must be closed to a ICall) */
  ICommit,  /* pop choice and jump to 'offset' */
  IPartialCommit,  /* update top choice to current position and jump */
  IBackCommit,  /* "fails" but jump to its own 'offset' */
  IFailTwice,  /* pop one choice and then fail */
  IFail,  /* go back to saved state on choice and jump to saved offset */
  IGiveup,  /* internal use */
  IFullCapture,  /* complete capture of last 'off' chars */
  IOpenCapture,  /* start a capture */
  ICloseCapture,
  ICloseRunTime
} Opcode;

typedef union Instruction {
  struct Inst {
    byte code;
    byte aux;
    short key;
  } i;
  int offset;
  byte buff[1];
} Instruction;

void printpatt (Instruction *p, int n);
const char *match (lua_State *L, const char *o, const char *s, const char *e,
		   Instruction *op, Capture *capture, int ptop);

#endif


text:
using System;
using System.Runtime.InteropServices;

namespace Vlc.DotNet.Core.Interops.Signatures
{
    [LibVlcFunction("libvlc_media_player_set_video_title_display")]
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    internal delegate void SetVideoTitleDisplay(IntPtr mp, Position position, int timeout);
}


text:
package deployment

import (
	"errors"
	"reflect"
	"testing"

	"github.com/kubernetes/dashboard/src/app/backend/api"
	metricapi "github.com/kubernetes/dashboard/src/app/backend/integration/metric/api"
	"github.com/kubernetes/dashboard/src/app/backend/resource/common"
	"github.com/kubernetes/dashboard/src/app/backend/resource/dataselect"
	k8serrors "k8s.io/apimachinery/pkg/api/errors"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	v1 "k8s.io/client-go/pkg/api/v1"
	extensions "k8s.io/client-go/pkg/apis/extensions/v1beta1"
)

func getReplicasPointer(replicas int32) *int32 {
	return &replicas
}

func TestGetDeploymentListFromChannels(t *testing.T) {
	cases := []struct {
		k8sDeployment      extensions.DeploymentList
		k8sDeploymentError error
		pods               *v1.PodList
		expected           *DeploymentList
		expectedError      error
	}{
		{
			extensions.DeploymentList{},
			nil,
			&v1.PodList{},
			&DeploymentList{
				ListMeta:          api.ListMeta{},
				Deployments:       []Deployment{},
				CumulativeMetrics: make([]metricapi.Metric, 0),
				Errors:            []error{},
			},
			nil,
		},
		{
			extensions.DeploymentList{},
			errors.New("MyCustomError"),
			&v1.PodList{},
			nil,
			errors.New("MyCustomError"),
		},
		{
			extensions.DeploymentList{},
			&k8serrors.StatusError{},
			&v1.PodList{},
			nil,
			&k8serrors.StatusError{},
		},
		{
			extensions.DeploymentList{},
			&k8serrors.StatusError{ErrStatus: metaV1.Status{}},
			&v1.PodList{},
			nil,
			&k8serrors.StatusError{ErrStatus: metaV1.Status{}},
		},
		{
			extensions.DeploymentList{},
			&k8serrors.StatusError{ErrStatus: metaV1.Status{Reason: "foo-bar"}},
			&v1.PodList{},
			nil,
			&k8serrors.StatusError{ErrStatus: metaV1.Status{Reason: "foo-bar"}},
		},
		{
			extensions.DeploymentList{
				Items: []extensions.Deployment{{
					ObjectMeta: metaV1.ObjectMeta{
						Name:              "rs-name",
						Namespace:         "rs-namespace",
						Labels:            map[string]string{"key": "value"},
						CreationTimestamp: metaV1.Unix(111, 222),
					},
					Spec: extensions.DeploymentSpec{
						Selector: &metaV1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}},
						Replicas: getReplicasPointer(21),
					},
					Status: extensions.DeploymentStatus{
						Replicas: 7,
					},
				}},
			},
			nil,
			&v1.PodList{},
			&DeploymentList{
				ListMeta:          api.ListMeta{TotalItems: 1},
				CumulativeMetrics: make([]metricapi.Metric, 0),
				Deployments: []Deployment{{
					ObjectMeta: api.ObjectMeta{
						Name:              "rs-name",
						Namespace:         "rs-namespace",
						Labels:            map[string]string{"key": "value"},
						CreationTimestamp: metaV1.Unix(111, 222),
					},
					TypeMeta: api.TypeMeta{Kind: api.ResourceKindDeployment},
					Pods: common.PodInfo{
						Current:  7,
						Desired:  getReplicasPointer(21),
						Failed:   0,
						Warnings: []common.Event{},
					},
				}},
				Errors: []error{},
			},
			nil,
		},
	}

	for _, c := range cases {
		channels := &common.ResourceChannels{
			DeploymentList: common.DeploymentListChannel{
				List:  make(chan *extensions.DeploymentList, 1),
				Error: make(chan error, 1),
			},
			NodeList: common.NodeListChannel{
				List:  make(chan *v1.NodeList, 1),
				Error: make(chan error, 1),
			},
			ServiceList: common.ServiceListChannel{
				List:  make(chan *v1.ServiceList, 1),
				Error: make(chan error, 1),
			},
			PodList: common.PodListChannel{
				List:  make(chan *v1.PodList, 1),
				Error: make(chan error, 1),
			},
			EventList: common.EventListChannel{
				List:  make(chan *v1.EventList, 1),
				Error: make(chan error, 1),
			},
			ReplicaSetList: common.ReplicaSetListChannel{
				List:  make(chan *extensions.ReplicaSetList, 1),
				Error: make(chan error, 1),
			},
		}

		channels.DeploymentList.Error <- c.k8sDeploymentError
		channels.DeploymentList.List <- &c.k8sDeployment

		channels.NodeList.List <- &v1.NodeList{}
		channels.NodeList.Error <- nil

		channels.ServiceList.List <- &v1.ServiceList{}
		channels.ServiceList.Error <- nil

		channels.PodList.List <- c.pods
		channels.PodList.Error <- nil

		channels.EventList.List <- &v1.EventList{}
		channels.EventList.Error <- nil

		channels.ReplicaSetList.List <- &extensions.ReplicaSetList{}
		channels.ReplicaSetList.Error <- nil

		actual, err := GetDeploymentListFromChannels(channels, dataselect.NoDataSelect, nil)
		if !reflect.DeepEqual(actual, c.expected) {
			t.Errorf("GetDeploymentListFromChannels() ==\n          %#v\nExpected: %#v", actual, c.expected)
		}
		if !reflect.DeepEqual(err, c.expectedError) {
			t.Errorf("GetDeploymentListFromChannels() ==\n          %#v\nExpected: %#v", err, c.expectedError)
		}
	}
}


text:
<?php

	/* Constant:	  conn_string;                                                                *\
	 * Description:   Connection string. Uses the format:                                         *
	\*                mysql://username:password@hostname/database                                 */
define("conn_string", "mysql://root:root@localhost:8888/bookmarks");

	/* Constant:	  EMAIL_REGISTRATION;                                                         *\
	 * Description:   If 1 then the use4r must activate the account after registration via a link *
	 *                sent by email. Helpful to check the validity of the email.                  *
	\*                If 0 the user will be automatically logged in after registration.           */
define("EMAIL_REGISTRATION", "0");

	/* Constant:	  site_root;                                                                  *\
	\ * Description:   Main root of the project.                                                   */
define("site_root", "http://localhost/bookmarks");

?>


text:
<properties
	pageTitle="Get Started with a Visual Studio .NET mobile services project (Connected Services) | Microsoft Azure"
	description="How to get started with Azure Mobile Services in a Visual Studio .NET project"
	services="mobile-services"
	documentationCenter=""
	authors="mlhoop"
	manager="douge"
	editor=""/>

<tags
	ms.service="mobile-services"
	ms.workload="mobile"
	ms.tgt_pltfrm="vs-getting-started"
	ms.devlang="dotnet"
	ms.topic="article"
	ms.date="07/21/2016"
	ms.author="mlearned"/>

# Getting Started with Mobile Services (.NET Projects)

>[AZURE.WARNING] This is an **Azure Mobile Services** topic.  This service has been superseded by Azure App Service Mobile Apps and is scheduled for removal from Azure.  We recommend using Azure Mobile Apps for all new mobile backend deployments.  Read [this announcement](https://azure.microsoft.com/blog/transition-of-azure-mobile-services/) to learn more about the pending deprecation of this service.
>
> Learn about [migrating your site to Azure App Service](https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-migrating-from-mobile-services/).
>
> Get started with Azure Mobile Apps, see the [Azure Mobile Apps documentation center](https://azure.microsoft.com/documentation/learning-paths/appservice-mobileapps/).

The first step you need to do in order to follow the code in these examples depends on what type of mobile service you connected to.

- For a JavaScript backend mobile service, create a table called TodoItem.  To create a table,  locate the mobile service under the Azure node in Server Explorer, right-click the mobile service's node to open the context menu, and choose **Create Table**. Enter "TodoItem" as the table name.

- If you have a .NET backend mobile service, there's already a TodoItem table in the default project template that Visual Studio created for you, but you need to publish it to Azure. To publish it, open the context menu for the mobile service project in Solution Explorer, and choose **Publish Web**. Accept the defaults, and choose the **Publish** button.

##Get a reference to a table

The following code creates a reference to a table (`todoTable`) that contains data for a TodoItem, which you can use in subsequent operations to read and update the data table. You'll need the TodoItem class with attributes set up to interpet the JSON that the mobile service sends in response to your queries.

	public class TodoItem
    {
        public string Id { get; set; }

        [JsonProperty(PropertyName = "text")]
        public string Text { get; set; }

        [JsonProperty(PropertyName = "complete")]
        public bool Complete { get; set; }
    }

	IMobileServiceTable<TodoItem> todoTable = App.<yourClient>.GetTable<TodoItem>();

This code works if your table has permissions set to **Anybody with an Application Key**. If you change the permissions to secure your mobile service, you'll need to add user authentication support. See [Get Started with Authentication](mobile-services-dotnet-backend-windows-universal-dotnet-get-started-users.md).

##Add a table item

Insert a new item into a data table.

	TodoItem todoItem = new TodoItem() { Text = "My first to do item", Complete = false };
	await todoTable.InsertAsync(todoItem);

##Read or query a table

The following code queries a table for all items. Note that it returns only the first page of data, which by default is 50 items. You can pass the page size you want, since it's an optional parameter.

    List<TodoItem> items;
    try
    {
        // Query that returns all items.
        items = await todoTable.ToListAsync();
    }
    catch (MobileServiceInvalidOperationException e)
    {
        // handle exception
    }

##Update a table item

Update a row in a data table. The parameter item is the TodoItem object to be updated.

	await todoTable.UpdateAsync(item);

##Delete a table item

Delete a row in the database. The parameter item is the TodoItem object to be deleted.

	await todoTable.DeleteAsync(item);

[Learn more about mobile services](https://azure.microsoft.com/documentation/services/mobile-services/)


text:
package org.strategy.world;

import java.util.ArrayList;
import java.util.HashMap;

import org.engine.physics.Enviroment;
import org.engine.rendeing.material.Material;
import org.engine.rendeing.material.Texture2D;
import org.engine.rendeing.model.Model;
import org.engine.util.Maths;
import org.json.JSONObject;
import org.lwjgl.util.vector.Matrix4f;
import org.strategy.entity.player.Player;
import org.strategy.rendering.RenderingEngineStrategy;

import glib.util.vector.GMatrix4f;
import glib.util.vector.GVector3f;

public class Block extends BasicBlock{
	public final static int VOID = 0;
	public final static int GRASS = 1;
	public final static int DIRT = 2;
	public final static int ROCK = 3;
	public final static int WATER = 4;
	public final static int WOOD = 5;
	public final static int IRON = 6;
	public final static int BRICK = 7;
	public final static int LAVA = 8;
	public final static int CONCRETE = 9;
	public final static int TILE = 10;
	public final static int PATH = 11;

	private final static int MAX_COLLISION_DISTANCE = 100;

//	private ArrayList<Block> dependOn = new ArrayList<Block>();
//	private LinkedHashSet<Block> connection = new LinkedHashSet<Block>();
	private Block[] neightboars = new Block[6];
	public static int WIDTH = 1;
	public static int HEIGHT = 1;
	public static int DEPTH = 1;
	private World world;
	public static final HashMap<Integer,JSONObject> blockDatas;
	private static final Model[] model = new Model[6];
	private GVector3f direction = new GVector3f();
//	private boolean fall = false;
	private boolean clickable = true;
	private GVector3f relativePos = new GVector3f();

	private boolean[] sides = new boolean[]{true,true,true,true,true,true};
	static{
		blockDatas = new HashMap<Integer,JSONObject>();
		getBlockData();
		model[0] = getTop();
		model[1] = getRight();
		model[2] = getBottom();
		model[3] = getLeft();
		model[4] = getBack();
		model[5] = getForward();
	}

	// CONTRUCTORS

	public Block(GVector3f position, int type) {
		super(position, type);
		direction = new GVector3f();
	}

	public Block(JSONObject data){
		super(new GVector3f((float)data.getDouble("posX"),(float)data.getDouble("posY"),(float)data.getDouble("posZ")),data.getInt("typ"));
		direction = new GVector3f();
	}

	//OTHERS

	private void startFalling(Chunk3D c){
		if(!direction.isNull())
			return;

//		world.remove(this,false);
		clickable = false;
		direction = new GVector3f(0,-0.001,0);
//		relativePos = new GVector3f(0,Block.HEIGHT,0);
//		c.moveDown(this);
	}

	public static void getBlockData(){
		String postFix = "_64.jpg";
		JSONObject adding = new JSONObject();
		adding.put("name", "Grass");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 0.1);//specularIntensity
		adding.put("sp", 15);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(GRASS, adding);

		adding = new JSONObject();
		adding.put("name", "Dirt");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 0.2);//specularIntensity
		adding.put("sp", 10);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(DIRT, adding);

		adding = new JSONObject();
		adding.put("name", "Rock");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 0.5);//specularIntensity
		adding.put("sp", 8);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(ROCK, adding);

		adding = new JSONObject();
		adding.put("name", "Water");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", true);//transparent
		adding.put("si", 0.7);//specularIntensity
		adding.put("sp", 15);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(WATER, adding);

		adding = new JSONObject();
		adding.put("name", "Wood");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 0.1);//specularIntensity
		adding.put("sp", 8);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(WOOD, adding);

		adding = new JSONObject();
		adding.put("name", "Iron");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 1);//specularIntensity
		adding.put("sp", 50);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(IRON, adding);

		adding = new JSONObject();
		adding.put("name", "Brick");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 0.2);//specularIntensity
		adding.put("sp", 8);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(BRICK, adding);

		adding = new JSONObject();
		adding.put("name", "Lava");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 0.1);//specularIntensity
		adding.put("sp", 8);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(LAVA, adding);

		adding = new JSONObject();
		adding.put("name", "Concrete");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 0.5);//specularIntensity
		adding.put("sp", 8);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(CONCRETE, adding);

		adding = new JSONObject();
		adding.put("name", "Tile");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 1.001);//specularIntensity
		adding.put("sp", 80);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(TILE, adding);

		adding = new JSONObject();
		adding.put("name", "Path");
		adding.put("rX", 1);//repeatY
		adding.put("rY", 1);//repeatX
		adding.put("rep", true);//repeat
		adding.put("t", false);//transparent
		adding.put("si", 0.2);//specularIntensity
		adding.put("sp", 8);//specularPower
		adding.put("mat",new Material(new Texture2D(adding.getString("name").toLowerCase()+postFix), adding.getInt("si"), adding.getInt("sp")));
		blockDatas.put(PATH, adding);
	}

	private boolean checkFall(ArrayList<Block> b, int level){
		if(level<=0)
			return true;
		for(int i=0 ; i<6 ; i++){
			if(neightboars[i] != null){
				if(!b.contains(neightboars[i])){
					b.add(neightboars[i]);
					if(neightboars[i].checkFall(b, level-1))
						return true;
				}
			}
		}
		return false;
	}

	public void removeNeighboard(Block b){
		for(int i=0 ; i<6 ; i++){
			if(neightboars[i] == b){
				neightboars[i] = null;
				return;
			}
		}
	}

	public void remove(Chunk3D c) {
		for(int i=0 ; i<6 ; i++){
			Block b = neightboars[i];
			if(b!=null){
				b.removeNeighboard(this);
				if(b.checkFall())
					b.startFalling(c);
				ArrayList<Block> collizable = new ArrayList<Block>();
				if(!b.checkFall(collizable,MAX_COLLISION_DISTANCE)){
					for(int j=0 ; j<collizable.size() ; j++){
						Block n = collizable.get(j);
						n.startFalling(c);
					}
				}
			}
		}
	}

	private boolean checkFall() {
		for(int i=0 ; i<6 ; i++){
			if(neightboars[i]!=null)
				return false;

		}
		return true;
	}

	//OVERRIDES

	public GMatrix4f getTransformationMatrix(){
		Matrix4f trans = Maths.createTransformationMatrix(getPosition().add(relativePos),getRotation(), getScale());
		return Maths.MatrixToGMatrix(trans);
	}

	public String toString(){
		return "typ: "+blockDatas.get(type).getString("name");
	}

	public void render(RenderingEngineStrategy renderingEngine) {
		renderingEngine.renderBlock(this);
	}

	public void update(){
		if(!direction.isNull()){
			relativePos = relativePos.add(direction);
			if(direction.getY() > -Player.MAX_FALLING_SPEED);
				direction = direction.add(Enviroment.GRAVITY);
			if(world != null && getPosition() != null && relativePos != null ){
				Block imp = world.getBlock(getPosition().add(relativePos).sub(new GVector3f(0,Block.HEIGHT,0)));
				if(imp != null && imp.isClickable()){
					world.blockInpact(this,imp);
				}
			}
		}
	}

	//GETTERS

	public World getWorld() {
		return world;
	}

	public boolean getSide(int side){
		return sides[side];
	}

	public boolean isClickable() {
		return clickable;
	}

	public GVector3f getRelativePos() {
		return relativePos;
	}

	public Model getModel(int i) {
		return model[i];
	}

	//SETTERS

	public void setWorld(World world) {
		this.world = world;
	}

	public void setNeighboard(int i, Block val){
		neightboars[i] = val;
	}

	public void setSide(int side, boolean value){
		sides[side] = value;
		active = sides[0] || sides[1] || sides[2] || sides[3] || sides[4] || sides[5] ;
	}

	public void setClickable(boolean clickable) {
		this.clickable = clickable;
	}

}


text:
<?php
/*-------------------------------------------------------
*
*	Plugin "AmazonS3"
*	Author: Vladimir Yuriev (extravert)
*	Official site: lsmods.ru
*	Contact e-mail: support@lsmods.ru
*
---------------------------------------------------------
*/

if (!class_exists('Plugin')) {
  die('Hacking attemp!');
}

class PluginAmazons3 extends Plugin {

	protected $aInherits=array(
	   'module'  => array(
			'ModuleTopic',
			'ModuleImage',
			'PluginLsgallery_ModuleImage'=>'_ModuleGalleryimage'
		),
		'entity'  =>array('PluginLsgallery_ModuleImage_EntityImage'=>'_ModuleGalleryimage_EntityImage'),

	);

	public function Init() {
        return true;
	}

	public function Activate() {
		return true;
	}

	public function Deactivate() {
		return true;
	}
}


text:
Dammit, Dann, this is getting to be a habit.

I haven't gotten to the bottom of the squares problem yet, and yesterday was the monthly Toronto Code Retreat. Which means my time is effectively up thanks to this new problem we're being handed. I'm sure there's a canonical, three-line solution out there somewhere, but I didn't want to read up on it until after the event, so I'm thinking at this from first principles. As a result, it won't be pretty or optimized.

### The Problem

Near as I can tell, [Sudoku](http://en.wikipedia.org/wiki/Sudoku) is a Set problem. This isn't how I first heard the rules described, but it fits. A solved Sudoku board is one where

- each number is filled in
- each row is a set
- each column is a set
- each disjoint `nxn` square is a set (where `n` is the square root of the board size)

we'll call this "The Sudoku Property"

Now there's actually two problems; one is generating boards and one is solving boards. Solving seems to be pretty straightforward:

1.   take a board
1.   optionally, fill in all obvious squares until there are no more (an obvious square is one where only one legal move exists)
1.   for each blank square, try each possibility

If it can't be done, you've got an unsolvable board. If it can, return the first solution you find[|1|](#foot-Wed-May-22-155922EDT-2013). That seems to be that.

Generating is a bit of a different story. The naive solution is to generate a bunch of numbers and place them onto a board such that they respect TSP. Essentially, we're solving an empty board by starting with some random seeds. It really seems like this should work, but I can't convince myself that placing a number in an empty square while respecting the TSP will *certainly* avoid generating impossible boards. That is, an otherwise valid board which contains one or more empty squares whose set of possibilities is the empty set. It might be a better idea to start with nine sets and perform some sort transformation on it until we get something that respects TSP, rather than building it up piecemeal.

### The Event

We did this pretty casually. The problem as presented was to solve boards generated by [this site](http://www.sudoku-solutions.com/), and not bother with the generation side of things. In practice, no group ever got to the point of a general brute-force Sudoku solver. Three groups managed to solve obvious boards (ones where it's possible to find a complete solution without guessing), and one managed to hook together a [bogosort](http://en.wikipedia.org/wiki/Bogosort)-style solution that could, in principle, if we left it running for a few years, solve an arbitrary 9x9 Sudoku board.

We went the usual three sessions, and I did my usual and used a different language each time. First up, we had a mostly-ideation session in which we ostensibly worked in Python. The only snippet I've got left over from that is

```haskell
def makeBoard(regionWidth):
    side = regionWidth * regionWidth
    return [[0 for x in xrange(side)] for y in xrange(side)]

sample = [[0, 7, 1, 4, 0, 0, 0, 0, 5],
          [0, 0, 0, 0, 5, 0, 0, 8, 0],
          [0, 0, 3, 9, 0, 7, 6, 0, 0],
          [0, 0, 0, 0, 0, 1, 0, 0, 0],
          [0, 9, 0, 8, 0, 6, 0, 0, 3],
          [0, 0, 0, 0, 0, 0, 8, 2, 0],
          [0, 6, 0, 0, 4, 0, 7, 0, 8],
          [3, 0, 0, 0, 0, 0, 0, 9, 0],
          [0, 0, 0, 0, 8, 5, 0, 0, 0]]

def placements(board, n):
    """Return list of coords where `n` is a legal placement."""
    emptyRows = [i for i, row in enumerate(board) if not n in row]
    res = []
    for i in emptyRows:
        for j, col in enumerate(board[i]):
            if col == 0: res.append((i, j))
    return res
```

The idea would be to get a function which takes a `board` and an `n`, and finds out what the possible placements of `n` are. I'm not entirely sure how we would have proceeded if this ended up working; I think we'd have to hope really hard that at least one of the digits has only one possible position, which doesn't sound terribly likely in general. The fully implemented version of that function would also check for column and block presences, rather than just filtering rows poorly.

For round two, I got into a group of three with two people who wanted to see Haskell in action. So, after some type-system snafus, we did this:

```haskell
module Sudoku where

import Data.Set (Set(..), fromList, union, difference)
import Data.List (genericIndex, genericTake)

type Board = [[Int]]

sample :: Board
sample = [[0, 7, 1, 4, 0, 0, 0, 0, 5],
          [0, 0, 0, 0, 5, 0, 0, 8, 0],
          [0, 0, 3, 9, 0, 7, 6, 0, 0],
          [0, 0, 0, 0, 0, 1, 0, 0, 0],
          [0, 9, 0, 8, 0, 6, 0, 0, 3],
          [0, 0, 0, 0, 0, 0, 8, 2, 0],
          [0, 6, 0, 0, 4, 0, 7, 0, 8],
          [3, 0, 0, 0, 0, 0, 0, 9, 0],
          [0, 0, 0, 0, 8, 5, 0, 0, 0]]

row :: Board -> (Int, Int) -> Set Int
row board (x, y) = fromList $ genericIndex board y

col :: Board -> (Int, Int) -> Set Int
col board (x, y) = fromList $ map (flip genericIndex x) board

origin :: Int -> Int
-- origin n = 3 * fromIntegral $ floor $ n / 3
origin n
  | 3 > n = 0
  | 6 > n = 3
  | otherwise = 6

block :: Board -> (Int, Int) -> Set Int
block board (x, y) = fromList . concat . map (genericTake blockSize . drop ox) $ genericTake blockSize $ drop oy board
  where blockSize = 3
        ox = origin x
        oy = origin y

possibilities :: Board -> (Int, Int) -> Set Int
possibilities board (x, y) = difference (fromList [1..9]) b
  where a = union (row board (x, y)) $ col board (x, y)
        b = union a $ block board (x, y)
```

...which is also ugly as fuck. Let me zoom into two particular pieces for you

```haskell
origin :: Int -> Int
-- origin n = 3 * fromIntegral $ floor $ n / 3
origin n
  | 3 > n = 0
  | 6 > n = 3
  | otherwise = 6
```

That commented line is what we wanted to do initially. Actually, what we wanted was just `blockSize * (floor $ n/blockSize)`, except that `Int`s apparently don't derive `RealFrac`? I don't know what the actual problem there is, and I'll likely toss the question up to SO later, but at the time, we went with the ugly, 9x9-specific, guard-based approach.

```haskell
block :: Board -> (Int, Int) -> Set Int
block board (x, y) = fromList . concat . map (genericTake blockSize . drop ox) $ genericTake blockSize $ drop oy board
  where blockSize = 3
        ox = origin x
        oy = origin y
```

Note that `blockSize` is specified as 3. Which means that this function is *also* specific to 9x9 Sudoku boards. We went this route for the same reasons as before; the type system doesn't like it when you try to use `fromIntegral . sqrt $ length board` for some reason, and we didn't have enough time left to figure out what type annotations we'd need to convince `GHCi` that yes, this is really what we mean.

We also didn't really have enough time in one 40-minute session to write `solve`, *and* chat about Haskell *and* try to form theories about the errors we were seeing, but it's a reasonable-if-rushed implementation of the approach I was assuming we'd use.

The last session, my partner and I decided to have some fun with JavaScript. Except neither of us had `node` installed standalone, so we ended up using the Chromium JS console. Once we loaded up [underscore](http://underscorejs.org/), things went much faster than expected. We managed to put together a solution that works on any valid board size, that could solve boards where it doesn't need to guess.

```javascript
var sample4x4 = [[1, 0, 3, 0],
                 [0, 4, 0, 2],
                 [0, 3, 4 ,0],
                 [4, 0, 2, 3]];

var sample9x9 = [[0, 7, 1, 4, 0, 0, 0, 0, 5],
                 [0, 0, 0, 0, 5, 0, 0, 8, 0],
                 [0, 0, 3, 9, 0, 7, 6, 0, 0],
                 [0, 0, 0, 0, 0, 1, 0, 0, 0],
                 [0, 9, 0, 8, 0, 6, 0, 0, 3],
                 [0, 0, 0, 0, 0, 0, 8, 2, 0],
                 [0, 6, 0, 0, 4, 0, 7, 0, 8],
                 [3, 0, 0, 0, 0, 0, 0, 9, 0],
                 [0, 0, 0, 0, 8, 5, 0, 0, 0]];

function possibilities (board, x, y) {
    return _.difference(_.range(1, _.size(board[0]) + 1),
                        row(board, x, y),
                        col(board, x, y),
                        block(board, x, y))
}

function row(board, x, y) {
    return board[y];
}

function col(board, x, y) {
    return _.map(board, function (row) { row[x] })
}

function block(board, x, y) {
    var blockSize = Math.sqrt(_.size(board[0]))
    var origin = function (n) {
        return blockSize * Math.floor(n / blockSize)
    }
    var relevantRows = _.take(_.drop(board, origin(y)), blockSize);
    return _.reduce(relevantRows, function (memo, row) {
        return _.union(memo, _.take(_.drop(row, origin(y)), blockSize))
    }, []);
}

function isFilled (board) {
    return _.every(board, function (row) { _.every(row, function (val) { val != 0; })})
}

function solve(board) {
    if (isFilled(board)) {
        return board;
    } else {
        return solve(_.map(board, function (row, y) {
            return _.map(row, function (val, x) {
                var poss = possibilities(board, x, y);
                if (val != 0) {
                    return val;
                } else if ((val == 0) && (_.size(poss) == 1)) {
                    return poss[0];
                } else {
                    console.log("UNSOLVED");
                    return 0;
                }
            })
        }));
    }
}
```

Easily the most annoying thing about writing quickly in JS after having gotten so used to the functional paradigm is having to return things explicitly. That bugs the crap out of me over in Python-land too, but at least Python makes up for it by saving you from lines like this

```javascript
                }
            })
        }));
    }
}
```

I could do the Lisp-esque thing and start writing

```javascript
                }})}));}}
```

but doubt anyone would appreciate that.

### Further Reading

The Sudoku situation isn't quite as solved as I assumed before reading up on it. The [appropriate Rosetta Code page](http://rosettacode.org/wiki/Sudoku) doesn't have any solutions that leave me gobsmacked by elegance the way that [the Clojure Game of Life](http://rosettacode.org/wiki/Conway%27s_Game_of_Life#Clojure) did. Though [the Prolog approach](http://rosettacode.org/wiki/Sudoku#Prolog) looks quite interesting. Also, the Haskellers apparently look at Sudoku-solver-writing as a hobby, so it has its own [page over at the Haskell wiki](http://www.haskell.org/haskellwiki/Sudoku). "Elegant" isn't something I'd say about any of these, but that's probably because my Math level isn't high enough.

The last note I'll leave you on is that brute-forcing apparently isn't the best solution here. Sudoku is an instance of something called the [Exact cover problem](http://en.wikipedia.org/wiki/Exact_cover), and a Marlboro College student named Sam Auciello wrote an [implementation of that solution](http://cs.marlboro.edu/courses/fall2012/dedhour/sudoku) in Python (links to code files at the bottom of that page page). I haven't quite gotten my head around this one yet, and that's probably what I'll be doing with my next few chunklets of spare time.

* * *
##### Footnotes

1 - [|back|](#note-Wed-May-22-155922EDT-2013) -  (If you're doing this functionally and recursively, it seems like it would be fairly straight-forward. Side-effects complicate things slightly since you have to copy your board out at each decision step, or devise some other method of backtracking)


text:
This bix was created to experiment with jessie release.

## Steps

* Download jessie iso
```shell
$ wget http://cdimage.debian.org/debian-cd/8.0.0/amd64/iso-cd/debian-8.0.0-amd64-netinst.iso
$ sha1sum debian-8.0.0-amd64-netinst.iso
==>  eab72f4ba73adea580aeaec91649e846aac89fa9  debian-8.0.0-amd64-netinst.iso
```

* Clone the magic repo that lnows how to create *.box files
```shell
$ git clone git@github.com:dotzero/vagrant-debian-jessie-64.git
$ mkdir vagrant-debian-jessie-64/iso
$ mv ../debian-8.0.0-amd64-netinst.iso iso/
$ brew install cdrtools
$ brew install p7zip
$ ./build.sh
...wait ~10 min
==> debian-jessie: Exporting VM...
==> debian-jessie: Compressing package to: /Users/asura/jessie/vagrant-debian-jessie-64/debian-jessie.box
```

* Verify what we got
```shell
$ du -hcs debian-jessie.box
==> 516M    debian-jessie.box
$ sha1sum debian-jessie.box
==> 50df5b2cdfc31bbbcb356f1cd7f2d041fdd17589  debian-jessie.box
```

* Add it to the list of available images
```shell
$ vagrant box add "debian-jessie" debian-jessie.box
```

* Use it in a Vagrantfile
```ruby
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  # config.vm.box = "puphpet/debian75-x64"
  config.vm.box = "debian-jessie"
  config.vm.hostname = "redi-dropper-client"
  config.vm.synced_folder "../app", "/var/www/app"
  config.vm.network "forwarded_port", guest: 80, host: 8088
  config.vm.network :forwarded_port, guest: 443, host: 7088

  config.vm.provision "shell" do |s|
    s.path = "bootstrap.sh"
  end
end
```

# Hosting

GitHub does not allow to store the produced file because the size is more than 100MB

https://help.github.com/articles/configuring-git-large-file-storage/