text:
@interface XNGAPIClient()
@property(nonatomic, strong, readwrite) XNGOAuthHandler *oAuthHandler;
@property(nonatomic, strong, readwrite) NSURL *baseURL;
@property(nonatomic, strong, readwrite) NSString *callbackScheme;
@end

@implementation XNGAPIClient

NSString * const XNGAPIClientInvalidTokenErrorNotification = @"com.xing.apiClient.error.invalidToken";
NSString * const XNGAPIClientDeprecationErrorNotification = @"com.xing.apiClient.error.deprecatedAPI";
NSString * const XNGAPIClientDeprecationWarningNotification = @"com.xing.apiClient.warning.deprecatedAPI";

static XNGAPIClient *_sharedClient = nil;

+ (XNGAPIClient *)clientWithBaseURL:(NSURL *)url {
    return [[XNGAPIClient alloc] initWithBaseURL:url];
}

+ (XNGAPIClient *)sharedClient {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_sharedClient == nil) {
            NSURL *baseURL = [NSURL URLWithString:@"https://www.xing.com"];
            _sharedClient = [[XNGAPIClient alloc] initWithBaseURL:baseURL];
        }
    });
    return _sharedClient;
}

+ (void)setSharedClient:(XNGAPIClient *)sharedClient {
    _sharedClient = sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
        _oAuthHandler = [[XNGOAuthHandler alloc] init];
        self.baseURL = url;
        [self registerHTTPOperationClass:[XNGJSONRequestOperation class]];
        [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    }
    return self;
}

#pragma mark - Getters / Setters

- (NSString *)callbackScheme {
    if (!_callbackScheme) {
        _callbackScheme =[NSString stringWithFormat:@"xingapp%@",self.consumerKey];
    }
    return _callbackScheme;
}

- (void)setUserAgent:(NSString *)userAgent {
    [self setDefaultHeader:@"User-Agent" value:userAgent];
}

#pragma mark - XAuth signing

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                      path:(NSString *)path
                                parameters:(NSDictionary *)parameters {
    NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
    [self.oAuthHandler.GTMOAuthAuthentication authorizeRequest:request];
    return request;
}

#pragma mark - handling login / logout

- (BOOL)isLoggedin {
    return [self.oAuthHandler hasAccessToken];
}

- (void)logout {
    return [self.oAuthHandler deleteKeychainEntriesAndGTMOAuthAuthentication];
}

- (void)loginOAuthWithSuccess:(void (^)(void))success
                      failure:(void (^)(NSError *error))failure {
    if (self.isLoggedin) {
        [[self exceptionForUserAlreadyLoggedIn] raise];
        return;
    }

    if ([self.consumerKey length] == 0) {
        [[self exceptionForNoConsumerKey] raise];
        return;
    }

    if ([self.consumerSecret length] == 0) {
        [[self exceptionForNoConsumerSecret] raise];
        return;
    }

    NSURL *callbackURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@://success",self.callbackScheme]];

    __weak __typeof(&*self)weakSelf = self;
    XNGOAuth1Client *oauthClient = [[XNGOAuth1Client alloc] initWithBaseURL:self.baseURL
                                                                      key:self.consumerKey
                                                                   secret:self.consumerSecret];
    [oauthClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [oauthClient authorizeUsingOAuthWithRequestTokenPath:@"v1/request_token"
                                   userAuthorizationPath:@"v1/authorize"
                                             callbackURL:callbackURL
                                         accessTokenPath:@"v1/access_token"
                                            accessMethod:@"POST"
                                                   scope:nil
                                                 success:
     ^(AFOAuth1Token *accessToken, id responseObject) {
         NSString *userID = [accessToken.additionalParameters xng_stringForKey:@"user_id"];
         [weakSelf.oAuthHandler saveUserID:userID
                               accessToken:accessToken.key
                                    secret:accessToken.secret
                                   success:success
                                   failure:failure];
     } failure:^(NSError *error) {
         failure(error);
     }];
}

- (BOOL)handleOpenURL:(NSURL *)URL {
    if([[URL scheme] isEqualToString:self.callbackScheme] == NO) {
        return NO;
    }

    NSDictionary *dict = [NSDictionary dictionaryWithObject:URL forKey:kAFApplicationLaunchOptionsURLKey];
    NSNotification *notification = [NSNotification notificationWithName:kAFApplicationLaunchedWithURLNotification
                                                                 object:nil
                                                               userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];

    return YES;
}

- (void)loginXAuthWithUsername:(NSString*)username
                      password:(NSString*)password
                       success:(void (^)(void))success
                       failure:(void (^)(NSError *error))failure {
    if (self.isLoggedin) {
        [[self exceptionForUserAlreadyLoggedIn] raise];
        return;
    }

    if ([self.consumerKey length] == 0) {
        [[self exceptionForNoConsumerKey] raise];
        return;
    }

    if ([self.consumerSecret length] == 0) {
        [[self exceptionForNoConsumerSecret] raise];
        return;
    }

    [self postRequestXAuthAccessTokenWithUsername:username
                                         password:password
                                          success:
     ^(AFHTTPRequestOperation *operation, id responseJSON) {
         NSString *body = [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding];
         NSDictionary *xAuthResponseFields = [NSString xng_URLDecodedDictionaryFromString:body];

         [self.oAuthHandler saveXAuthResponseParametersToKeychain:xAuthResponseFields
                                                          success:success
                                                          failure:failure];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         failure(error);
     }];
}

- (void)postRequestXAuthAccessTokenWithUsername:(NSString*)username
                                       password:(NSString*)password
                                        success:(void (^)(AFHTTPRequestOperation *operation, id responseJSON))success
                                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure {
    NSParameterAssert(username);
    NSParameterAssert(password);

	NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"oauth_consumer_key"] =  self.consumerKey;
    parameters[@"x_auth_username"] = username;
    parameters[@"x_auth_password"] = password;
    parameters[@"x_auth_mode"] = @"client_auth";

    NSString* path = [NSString stringWithFormat:@"%@/v1/xauth", self.baseURL];
    [self postPath:path parameters:parameters success:success failure:failure];
}

#pragma mark - block-based GET / PUT / POST / DELETE

- (void)getJSONPath:(NSString *)path
         parameters:(NSDictionary *)parameters
            success:(void (^)(id JSON))success
            failure:(void (^)(NSError *error))failure {
    NSMutableURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
    [self enqueueJSONRequest:request success:success failure:failure];
}

- (void)putJSONPath:(NSString *)path
         parameters:(NSDictionary *)parameters
            success:(void (^)(id JSON))success
            failure:(void (^)(NSError *error))failure {
    NSMutableURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters];
    [self enqueueJSONRequest:request success:success failure:failure];
}

- (void)postJSONPath:(NSString *)path
          parameters:(NSDictionary *)parameters
             success:(void (^)(id JSON))success
             failure:(void (^)(NSError *error))failure {
    NSMutableURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];
    [self enqueueJSONRequest:request success:success failure:failure];
}

- (void)deleteJSONPath:(NSString *)path
            parameters:(NSDictionary *)parameters
               success:(void (^)(id JSON))success
               failure:(void (^)(NSError *error))failure {
    NSMutableURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters];
    [self enqueueJSONRequest:request success:success failure:failure];
}

#pragma mark - OAuth related methods

- (NSString *)currentUserID {
    return self.oAuthHandler.userID;
}

- (void)setConsumerKey:(NSString *)consumerKey {
    self.oAuthHandler.consumerKey = consumerKey;
}

- (void)setConsumerSecret:(NSString *)consumerSecret {
    self.oAuthHandler.consumerSecret = consumerSecret;
}

- (void)setSignatureMethod:(NSString *)signatureMethod {
    self.oAuthHandler.signatureMethod = signatureMethod;
}

- (void)setServiceProvider:(NSString *)serviceProvider {
    self.oAuthHandler.serviceProvider = serviceProvider;
}

#pragma mark - OAuth related methods (private)

- (NSString *)consumerKey {
    NSAssert([self.oAuthHandler.consumerKey length], @"No ConsumerKey returned. \n Did you forget to implement XNGAPIClient delegate method consumerKeyForXNGAPIClient: ?");
    return self.oAuthHandler.consumerKey;
}

- (NSString *)consumerSecret {
    NSAssert([self.oAuthHandler.consumerSecret length], @"No ConsumerSecret returned. \n Did you forget to implement XNGAPIClient delegate method consumerSecretForXNGAPIClient: ?");
    return self.oAuthHandler.consumerSecret;
}

- (NSString *)signatureMethod {
    return self.oAuthHandler.signatureMethod;
}

- (NSString *)serviceProvider {
    return self.oAuthHandler.serviceProvider;
}

#pragma mark - checking methods

- (void)checkForGlobalErrors:(NSHTTPURLResponse *)response
                    withJSON:(id)JSON {
    if (response.statusCode == 410) {
        [[NSNotificationCenter defaultCenter] postNotificationName:XNGAPIClientDeprecationErrorNotification object:nil];
        return;
    }
    if ([JSON isKindOfClass:[NSDictionary class]] &&
        [[JSON xng_stringForKey:@"error_name"] isEqualToString:@"INVALID_OAUTH_TOKEN"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:XNGAPIClientInvalidTokenErrorNotification object:nil];
        return;
    }
}

- (void)checkForDeprecation:(NSHTTPURLResponse *)response {
    if ([[response.allHeaderFields xng_stringForKey:@"X-Xing-Deprecation-Status"] isEqualToString:@"deprecated"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:XNGAPIClientDeprecationWarningNotification object:nil];
    }
}

#pragma mark - cancel requests methods

- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method paths:(NSArray *)paths {
    for (NSString* path in paths) {
        [self cancelAllHTTPOperationsWithMethod:method path:path];
    }
}

- (void)cancelAllHTTPOperations {
    for (NSOperation *operation in self.operationQueue.operations) {
        operation.completionBlock = nil;
        [operation cancel];
    }
}

#pragma mark - HTTP Operation queue methods

- (void)enqueueJSONRequest:(NSMutableURLRequest *)request
                   success:(void (^)(id JSON))success
                   failure:(void (^)(NSError *error))failure {
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    __weak __typeof(&*self)weakSelf = self;
    XNGJSONRequestOperation *operation = nil;
    operation = [XNGJSONRequestOperation JSONRequestOperationWithRequest:request
                                                                 success:
                 ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                     [weakSelf checkForDeprecation:response];
                     if (success) {
                         success(JSON);
                     }
                 } failure:
                 ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                     [weakSelf checkForDeprecation:response];
                     [weakSelf checkForGlobalErrors:response withJSON:JSON];

                     if ([JSON isKindOfClass:[NSDictionary class]]) {
                         error = [NSError xwsErrorWithStatusCode:response.statusCode
                                                        userInfo:JSON];
                     }

                     if (failure) {
                         failure(error);
                     }
                 }];
    [self enqueueHTTPRequestOperation:operation];
}

#pragma mark - Helper methods

- (NSException *)exceptionForUserAlreadyLoggedIn {
    return [NSException exceptionWithName:@"XNGUserLoginException" reason:@"A User is already loggedIn. Use the isLoggedin method to verfiy that no user is logged in before you use this method." userInfo:@{@"XNGLoggedInUserID":self.currentUserID}];
}

- (NSException *)exceptionForNoConsumerKey {
    return [NSException exceptionWithName:@"XNGNoConsumerKeyException"
                                   reason:@"There is no Consumer Key set yet. Please set it first before invoking login."
                                 userInfo:nil];
}

- (NSException *)exceptionForNoConsumerSecret {
    return [NSException exceptionWithName:@"XNGNoConsumerSecretException"
                                   reason:@"There is no Consumer Secret set yet. Please set it first before invoking login."
                                 userInfo:nil];
}

@end


text:
from setuptools import setup, find_packages
import sys

if not (sys.version_info[0]== 2 and sys.version_info[1] == 7):
    print "Sorry, only python 2.7.x is supported for mosaic"
    sys.exit(1)

with open('README.md') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='mosaic',
    version='0.2.0',
    description="Create images similar to Delta909's Pixel Matrix on arbitrary pictures",
    long_description=readme,
    author='Indraniel Das',
    author_email='indraniel@gmail.com',
    url='https://github.com/indraniel/tinted-mosaic',
    license=license,
    scripts=['bin/pixel-art'],
    install_requires=['nose==1.3.0','Pillow==2.2.1'],
    packages=find_packages(exclude=('tests', 'docs')),
    package_data={ '': ['*.md', 'LICENSE'], },
    include_package_data=True
)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Bot\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * DeckCalculate
 *
 * @ORM\Table(name="deck_calculate")
 * @ORM\Entity(repositoryClass="Bot\CoreBundle\Entity\DeckCalculateRepository")
 * @ORM\HasLifecycleCallbacks
 */
class DeckCalculate
{
    const STATE_NEW = 1;
    const STATS_PROCESS = 2;
    const STATE_CALCULATED = 3;
    const STATE_ERROR = 4;
    const STATE_DEFEAT = 5;
    const STATE_STOPPED = 6;

    const ENEMY_DECK_TYPE_MISSION = 1;
    const ENEMY_DECK_TYPE_TILE_SLOT = 2;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

   /**
     * @ORM\ManyToOne(targetEntity="Bot")
     * @ORM\JoinColumn(name="bot_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $bot;

    /**
     * @ORM\ManyToOne(targetEntity="TileSlot")
     * @ORM\JoinColumn(name="tile_slot_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
     */
    protected $tileSlot;

    /**
     * @var integer
     * @ORM\Column(name="enemy_deck_type", type="integer")
     */
    protected $enemyDeckType;

    /**
     * @var string
     * @ORM\Column(name="enemy_deck_hash", type="string")
     */
    protected $enemyDeckHash;

    /**
     * @var text
     * @ORM\Column(name="enemy_options", type="text")
     */
    protected $enemyOptions;

    /**
     * @var string
     * @ORM\Column(name="calculated_hash", type="string", nullable=true)
     */
    protected $calculatedHash;

    /**
     * @var integer
     * @ORM\Column(name="calculated_percent", type="integer", nullable=true)
     */
    protected $calculatedPercent;

    /**
     * @var integer
     * @ORM\Column(name="state", type="integer", nullable=true)
     */
    protected $state;

    /**
     * @var integer
     * @ORM\Column(name="created_time", type="integer")
     */
    protected $createdTime;

    /**
     * @var integer
     * @ORM\Column(name="finished_time", type="integer", nullable=true)
     */
    protected $finishedTime;

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

    /**
     * Set enemyDeckType
     *
     * @param integer $enemyDeckType
     * @return DeckCalculate
     */
    public function setEnemyDeckType($enemyDeckType)
    {
        $this->enemyDeckType = $enemyDeckType;

        return $this;
    }

    /**
     * Get enemyDeckType
     *
     * @return integer
     */
    public function getEnemyDeckType()
    {
        return $this->enemyDeckType;
    }

    /**
     * Set enemyDeckHash
     *
     * @param string $enemyDeckHash
     * @return DeckCalculate
     */
    public function setEnemyDeckHash($enemyDeckHash)
    {
        $this->enemyDeckHash = $enemyDeckHash;

        return $this;
    }

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

    /**
     * Set enemyOptions
     *
     * @param string $enemyOptions
     * @return DeckCalculate
     */
    public function setEnemyOptions($enemyOptions)
    {
        $this->enemyOptions = $enemyOptions;

        return $this;
    }

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

    /**
     * Set calculatedHash
     *
     * @param string $calculatedHash
     * @return DeckCalculate
     */
    public function setCalculatedHash($calculatedHash)
    {
        $this->calculatedHash = $calculatedHash;

        return $this;
    }

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

    /**
     * Set calculatedPercent
     *
     * @param integer $calculatedPercent
     * @return DeckCalculate
     */
    public function setCalculatedPercent($calculatedPercent)
    {
        $this->calculatedPercent = $calculatedPercent;

        return $this;
    }

    /**
     * Get calculatedPercent
     *
     * @return integer
     */
    public function getCalculatedPercent()
    {
        return $this->calculatedPercent;
    }

    /**
     * Set state
     *
     * @param integer $state
     * @return DeckCalculate
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * Get state
     *
     * @return integer
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Set createdTime
     *
     * @param integer $createdTime
     * @return DeckCalculate
     */
    public function setCreatedTime($createdTime)
    {
        $this->createdTime = $createdTime;

        return $this;
    }

    /**
     * Get createdTime
     *
     * @return integer
     */
    public function getCreatedTime()
    {
        return $this->createdTime;
    }

    /**
     * Set finishedTime
     *
     * @param integer $finishedTime
     * @return DeckCalculate
     */
    public function setFinishedTime($finishedTime)
    {
        $this->finishedTime = $finishedTime;

        return $this;
    }

    /**
     * Get finishedTime
     *
     * @return integer
     */
    public function getFinishedTime()
    {
        return $this->finishedTime;
    }

    /**
     * Set bot
     *
     * @param \Bot\CoreBundle\Entity\Bot $bot
     * @return DeckCalculate
     */
    public function setBot(\Bot\CoreBundle\Entity\Bot $bot = null)
    {
        $this->bot = $bot;

        return $this;
    }

    /**
     * Get bot
     *
     * @return \Bot\CoreBundle\Entity\Bot
     */
    public function getBot()
    {
        return $this->bot;
    }

    /**
     * @param mixed $tileSlot
     */
    public function setTileSlot($tileSlot)
    {
        $this->tileSlot = $tileSlot;
    }

    /**
     * @return mixed
     */
    public function getTileSlot()
    {
        return $this->tileSlot;
    }

    /**
     * @ORM\PrePersist()
     */
    public function prePersist()
    {
        if (is_null($this->getState())) {
            $this->setState(self::STATE_NEW);
        }
        if (is_null($this->getCreatedTime())) {
            $this->setCreatedTime(time());
        }

    }

}


text:
package org.apache.taverna.workflowmodel.processor.iteration;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

import javax.swing.tree.TreeNode;

import org.apache.taverna.invocation.Completion;
import org.apache.taverna.workflowmodel.processor.activity.Job;

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

/**
 * Test {@link AbstractIterationStrategyNode} implementations for
 * {@link TreeNode} behaviour.
 *
 * @author Stian Soiland-Reyes
 *
 */
public class TestIterationStrategyNodes {

	TerminalNode root;
	private NamedInputPortNode input1;
	private NamedInputPortNode input2;
	private CrossProduct crossProduct1;
	private CrossProduct crossProduct2;
	private DotProduct dotProduct1;
	private DotProduct dotProduct2;

	@Test
	public void addSingleChildToTerminal() throws Exception {
		assertNull(input1.getParent());
		assertEquals(0, root.getChildCount());
		root.insert(input1);
		assertEquals(root, input1.getParent());
		assertEquals(1, root.getChildCount());
		assertEquals(input1, root.getChildAt(0));
		assertEquals(Arrays.asList(input1), root.getChildren());

		root.insert(input1);
		assertEquals(1, root.getChildCount());

		root.insert(input1, 0);
		assertEquals(1, root.getChildCount());
	}

	@Test(expected = IllegalStateException.class)
	public void cantAddSeveralChildrenToTerminal() throws Exception {
		root.insert(input1);
		root.insert(input2);
	}

	@Test
	public void addCrossProduct() throws Exception {
		assertNull(crossProduct1.getParent());
		crossProduct1.setParent(root);
		assertEquals(root, crossProduct1.getParent());
		assertEquals(1, root.getChildCount());
		assertEquals(crossProduct1, root.getChildAt(0));
		assertEquals(Arrays.asList(crossProduct1), root.getChildren());
		assertEquals(0, crossProduct1.getChildCount());

		crossProduct1.insert(input1);
		assertEquals(input1, crossProduct1.getChildAt(0));
		crossProduct1.insert(input2, 0);
		assertEquals(input2, crossProduct1.getChildAt(0));
		assertEquals(input1, crossProduct1.getChildAt(1));
		assertEquals(2, crossProduct1.getChildCount());
		assertEquals(Arrays.asList(input2, input1), crossProduct1.getChildren());

		// A re-insert should move it
		crossProduct1.insert(input2, 2);
		assertEquals(2, crossProduct1.getChildCount());
		assertEquals(Arrays.asList(input1, input2), crossProduct1.getChildren());

		crossProduct1.insert(input2, 0);
		assertEquals(Arrays.asList(input2, input1), crossProduct1.getChildren());

		crossProduct1.insert(input1, 1);
		assertEquals(Arrays.asList(input2, input1), crossProduct1.getChildren());
	}

	@Test
	public void addCrossProductMany() {
		crossProduct1.insert(dotProduct1);
		crossProduct1.insert(dotProduct2);
		crossProduct1.insert(input1);
		crossProduct1.insert(input2);
		crossProduct1.insert(crossProduct2);
		assertEquals(5, crossProduct1.getChildCount());
		assertEquals(Arrays.asList(dotProduct1, dotProduct2, input1, input2,
				crossProduct2), crossProduct1.getChildren());
		Enumeration<IterationStrategyNode> enumeration = crossProduct1
				.children();
		assertTrue(enumeration.hasMoreElements());
		assertEquals(dotProduct1, enumeration.nextElement());
		assertEquals(dotProduct2, enumeration.nextElement());
		assertEquals(input1, enumeration.nextElement());
		assertEquals(input2, enumeration.nextElement());
		assertEquals(crossProduct2, enumeration.nextElement());
		assertFalse(enumeration.hasMoreElements());
	}

	@Test
	public void moveNodeToDifferentParent() {
		crossProduct1.setParent(root);
		crossProduct1.insert(input1);
		crossProduct1.insert(dotProduct1);
		dotProduct1.insert(input2);
		dotProduct1.insert(crossProduct2);

		// Check tree
		assertEquals(crossProduct2, root.getChildAt(0).getChildAt(1)
				.getChildAt(1));
		assertEquals(Arrays.asList(input2, crossProduct2), dotProduct1
				.getChildren());

		crossProduct1.insert(crossProduct2, 1);
		assertEquals(Arrays.asList(input1, crossProduct2, dotProduct1),
				crossProduct1.getChildren());
		assertEquals(crossProduct1, crossProduct2.getParent());
		// Should no longer be in dotProduct1
		assertEquals(Arrays.asList(input2), dotProduct1.getChildren());
	}

	@Test(expected = IllegalStateException.class)
	public void cantAddToNamedInput() throws Exception {
		input1.insert(dotProduct1);
	}

	@Test
	public void cantAddSelf() throws Exception {
		dotProduct1.setParent(crossProduct1);
		try {
			dotProduct1.insert(dotProduct1);
			fail("Didn't throw IllegalArgumentException");
		} catch (IllegalArgumentException ex) {
			// Make sure we didn't loose our old parent and
			// ended up in a funny state
			assertEquals(crossProduct1, dotProduct1.getParent());
			assertEquals(dotProduct1, crossProduct1.getChildAt(0));
		}
	}

	@Test
	public void cantSetSelfParent() throws Exception {
		crossProduct1.insert(dotProduct1);
		try {
			dotProduct1.setParent(dotProduct1);
			fail("Didn't throw IllegalArgumentException");
		} catch (IllegalArgumentException ex) {
			// Make sure we didn't loose our old parent and
			// ended up in a funny state
			assertEquals(crossProduct1, dotProduct1.getParent());
			assertEquals(dotProduct1, crossProduct1.getChildAt(0));
		}
	}

	@Before
	public void makeNodes() throws Exception {
		root = new DummyTerminalNode();
		input1 = new NamedInputPortNode("input1", 1);
		input2 = new NamedInputPortNode("input2", 2);
		crossProduct1 = new CrossProduct();
		crossProduct2 = new CrossProduct();
		dotProduct1 = new DotProduct();
		dotProduct2 = new DotProduct();
	}

	@SuppressWarnings("serial")
	protected final class DummyTerminalNode extends TerminalNode {

		@Override
		public int getIterationDepth(Map<String, Integer> inputDepths)
				throws IterationTypeMismatchException {
			return 0;
		}

		@Override
		public void receiveCompletion(int inputIndex, Completion completion) {
		}

		@Override
		public void receiveJob(int inputIndex, Job newJob) {
		}
	}

}


text:
using System.Threading.Tasks;
using Crosschat.Client.Model.Proxies;
using Crosschat.Server.Application.DataTransferObjects.Messages;
using Crosschat.Server.Application.DataTransferObjects.Requests;

namespace Crosschat.Client.Model.Managers
{
    public class SearchManager : ManagerBase
    {
        private readonly UsersSearchServiceProxy _searchServiceProxy;

        public SearchManager(ConnectionManager connectionManager, UsersSearchServiceProxy searchServiceProxy)
            : base(connectionManager)
        {
            _searchServiceProxy = searchServiceProxy;
        }

        public async Task<UserDto[]> SearchAsync(string query)
        {
            UsersSearchResponse response = await _searchServiceProxy.SearchUser(new UsersSearchRequest { QueryString = query });
            if (response.Result == null)
                return new UserDto[0];

            return response.Result;
        }
    }
}


text:
require "spec_helper"

describe RCrawler::Configuration do
  let(:config) {RCrawler::Configuration.instance}

  describe "defined accessors" do
    it "defined threads" do
      expect(config.respond_to? :threads).to be_true
    end

    it "defined timeout" do
      expect(config.respond_to? :timeout).to be_true
    end

    it "defined timeout_proc" do
      expect(config.respond_to? :timeout_proc).to be_true
    end
  end

  describe "#initialize" do
    it "threads should be a default" do
      expect(config.threads).to eq(8)
    end

    it "timeout should be a default" do
      expect(config.timeout).to eq(10)
    end

    it "timeout_proc should be a default" do
      expect(config.timeout_proc).to eq(:raise)
    end
  end

  describe "#configure" do
    before do
      config.configure do |c|
        c.threads = 20
        c.timeout = 30
        c.timeout_proc = :ignore
      end
    end

    it "threads should be a specified parameter" do
      expect(config.threads).to eq(20)
    end

    it "timeout should be a specified parameter" do
      expect(config.timeout).to eq(30)
    end

    it "timeout_proc should be a specified parameter" do
      expect(config.timeout_proc).to eq(:ignore)
    end

    it "raise error unknown setting" do
      expect {
        config.configure do |c|
          c.unknown = true
        end
      }.to raise_error
    end
  end

  describe "#reset" do
    before do
      config.configure do |c|
        c.threads = 20
        c.timeout = 30
        c.timeout_proc = :ignore
      end
      config.reset
    end

    it "threads should be a default" do
      expect(config.threads).to eq(8)
    end

    it "timeout should be a default" do
      expect(config.timeout).to eq(10)
    end

    it "timeout_proc should be a default" do
      expect(config.timeout_proc).to eq(:raise)
    end
  end
end


text:
package goConsulRoundRobin

import (
	"log"
	"os"
	"strconv"
	"time"

	consulapi "github.com/hashicorp/consul/api"
)

type consulHealthAgent interface {
	Service(service, tag string, passingOnly bool, q *consulapi.QueryOptions) ([]*consulapi.ServiceEntry, *consulapi.QueryMeta, error)
}

type agentStruct struct {
	endpoints []string
	err       error
}

var consulIP string
var consulRefreshRate time.Duration
var healthClient consulHealthAgent
var testAgent agentStruct

func init() {
	consulRefreshRateString := os.Getenv("SERVICE_CACHE_TIMEOUT")

	var err error
	consulRefreshRateInt, err := strconv.Atoi(consulRefreshRateString)
	if err != nil {
		log.Fatal(err)
	}
	consulRefreshRate = time.Millisecond * time.Duration(consulRefreshRateInt)

	consulIP = os.Getenv("CONSUL_IP")
	//***** if consul ip = "test" then use test client *****
	if consulIP == "test" {
		//set test agent here
		consulRefreshRate = time.Millisecond
	} else {
		healthClient, err = newConsulHealthClient(consulIP, ":8500")
		if err != nil {
			log.Fatal(err)
		}
	}
}

func getHealthyEndpoints(service string) (serviceEndpoints []string, err error) {
	if consulIP == "test" {
		return testAgent.endpoints, testAgent.err
	}
	agent := healthClient

	healthyServiceEntries, _, err := agent.Service(service, "", true, &consulapi.QueryOptions{})
	if err != nil {
		return []string{}, err
	}

	serviceEndpoints = getEndpointsFromServiceEntries(healthyServiceEntries)

	return serviceEndpoints, nil
}

// how to test, need a mocked consul server?
func newConsulHealthClient(consulIP string, consulPort string) (*consulapi.Health, error) {
	config := consulapi.DefaultConfig()
	config.Address = consulIP + consulPort

	consul, err := consulapi.NewClient(config)
	if err != nil {
		return &consulapi.Health{}, err
	}

	consulHealthAgent := consul.Health()
	return consulHealthAgent, nil
}

func getEndpointsFromServiceEntries(serviceEntries []*consulapi.ServiceEntry) (serviceEndpoints []string) {
	for i := 0; i < len(serviceEntries); i++ {
		serviceAddress := serviceEntries[i].Service.Address
		servicePortInt := serviceEntries[i].Service.Port
		serviceEndpoint := serviceAddress + ":" + strconv.Itoa(servicePortInt)
		serviceEndpoints = append(serviceEndpoints, serviceEndpoint)
	}
	return serviceEndpoints
}


text:
'''Test colour buffer save.

A scene consisting of a single coloured triangle will be rendered.  The
colour buffer will then be saved to a stream and loaded as a texture.

You will see the original scene first for up to several seconds before the
buffer image appears (because retrieving and saving the image is a slow
operation).  Messages will be printed to stdout indicating what stage is
occuring.
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id: $'

import unittest
import base_save

from pyglet.gl import *
from pyglet import image
from pyglet.compat import BytesIO

class TEST_BUFFER_SAVE(base_save.TestSave):
    alpha = False

    def draw_original(self):
        glBegin(GL_TRIANGLES)
        glColor4f(1, 0, 0, 1)
        glVertex3f(0, 0, -1)
        glColor4f(0, 1, 0, 1)
        glVertex3f(200, 0, 0)
        glColor4f(0, 0, 1, 1)
        glVertex3f(0, 200, 1)
        glEnd()

        glColor4f(1, 1, 1, 1)

    def load_texture(self):
        print('Drawing scene...')
        self.window.set_visible()
        self.window.dispatch_events()
        self.draw()

        print('Saving colour image...')
        img = image.get_buffer_manager().get_color_buffer()
        file = BytesIO()
        img.save('buffer.png', file)

        print('Loading colour image as texture...')
        file.seek(0)
        self.saved_texture = image.load('buffer.png', file)

        print('Done.')
        self.window.set_visible(False)

if __name__ == '__main__':
    unittest.main()


text:
package v7_test

import (
	"errors"

	"code.cloudfoundry.org/cli/actor/actionerror"
	"code.cloudfoundry.org/cli/actor/v7action"
	"code.cloudfoundry.org/cli/command/commandfakes"
	"code.cloudfoundry.org/cli/command/flag"
	. "code.cloudfoundry.org/cli/command/v7"
	"code.cloudfoundry.org/cli/command/v7/v7fakes"
	"code.cloudfoundry.org/cli/resources"
	"code.cloudfoundry.org/cli/util/configv3"
	"code.cloudfoundry.org/cli/util/ui"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
)

var _ = Describe("unmap-route Command", func() {
	var (
		cmd             UnmapRouteCommand
		testUI          *ui.UI
		fakeConfig      *commandfakes.FakeConfig
		fakeSharedActor *commandfakes.FakeSharedActor
		fakeActor       *v7fakes.FakeActor
		input           *Buffer
		binaryName      string
		executeErr      error
		domain          string
		appName         string
		hostname        string
		path            string
		orgGUID         string
		orgName         string
		spaceGUID       string
		spaceName       string
		userName        string
		port            int
	)

	BeforeEach(func() {
		input = NewBuffer()
		testUI = ui.NewTestUI(input, NewBuffer(), NewBuffer())
		fakeConfig = new(commandfakes.FakeConfig)
		fakeSharedActor = new(commandfakes.FakeSharedActor)
		fakeActor = new(v7fakes.FakeActor)

		binaryName = "faceman"
		fakeConfig.BinaryNameReturns(binaryName)
		appName = "my-app"
		domain = "some-domain.com"
		hostname = "host"
		path = "/path"
		orgGUID = "some-org-guid"
		orgName = "some-org"
		spaceGUID = "some-space-guid"
		spaceName = "some-space"
		userName = "steve"
		port = 0

		cmd = UnmapRouteCommand{
			RequiredArgs: flag.AppDomain{App: appName, Domain: domain},
			Hostname:     hostname,
			Path:         flag.V7RoutePath{Path: path},
			Port:         port,
			BaseCommand: BaseCommand{
				UI:          testUI,
				Config:      fakeConfig,
				SharedActor: fakeSharedActor,
				Actor:       fakeActor,
			},
		}

		fakeConfig.TargetedOrganizationReturns(configv3.Organization{
			Name: orgName,
			GUID: orgGUID,
		})

		fakeConfig.TargetedSpaceReturns(configv3.Space{
			Name: spaceName,
			GUID: spaceGUID,
		})

		fakeActor.GetCurrentUserReturns(configv3.User{Name: userName}, nil)

		fakeActor.GetDomainByNameReturns(
			resources.Domain{Name: "some-domain.com", GUID: "domain-guid"},
			v7action.Warnings{"get-domain-warnings"},
			nil,
		)

		fakeActor.GetApplicationByNameAndSpaceReturns(
			resources.Application{Name: "app", GUID: "app-guid"},
			v7action.Warnings{"get-app-warnings"},
			nil,
		)

		fakeActor.GetRouteByAttributesReturns(
			resources.Route{GUID: "route-guid"},
			v7action.Warnings{"get-route-warnings"},
			nil,
		)

		fakeActor.GetRouteDestinationByAppGUIDReturns(
			resources.RouteDestination{GUID: "destination-guid"},
			nil,
		)

		fakeActor.UnmapRouteReturns(
			v7action.Warnings{"unmap-route-warnings"},
			nil,
		)
	})

	JustBeforeEach(func() {
		executeErr = cmd.Execute(nil)
	})

	When("checking target fails", func() {
		BeforeEach(func() {
			fakeSharedActor.CheckTargetReturns(actionerror.NoOrganizationTargetedError{BinaryName: binaryName})
		})

		It("returns an error", func() {
			Expect(executeErr).To(MatchError(actionerror.NoOrganizationTargetedError{BinaryName: binaryName}))

			Expect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))
			checkTargetedOrg, checkTargetedSpace := fakeSharedActor.CheckTargetArgsForCall(0)
			Expect(checkTargetedOrg).To(BeTrue())
			Expect(checkTargetedSpace).To(BeTrue())
		})
	})

	When("the user is not logged in", func() {
		var expectedErr error

		BeforeEach(func() {
			expectedErr = errors.New("some current user error")
			fakeActor.GetCurrentUserReturns(configv3.User{}, expectedErr)
		})

		It("return an error", func() {
			Expect(executeErr).To(Equal(expectedErr))
		})
	})

	When("getting the domain errors", func() {
		BeforeEach(func() {
			fakeActor.GetDomainByNameReturns(resources.Domain{}, v7action.Warnings{"get-domain-warnings"}, errors.New("get-domain-error"))
		})

		It("returns the error and displays warnings", func() {
			Expect(testUI.Err).To(Say("get-domain-warnings"))
			Expect(executeErr).To(MatchError(errors.New("get-domain-error")))
			Expect(fakeActor.UnmapRouteCallCount()).To(Equal(0))
		})
	})

	It("gets the domain and displays warnings", func() {
		Expect(testUI.Err).To(Say("get-domain-warnings"))

		Expect(fakeActor.GetDomainByNameCallCount()).To(Equal(1))
		Expect(fakeActor.GetDomainByNameArgsForCall(0)).To(Equal(domain))
	})

	When("getting the app errors", func() {
		BeforeEach(func() {
			fakeActor.GetApplicationByNameAndSpaceReturns(
				resources.Application{},
				v7action.Warnings{"get-app-warnings"},
				errors.New("get-app-error"),
			)
		})

		It("returns the error and displays warnings", func() {
			Expect(testUI.Err).To(Say("get-app-warnings"))
			Expect(executeErr).To(MatchError(errors.New("get-app-error")))
			Expect(fakeActor.UnmapRouteCallCount()).To(Equal(0))
		})
	})

	It("gets the app and displays the warnings", func() {
		Expect(testUI.Err).To(Say("get-app-warnings"))

		Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
		actualAppName, actualSpaceGUID := fakeActor.GetApplicationByNameAndSpaceArgsForCall(0)
		Expect(actualAppName).To(Equal(appName))
		Expect(actualSpaceGUID).To(Equal(spaceGUID))
	})

	When("getting the route errors", func() {
		BeforeEach(func() {
			fakeActor.GetRouteByAttributesReturns(
				resources.Route{},
				v7action.Warnings{"get-route-warnings"},
				errors.New("get-route-error"),
			)
		})

		It("returns the error and displays warnings", func() {
			Expect(testUI.Err).To(Say("get-route-warnings"))
			Expect(executeErr).To(MatchError(errors.New("get-route-error")))

			Expect(fakeActor.UnmapRouteCallCount()).To(Equal(0))
		})
	})

	When("the route is TCP", func() {
		BeforeEach(func() {
			cmd.Hostname = ""
			cmd.Path = flag.V7RoutePath{Path: ""}
			cmd.Port = 1024
		})

		It("gets the routes and displays warnings", func() {
			Expect(testUI.Err).To(Say("get-route-warnings"))

			Expect(testUI.Out).To(Say(
				`Removing route %s from app %s in org %s / space %s as %s\.\.\.`,
				"some-domain.com:1024",
				appName,
				orgName,
				spaceName,
				userName,
			))

			Expect(fakeActor.GetRouteByAttributesCallCount()).To(Equal(1))
			actualDomain, _, _, actualPort := fakeActor.GetRouteByAttributesArgsForCall(0)
			Expect(actualDomain.Name).To(Equal("some-domain.com"))
			Expect(actualDomain.GUID).To(Equal("domain-guid"))
			Expect(actualPort).To(Equal(1024))
		})
	})

	It("gets the routes and displays warnings", func() {
		Expect(testUI.Err).To(Say("get-route-warnings"))

		Expect(fakeActor.GetRouteByAttributesCallCount()).To(Equal(1))
		actualDomain, actualHostname, actualPath, actualPort := fakeActor.GetRouteByAttributesArgsForCall(0)
		Expect(actualDomain.Name).To(Equal("some-domain.com"))
		Expect(actualDomain.GUID).To(Equal("domain-guid"))
		Expect(actualHostname).To(Equal(hostname))
		Expect(actualPath).To(Equal(path))
		Expect(actualPort).To(Equal(0))
	})

	It("prints flavor text", func() {
		Expect(testUI.Out).To(Say(
			`Removing route %s from app %s in org %s / space %s as %s\.\.\.`,
			"host.some-domain.com/path",
			appName,
			orgName,
			spaceName,
			userName,
		))
	})

	When("getting the route destination fails because the app is not mapped", func() {
		BeforeEach(func() {
			fakeActor.GetRouteDestinationByAppGUIDReturns(
				resources.RouteDestination{},
				actionerror.RouteDestinationNotFoundError{},
			)
		})

		It("prints a message and returns without an error", func() {
			Expect(executeErr).NotTo(HaveOccurred())
			Expect(testUI.Out).To(Say("Route to be unmapped is not currently mapped to the application."))
			Expect(testUI.Out).To(Say("OK"))
		})
	})

	It("gets the route destination and prints the warnings", func() {
		Expect(fakeActor.GetRouteDestinationByAppGUIDCallCount()).To(Equal(1))
		givenRoute, givenAppGUID := fakeActor.GetRouteDestinationByAppGUIDArgsForCall(0)
		Expect(givenRoute.GUID).To(Equal("route-guid"))
		Expect(givenAppGUID).To(Equal("app-guid"))
	})

	When("unmapping the route fails", func() {
		BeforeEach(func() {
			fakeActor.UnmapRouteReturns(
				v7action.Warnings{"unmap-route-warnings"},
				errors.New("failed to unmap route"),
			)
		})

		It("prints warnings and returns the error", func() {
			Expect(fakeActor.UnmapRouteCallCount()).To(Equal(1))
			givenRouteGUID, givenDestinationGUID := fakeActor.UnmapRouteArgsForCall(0)
			Expect(givenRouteGUID).To(Equal("route-guid"))
			Expect(givenDestinationGUID).To(Equal("destination-guid"))

			Expect(executeErr).To(MatchError("failed to unmap route"))
		})
	})

	It("prints warnings and does not return an error", func() {
		Expect(executeErr).NotTo(HaveOccurred())
		Expect(testUI.Out).To(Say("OK"))

		Expect(fakeActor.UnmapRouteCallCount()).To(Equal(1))
		givenRouteGUID, givenDestinationGUID := fakeActor.UnmapRouteArgsForCall(0)
		Expect(givenRouteGUID).To(Equal("route-guid"))
		Expect(givenDestinationGUID).To(Equal("destination-guid"))
	})
})


text:
DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `id`          INT UNSIGNED     NOT NULL  PRIMARY KEY AUTO_INCREMENT,
  `name`        VARCHAR(32)      NOT NULL  DEFAULT '',
  `mailbox`     VARCHAR(128)     NOT NULL  DEFAULT '',
  `sex`         TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
  `age`         INT UNSIGNED     NOT NULL  DEFAULT 0,
  `description` VARCHAR(256)     NOT NULL  DEFAULT '',
  `password`    VARCHAR(32)      NOT NULL  DEFAULT '',
  `head_url`    VARCHAR(255)     NOT NULL  DEFAULT '',
  `longitude`   float DEFAULT NULL COMMENT '位置经度',
  `latitude`    float DEFAULT NULL COMMENT '位置纬度',
  `status`      TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
  `created_at`   BIGINT(20)      NOT NULL DEFAULT '0',
  `updated_at`   BIGINT(20)      NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `blogs`;
CREATE TABLE `blogs` (
  `id`          INT UNSIGNED     NOT NULL  PRIMARY KEY AUTO_INCREMENT,
  `user_id` INT UNSIGNED     NOT NULL DEFAULT 0,
  `title`       VARCHAR(32)      NOT NULL  DEFAULT '',
  `content`     TEXT             NOT NULL ,
  `status`      TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
  `readed`  INT UNSIGNED     NOT NULL DEFAULT 0,
  `created_at`   TIMESTAMP       NOT NULL  DEFAULT CURRENT_TIMESTAMP,
  `updated_at`   TIMESTAMP       NOT NULL  DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE VIEW user_base_info AS SELECT `id`,`name`,`mailbox`,`sex` FROM users;


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit83bdd9c4f7cda2dfdb19f1cc88933d94::getLoader();


text:
from flask import session

from indico.core import signals
from indico.core.logger import Logger
from indico.core.settings import SettingsProxy
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.menu import SideMenuItem

logger = Logger.get('news')

news_settings = SettingsProxy('news', {
    # Whether to show the recent news on the home page
    'show_recent': True,
    # The number of recent news to show on the home page
    'max_entries': 3,
    # How old a news may be to be shown on the home page
    'max_age': 0,
    # How long a news is labelled as 'new'
    'new_days': 14
})

@signals.menu.items.connect_via('admin-sidemenu')
def _sidemenu_items(sender, **kwargs):
    if session.user.is_admin:
        yield SideMenuItem('news', _('News'), url_for('news.manage'), section='homepage')


text:
NAME="gosl"
VERSION="latest"

docker logout
docker login
docker push gosl/$NAME:$VERSION


text:
package org.zstack.compute.vm;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.compute.host.HostSystemTags;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.Q;
import org.zstack.core.db.SQL;
import org.zstack.header.volume.VolumeType;

import javax.persistence.Tuple;
import java.util.List;

/**
 * Created by MaJin on 2021/1/8.
 */

@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class VmExtraInfoGetter {
    @Autowired
    private DatabaseFacade dbf;

    private String uuid;

    private VmExtraInfoGetter(String uuid) {
        this.uuid = uuid;
    }

    public static VmExtraInfoGetter New(String uuid) {
        return new VmExtraInfoGetter(uuid);
    }

    public boolean isVirtio() {
        return VmSystemTags.VIRTIO.hasTag(uuid);
    }
}


text:
"""
SYNOPSIS

    TODO helloworld [-h,--help] [-v,--verbose] [--version]

DESCRIPTION

    TODO This describes how to use this script. This docstring
    will be printed by the script if there is an error or
    if the user requests help (-h or --help).

EXAMPLES

    TODO: Show some examples of how to use this script.

EXIT STATUS

    TODO: List exit codes

AUTHOR

    TODO: Name <name@example.org>

LICENSE

    This script is in the public domain, free from copyrights or restrictions.

VERSION

    $Id$
"""
__author__ = 'rochelle'

import os
#from os import listdir, path
import gzip
import re

def listMatchingFiles(base_dir, pattern):
    # build list of files matching pattern
    fileList = []
    if not pattern:
        pattern = '.*'
    if os.path.exists(base_dir):
        _all_files = os.listdir(base_dir)
        for _fn in _all_files:
            _pth = os.path.join(base_dir, _fn)
            if not os.path.isdir(_pth):
                if re.match(pattern, _fn):
                    fileList.append(_pth)
    return fileList

def buildFileList(base_dir, extension='.tif'):
    fileList = []
    if os.path.exists(base_dir):
        all_files = os.listdir(base_dir)
        for fname in all_files:
            pth = os.path.join(base_dir, fname)
            if os.path.isdir(pth):
                # skip directories
                continue
            else:
                # file
                fn, ext = os.path.splitext(fname)
                if ext == extension:
                    fileList.append(pth)
    return fileList

def getMatchingFiles(base_dir, filter):
    fileList = []
    if os.path.exists(base_dir):
        all_files = os.listdir(base_dir)
        for f in all_files:
            pth = os.path.join(base_dir, f)
            if not os.path.isdir(pth):
                # check file against filter
                if re.match(filter, f):
                    fileList.append(pth)
    return fileList

def getNewFilename(filename, prefix, ext, pattern, new_pattern):

    f= os.path.basename(filename)
    m = re.match(pattern, f)
    new_filename = re.sub(pattern,
                         lambda match: new_pattern.format(
                             prefix = prefix,
                             datestamp = match.group('datestamp'),
                             ext = ext)
                         if match.group('datestamp') else f, f)

    return os.path.join(os.path.dirname(filename), new_filename)

def unzipFiles(base_dir, extension='.gz'):
    filesList = buildFileList(base_dir, extension)
    for fl in filesList:
        if not os.path.isdir(fl):
            with gzip.open(fl, 'rb') as in_file:
                s = in_file.read()
            # Now store the uncompressed data
            path_to_store = fl[:-3]  # remove the '.gz' from the filename
            # store uncompressed file data from 's' variable
            with open(path_to_store, 'wb') as f:
                f.write(s)
    return 0

def unzipFile(fname, extension='.gz'):
    inF = gzip.open(fname, 'rb')
    outfilename = fname[:-3]
    outF = open(outfilename, 'wb')
    outF.write( inF.read() )
    inF.close()
    outF.close()
    return outfilename


text:
#include <aws/appmesh/model/GatewayRouteRef.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace AppMesh
{
namespace Model
{

GatewayRouteRef::GatewayRouteRef() :
    m_arnHasBeenSet(false),
    m_createdAtHasBeenSet(false),
    m_gatewayRouteNameHasBeenSet(false),
    m_lastUpdatedAtHasBeenSet(false),
    m_meshNameHasBeenSet(false),
    m_meshOwnerHasBeenSet(false),
    m_resourceOwnerHasBeenSet(false),
    m_version(0),
    m_versionHasBeenSet(false),
    m_virtualGatewayNameHasBeenSet(false)
{
}

GatewayRouteRef::GatewayRouteRef(JsonView jsonValue) :
    m_arnHasBeenSet(false),
    m_createdAtHasBeenSet(false),
    m_gatewayRouteNameHasBeenSet(false),
    m_lastUpdatedAtHasBeenSet(false),
    m_meshNameHasBeenSet(false),
    m_meshOwnerHasBeenSet(false),
    m_resourceOwnerHasBeenSet(false),
    m_version(0),
    m_versionHasBeenSet(false),
    m_virtualGatewayNameHasBeenSet(false)
{
  *this = jsonValue;
}

GatewayRouteRef& GatewayRouteRef::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("arn"))
  {
    m_arn = jsonValue.GetString("arn");

    m_arnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("createdAt"))
  {
    m_createdAt = jsonValue.GetDouble("createdAt");

    m_createdAtHasBeenSet = true;
  }

  if(jsonValue.ValueExists("gatewayRouteName"))
  {
    m_gatewayRouteName = jsonValue.GetString("gatewayRouteName");

    m_gatewayRouteNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("lastUpdatedAt"))
  {
    m_lastUpdatedAt = jsonValue.GetDouble("lastUpdatedAt");

    m_lastUpdatedAtHasBeenSet = true;
  }

  if(jsonValue.ValueExists("meshName"))
  {
    m_meshName = jsonValue.GetString("meshName");

    m_meshNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("meshOwner"))
  {
    m_meshOwner = jsonValue.GetString("meshOwner");

    m_meshOwnerHasBeenSet = true;
  }

  if(jsonValue.ValueExists("resourceOwner"))
  {
    m_resourceOwner = jsonValue.GetString("resourceOwner");

    m_resourceOwnerHasBeenSet = true;
  }

  if(jsonValue.ValueExists("version"))
  {
    m_version = jsonValue.GetInt64("version");

    m_versionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("virtualGatewayName"))
  {
    m_virtualGatewayName = jsonValue.GetString("virtualGatewayName");

    m_virtualGatewayNameHasBeenSet = true;
  }

  return *this;
}

JsonValue GatewayRouteRef::Jsonize() const
{
  JsonValue payload;

  if(m_arnHasBeenSet)
  {
   payload.WithString("arn", m_arn);

  }

  if(m_createdAtHasBeenSet)
  {
   payload.WithDouble("createdAt", m_createdAt.SecondsWithMSPrecision());
  }

  if(m_gatewayRouteNameHasBeenSet)
  {
   payload.WithString("gatewayRouteName", m_gatewayRouteName);

  }

  if(m_lastUpdatedAtHasBeenSet)
  {
   payload.WithDouble("lastUpdatedAt", m_lastUpdatedAt.SecondsWithMSPrecision());
  }

  if(m_meshNameHasBeenSet)
  {
   payload.WithString("meshName", m_meshName);

  }

  if(m_meshOwnerHasBeenSet)
  {
   payload.WithString("meshOwner", m_meshOwner);

  }

  if(m_resourceOwnerHasBeenSet)
  {
   payload.WithString("resourceOwner", m_resourceOwner);

  }

  if(m_versionHasBeenSet)
  {
   payload.WithInt64("version", m_version);

  }

  if(m_virtualGatewayNameHasBeenSet)
  {
   payload.WithString("virtualGatewayName", m_virtualGatewayName);

  }

  return payload;
}

} // namespace Model
} // namespace AppMesh
} // namespace Aws


text:
SELECT REGEXP_COUNT('123123123123123', '(12)3', 1, 'i');
SELECT REGEXP_COUNT();
SELECT REGEXP_COUNT ('abc');
SELECT REGEXP_COUNT ('aabbb', 'ab{-1,3}$');
SELECT REGEXP_COUNT('', ',[^,]+,');
SELECT REGEXP_COUNT('123', '');
SELECT REGEXP_COUNT(NULL, ',[^,]+,');
SELECT REGEXP_COUNT('123123123123123', NULL);

--optional arguments
SELECT REGEXP_COUNT('123123123123123', '(12)3', 5);
SELECT REGEXP_COUNT('123123123123123', '(12)3', 'a');
SELECT REGEXP_COUNT('123123123123123', '(12)3', 0);
SELECT REGEXP_COUNT('123123123123123', '(12)3', -3);
SELECT REGEXP_COUNT('123123123123123', '(12)3', 500);
SELECT REGEXP_COUNT('123123123123123', '(12)3', NULL);
SELECT REGEXP_COUNT('ABCABCabcabc', 'a|b', 1, 'i');
SELECT REGEXP_COUNT('ABCABCabcabc', 'a|b', 1, 'c');
SELECT REGEXP_COUNT('ABCABCabcabc', 'a|b', 1, '');
SELECT REGEXP_COUNT('ABCABCabcabc', 'a|b', 1, 'a');
SELECT REGEXP_COUNT('ABCABCabcabc', 'a|b', 1, NULL);

--functional test
SELECT REGEXP_COUNT('abcabcabcabcabc', 'abc', 1) AS C1,
REGEXP_COUNT('abcabcabcabcabc', 'abc', 4) AS C2;

drop table if exists p1;
create table p1 (num int primary key, code varchar(40) not null, pos int, match_type varchar);
insert into p1 values(001, '[a-e]', 3, 'c');
insert into p1 values(002, '[f-z]', 2, 'c');
insert into p1 values(003, '[[:alpha:]]+', 1, 'c');
insert into p1 values(004, 'a|e|i|o|u', 2, 'c');
select * from p1 order by 1;

DROP TABLE IF EXISTS athlete;
CREATE TABLE athlete (name VARCHAR(40) NOT NULL);
INSERT INTO athlete VALUES ('Aline');
INSERT INTO athlete VALUES ('Balachov Roman');
INSERT INTO athlete VALUES ('Chiang Tai-Chuan');
INSERT INTO athlete VALUES ('Chamot Jose Antonio');
INSERT INTO athlete VALUES ('De La Hoya Oscar');
INSERT INTO athlete VALUES ('Guidry-White Carlette D.');
INSERT INTO athlete VALUES ('Oliva Hortencia De Fatima Marcari');
INSERT INTO athlete VALUES ('Van Der Ploeg G. Jose M.');
SELECT * FROM athlete ORDER BY 1;

SELECT REGEXP_COUNT(name, '[[:alpha:]]+') FROM athlete order by 1;
SELECT REGEXP_COUNT(athlete.name, p1.code), p1.code FROM athlete, p1 ORDER BY p1.num;
SELECT REGEXP_COUNT(athlete.name, p1.code, p1.pos), p1.code, p1.pos FROM athlete, p1 ORDER BY p1.num;
SELECT REGEXP_COUNT(athlete.name, p1.code, p1.pos, p1.match_type), p1.code, p1.pos,  p1.match_type FROM athlete, p1 ORDER BY p1.num;

SELECT name FROM athlete WHERE REGEXP_COUNT (name, '[[:alpha:]]+') > 5 order by 1;

DROP TABLE IF EXISTS many_word_name;
CREATE TABLE many_word_name ( name VARCHAR ) AS SELECT name FROM athlete WHERE REGEXP_COUNT (name, '[[:alpha:]]+') > 2;
SELECT * FROM many_word_name order by 1;

DROP TABLE IF EXISTS many_word_name;
CREATE TABLE many_word_name ( name VARCHAR );
INSERT INTO many_word_name SELECT name FROM athlete WHERE REGEXP_COUNT (name, '[[:alpha:]]+') > 2;
SELECT * FROM many_word_name order by 1;

DROP TABLE IF EXISTS many_word_name;
DROP TABLE IF EXISTS athlete;
DROP TABLE IF EXISTS p1;


text:
package osgi.logger.provider;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.regex.Pattern;

import org.osgi.service.log.LogService;

import osgi.enroute.logger.api.LoggerAdmin.Control;

/**
 * Logging is so much fun! Everybody should have their own logging API!
 * <p>
 * Anyway, this class links into the (quite horrible) Java Util Logging API and
 * forwards the messages to the OSGi Log Service.
 */

class JavaUtilLoggingHandler extends Handler {

	/*
	 * Loggers have a name. So we maintain a cache of the last 1000 loggers
	 */

	private final Map<String,AbstractLogger>	loggers	= new LinkedHashMap<String,AbstractLogger>() {
															private static final long	serialVersionUID	= 1L;

															protected boolean removeEldestEntry(
																	Map.Entry<String,AbstractLogger> eldest) {
																if (size() > 1000) {
																	eldest.getValue().close();
																}
																return false;
															}
														};

	/*
	 * Java util logging is a bit confusing and horribly designed. The Logger
	 * class is quite messed up with the reporting (slf4j is much better in that
	 * way). This publish method has already passed any filters (which are
	 * applied on local Loggers but can be inherited). Anyway, this method
	 * has passed the hurdles and needs to be queued.
	 */
	@Override
	public void publish(LogRecord record) {
		AbstractLogger l;

		synchronized (loggers) {

			//
			// Try to find the name in the cache. If not found, create a new one.
			//

			l = loggers.get(record.getLoggerName());
			if (l == null) {
				l = new AbstractLogger(LoggerDispatcher.classContext.getCallerBundle(), record.getLoggerName());
				loggers.put(record.getLoggerName(), l);
			}

			Level level = record.getLevel();

			//
			// Translate the JUL to the OSGi log levels
			//

			if (level == Level.INFO) {
				if (l.isInfoEnabled())
					message(l, LogService.LOG_INFO, record);
				return;
			}
			if (level == Level.SEVERE) {
				if (l.isErrorEnabled())
					message(l, LogService.LOG_ERROR, record);
				return;
			}
			if (level == Level.WARNING) {
				if (l.isWarnEnabled())
					message(l, LogService.LOG_WARNING, record);
				return;
			}

			//
			// All other levels we assume are trace levels
			//

			if (l.isTraceEnabled())
				message(l, LoggerAdminImpl.LOG_TRACE, record);
		}
	}

	static Object[]	EMPTY	= new Object[0];

	/*
	 * convert what we have to an OSGi record
	 */
	private void message(AbstractLogger l, int level, LogRecord record) {
		Object[] parameters = record.getParameters();
		if (parameters == null)
			parameters = EMPTY;

		l.message(level, record.getMessage(), parameters);
	}

	/* Duh ...
	 */
	@Override
	public void flush() {}

	/*
	 * Wow, a life cycle method ... we just close all our loggers.
	 */
	@Override
	public void close() throws SecurityException {
		synchronized (loggers) {
			for (AbstractLogger l : loggers.values()) {
				l.close();
			}
			loggers.clear();
		}
	}

	/*
	 *  TODO Not sure if this is needed
	 */
	void update(Map<Pattern,Control> controls) {
	}

}


text:
namespace Orchard.Data.Providers {
    public class SqlCeStatementProvider : ISqlStatementProvider {
        public string DataProvider {
            get { return "SqlCe"; }
        }

        public string GetStatement(string command) {
            switch (command) {
                case "random":
                    return "newid()";
                case "table_names":
                    return "select table_name from information_schema.tables";
            }

            return null;
        }
    }
}


text:
// Copyright 2021 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <grpc/grpc.h>

#include "src/core/ext/transport/binder/transport/binder_transport.h"
#include "src/core/lib/config/core_configuration.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/server.h"
#include "src/libfuzzer/libfuzzer_macro.h"
#include "test/core/transport/binder/end2end/fuzzers/binder_transport_fuzzer.pb.h"
#include "test/core/transport/binder/end2end/fuzzers/fuzzer_utils.h"

bool squelch = true;
bool leak_check = true;

static void* tag(intptr_t t) { return reinterpret_cast<void*>(t); }

static void dont_log(gpr_log_func_args* /*args*/) {}

DEFINE_PROTO_FUZZER(const binder_transport_fuzzer::Input& input) {
  grpc_test_only_set_slice_hash_seed(0);
  if (squelch) gpr_set_log_function(dont_log);
  grpc_init();
  {
    // Copied and modified from grpc/test/core/end2end/fuzzers/server_fuzzer.cc
    grpc_core::ExecCtx exec_ctx;
    grpc_core::Executor::SetThreadingAll(false);

    grpc_server* server = grpc_server_create(nullptr, nullptr);
    grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
    grpc_server_register_completion_queue(server, cq, nullptr);
    // TODO(ctiller): add more registered methods (one for POST, one for PUT)
    grpc_server_register_method(server, "/reg", nullptr, {}, 0);
    grpc_server_start(server);
    grpc_transport* server_transport = grpc_create_binder_transport_server(
        absl::make_unique<grpc_binder::fuzzing::BinderForFuzzing>(
            input.incoming_parcels()),
        std::make_shared<
            grpc::experimental::binder::UntrustedSecurityPolicy>());
    const grpc_channel_args* channel_args =
        grpc_core::CoreConfiguration::Get()
            .channel_args_preconditioning()
            .PreconditionChannelArgs(nullptr)
            .ToC();
    (void)grpc_core::Server::FromC(server)->SetupTransport(
        server_transport, nullptr, channel_args, nullptr);
    grpc_channel_args_destroy(channel_args);
    grpc_call* call1 = nullptr;
    grpc_call_details call_details1;
    grpc_metadata_array request_metadata1;
    grpc_call_details_init(&call_details1);
    grpc_metadata_array_init(&request_metadata1);
    int requested_calls = 0;

    GPR_ASSERT(GRPC_CALL_OK ==
               grpc_server_request_call(server, &call1, &call_details1,
                                        &request_metadata1, cq, cq, tag(1)));
    requested_calls++;

    grpc_event ev;
    while (true) {
      grpc_core::ExecCtx::Get()->Flush();
      ev = grpc_completion_queue_next(cq, gpr_inf_past(GPR_CLOCK_REALTIME),
                                      nullptr);
      switch (ev.type) {
        case GRPC_QUEUE_TIMEOUT:
          goto done;
        case GRPC_QUEUE_SHUTDOWN:
          break;
        case GRPC_OP_COMPLETE:
          if (ev.tag == tag(1)) {
            requested_calls--;
            // TODO(ctiller): keep reading that call!
          }
          break;
      }
    }

  done:
    grpc_binder::fuzzing::JoinFuzzingThread();
    if (call1 != nullptr) grpc_call_unref(call1);
    grpc_call_details_destroy(&call_details1);
    grpc_metadata_array_destroy(&request_metadata1);
    grpc_server_shutdown_and_notify(server, cq, tag(0xdead));
    grpc_server_cancel_all_calls(server);
    grpc_core::Timestamp deadline =
        grpc_core::ExecCtx::Get()->Now() + grpc_core::Duration::Seconds(5);
    for (int i = 0; i <= requested_calls; i++) {
      // A single grpc_completion_queue_next might not be sufficient for getting
      // the tag from shutdown, because we might potentially get blocked by
      // an operation happening on the timer thread.
      // For example, the deadline timer might expire, leading to the timer
      // thread trying to cancel the RPC and thereby acquiring a few references
      // to the call. This will prevent the shutdown to complete till the timer
      // thread releases those references.
      // As a solution, we are going to keep performing a cq_next for a
      // liberal period of 5 seconds for the timer thread to complete its work.
      do {
        ev = grpc_completion_queue_next(cq, gpr_inf_past(GPR_CLOCK_REALTIME),
                                        nullptr);
        grpc_core::ExecCtx::Get()->InvalidateNow();
      } while (ev.type != GRPC_OP_COMPLETE &&
               grpc_core::ExecCtx::Get()->Now() < deadline);
      GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
    }
    grpc_completion_queue_shutdown(cq);
    for (int i = 0; i <= requested_calls; i++) {
      do {
        ev = grpc_completion_queue_next(cq, gpr_inf_past(GPR_CLOCK_REALTIME),
                                        nullptr);
        grpc_core::ExecCtx::Get()->InvalidateNow();
      } while (ev.type != GRPC_QUEUE_SHUTDOWN &&
               grpc_core::ExecCtx::Get()->Now() < deadline);
      GPR_ASSERT(ev.type == GRPC_QUEUE_SHUTDOWN);
    }
    grpc_server_destroy(server);
    grpc_completion_queue_destroy(cq);
  }
  grpc_shutdown();
}


text:
package com.appleframework.orm.mybatis.pagehelper.parser;

import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.*;

import java.util.List;

/**
 * 处理 Order by
 *
 * @author liuzh
 * @since 2015-06-27
 */
public class OrderByParser {
    /**
     * convert to order by sql
     *
     * @param sql
     * @param orderBy
     * @return
     */
    public static String converToOrderBySql(String sql, String orderBy) {
        //解析SQL
        Statement stmt = null;
        try {
            stmt = CCJSqlParserUtil.parse(sql);
            Select select = (Select) stmt;
            SelectBody selectBody = select.getSelectBody();
            //处理body-去最外层order by
            List<OrderByElement> orderByElements = extraOrderBy(selectBody);
            String defaultOrderBy = PlainSelect.orderByToString(orderByElements);
            if (defaultOrderBy.indexOf('?') != -1) {
                throw new RuntimeException("原SQL[" + sql + "]中的order by包含参数,因此不能使用OrderBy插件进行修改!");
            }
            //新的sql
            sql = select.toString();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return sql + " order by " + orderBy;
    }

    /**
     * extra order by and set default orderby to null
     *
     * @param selectBody
     */
    public static List<OrderByElement> extraOrderBy(SelectBody selectBody) {
        if (selectBody instanceof PlainSelect) {
            List<OrderByElement> orderByElements = ((PlainSelect) selectBody).getOrderByElements();
            ((PlainSelect) selectBody).setOrderByElements(null);
            return orderByElements;
        } else if (selectBody instanceof WithItem) {
            WithItem withItem = (WithItem) selectBody;
            if (withItem.getSelectBody() != null) {
                return extraOrderBy(withItem.getSelectBody());
            }
        } else {
            SetOperationList operationList = (SetOperationList) selectBody;
            if (operationList.getSelects() != null && operationList.getSelects().size() > 0) {
                List<SelectBody> plainSelects = operationList.getSelects();
                return extraOrderBy(plainSelects.get(plainSelects.size() - 1));
            }
        }
        return null;
    }
}


text: Solutions for Hackerranks 30 Days of Code challenge


text:
package io.sniffy.boot;

import io.sniffy.Sniffy;
import io.sniffy.configuration.SniffyConfiguration;
import io.sniffy.servlet.SniffyFilter;
import io.sniffy.sql.SniffyDataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import javax.servlet.DispatcherType;
import javax.sql.DataSource;
import java.util.EnumSet;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @since 3.1
 */
@Configuration
public class SniffySpringConfiguration implements ImportAware, BeanFactoryAware, BeanPostProcessor {

    private ConfigurableBeanFactory beanFactory;
    private BeanExpressionResolver resolver;
    private BeanExpressionContext expressionContext;
    private TypeConverter typeConverter;

    private AnnotationAttributes enableSniffy;

    private Boolean monitorJdbc;
    private Boolean monitorSocket;
    private Boolean monitorNio;

    private Integer topSqlCapacity;

    private Boolean filterEnabled;
    private Pattern excludePattern;

    private Boolean injectHtml;
    private Pattern injectHtmlExcludePattern;

    @Override
    public void setImportMetadata(AnnotationMetadata importMetadata) {
        Map<String, Object> map = importMetadata.getAnnotationAttributes(EnableSniffy.class.getName());
        this.enableSniffy = AnnotationAttributes.fromMap(map);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (ConfigurableBeanFactory) beanFactory;
        resolver = this.beanFactory.getBeanExpressionResolver();
        expressionContext = new BeanExpressionContext(this.beanFactory, null);
        typeConverter = this.beanFactory.getTypeConverter();
    }

    @Bean
    public SniffyFilter sniffyFilter() {

        SniffyConfiguration.INSTANCE.setMonitorJdbc(isMonitorJdbc());
        SniffyConfiguration.INSTANCE.setMonitorSocket(isMonitorSocket());
        SniffyConfiguration.INSTANCE.setMonitorNio(isMonitorNio());
        SniffyConfiguration.INSTANCE.setTopSqlCapacity(getTopSqlCapacity());

        Sniffy.initialize();

        SniffyFilter sniffyFilter = new SniffyFilter();

        sniffyFilter.setFilterEnabled(isFilterEnabled());
        sniffyFilter.setExcludePattern(getExcludePattern());

        sniffyFilter.setInjectHtml(isInjectHtml());
        sniffyFilter.setInjectHtmlExcludePattern(getInjectHtmlExcludePattern());

        return sniffyFilter;
    }

    @Bean
    public FilterRegistrationBean sniffyFilterRegistration(SniffyFilter sniffyFilter) {

        FilterRegistrationBean filterRegistration = new FilterRegistrationBean(sniffyFilter);
        filterRegistration.setAsyncSupported(true);
        filterRegistration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));

        filterRegistration.setName("sniffyFilter");
        filterRegistration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        filterRegistration.setMatchAfter(false);

        filterRegistration.addUrlPatterns("/*");

        return filterRegistration;

    }

    private boolean isMonitorJdbc() {
        if (null == monitorJdbc) {
            monitorJdbc = resolveBooleanProperty(enableSniffy.getString("monitorJdbc"));
        }
        return monitorJdbc;
    }

    private boolean isMonitorSocket() {
        if (null == monitorSocket) {
            monitorSocket = resolveBooleanProperty(enableSniffy.getString("monitorSocket"));
        }
        return monitorSocket;
    }

    private boolean isMonitorNio() {
        if (null == monitorNio) {
            monitorNio = resolveBooleanProperty(enableSniffy.getAnnotation("advanced").getString("monitorNio"));
        }
        return monitorNio;
    }

    private int getTopSqlCapacity() {
        if (null == topSqlCapacity) {
            topSqlCapacity = resolveIntProperty(
                    enableSniffy.getAnnotation("advanced").getString("topSqlCapacity")
            );
        }
        return topSqlCapacity;
    }

    private boolean isInjectHtml() {
        if (null == injectHtml) {
            injectHtml = resolveBooleanProperty(enableSniffy.getString("injectHtml"));
        }
        return injectHtml;
    }

    public Pattern getInjectHtmlExcludePattern() {
        if (null == injectHtmlExcludePattern) {

            try {
                String injectHtmlExcludePattern = resolveStringProperty(
                        enableSniffy.getAnnotation("advanced").getString("injectHtmlExcludePattern")
                );
                if (!injectHtmlExcludePattern.isEmpty()) {
                    this.injectHtmlExcludePattern = Pattern.compile(injectHtmlExcludePattern);
                }
            } catch (PatternSyntaxException e) {
                // TODO: log me maybe?
            }

        }
        return injectHtmlExcludePattern;
    }

    private boolean isFilterEnabled() {
        if (null == filterEnabled) {
            filterEnabled = resolveBooleanProperty(enableSniffy.getString("filterEnabled"));
        }
        return filterEnabled;
    }

    public Pattern getExcludePattern() {
        if (null == excludePattern) {

            try {
                String excludePattern = resolveStringProperty(
                        enableSniffy.getAnnotation("advanced").getString("excludePattern")
                );
                if (!excludePattern.isEmpty()) {
                    this.excludePattern = Pattern.compile(excludePattern);
                }
            } catch (PatternSyntaxException e) {
                // TODO: log me maybe?
            }

        }
        return excludePattern;
    }

    private boolean resolveBooleanProperty(String attributeValue) {
        Boolean value;

        String resolvedValue = beanFactory.resolveEmbeddedValue(attributeValue);
        Object injectHtmlObj = resolver.evaluate(resolvedValue, expressionContext);
        try {
            value = typeConverter.convertIfNecessary(injectHtmlObj, Boolean.class);
        } catch (TypeMismatchException e) {
            value = false;
        }

        if (null == value) {
            value = false;
        }

        return value;
    }

    private int resolveIntProperty(String attributeValue) {
        int value;

        String resolvedValue = beanFactory.resolveEmbeddedValue(attributeValue);
        Object injectHtmlObj = resolver.evaluate(resolvedValue, expressionContext);
        try {
            value = typeConverter.convertIfNecessary(injectHtmlObj, Integer.class);
        } catch (TypeMismatchException e) {
            value = 0;
        }

        return value;
    }

    private String resolveStringProperty(String attributeValue) {
        String value;

        String resolvedValue = beanFactory.resolveEmbeddedValue(attributeValue);
        Object injectHtmlObj = resolver.evaluate(resolvedValue, expressionContext);
        try {
            value = typeConverter.convertIfNecessary(injectHtmlObj, String.class);
        } catch (TypeMismatchException e) {
            value = null;
        }

        return value;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        if (isMonitorJdbc() && bean instanceof DataSource && !(bean instanceof SniffyDataSource)) {
            return SniffyDataSource.wrap(DataSource.class.cast(bean));
        } else {
            return bean;
        }

    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}


text:
import os
import logging
import tornado
from tornado.options import define, options

from server.config import Config

# Make file path relative to settings.
dirname = os.path.dirname
ROOT = dirname(dirname(os.path.abspath(__file__)))

define('port', default=Config.app_port, help='run on the given port', type=int)
define('config', default=None, help='tornado config file')
define('debug', default=False, help='debug mode')
tornado.options.parse_command_line()

STATIC_ROOT = os.path.join(ROOT, 'client')

class DeploymentType:
    PRODUCTION = 'PRODUCTION'
    DEV = 'DEV'
    SOLO = 'SOLO'
    STAGING = 'STAGING '
    dict = {
        PRODUCTION : 1,
        DEV : 2,
        SOLO : 3,
        STAGING : 4
    }

if 'DEPLOYMENT_TYPE' in os.environ:
    DEPLOYMENT = os.environ['DEPLOYMENT_TYPE'].upper()
else:
    DEPLOYMENT = DeploymentType.SOLO

settings = {}
settings['debug'] = DEPLOYMENT != DeploymentType.PRODUCTION or options.debug
settings['static_path'] = STATIC_ROOT
settings['cookie_secret'] = 'there should be someone'
settings['xsrf_cookies'] = False

SYSLOG_TAG = 'cg'
SYSTEM_FACILITY = logging.handlers.SysLogHandler.LOG_LOCAL2

LOGGERS = {
    'loggers': {
        'cg': {},
    },
}

if settings['debug']:
    LOG_LEVEL = logging.DEBUG
else:
    LOG_LEVEL = logging.INFO
USE_SYSLOG = DEPLOYMENT != DeploymentType.SOLO

if options.config:
    tornado.options.parse_config_file(options.config)


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!--彩蛋条目(左上左下圆角)-按下状态-->
    <solid android:color="@color/sz_main" />
    <corners
        android:bottomLeftRadius="8dp"
        android:topLeftRadius="8dp" />
    <stroke
        android:width="0.5dp"
        android:color="@android:color/transparent" />
</shape>


text:
.. Copyright (c) 2016, Ruslan Baratov
.. All rights reserved.

Android
-------

.. toctree::
  :maxdepth: 1

  /platforms/android/hints


text:
.class public Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;
.super Ljava/lang/Object;
.source "AccessibilityNodeInfoCompat.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "CollectionInfoCompat"
.end annotation

# static fields
.field public static final SELECTION_MODE_MULTIPLE:I = 0x2

.field public static final SELECTION_MODE_NONE:I = 0x0

.field public static final SELECTION_MODE_SINGLE:I = 0x1

# instance fields
.field final mInfo:Ljava/lang/Object;

# direct methods
.method private constructor <init>(Ljava/lang/Object;)V
    .locals 0
    .param p1, "info"    # Ljava/lang/Object;

    .prologue
    .line 395
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 396
    iput-object p1, p0, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;->mInfo:Ljava/lang/Object;

    .line 397
    return-void
.end method

.method synthetic constructor <init>(Ljava/lang/Object;Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$1;)V
    .locals 0
    .param p1, "x0"    # Ljava/lang/Object;
    .param p2, "x1"    # Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$1;

    .prologue
    .line 372
    invoke-direct {p0, p1}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;-><init>(Ljava/lang/Object;)V

    return-void
.end method

.method public static obtain(IIZI)Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;
    .locals 2
    .param p0, "rowCount"    # I
    .param p1, "columnCount"    # I
    .param p2, "hierarchical"    # Z
    .param p3, "selectionMode"    # I

    .prologue
    .line 391
    new-instance v0, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;

    # getter for: Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;->IMPL:Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;
    invoke-static {}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;->access$000()Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;

    move-result-object v1

    invoke-interface {v1, p0, p1, p2, p3}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;->obtainCollectionInfo(IIZI)Ljava/lang/Object;

    move-result-object v1

    invoke-direct {v0, v1}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;-><init>(Ljava/lang/Object;)V

    return-object v0
.end method

# virtual methods
.method public getColumnCount()I
    .locals 2

    .prologue
    .line 400
    # getter for: Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;->IMPL:Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;
    invoke-static {}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;->access$000()Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;

    move-result-object v0

    iget-object v1, p0, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;->mInfo:Ljava/lang/Object;

    invoke-interface {v0, v1}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;->getCollectionInfoColumnCount(Ljava/lang/Object;)I

    move-result v0

    return v0
.end method

.method public getRowCount()I
    .locals 2

    .prologue
    .line 404
    # getter for: Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;->IMPL:Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;
    invoke-static {}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;->access$000()Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;

    move-result-object v0

    iget-object v1, p0, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;->mInfo:Ljava/lang/Object;

    invoke-interface {v0, v1}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;->getCollectionInfoRowCount(Ljava/lang/Object;)I

    move-result v0

    return v0
.end method

.method public isHierarchical()Z
    .locals 2

    .prologue
    .line 408
    # getter for: Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;->IMPL:Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;
    invoke-static {}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat;->access$000()Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;

    move-result-object v0

    iget-object v1, p0, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$CollectionInfoCompat;->mInfo:Ljava/lang/Object;

    invoke-interface {v0, v1}, Landroid/support/v4/view/accessibility/AccessibilityNodeInfoCompat$AccessibilityNodeInfoImpl;->isCollectionInfoHierarchical(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method


text:
package org.vocefiscal.bitmaps;

import org.vocefiscal.BuildConfig;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;

/**
 * A BitmapDrawable that keeps track of whether it is being displayed or cached.
 * When the drawable is no longer being displayed or cached,
 * {@link android.graphics.Bitmap#recycle() recycle()} will be called on this drawable's bitmap.
 */
public class RecyclingBitmapDrawable extends BitmapDrawable {

    static final String TAG = "CountingBitmapDrawable";

    private int mCacheRefCount = 0;
    private int mDisplayRefCount = 0;

    private boolean mHasBeenDisplayed;

    public RecyclingBitmapDrawable(Resources res, Bitmap bitmap) {
        super(res, bitmap);
    }

    /**
     * Notify the drawable that the displayed state has changed. Internally a
     * count is kept so that the drawable knows when it is no longer being
     * displayed.
     *
     * @param isDisplayed - Whether the drawable is being displayed or not
     */
    public void setIsDisplayed(boolean isDisplayed) {
        //BEGIN_INCLUDE(set_is_displayed)
        synchronized (this) {
            if (isDisplayed) {
                mDisplayRefCount++;
                mHasBeenDisplayed = true;
            } else {
                mDisplayRefCount--;
            }
        }

        // Check to see if recycle() can be called
        checkState();
        //END_INCLUDE(set_is_displayed)
    }

    /**
     * Notify the drawable that the cache state has changed. Internally a count
     * is kept so that the drawable knows when it is no longer being cached.
     *
     * @param isCached - Whether the drawable is being cached or not
     */
    public void setIsCached(boolean isCached) {
        //BEGIN_INCLUDE(set_is_cached)
        synchronized (this) {
            if (isCached) {
                mCacheRefCount++;
            } else {
                mCacheRefCount--;
            }
        }

        // Check to see if recycle() can be called
        checkState();
        //END_INCLUDE(set_is_cached)
    }

    private synchronized void checkState() {
        //BEGIN_INCLUDE(check_state)
        // If the drawable cache and display ref counts = 0, and this drawable
        // has been displayed, then recycle
        if (mCacheRefCount <= 0 && mDisplayRefCount <= 0 && mHasBeenDisplayed
                && hasValidBitmap()) {
//            if (BuildConfig.DEBUG) {
//                Log.d(TAG, "No longer being used or cached so recycling. "
//                        + toString());
//            }

            getBitmap().recycle();
        }
        //END_INCLUDE(check_state)
    }

    private synchronized boolean hasValidBitmap() {
        Bitmap bitmap = getBitmap();
        return bitmap != null && !bitmap.isRecycled();
    }

}


text:
package li.barter.http;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyError.ErrorCode;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.MultiPartRequest;

import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Request class for submitting multipart requests to Volley
 *
 * @author Vinay S Shenoy
 */
public class BlMultiPartRequest extends MultiPartRequest<ResponseInfo>
                implements IBlRequestContract {

    /**
     * An identifier for the request that was made
     */
    private int                 mRequestId;

    /**
     * Any extras that can be passed into the request
     */
    private Map<String, Object> mExtras;

    /**
     * @param method One of the constants from {@link Method} class to identify
     *            the request type
     * @param url The API endpoint
     * @param volleyCallbacks The {@link VolleyCallbacks} reference to receive
     *            the callbacks
     */
    public BlMultiPartRequest(final int method, final String url, final String requestBody, final VolleyCallbacks volleyCallbacks) {
        super(method, url, volleyCallbacks, volleyCallbacks);
    }

    @Override
    protected Response<ResponseInfo> parseNetworkResponse(
                    final NetworkResponse response) {

        final HttpResponseParser parser = new HttpResponseParser();
        try {
            final ResponseInfo responseInfo = parser
                            .getSuccessResponse(mRequestId, new String(response.data, HTTP.UTF_8));

            if (responseInfo.success) {
                return Response.success(responseInfo, HttpHeaderParser
                                .parseCacheHeaders(response));
            }

            return Response.error(new ParseError("Unable to parse and store data!"));
        } catch (final JSONException e) {
            return Response.error(new ParseError(e));
        } catch (final UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (final XmlPullParserException e) {
            return Response.error(new ParseError(e));
        } catch (final IOException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected VolleyError parseNetworkError(final VolleyError volleyError) {

        if (volleyError.errorCode == ErrorCode.BAD_REQUEST_ERROR) {
            try {

                final HttpResponseParser parser = new HttpResponseParser();
                return parser.getErrorResponse(mRequestId, new String(volleyError.networkResponse.data, HTTP.UTF_8));
            } catch (final UnsupportedEncodingException e) {
                return new ParseError(e);
            } catch (final JSONException e) {
                return new ParseError(e);
            }
        } else {
            return super.parseNetworkError(volleyError);
        }
    }

    /**
     * Gets the extras associated with this request
     *
     * @return The extras returned with this request. Will not be
     *         null
     */
    @Override
    public Map<String, Object> getExtras() {

        if (mExtras != null) {
            return mExtras;
        }

        return Collections.<String, Object> emptyMap();
    }

    /**
     * Add an extra to the request
     *
     * @param key The key
     * @param value The value to map to the key
     */
    @Override
    public void addExtra(final String key, final Object value) {

        if (mExtras == null) {
            mExtras = new HashMap<String, Object>();
        }
        mExtras.put(key, value);
    }

    @Override
    public void setRequestId(final int requestId) {
        mRequestId = requestId;
    }

    @Override
    public int getRequestId() {
        return mRequestId;
    }

}


text:
"""
Validates the media_metric.
"""

from cli_tools.tbmv3.validators import simple_validator

def CompareHistograms(test_ctx):
  v2_metric = 'mediaMetric'
  v3_metric = 'media_metric'
  v2_histograms = test_ctx.RunTBMv2(v2_metric)
  v3_histograms = test_ctx.RunTBMv3(v3_metric)

  simple_config = {
      'v2_metric': v2_metric,
      'v3_metric': v3_metric,
      # 1 microsecond precision - default for ms unit histograms.
      'float_precision': 1e-3,
      'histogram_mappings': {
          # mappings are 'v2_histogram: 'v3_histogram'.
          'time_to_video_play': 'media::time_to_video_play',
          'time_to_audio_play': 'media::time_to_audio_play',
          # Dropped frame count is broken in the TBMv2 metric.
          # 'dropped_frame_count': 'media::dropped_frame_count',
          'buffering_time': 'media::buffering_time',
          # Roughness is reported as double in the v3 metric, but as int in v2.
          'roughness': ('media::roughness', 1),
          'freezing': 'media::freezing'
      },
  }

  simple_validator.CompareSimpleHistograms(test_ctx, simple_config,
                                           v2_histograms, v3_histograms)

  # seek time histograms are merged.
  seek_time_histograms = [
      # v3 histogram => set of v2 histograms that are merged into it.
      ['media::seek_time', ['seek_time_0_5', 'seek_time_9']],
      [
          'media::pipeline_seek_time',
          ['pipeline_seek_time_0_5', 'pipeline_seek_time_9']
      ],
  ]

  for entry in seek_time_histograms:
    v3_hist_name = entry[0]
    v3_hist = simple_validator.OptionalGetHistogram(v3_histograms, v3_hist_name,
                                                    v3_metric, 'v3')

    v2_hists = []
    for v2_hist_name in entry[1]:
      v2_hist = simple_validator.OptionalGetHistogram(v2_histograms,
                                                      v2_hist_name, v2_metric,
                                                      'v2')
      if v2_hist is None:
        continue
      v2_hists += [v2_hist]

    if v3_hist is None:
      if len(v2_hists) > 0:
        raise Exception('Expected a %s v3 histogram, but none exists' %
                        (v3_hist_name))
      continue

    if len(v2_hists) == 0:
      raise Exception('Have a %s v3 histogram but no matching v2 ones' %
                      (v3_hist_name))

    v2_samples = []
    for v2_hist in v2_hists:
      v2_samples += [s for s in v2_hist.sample_values if s is not None]
    v3_samples = [s for s in v3_hist.sample_values if s is not None]

    test_ctx.assertEqual(len(v2_samples), len(v3_samples))
    v2_samples.sort()
    v3_samples.sort()
    for v2_sample, v3_sample in zip(v2_samples, v3_samples):
      test_ctx.assertAlmostEqual(v2_sample,
                                 v3_sample,
                                 delta=simple_config['float_precision'])


text:
echo ##### restoring
adb shell twrp restore /sdcard/backup/twrp_backup
::Delete the backup folder
adb shell rm -R /sdcard/backup/twrp_backup


text:
puts "ZoneMember..."
puts "USA Zones"
continental_zone = Zone.find_or_create_by_name('Continental USA', :description => 'Continental United States')
non_continental_zone = Zone.find_or_create_by_name('Non-continental USA', :description => 'Non-continental United States')
armed_forces_zone = Zone.find_or_create_by_name('APO/AFO', :description => 'US Armed Forces')
territories_zone = Zone.find_or_create_by_name('US Territories', :description => 'United States Territories & Minor Outlying Islands')
all_usa_zone = Zone.find_or_create_by_name('ALL US', :description => 'All US Sates & Territories, Including Armed Forces')

non_continental_states = %w(HI AK)
armed_forces_states = %w(AP AA AE)
territories = %w(MH PW FM AS GU MP PR VI UM)

# add states to correct zone
puts "\tAdd states to correct zone"
Country.find_by_iso('US').states.order('abbr asc').each do |state|
  if non_continental_states.include?(state.abbr)
    zone = non_continental_zone
  elsif armed_forces_states.include?(state.abbr)
    zone = armed_forces_zone
  else
    zone = continental_zone
  end

  next if zone.includes_zoneable? state

  puts "#{state.abbr} -> #{zone.name}"
  member = ZoneMember.create(:zone => zone, :zoneable => state, :zoneable_type => 'State')
  zone.members << member
end

puts "\tAdd territories to territory_zone"
territories.each do |t|
  state = State.find_by_abbr!(t)
  next if territories_zone.includes_zoneable? state
  puts "\t\t#{state.abbr} -> #{territories_zone.name}"
  member = ZoneMember.create(:zone => territories_zone, :zoneable => state, :zoneable_type => 'State')
  territories_zone.members << member
end

puts "\tAdd all us zones to USA"
[continental_zone, non_continental_zone, armed_forces_zone, territories_zone].each do |zone|
  next if all_usa_zone.includes_zoneable? zone
  member = ZoneMember.create(:zone => all_usa_zone, :zoneable => zone, :zoneable_type => 'Zone')
  all_usa_zone.members << member
end

puts "International Zone"
intl_zone = Zone.find_or_create_by_name('International', :description => 'International Zone')
Country.where('iso not in (?)', Zone.find_by_name('ALL US').country_list.collect(&:iso)).each do |country|
  intl_zone.members << ZoneMember.create(:zone => intl_zone, :zoneable => country, :zoneable_type => 'Country')
end


text:
// Copyright (c) Dominick Baier & Brock Allen. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using Newtonsoft.Json;
using System;
using System.Security.Claims;

namespace IdentityModel.AspNetCore.OAuth2Introspection
{
    internal class ClaimConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(Claim) == objectType;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var source = serializer.Deserialize<ClaimLite>(reader);
            var target = new Claim(source.Type, source.Value);

            return target;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Claim source = (Claim)value;

            var target = new ClaimLite
            {
                Type = source.Type,
                Value = source.Value
            };

            serializer.Serialize(writer, target);
        }
    }

    internal class ClaimLite
    {
        public string Type { get; set; }
        public string Value { get; set; }
    }
}


text:
if (($# < 1)); then
  echo "Usage: $0 package1 package2 ..." >&2
  echo "Env variables with their defaults:" >&2
  echo "  - INDEXER_OUTPUT_DIR=/tmp/indexer-output" >&2
  echo "    Where to put indexing logs and output entries." >&2
  exit 1
fi

# Directory where to build the index. Need to export it, so the GHC wrapper
# executed as subprocess has access to it. Has to be an absolute path,
# since the wrapper will be invoked in various directories.
export INDEXER_OUTPUT_DIR=$(readlink -f "${INDEXER_OUTPUT_DIR:-/tmp/indexer-output}")
[ ! -d "$INDEXER_OUTPUT_DIR" ] && mkdir -p "$INDEXER_OUTPUT_DIR"

# REALGHC is used by stack wrapper ghc. Note that it must be set before
# altering the PATH.
export REALGHC=$(stack path --compiler-exe)

project_root=$(cd "$(dirname "$0")"; pwd)

# Build and index the packages
# ============================
# `stack build` does not rebuild packages if they have been registered in the
# snapshot database (something like ~/.stack/snapshots/x86_64-linux/lts-8.17/8.0.2/pkgdb),
# thus we unregister the packages first to force rebuilding.
# Note: `ghc-pkg unregister` does not unregister dependencies, so dependencies
# won't be reindexed unless explicitly specified in the command line.
#
# Note: disabling for now, as it was not a reliable way to force rebuild, also can break
# the package database.
#
# for i in "${@:1}"; do
#   stack exec -- ghc-pkg latest "$i" &> /dev/null && stack exec \
#     -- ghc-pkg unregister --force "$i" || :
# done

# Put stack wrapper ghc script, ghc-pkg (from compiler-bin) and
# ghc_kythe_wrapper (from local-install-root, invoked by wrappers/stack/ghc) on the PATH.
# $(stack path --compiler-bin) is also on the PATH to make --system-ghc pick it instead
# of system ghc (e.g. /usr/bin/ghc).
PATH="$project_root/wrappers/stack:$(stack path --compiler-bin):$PATH:$(stack path --local-install-root)/bin" \
  stack --system-ghc --force-dirty build "${@:1}"