text:
<?php

return [
    /*
    |--------------------------------------------------------------------------
    | General config
    |--------------------------------------------------------------------------
    */
    'date_format'                   => 'd.m.Y H:i:s',
    'use_register'                  => true,                    // if you want to use register form
    'icons' => [
        'role'                  => 'icon-users',
        'user'                  => 'icon-user'
    ],

    /*
    |--------------------------------------------------------------------------
    | model non visibility
    |--------------------------------------------------------------------------
    */
    'non_visibility' => [
        'super_admin'   => true,
        'role_slugs'    => ['customer']
    ],

    /*
    |--------------------------------------------------------------------------
    | URL config
    |--------------------------------------------------------------------------
    */
    'url' => [
        'login_route'               => 'login',                 // login url
        'logout_route'              => 'logout',                // logout url
        'register_route'            => 'register',              // register url
        'activate_route'            => 'account-activate',      // account activate url
        'forget_password_route'     => 'forget-password',       // forget password url
        'reset_password_route'      => 'reset-password',        // reset password url
        'user'                      => 'users',                 // users url
        'role'                      => 'roles',                 // users url
        'redirect_route'            => 'admin',                 // redirect dashboard route name after login
        'admin_url_prefix'          => 'admin',                 // admin dashboard url prefix
    ],

    /*
    |--------------------------------------------------------------------------
    | Routes on / off
    | if you don't use any route; set false
    |--------------------------------------------------------------------------
    */
    'routes' => [
        'admin' => [
            'role'                  => true,                // admin role resource route
            'user'                  => true,                // admin user resource route
            'user_changePassword'   => true,                // admin user publish get route
            'user_permission'       => true,                // admin user not publish get route
        ],
        'api' => [
            'role'                  => true,                // api role resource route
            'role_models'           => true,                // api role model post route
            'role_group'            => true,                // api role group post route
            'role_detail'           => true,                // api role detail get route
            'role_fastEdit'         => true,                // api role fast edit post route
            'user'                  => true,                // api user resource route
            'user_group'            => true,                // api user group post route
            'user_detail'           => true,                // api user detail get route
            'user_fastEdit'         => true,                // api user fast edit post route
            'user_activate'         => true,                // api user activate get route
            'user_notActivate'      => true,                // api user not activate get route
            'user_avatarPhoto'      => true,                // api user avatar photo post route
            'user_destroyAvatar'    => true,                // api user destroy avatar photo post route
        ]
    ],

    /*
    |--------------------------------------------------------------------------
    | View config
    |--------------------------------------------------------------------------
    | dot notation of blade view path, its position on the /resources/views directory
    */
    'views' => [
        // auth views
        'auth' => [
            'layout'                => 'laravel-modules-core::layouts.auth',        // auth layout
            'login'                 => 'laravel-modules-core::auth.login',          // get login view blade
            'register'              => 'laravel-modules-core::auth.register',       // get register view blade
            'forget_password'       => 'laravel-modules-core::auth.forget_password',// get forget password view blade
            'reset_password'        => 'laravel-modules-core::auth.reset_password', // get reset password view blade
        ],
        // user view
        'user' => [
            'layout'                => 'laravel-modules-core::layouts.admin',       // user layout
            'index'                 => 'laravel-modules-core::user.index',          // get user index view blade
            'create'                => 'laravel-modules-core::user.operation',      // get user create view blade
            'show'                  => 'laravel-modules-core::user.show',           // get user show view blade
            'edit'                  => 'laravel-modules-core::user.operation',      // get user edit view blade
        ],
        // role view
        'role' => [
            'layout'                => 'laravel-modules-core::layouts.admin',       // role layout
            'index'                 => 'laravel-modules-core::role.index',          // get role index view blade
            'create'                => 'laravel-modules-core::role.operation',      // get role create view blade
            'show'                  => 'laravel-modules-core::role.show',           // get role show view blade
            'edit'                  => 'laravel-modules-core::role.operation',      // get role edit view blade
        ],
        // email views
        'email' => [
            'activation'            => 'laravel-modules-core::emails.activation',   // activation mail view blade
            'forget_password'       => 'laravel-modules-core::emails.forget_password'// forget password mail view blade
        ]
    ],

    /*
    |--------------------------------------------------------------------------
    | Models config
    |--------------------------------------------------------------------------
    |
    | ## Options
    |
    | - default_img_path                : model default avatar or photo
    |
    | --- uploads                       : model uploads options
    | - path                            : file path
    | - max_size                        : file allowed maximum size
    | - aspect_ratio                    : if file is image; crop aspect ratio
    | - mimes                           : file allowed mimes
    | - thumbnails                      : if file is image; its thumbnails options
    |
    | NOT: Thumbnails fotoğrafları yüklenirken bakılır:
    |       1. eğer post olarak x1, y1, x2, y2, width ve height değerleri gönderilmemiş ise bu değerlere göre
    |       thumbnails ayarlarında belirtilen resimleri sistem içine kaydeder.
    |       Yani bu değerler post edilmişse aşağıdaki değerleri yok sayar.
    |       2. Eğer yukarıdaki ilgili değerler post edilmemişse, thumbnails ayarlarında belirtilen değerleri
    |       dikkate alarak thumbnails oluşturur
    |
    |       Ölçü Belirtme:
    |       1. İstenen resmin width ve height değerleri verilerek istenen net bir ölçüde resimler oluşturulabilir
    |       2. Width değeri null verilerek, height değerine göre ölçeklenebilir
    |       3. Height değeri null verilerek, width değerine göre ölçeklenebilir
    |--------------------------------------------------------------------------
    */
    'user' => [
        'default_img_path'          => 'vendor/laravel-modules-core/assets/global/img/avatar',
        'uploads' => [
            // profile photo options
            'photo' => [
                'relation'              => false,
                'relation_model'        => null,
                'type'                  => 'image',
                'number_type'           => 'single',
                'column'                => 'photo',
                'path'                  => 'uploads/user',
                'aspect_ratio'          => 1,
                'max_size'              => '5120',
                'mimes'                 => 'jpeg,jpg,jpe,png',
                'thumbnails' => [
                    'small'             => [ 'width' => 35, 'height' => 35],
                    'normal'            => [ 'width' => 300, 'height' => 300],
                    'big'               => [ 'width' => 800, 'height' => 800],
                ]
            ]
        ]
    ],

    /*
    |--------------------------------------------------------------------------
    | Permissions
    |--------------------------------------------------------------------------
    */
    'permissions' => [
        'role' => [
            'title'                 => 'Yönetici Rolleri',
            'routes' => [
                'admin.role.index' => [
                    'title'         => 'Veri Tablosu',
                    'description'   => 'Bu izne sahip olanlar yönetici rolleri veri tablosu sayfasına gidebilir.',
                ],
                'admin.role.create' => [
                    'title'         => 'Ekleme Sayfası',
                    'description'   => 'Bu izne sahip olanlar yönetici rolü ekleme sayfasına gidebilir',
                ],
                'admin.role.store' => [
                    'title'         => 'Ekleme',
                    'description'   => 'Bu izne sahip olanlar yönetici rolü ekleyebilir',
                ],
                'admin.role.show' => [
                    'title'         => 'Gösterme',
                    'description'   => 'Bu izne sahip olanlar yönetici rolü bilgilerini görüntüleyebilir',
                ],
                'admin.role.edit' => [
                    'title'         => 'Düzenleme Sayfası',
                    'description'   => 'Bu izne sahip olanlar yönetici rolünü düzenleme sayfasına gidebilir',
                ],
                'admin.role.update' => [
                    'title'         => 'Düzenleme',
                    'description'   => 'Bu izne sahip olanlar yönetici rolünü düzenleyebilir',
                ],
                'admin.role.destroy' => [
                    'title'         => 'Silme',
                    'description'   => 'Bu izne sahip olanlar yönetici rolünü silebilir',
                ],
                'api.role.index' => [
                    'title'         => 'Listeleme',
                    'description'   => 'Bu izne sahip olanlar yönetici rollerini veri tablosunda listeleyebilir',
                ],
                'api.role.store' => [
                    'title'         => 'Hızlı Ekleme',
                    'description'   => 'Bu izne sahip olanlar yönetici rollerini veri tablosunda hızlı ekleyebilir.',
                ],
                'api.role.update' => [
                    'title'         => 'Hızlı Düzenleme',
                    'description'   => 'Bu izne sahip olanlar yönetici rollerini veri tablosunda hızlı düzenleyebilir.',
                ],
                'api.role.destroy' => [
                    'title'         => 'Silme',
                    'description'   => 'Bu izne sahip olanlar yönetici rollerini veri tablosunda silebilir',
                ],
                'api.role.models' => [
                    'title'         => 'Seçim İçin Listeleme',
                    'description'   => 'Bu izne sahip olanlar yönetici rollerini bazı seçim kutularında listeleyebilir',
                ],
                'api.role.group' => [
                    'title'         => 'Toplu İşlem',
                    'description'   => 'Bu izne sahip olanlar yönetici rollerini veri tablosunda toplu işlem yapabilir',
                ],
                'api.role.detail' => [
                    'title'         => 'Detaylar',
                    'description'   => 'Bu izne sahip olanlar yönetici rollerini tablosunda detayını görebilir.',
                ],
                'api.role.fastEdit' => [
                    'title'         => 'Hızlı Düzenleme Bilgileri',
                    'description'   => 'Bu izne sahip olanlar yönetici rollerini tablosunda hızlı düzenleme amacıyla bilgileri getirebilir.',
                ],
            ],
        ],
        'user' => [
            'title'                 => 'Yöneticiler',
            'routes' => [
                'admin.user.index' => [
                    'title'         => 'Veri Tablosu',
                    'description'   => 'Bu izne sahip olanlar yöneticiler veri tablosu sayfasına gidebilir.',
                ],
                'admin.user.create' => [
                    'title'         => 'Ekleme Sayfası',
                    'description'   => 'Bu izne sahip olanlar yönetici ekleme sayfasına gidebilir',
                ],
                'admin.user.store' => [
                    'title'         => 'Ekleme',
                    'description'   => 'Bu izne sahip olanlar yönetici ekleyebilir',
                ],
                'admin.user.show' => [
                    'title'         => 'Gösterme',
                    'description'   => 'Bu izne sahip olanlar yönetici bilgilerini görüntüleyebilir',
                ],
                'admin.user.edit' => [
                    'title'         => 'Düzenleme Sayfası',
                    'description'   => 'Bu izne sahip olanlar yöneticiyi düzenleme sayfasına gidebilir',
                ],
                'admin.user.update' => [
                    'title'         => 'Düzenleme',
                    'description'   => 'Bu izne sahip olanlar yöneticiyi düzenleyebilir',
                ],
                'admin.user.destroy' => [
                    'title'         => 'Silme',
                    'description'   => 'Bu izne sahip olanlar yöneticiyi silebilir',
                ],
                'admin.user.changePassword' => [
                    'title'         => 'Şifre Değiştirme',
                    'description'   => 'Bu izne sahip olanlar yönetici şifresini değiştirebilir.)',
                ],
                'admin.user.permission' => [
                    'title'         => 'İşlem İzinleri',
                    'description'   => 'Bu izne sahip olanlar yönetici işlem izinlerini güncelleyebilir.',
                ],
                'api.user.index' => [
                    'title'         => 'Listeleme',
                    'description'   => 'Bu izne sahip olanlar yöneticileri veri tablosunda listeleyebilir',
                ],
                'api.user.store' => [
                    'title'         => 'Hızlı Ekleme',
                    'description'   => 'Bu izne sahip olanlar yöneticileri veri tablosunda hızlı ekleyebilir.',
                ],
                'api.user.update' => [
                    'title'         => 'Hızlı Düzenleme',
                    'description'   => 'Bu izne sahip olanlar yöneticileri veri tablosunda hızlı düzenleyebilir.',
                ],
                'api.user.destroy' => [
                    'title'         => 'Silme',
                    'description'   => 'Bu izne sahip olanlar yöneticileri veri tablosunda silebilir',
                ],
                'api.user.group' => [
                    'title'         => 'Toplu İşlem',
                    'description'   => 'Bu izne sahip olanlar yöneticiler veri tablosunda toplu işlem yapabilir',
                ],
                'api.user.detail' => [
                    'title'         => 'Detaylar',
                    'description'   => 'Bu izne sahip olanlar yöneticiler tablosunda detayını görebilir.',
                ],
                'api.user.fastEdit' => [
                    'title'         => 'Hızlı Düzenleme Bilgileri',
                    'description'   => 'Bu izne sahip olanlar yöneticiler tablosunda hızlı düzenleme amacıyla bilgileri getirebilir.',
                ],
                'api.user.activate' => [
                    'title'         => 'Aktifleştirme',
                    'description'   => 'Bu izne sahip olanlar yöneticinin durumunu aktifleştirebilir.',
                ],
                'api.user.notActivate' => [
                    'title'         => 'Aktifliği Kaldırma',
                    'description'   => 'Bu izne sahip olanlar yöneticinin aktifliğini kaldırabilir.',
                ],
                'api.user.avatarPhoto' => [
                    'title'         => 'Profil Fotoğrafı',
                    'description'   => 'Bu izne sahip olanlar yöneticinin profil fotoğrafını güncelleyebilir.',
                ],
                'api.user.destroyAvatar' => [
                    'title'         => 'Profil Fotoğrafı Silme',
                    'description'   => 'Bu izne sahip olanlar yöneticinin profil fotoğrafını silebilir.',
                ],
            ],
        ],
    ],
];


text:
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Net;
using System.Text;
using System.Web.Http;

namespace PageAccessToken.Controllers
{
    public class AccessTokenController : ApiController //extends the ApiController class as ApiControllers are specialized for returning data to the client
    {
        string Server = "https://api.chayns.net/v2.0/";
        //replace the following string with the tapp secret of your developer tapp
        string Secret = "";

        //Call this controller method with localhost/PageAccessToken/AccessToken?locationId=chayns.env.site.locationId&tappId=chayns.env.site.tapp.id
        public IHttpActionResult Get(int locationId, int tappId)
        {
            try
            {
                /*
                * The following variable keeps all the permissions that should be available with the created accessToken.
                * Remember to only set those permissions, you have set in the tapp administration as well.
                */
                string[] permissions = new string[] { "PublicInfo", "UserInfo", "SeeUAC", "EditUAC", "DeviceInfo", "Push", "Intercom", "Email" };

                string authHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToString(tappId) + ":" + Secret)); //for more information see the chayns-backend wiki/authorization
                RestClient rc = new RestClient(Server);

                RestRequest rr = new RestRequest(locationId + "/AccessToken", Method.POST);

                rr.AddHeader("Authorization", "Basic " + authHeader);
                rr.AddHeader("Content-Type", "application/json");
                rr.RequestFormat = DataFormat.Json;
                rr.AddBody(new { Permissions = permissions });

                IRestResponse rs = rc.Execute(rr);  //At this point we already got the response from the chayns backend api

                //If all parameters were set correctly, this should've returned a status 200
                if (rs.StatusCode == HttpStatusCode.OK)
                {
                    dynamic data = JObject.Parse(rs.Content);
                    return Ok(new { PageAccessToken = data.data[0].pageAccessToken });
                }
                else
                {
                    return StatusCode(rs.StatusCode);
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Oro\Bundle\MessageQueueBundle\Tests\Unit\Consumption\Extension;

use Doctrine\DBAL\Connection;
use Oro\Bundle\MessageQueueBundle\Consumption\Extension\DoctrinePingConnectionExtension;
use Oro\Component\MessageQueue\Consumption\Context;
use Oro\Component\MessageQueue\Consumption\MessageProcessorInterface;
use Oro\Component\MessageQueue\Transport\MessageConsumerInterface;
use Oro\Component\MessageQueue\Transport\SessionInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;

class DoctrinePingConnectionExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testCouldBeConstructedWithRequiredAttributes()
    {
        new DoctrinePingConnectionExtension($this->createRegistryMock());
    }

    public function testShouldNotReconnectIfConnectionIsOK()
    {
        $connection = $this->createConnectionMock();
        $connection
            ->expects($this->once())
            ->method('ping')
            ->will($this->returnValue(true))
        ;
        $connection
            ->expects($this->never())
            ->method('close')
        ;
        $connection
            ->expects($this->never())
            ->method('connect')
        ;

        $context = $this->createContext();
        $context->getLogger()
            ->expects($this->never())
            ->method('debug')
        ;

        $registry = $this->createRegistryMock();
        $registry
            ->expects($this->once())
            ->method('getConnections')
            ->will($this->returnValue([$connection]))
        ;

        $extension = new DoctrinePingConnectionExtension($registry);
        $extension->onPreReceived($context);
    }

    public function testShouldDoesReconnectIfConnectionFailed()
    {
        $connection = $this->createConnectionMock();
        $connection
            ->expects($this->once())
            ->method('ping')
            ->will($this->returnValue(false))
        ;
        $connection
            ->expects($this->once())
            ->method('close')
        ;
        $connection
            ->expects($this->once())
            ->method('connect')
        ;

        $context = $this->createContext();
        $context->getLogger()
            ->expects($this->at(0))
            ->method('debug')
            ->with('[DoctrinePingConnectionExtension] Connection is not active trying to reconnect.')
        ;
        $context->getLogger()
            ->expects($this->at(1))
            ->method('debug')
            ->with('[DoctrinePingConnectionExtension] Connection is active now.')
        ;

        $registry = $this->createRegistryMock();
        $registry
            ->expects($this->once())
            ->method('getConnections')
            ->will($this->returnValue([$connection]))
        ;

        $extension = new DoctrinePingConnectionExtension($registry);
        $extension->onPreReceived($context);
    }

    /**
     * @return Context
     */
    protected function createContext()
    {
        $context = new Context($this->getMock(SessionInterface::class));
        $context->setLogger($this->getMock(LoggerInterface::class));
        $context->setMessageConsumer($this->getMock(MessageConsumerInterface::class));
        $context->setMessageProcessor($this->getMock(MessageProcessorInterface::class));

        return $context;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|RegistryInterface
     */
    protected function createRegistryMock()
    {
        return $this->getMock(RegistryInterface::class);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|Connection
     */
    protected function createConnectionMock()
    {
        return $this->getMock(Connection::class, [], [], '', false);
    }
}


text:
cask "deezer" do
  version "5.30.120"
  sha256 "cc96bc16faa85d77f9f4baa7e8a2ea7ce1cccd1ede4d78c9c0d9c4574a8b93d7"

  url "https://www.deezer.com/desktop/download/artifact/darwin/x64/#{version}"
  name "Deezer"
  desc "Music player"
  homepage "https://www.deezer.com/download"

  livecheck do
    url "https://www.deezer.com/desktop/download?platform=darwin&architecture=x64"
    strategy :header_match
  end

  auto_updates true
  depends_on macos: ">= :yosemite"

  app "Deezer.app"

  zap trash: [
    "~/Library/Application Support/Caches/deezer-desktop-updater",
    "~/Library/Application Support/deezer-desktop",
    "~/Library/Caches/com.deezer.deezer*",
    "~/Library/Logs/Deezer",
    "~/Library/Logs/deezer-desktop",
    "~/Library/Preferences/ByHost/com.deezer.*",
    "~/Library/Preferences/com.deezer.deezer-desktop.plist",
    "~/Library/Saved Application State/com.deezer.deezer-desktop.savedState",
  ]
end


text:
require_relative 'quincite/core.rb'
require_relative 'quincite/components'
require_relative 'quincite/events.rb'


text:
yozen
=====

Zenman Yeoman Generator


text:
CLANG?=/usr/local/opt/llvm/bin/clang
CLANGCMD=${CLANG} -emit-llvm -DFULL_UNROLL
LLVM_LINK?=/usr/local/opt/llvm/bin/llvm-link
SAW?=../../bin/saw
DEPS?=../../deps
CRYPTOL?=${DEPS}/cryptol
CRYPTOLPATH?=${CRYPTOL}/examples

OPENSSL_VERSION?=1.1.1g
SRCDIR=openssl-${OPENSSL_VERSION}
TARBALL=${SRCDIR}.tar.gz

CFLAGS=-I${SRCDIR}/include \
       -I${SRCDIR}/crypto/aes

all: aes.log

${TARBALL}:
	wget http://openssl.org/source/${TARBALL}

${SRCDIR}/Configure: ${TARBALL}
	tar -xzvf ${TARBALL}

# Notes on "Configure":
#   * The "darwin64" choice is arbitrary. Other platforms should work.
#   * The "debug" portion avoids optimization. This is critical because
#     we currently don't support some instructions generated by the
#     optimizing build.
#   * The "no-asm" bit is crucial because we can't currently analyze asm.
${SRCDIR}/Makefile: ${SRCDIR}/Configure
	(cd ${SRCDIR} && CC="${CLANGCMD}" ./Configure debug-darwin64-x86_64-cc no-asm)

${SRCDIR}/crypto/aes/aes_core.o: ${SRCDIR}/Makefile
	(cd ${SRCDIR} && make CC="${CLANGCMD}" include/openssl/opensslconf.h crypto/aes/aes_core.o)

aes_wrap.bc: aes_wrap.c ${SRCDIR}/crypto/aes/aes_core.o
	${CLANGCMD} -c ${CFLAGS} -o $@ $<

aes_all.bc: aes_wrap.bc ${SRCDIR}/crypto/aes/aes_core.o
	${LLVM_LINK} -o $@ $^

export CRYPTOLPATH := ${CRYPTOLPATH}
aes.log: aes_all.bc aes.saw
	${SAW} aes.saw 2>&1 | tee $@

clean:
	rm -rf ${SRCDIR}
	rm -f aes_wrap.bc aes_all.bc


text:
		Star

		{stargazers_count}

		Fork

		{forks_count}


text:
import EventCalendarComponent from 'ember-cli-event-calendar/components/event-calendar';
export default EventCalendarComponent;


text:
<?xml version="1.0"?>

<scenario xmlns="http://www.github/gregtampa/HBCTF-Battlegrounds/scenario"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.github/gregtampa/HBCTF-Battlegrounds/scenario">

  <system>
    <system_name>storage_server</system_name>
    <base platform="linux"/>

    <vulnerability module_path="modules/vulnerabilities/unix/bash/shellshock"/>

    <network type="private_network" range="dhcp"/>
  </system>

</scenario>


text:
/************************************************************
 * @file         GroupEntity.h
 * @author       快刀<kuaidao@mogujie.com>
 * summery       群实体信息
 ************************************************************/

#import <Foundation/Foundation.h>
#import "DDBaseEntity.h"
static NSString* const GROUP_PRE = @"group_";          //group id 前缀

enum
{
    GROUP_TYPE_FIXED = 1,       //固定群
    GROUP_TYPE_TEMPORARY,       //临时群
};

@interface DDGroupEntity : DDBaseEntity

@property(nonatomic,strong) NSString* groupCreatorId;        //群创建者ID
@property(nonatomic,assign) int groupType;                //群类型
@property(nonatomic,strong) NSString* groupId;               //群ID
@property(nonatomic,strong) NSString* name;                  //群名称
@property(nonatomic,strong) NSString* avatar;                //群头像
@property(nonatomic,strong) NSMutableArray* groupUserIds;    //群用户列表ids
@property(nonatomic,readonly)NSMutableArray* fixGroupUserIds;//固定的群用户列表IDS,用户生成群头像
@property(strong)NSString *lastMsg;
//对群成员排序
-(void)sortGroupUsers;

-(void)copyContent:(DDGroupEntity*)entity;

- (void)addFixOrderGroupUserIDS:(NSString*)ID;
+(DDGroupEntity *)dicToGroupEntity:(NSDictionary *)dic;
@end


text:
package com.verigreen.restclient;

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

import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.MediaType;

public class Request {

    private final String _uri;
    private Map<String, String> _queryParams;
    private Map<String, Object> _pathTemplateParams;
    private final Object _entity;
    private final String _mediaType;

    private Collection<Cookie> _cookies = new ArrayList<>();
    private Map<String, Object> _headers = new HashMap<>();
    private String _body;

    public Request(String uri, Object entity, MediaType mediaType) {

        this(uri, entity, mediaType.toString(), null, null);
    }

    public Request(String uri, Object entity, String mediaType) {

        this(uri, entity, mediaType, null, null);
    }

    public Request(
            String uri,
            Object entity,
            String mediaType,
            List<Cookie> cookies,
            Map<String, Object> headers) {

        _uri = uri;
        _entity = entity;
        _mediaType = mediaType;
        if (cookies != null) {
            _cookies = cookies;
        }
        if (headers != null) {
            _headers = headers;
        }
    }

    public Request(String uri) {

        this(uri, null, MediaType.APPLICATION_JSON_TYPE.toString(), null, null);
    }

    public String getUri() {

        return _uri;
    }

    public Object getEntity() {

        return _entity;
    }

    public String getMediaType() {

        return _mediaType;
    }

    public Map<String, String> getQueryParams() {

        return _queryParams;
    }

    public void setQueryParams(Map<String, String> queryParams) {

        _queryParams = queryParams;
    }

    public Map<String, Object> getPathTemplateParams() {

        return _pathTemplateParams;
    }

    public void setPathTemplateParams(Map<String, Object> pathTemplateParams) {

        _pathTemplateParams = pathTemplateParams;
    }

    public Collection<Cookie> getCookies() {

        return _cookies;
    }

    public void setCookie(Cookie cookie) {

        _cookies.add(cookie);
    }

    public Map<String, Object> getHeaders() {

        return _headers;
    }

    public void addHeader(String name, String value) {

        _headers.put(name, value);
    }

    public String getBody() {

        return _body;
    }

    public void setBody(String body) {

        this._body = body;
    }
}


text:
int DEPTH=100;
size_t finished;
int verbose = 0;
int keepRunning = 1;
char *benchmarkFile = NULL, *logFile = NULL;
FILE *bfp = NULL, *lfp = NULL;
int openmode = 0;
char *dirPrefix = NULL;
size_t verify = 0, dofdatasync = 0;
size_t allocatePerFile = 0;

typedef struct {
  size_t threadid;
  size_t totalFileSpace;
  size_t maxthreads;
  size_t writesize;
  size_t filesize;
  size_t numfiles;
  size_t *fileid;
  char *actions;
} threadInfoType;

size_t diskSpace(const char *prefix)
{
  struct statvfs buf;

  statvfs(prefix, &buf);
  size_t t =  buf.f_blocks;
  t = t * buf.f_bsize;
  return t;
}

int createAction(const char *filename, char *buf, const size_t size, const size_t writesize)
{
  int fd = open(filename, openmode | O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);

  if (fd > 0) {
    size_t towrite = size;
    while (towrite > 0) {
      int written = write(fd, buf, MIN(towrite, writesize));
      //      fprintf(stderr,"%s %zd\n", filename, MIN(towrite, writesize));
      if (written > 0) {
        towrite -= written;
      } else if (written == 0) {
        fprintf(stderr,"zero byte write\n");
      } else {
        perror("write");
        break;
      }
    }
    if (dofdatasync) fsync(fd);
    close(fd);
    if (verbose) fprintf(stderr,"*info* wrote file %s, size %zd, char %d\n", filename, size, buf[0]);
    return 0;
  } else {
    perror(filename);
    fprintf(stderr,"*error* didn't write %s, skipping\n", filename);
    return 1;
  }
}

int readAction(const char *filename, char *buf, size_t size)
{
  int fd = open(filename, openmode | O_RDONLY);
  int ret = -1;

  if (fd > 0) {
    ret = 0;
    size_t toread = 0;
    size_t zerocount = 0;
    while (toread != size) {
      int readd = read(fd, buf, size);
      if (readd > 0) {
        toread += readd;
      } else if (readd == 0) {
        zerocount++;
        fprintf(stderr,"'%s' truncated at %zd before size %zd\n", filename, toread, size);
        ret = -3;
        break;
      } else {
        ret = -2;
        perror("read");
        break;
      }
    }
    close(fd);
    if (verbose) fprintf(stderr,"*info* read file %s, size %zd, char %d\n", filename, size, buf[0]);
  } else {
    ret = -3;
    //        fprintf(stderr,"*error* couldn't open %s, skipping\n", filename);
    //exit(1);
  }
  //  fprintf(stderr,"ret %d\n", ret);
  return ret;
}

void* worker(void *arg)
{
  threadInfoType *threadContext = (threadInfoType*)arg;
  const size_t totalfilespace = threadContext->totalFileSpace;
  size_t numfiles = threadContext->numfiles;

  char *verifybuf = aligned_alloc(4096, threadContext->filesize);
  assert(verifybuf);
  char *s = aligned_alloc(4096, 1024*1024);
  assert(s);
  char *buf = NULL;

  size_t processed = 0, sum = 0, skipped = 0, secsum = 0, lastsecsum = 0;
  double starttime = timedouble(), lasttime = starttime;
  size_t lastfin = 0, pass = 0;

  char outstring[1000], logstring[1000];

  while (!finished) {
    for (size_t i = 0; !finished && i < numfiles; i++) {

      if (!buf || allocatePerFile) {
        if (buf) free(buf);
        buf = aligned_alloc(4096, threadContext->filesize);
        assert(buf);
        memset(buf, threadContext->threadid, threadContext->filesize);
      }

      if (i == 0) {
        pass++;
      }
      const size_t wqfin = processed;

      {
        if (threadContext->threadid == 0) {
          const double thistime = timedouble();
          const double tm = thistime - lasttime;

          if (tm > 1) {
            const size_t fin = wqfin - lastfin;
            lastfin = wqfin;

            const double thistime = timedouble();
            const double tm = thistime - lasttime;
            lasttime = thistime;

            sprintf(logstring, "*info* [%zd] [pass %zd] [fileid %zd (%zd) / %zd], files %zd, %.0lf files/second, %.1lf GB, %.2lf LBA, %.0lf MB/s, %.1lf seconds (%.1lf), free %.0lf, dirty %.0lf, cached %.0lf\n", threadContext->maxthreads, pass, wqfin, wqfin % threadContext->numfiles, threadContext->numfiles, processed * threadContext->maxthreads, (fin * threadContext->maxthreads/ tm), TOGB(sum), sum * 1.0/totalfilespace, TOMB((secsum - lastsecsum) * 1.0)/tm, thistime - starttime, tm, TOMiB(freeRAM()), TOMiB(dirtyPagesBytes()), TOMiB(getCachedBytes()));

            sprintf(outstring, "%.3lf\t%zd\t%.0lf\n", thistime - starttime, processed * threadContext->maxthreads, (fin * threadContext->maxthreads/ tm));

            lasttime = thistime;
            lastsecsum = secsum;

            if (lfp) {
              fprintf(lfp, "%s", logstring);
              fflush(bfp);
            }
            if (bfp) {
              fprintf(bfp, "%s", outstring);
              fflush(bfp);
            }

            fprintf(stderr,"%s", logstring);
          }
        }
        // do the mahi

        unsigned int thisseed = threadContext->fileid[i] + threadContext->threadid;
        size_t val = rand_r(&thisseed);
        //	const size_t val = threadContext->fileid[i] + (i * threadContext->threadid);
        if (dirPrefix) {
          sprintf(s, "%s/%02x/%02x/%010zd.thread.%zd", dirPrefix, (((unsigned int)val)/DEPTH) % DEPTH, ((unsigned int)val)%DEPTH, val, threadContext->threadid);
        } else {
          sprintf(s, "%02x/%02x/%010zd.thread.%zd", (((unsigned int)val)/DEPTH) % DEPTH, ((unsigned int)val)%DEPTH, val, threadContext->threadid);
        }
        //	fprintf(stderr,"thread %zd, id %zd, filename '%s', dirPrefix '%s'\n", threadContext->threadid, val, s, dirPrefix ? dirPrefix : "");

        //      	  	  	  fprintf(stderr,"[%zd] %c %s\n", action.id, action.type, action.payload);
        switch (threadContext->actions[i]) {
        case 'W':
          if (createAction(s, buf, threadContext->filesize, threadContext->writesize) == 0) {
            processed++;
            sum += (threadContext->maxthreads * threadContext->filesize);
            secsum  = sum;

            if (verify) {
              memset(verifybuf, 0xff, threadContext->filesize);
              int ret = readAction(s, verifybuf, threadContext->filesize);
              if (ret == 0) {
                if (memcmp(buf, verifybuf, threadContext->filesize) != 0) {
                  fprintf(stderr,"*error* verification error on %s", s);
                  exit(1);
                } else {
                  if (verbose) fprintf(stderr,"*info* verified file %s OK, char %d\n", s, verifybuf[0]);
                }
              } else {
                perror(s);
                exit(1);
              }
            }

          }
          break;
        case 'R':
        {}
        int ret = readAction(s, buf, threadContext->filesize);
        if (ret == 0) {
          processed++;
          //	      fprintf(stderr,"%s\n", s);
          //	    fprintf(stderr,"process %zd ret %d\n", processed, ret);
          sum += (threadContext->maxthreads * threadContext->filesize);
        } else {
          //	    fprintf(stderr,"processed %zd, skipped %s\n", wqfin, s);
          skipped++;
        }
        break;
        default:
          abort();
        }
      }
    }
  }
  if (s) free(s);
  if (verifybuf) free(verifybuf);
  if (buf) free(buf);
  return NULL;
}

int threads = 32;
size_t filesize = 360*1024;
size_t writesize = 1024*1024;

void usage()
{

  fprintf(stdout, "Usage:\n");
  fprintf(stdout, "  fsfiller -F mountpath [-D] [-t 0] [-T %d] [-k %zd] [-K %zd] [-u] [-w] [-R 42] [option] [option]\n\n", threads, filesize/1024, writesize/1024);
  fprintf(stdout, "\nDescription:\n");
  fprintf(stdout, "  Calculates the disk space from mountpath, takes a high percentage (93%%)\n");
  fprintf(stdout, "  and estimates the total number of files / thread that can be created.\n");
  fprintf(stdout, "  Created files are placed in a 100x100 directory structure.\n");
  fprintf(stdout, "  Worker threads are spawned and the files are created in a loop.\n");
  fprintf(stdout, "\nOptions:\n");
  fprintf(stdout, "  -A         \tallocate RAM per file\n");
  fprintf(stdout, "  -B file    \tbenchmarke file\n");
  fprintf(stdout, "  -L file    \tstderr/logfile\n");
  fprintf(stdout, "  -d         \tdirect mode (O_DIRECT)\n");
  fprintf(stdout, "  -D         \tpagecache mode (default)\n");
  fprintf(stdout, "  -F path    \tset the path for testing\n");
  fprintf(stdout, "  -k filesize\tfile size in KiB (default %zd)\n", filesize / 1024);
  fprintf(stdout, "  -K size    \tblock size in KiB (default %zd)\n", writesize / 1024);
  fprintf(stdout, "  -r         \tread test\n");
  fprintf(stdout, "  -R         \tset seed to n (default %d)\n", 42);
  fprintf(stdout, "  -S         \tsend fsync() after writing\n");
  fprintf(stdout, "  -w         \twrite test (default)\n");
  fprintf(stdout, "  -t secs    \ttimelimit in seconds (default 0/unlimited)\n");
  fprintf(stdout, "  -T n       \tn threads (default %d)\n", threads);
  fprintf(stdout, "  -u         \tunique filenames (default)\n");
  fprintf(stdout, "  -U         \tnon-unique filenames (with replacement)\n");
  fprintf(stdout, "  -v         \tverify each write\n");
  fprintf(stdout, "  -V         \tverbose\n");

}

int main(int argc, char *argv[])
{

  int read = 0;
  int opt = 0, help = 0;
  unsigned int seed = 42;
  size_t unique = 1;
  size_t timelimit = 0;

  while ((opt = getopt(argc, argv, "T:Vk:K:hrwB:R:uUsDdt:F:vSH:L:")) != -1) {
    switch (opt) {
    case 'A':
      allocatePerFile = 1;
      break;
    case 'B':
      benchmarkFile = optarg;
      break;
    case 'L':
      logFile = optarg;
      break;
    case 'D':
      openmode = 0;
      break;
    case 'F':
      dirPrefix = optarg;
      break;
    case 'd':
      openmode = O_DIRECT;
      break;
    case 'r':
      read = 1;
      break;
    case 'H':
      DEPTH=atoi(optarg);
      if (DEPTH<1) DEPTH=1;
      break;
    case 'R':
      seed = atoi(optarg);
      break;
    case 'w':
      read = 0;
      break;
    case 'h':
      help = 1;
      break;
    case 'k':
      filesize = alignedNumber(1024 * atoi(optarg), 4096);
      break;
    case 'K':
      writesize = alignedNumber(1024 * atoi(optarg), 4096);
      break;
    case 'T':
      threads = atoi(optarg);
      break;
    case 'u':
      unique = 1;
      break;
    case 'U':
      unique = 0; // with replacement
      break;
    case 's':
      unique = 2; // 2 is sequential
      break;
    case 'S':
      dofdatasync = 1;
      break;
    case 't':
      timelimit = atoi(optarg);
      break;
    case 'v':
      verify = 1;
      break;
    case 'V':
      verbose++;
      break;
    }

  }

  if (help) {
    usage();
    exit(0);
  }

  if (swapTotal() != 0) {
    fprintf(stderr,"*warning* SWAP should be off. Pausing for 20 seconds (or you can just `swapoff -a`)\n");
    sleep(20);
  }

  size_t totalfilespace;
  if (dirPrefix) totalfilespace = diskSpace(dirPrefix);
  else totalfilespace = diskSpace(".");

  size_t numFiles = (totalfilespace / filesize) * 0.93 / threads;

  srand(seed);
  fprintf(stderr,"*info* dirPrefix '%s', diskspace %.0lf GB, number of threads %d, file size %zd (block size %zd), numFiles %zd, unique %zd, seed %u, O_DIRECT %d, read %d, %zd secs, verify %zd, fdatasync %zd, allocatePerFile %zd\n", dirPrefix ? dirPrefix : ".", TOGB(totalfilespace), threads, filesize, writesize, numFiles * threads, unique, seed, openmode, read, timelimit, verify, dofdatasync, allocatePerFile);

  printPowerMode();
  if (openmode == 0) {
    dropCaches();
  }

  size_t *fileid = calloc(numFiles, sizeof(size_t));
  assert(fileid);
  char *actions = calloc(numFiles, sizeof(char));
  assert(actions);

  if (read) {
    memset(actions, 'R', numFiles);
  } else {
    memset(actions, 'W', numFiles);
  }

  for (size_t i = 0; i < numFiles; i++) {
    if (unique) { // unique 1 or 2 for seq
      fileid[i] = i;
    } else {
      fileid[i] = rand() % numFiles;
    }
  }
  if (unique == 1) { // if randomise
    for (size_t i = 0; i < numFiles; i++) {
      const size_t j = rand() % numFiles;
      size_t tmp = fileid[i];
      fileid[i] = fileid[j];
      fileid[j] = tmp;
    }
  }

  finished = 0;

  char s[1000];
  fprintf(stderr,"*info* making %d top level directories\n", DEPTH);
  for (int id = 0; id < DEPTH; id++) {
    if (dirPrefix) {
      sprintf(s,"%s/%02x", dirPrefix, id);
    } else {
      sprintf(s,"%02x", id);
    }
    mkdir(s, 0777);
  }
  fprintf(stderr,"*info* making %d x %d two level directories\n", DEPTH, DEPTH);
  for (int id = 0; id < DEPTH * DEPTH; id++) {
    if (dirPrefix) {
      sprintf(s,"%s/%02x/%02x", dirPrefix, (((unsigned int)id)/DEPTH) % DEPTH, ((unsigned int)id)%DEPTH);
    } else {
      sprintf(s,"%02x/%02x", (((unsigned int)id)/DEPTH) % DEPTH, ((unsigned int)id)%DEPTH);
    }
    mkdir(s, 0777);
  }

  if (benchmarkFile) {
    fprintf(stderr,"*info* opening benchmark file '%s'\n", benchmarkFile);
    bfp = fopen(benchmarkFile, "wt");
    if (!bfp) {
      perror("fsfiller");
      exit(1);
    }
  }

  if (logFile) {
    fprintf(stderr,"*info* opening log file '%s'\n", logFile);
    lfp = fopen(logFile, "wt");
    if (!lfp) {
      perror("fsfiller");
      exit(1);
    }
  }

  // setup worker threads
  pthread_t *tid = calloc(threads, sizeof(pthread_t));
  assert(tid);

  threadInfoType *threadinfo = calloc(threads, sizeof(threadInfoType));
  assert(threadinfo);

  for (int i = 0; i < threads; i++) {
    threadinfo[i].threadid = i;
    threadinfo[i].maxthreads = threads;
    threadinfo[i].writesize = writesize;
    threadinfo[i].filesize = filesize;
    threadinfo[i].totalFileSpace = totalfilespace;
    threadinfo[i].numfiles = numFiles;
    threadinfo[i].actions = actions;
    threadinfo[i].fileid = fileid;
    int error = pthread_create(&(tid[i]), NULL, &worker, &threadinfo[i]); // start threads
    if (error != 0) {
      printf("\nThread can't be created :[%s]", strerror(error));
    }
  }

  double starttime = timedouble();
  while (!finished) {
    if (timelimit) {
      if (timedouble() - starttime >= timelimit) {
        finished = 1;
        break;
      }
    }
    sleep(1);
  }

  for (int i = 0; i < threads; i++) {
    pthread_join(tid[i], NULL);
  }

  free(threadinfo);
  free(tid);
  free(fileid);
  free(actions);

  if (bfp) {
    fclose(bfp);
  }

  if (lfp) {
    fclose(lfp);
  }
}


text:
var EventEmitter = require('events').EventEmitter
  , util = require('util')

/**
 * Creates a new instance of RingArray with the provided `size`.
 *
 * @param  {Number}    size The number of items in the RingArray.
 * @return {RingArray}      The newly-constructed RingArray.
 */
function RingArray(size) {
  if (!(this instanceof RingArray)) {
    return new RingArray(size)
  }

  if (typeof size !== 'number' || size < 1) {
    throw new Error('RingArray size must be a positive Number.')
  }

  Object.defineProperty(this, 'size', {
    value: size
  })

  this._items = new Array(size)
  this._nextIndex = 0
  this._overwrite = false
}
RingArray.createRingArray = RingArray
util.inherits(RingArray, EventEmitter)

/**
 * Pushes a new item onto the RingArray at its current write position. If an
 * item would be overwritten by this push, an `"overwrite"` event is fired with
 * that item as its only argument.
 *
 * @param  {Any}       item The item to be added.
 * @return {RingArray}      The RingArray instance, for cascading.
 */
RingArray.prototype.push = push
function push(item) {
  if (this._overwrite) {
    this.emit('overwrite', this._items[this._nextIndex])
  }

  this._items[this._nextIndex++] = item

  if (this._nextIndex >= this.size) {
    this._nextIndex = 0
    this._overwrite = true
  }

  return this
}

/**
 * Returns the item immediately following `index`. If `item` is passed in, it
 * will be checked for consistency against the item at `index`. If consistent
 * and there is no newer item, this method returns `null`.
 *
 * If either the consistency check is not requested or there is both
 * consistency and a newer item, this method returns that item.
 *
 * NOTE: If the same item is added multiple times, the consistency check can
 * produce false positives.
 *
 * @param  {Number} index  The index to follow.
 * @param  {Any}    [item] The item to check consistency against.
 * @return {Any}           The following item.
 */
RingArray.prototype.next = next
function next(index, item) {
  var nextIndex = (index + 1) % this.size

  if (item && this._nextIndex === nextIndex && item === this._items[index]) {
    return null;
  }

  return this._items[nextIndex];
}

/**
 * Returns a shallow copy of a portion of the items in the RingArray as an
 * Array.
 *
 * @param  {Number} begin Zero-based index at which to begin extraction.
 * @param  {Number} end   Zero-based index at which to end extraction. `slice`
 *                        extracts up to but not including end.
 * @return {Array}        A new Array with the `slice`d items.
 */
RingArray.prototype.slice = slice
function slice(begin, end) {
  return this._items.slice(begin, end)
}

/**
 * Returns a String representing the items in the RingArray.
 *
 * @return {String} A String representing the items in the RingArray.
 */
RingArray.prototype.toString = toString
function toString() {
  return String(this._items);
}

/*!
 * Export `RingArray`.
 */
module.exports = RingArray


text:
namespace cc {

// A layer that renders a surface referencing the output of another compositor
// instance or client.
class CC_EXPORT SurfaceLayer : public Layer {
 public:
  // This callback is run when a SurfaceSequence needs to be satisfied, but
  // the parent compositor is unable to. It can be called on either the main
  // or impl threads.
  using SatisfyCallback = base::Callback<void(SurfaceSequence)>;

  // This callback is run to require that a specific SurfaceSequence is
  // received before a SurfaceId is destroyed.
  using RequireCallback = base::Callback<void(SurfaceId, SurfaceSequence)>;

  static scoped_refptr<SurfaceLayer> Create(
      const SatisfyCallback& satisfy_callback,
      const RequireCallback& require_callback);

  void SetSurfaceId(SurfaceId surface_id, float scale, const gfx::Size& size);

  // Layer overrides.
  std::unique_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl) override;
  void SetLayerTreeHost(LayerTreeHost* host) override;
  void PushPropertiesTo(LayerImpl* layer) override;

 protected:
  SurfaceLayer(const SatisfyCallback& satisfy_callback,
               const RequireCallback& require_callback);
  bool HasDrawableContent() const override;

 private:
  ~SurfaceLayer() override;
  void CreateNewDestroySequence();
  void SatisfyDestroySequence();

  SurfaceId surface_id_;
  gfx::Size surface_size_;
  float surface_scale_;
  SurfaceSequence destroy_sequence_;
  SatisfyCallback satisfy_callback_;
  RequireCallback require_callback_;

  DISALLOW_COPY_AND_ASSIGN(SurfaceLayer);
};

}  // namespace cc

#endif  // CC_LAYERS_SURFACE_LAYER_H_


text:
/** @file pna_info.hpp
 *
 *  @brief Contains TDI Info classes for PNA
 *  Object
 */
#ifndef _PNA_INFO_HPP
#define _PNA_INFO_HPP

#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>

#include <tdi/common/tdi_defs.h>
#include <tdi/common/tdi_info.hpp>

#include <tdi/arch/pna/pna_defs.h>

/**
 * @brief Namespace for TDI
 */
namespace tdi {

namespace tdi_json {
namespace values {
namespace pna {
const std::string RANGE = "RANGE";
}  // namespace pna
}  // namespace values
}  // namespace tdi_json

namespace pna {

class TdiInfoMapper : public tdi::TdiInfoMapper {
 public:
  TdiInfoMapper() {
    // Match types
    matchEnumMapAdd(tdi_json::values::pna::RANGE,
                    static_cast<tdi_match_type_e>(TDI_MATCH_TYPE_RANGE));
  }
};

/**
 * @brief Class to help create the correct Table object with the
 * help of a map. Targets should override
 */
class TableFactory : public tdi::TableFactory {
 public:
  virtual std::unique_ptr<tdi::Table> makeTable(
      const TdiInfo * /*tdi_info*/,
      const tdi::TableInfo * /*table_info*/) const override {
    // No tables in PNA currently. Will eventually have Selector, Action profile
    // etc
    return nullptr;
  };
};

}  // namespace pna
}  // namespace tdi

#endif


text:
def terms_from_search_string(search_string):
    """
    Returns a ``(include_terms, exclude_terms)`` tuple, where ``include_terms``
    and ``exclude_terms`` are sets of strings. Currently extremely naive;
    doesn't handle quoted terms.

    """
    terms = set(search_string.split())
    exclude_terms = set((term for term in terms if term.startswith('-')))
    include_terms = terms - exclude_terms
    stripped_exclude_terms = set([term.lstrip('-') for term in exclude_terms])
    return include_terms, stripped_exclude_terms

def search_string_from_terms(include_terms, exclude_terms):
    """

    """
    marked_exclude_terms = ['-' + term for term in exclude_terms or []]
    search_term_list = list(include_terms) + marked_exclude_terms
    search_string = ' '.join(search_term_list)
    return search_string

def intersperse_results(iterators, max_results):
    """
    Given a list of video iterators, returns an iterator which returns one
    result for each iterator until either all iterators are exhausted or
    ``max_results`` videos have been returned.

    """
    # Make a copy of the original list.
    iterators = list(iterators)
    num_results = 0
    while len(iterators) > 0 and num_results < max_results:
        for iterator in iterators[:]:
            try:
                yield iterator.next()
            except StopIteration:
                iterators.remove(iterator)
            else:
                num_results += 1


text:
{% extends "index.html" %}
{% block body %}

Signature Dynamics of Protein Families

SignDy calculates the signature dynamics of families of proteins that share similar folds, but not necessarily similar sequences. Signature dynamics includes shared mode profiles, shared covariance between residue fluctuations, and their variations across family members.

Features

You can use SignDy to

create PDB ensembles of protein families from database searches including DALI and  CATH

evaluate signature dynamics profiles and cross-correlations

calculate shared global mode profiles for assessing conserved motions among family members

assess departures from shared mode profiles and other protein-specific features

examine the spectral overlaps between family members

generate sequence-, structure- and dynamics-based trees for analyzing their evolution

              Reference

              She Zhang, Hongchun Li, James M Krieger, Ivet Bahar.
              SignDy: Discovering the Signature Dynamics of Protein Families with Elastic Network Model Analysis.
              Mol Biol Evol 2019 36(9):2053–2068

              Karolina Mikulska-Ruminska, Indira Shrivastava, James Krieger, She Zhang, Hongchun Li, Hülya Bayır, Sally E Wenzel, Andrew P VanDemark, Valerian E Kagan, Ivet Bahar.
              Characterization of Differential Dynamics, Specificity, and Allostery of Lipoxygenase Family Members.
              J Chem Inf Model 2019 59(5):2496-2508

              Luca Ponzoni, She Zhang, Mary Hongying Cheng, Ivet Bahar.
              Shared dynamics of LeuT superfamily members and allosteric differentiation by structural irregularities and multimerization.
              Philos Trans Royal Soc B 2018 373:20170177.

{% endblock %}


text:
from random import randrange
import random
from model.contact import Contact

def test_contact_delete_first(app, db, check_ui):
    if len(db.get_contact_list()) == 0:
        app.contact.create_new(Contact(firstname="test_new_contact"))
    old_contacts = db.get_contact_list()
    contact = random.choice(old_contacts)
    app.contact.del_contact_by_id(contact.id)
    assert len(old_contacts)-1 == app.contact.count()
    new_contacts = db.get_contact_list()
    old_contacts.remove(contact)
    assert old_contacts == new_contacts
    if check_ui:
        assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_list(), key=Contact.id_or_max)
    ui_list = app.contact.get_list()
    def clean(contact):
        return Contact(firstname=contact.firstname.strip(), lastname=contact.lastname.strip())
    db_list = map(clean, db.get_contact_list())
    assert sorted(ui_list, key=Contact.id_or_max) == sorted(db_list, key=Contact.id_or_max)


text:
<?php
namespace Scheb;

if (version_compare(phpversion(), '5.4', '<')) {
    class CallbackFilterIterator extends \FilterIterator
    {
        protected $callback;

        public function __construct(\Iterator $iterator, \Closure $callback = null)
        {
            $this->callback = $callback;
            parent::__construct($iterator);
        }

        public function accept()
        {
            return call_user_func(
                $this->callback,
                $this->current(),
                $this->key(),
                $this->getInnerIterator()
            );
        }
    }
} else {
    class CallbackFilterIterator extends \CallbackFilterIterator {

    }
}


text:
@interface MOBProjectionEPSG37237 : MOBProjection

@end


text:
This widget is a modification on the standard Layer List Widget available in the standard **ESRI ArcGIS Viewer for Flex**.  It includes the addition of a help link in the widget title bar, the ability to add and remove layers and map services, and an enhanced TOC which can display specified Graphics layers.

**Developed by:**	Edward Correro, (Horizons Regional Council) & Ryan Elley (Environment Canterbury Regional Council)
**Source:**  This widget are based on the code from the Layer List Widget supplied with the ArcGIS Viewer for Flex.  Certain sections of code from  LiveMapsWidget by Robert Scheitlin.
**ArcGIS API for Flex version:**  3.6

## Features ##

- Configurable Help button in the widget title bar that can be used to link to a web page for this widget.  If no url is specified in the widget config file, the button will not be displayed.

- The spatial reference is now added to locally saved bookmarks and can be specified in the config settings.  When a bookmark is opened on a map that has a different coordinate system, the extent is projected to match the map coordinate system.  An error message is displayed if projection is not possible.

## Widget Config File Tag Reference ##

**<addbookmarks\>**
Boolean. Determines whether user defined bookmarks can be added. Default value is 'true'.  User defined bookmarks are saved in flash cookies (local shared objects) on the computer where they are created.

**<bookmarks\>**
Container of spatial bookmarks for the Viewer application. It has one child tag: (<bookmark\>)

**<bookmark\>**
Each bookmark has its own <bookmark> tag. The minimum x,y and maximum x,y coordinates that define the bookmark spatial extent must be in the same spatial reference as the map unless the wkid number for the spatial reference of the bookmark is added as 5th value . If using the Viewer default configuration, these values can be obtained using the Extent Helper application. It has the following attribute:

- name : Name of the bookmark.

**<helplocationurl\>**
Url of the web page that can be called from the help button that is added to the titlebar.  If no url is specified or the tag is blank, the button will not be displayed.

----------

**<labels\>**
The following tags can be used to set the label text displayed on the widget.

- **<bookmarkslabel\>**
ToolTip for the first title bar button (default for English is 'Bookmarks').
- **<addbookmarkslabel\>**
ToolTip for the second title bar button (default for English is 'Add Bookmark').
- **<addlabel\>**
Label for the Add Bookmark input window (default for English is 'Add current extent as a bookmark named').
- **<submitlabel\>**
Label for the custom bookmark creation button (default for English is 'Add Bookmark').
- **<errorlabel\>**
Error message reported when creating a custom bookmark fails (default for English is 'Please enter a name for the bookmark')
- **<helplabel\>**
Tooltip for the third title bar button (default for English is 'Help')

### Example Configuration File ###
	<?xml version="1.0" ?>
	<configuration>
		<addbookmarks>true</addbookmarks>
        <bookmarks>
            ...
            <bookmark> name="Victoria, BC, Canada">-13740900 6174200 -13722700 6181400 102100 </bookmark>
            <bookmark> name="Vancouver, BC, Canada">-13734100 6307700 -13661500 6336500 102100 </bookmark>
            ...
        </bookmarks>
		<helplocationurl>http://somewebsite.com/widgethelp.html</helplocationurl>

		<labels>
			<bookmarkslabel>Bookmarks</bookmarkslabel>
			<addbookmarkslabel>Add Bookmark</addbookmarkslabel>
			<addlabel>Add current extent as a bookmark named</addlabel>
			<submitlabel>Add Bookmark</submitlabel>
			<errorlabel>Please enter a name for the bookmark</errorlabel>
			<helplabel>Help</helplabel>
		</labels>
	</configuration>

## Change Log ##
The following lists the history of changes/updates made.

Change By	Change Date	Change Description

Edward Correro (HRC)	16 June 2010

Initial Development

Iain Campion (ECan)	10 August 2010

Flex Viewer Port

Ryan Elley (ECan)	12 January 2011

Flex Viewer Port 2.2 API and 2.2 viewer

Ryan Elley (ECan)	17 June 2011

Flex Viewer Port 2.3.1 API and 2.3.1 viewer

Ryan Elley (ECan)	30 July 2011

Flex Viewer Port 2.4 API and 2.4 viewer

Ryan Elley (ECan)	19 December 2011

Bug fix for feature layers not showing up in the remove layers list

Ryan Elley (ECan)	10 January 2012

Flex Viewer Port 2.5 API and 2.5 viewer.

Change to use a custom Legend skin to fix issue with extra space showing up if map services use multiple nested groups of layers.

Ryan Elley (ECan)	2 July 2012

Bug fix to applying proxy settings.

Ryan Elley (ECan)	1 October 2012

Bug fix for transparency slider firing when scroll button on mouse is used to zoom in on map.

Ryan Elley (ECan)	28 January 2013

Flex Viewer Port 3.1 API and 3.1 viewer

Ryan Elley (ECan)	21 May 2013

Flex Viewer Port 3.3 API and 3.3 viewer

Ryan Elley (ECan)	13 July 2014

Flex Viewer Port 3.6 API and 3.6 viewer


text:
package common

import (
	"bytes"
	"fmt"
	"io"
	"strconv"
	"strings"
	"time"

	"golang.org/x/net/websocket"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/tools/cache"
	watchtools "k8s.io/client-go/tools/watch"
	podutil "k8s.io/kubernetes/pkg/api/v1/pod"
	"k8s.io/kubernetes/pkg/kubelet"
	"k8s.io/kubernetes/test/e2e/framework"
	e2elog "k8s.io/kubernetes/test/e2e/framework/log"
	imageutils "k8s.io/kubernetes/test/utils/image"

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

var (
	buildBackOffDuration = time.Minute
	syncLoopFrequency    = 10 * time.Second
	maxBackOffTolerance  = time.Duration(1.3 * float64(kubelet.MaxContainerBackOff))
	// maxReadyStatusUpdateTolerance specifies the latency that allows kubelet to update pod status.
	// When kubelet is under heavy load (tests may be parallelized), the delay may be longer, hence
	// causing tests to be flaky.
	maxReadyStatusUpdateTolerance = 10 * time.Second
)

// testHostIP tests that a pod gets a host IP
func testHostIP(podClient *framework.PodClient, pod *v1.Pod) {
	ginkgo.By("creating pod")
	podClient.CreateSync(pod)

	// Try to make sure we get a hostIP for each pod.
	hostIPTimeout := 2 * time.Minute
	t := time.Now()
	for {
		p, err := podClient.Get(pod.Name, metav1.GetOptions{})
		framework.ExpectNoError(err, "Failed to get pod %q", pod.Name)
		if p.Status.HostIP != "" {
			e2elog.Logf("Pod %s has hostIP: %s", p.Name, p.Status.HostIP)
			break
		}
		if time.Since(t) >= hostIPTimeout {
			framework.Failf("Gave up waiting for hostIP of pod %s after %v seconds",
				p.Name, time.Since(t).Seconds())
		}
		e2elog.Logf("Retrying to get the hostIP of pod %s", p.Name)
		time.Sleep(5 * time.Second)
	}
}

func startPodAndGetBackOffs(podClient *framework.PodClient, pod *v1.Pod, sleepAmount time.Duration) (time.Duration, time.Duration) {
	podClient.CreateSync(pod)
	time.Sleep(sleepAmount)
	gomega.Expect(pod.Spec.Containers).NotTo(gomega.BeEmpty())
	podName := pod.Name
	containerName := pod.Spec.Containers[0].Name

	ginkgo.By("getting restart delay-0")
	_, err := getRestartDelay(podClient, podName, containerName)
	if err != nil {
		framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
	}

	ginkgo.By("getting restart delay-1")
	delay1, err := getRestartDelay(podClient, podName, containerName)
	if err != nil {
		framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
	}

	ginkgo.By("getting restart delay-2")
	delay2, err := getRestartDelay(podClient, podName, containerName)
	if err != nil {
		framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
	}
	return delay1, delay2
}

func getRestartDelay(podClient *framework.PodClient, podName string, containerName string) (time.Duration, error) {
	beginTime := time.Now()
	var previousRestartCount int32 = -1
	var previousFinishedAt time.Time
	for time.Since(beginTime) < (2 * maxBackOffTolerance) { // may just miss the 1st MaxContainerBackOff delay
		time.Sleep(time.Second)
		pod, err := podClient.Get(podName, metav1.GetOptions{})
		framework.ExpectNoError(err, fmt.Sprintf("getting pod %s", podName))
		status, ok := podutil.GetContainerStatus(pod.Status.ContainerStatuses, containerName)
		if !ok {
			e2elog.Logf("getRestartDelay: status missing")
			continue
		}

		// the only case this happens is if this is the first time the Pod is running and there is no "Last State".
		if status.LastTerminationState.Terminated == nil {
			e2elog.Logf("Container's last state is not \"Terminated\".")
			continue
		}

		if previousRestartCount == -1 {
			if status.State.Running != nil {
				// container is still Running, there is no "FinishedAt" time.
				continue
			} else if status.State.Terminated != nil {
				previousFinishedAt = status.State.Terminated.FinishedAt.Time
			} else {
				previousFinishedAt = status.LastTerminationState.Terminated.FinishedAt.Time
			}
			previousRestartCount = status.RestartCount
		}

		// when the RestartCount is changed, the Containers will be in one of the following states:
		//Running, Terminated, Waiting (it already is waiting for the backoff period to expire, and the last state details have been stored into status.LastTerminationState).
		if status.RestartCount > previousRestartCount {
			var startedAt time.Time
			if status.State.Running != nil {
				startedAt = status.State.Running.StartedAt.Time
			} else if status.State.Terminated != nil {
				startedAt = status.State.Terminated.StartedAt.Time
			} else {
				startedAt = status.LastTerminationState.Terminated.StartedAt.Time
			}
			e2elog.Logf("getRestartDelay: restartCount = %d, finishedAt=%s restartedAt=%s (%s)", status.RestartCount, previousFinishedAt, startedAt, startedAt.Sub(previousFinishedAt))
			return startedAt.Sub(previousFinishedAt), nil
		}
	}
	return 0, fmt.Errorf("timeout getting pod restart delay")
}

var _ = framework.KubeDescribe("Pods", func() {
	f := framework.NewDefaultFramework("pods")
	var podClient *framework.PodClient
	ginkgo.BeforeEach(func() {
		podClient = f.PodClient()
	})

	/*
		Release : v1.9
		Testname: Pods, assigned hostip
		Description: Create a Pod. Pod status MUST return successfully and contains a valid IP address.
	*/
	framework.ConformanceIt("should get a host IP [NodeConformance]", func() {
		name := "pod-hostip-" + string(uuid.NewUUID())
		testHostIP(podClient, &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: name,
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:  "test",
						Image: imageutils.GetPauseImageName(),
					},
				},
			},
		})
	})

	/*
		Release : v1.9
		Testname: Pods, lifecycle
		Description: A Pod is created with a unique label. Pod MUST be accessible when queried using the label selector upon creation. Add a watch, check if the Pod is running. Pod then deleted, The pod deletion timestamp is observed. The watch MUST return the pod deleted event. Query with the original selector for the Pod MUST return empty list.
	*/
	framework.ConformanceIt("should be submitted and removed [NodeConformance]", func() {
		ginkgo.By("creating the pod")
		name := "pod-submit-remove-" + string(uuid.NewUUID())
		value := strconv.Itoa(time.Now().Nanosecond())
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: name,
				Labels: map[string]string{
					"name": "foo",
					"time": value,
				},
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:  "nginx",
						Image: imageutils.GetE2EImage(imageutils.Nginx),
					},
				},
			},
		}

		ginkgo.By("setting up watch")
		selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
		options := metav1.ListOptions{LabelSelector: selector.String()}
		pods, err := podClient.List(options)
		framework.ExpectNoError(err, "failed to query for pods")
		gomega.Expect(len(pods.Items)).To(gomega.Equal(0))
		options = metav1.ListOptions{
			LabelSelector:   selector.String(),
			ResourceVersion: pods.ListMeta.ResourceVersion,
		}

		listCompleted := make(chan bool, 1)
		lw := &cache.ListWatch{
			ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
				options.LabelSelector = selector.String()
				podList, err := podClient.List(options)
				if err == nil {
					select {
					case listCompleted <- true:
						e2elog.Logf("observed the pod list")
						return podList, err
					default:
						e2elog.Logf("channel blocked")
					}
				}
				return podList, err
			},
			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
				options.LabelSelector = selector.String()
				return podClient.Watch(options)
			},
		}
		_, _, w, _ := watchtools.NewIndexerInformerWatcher(lw, &v1.Pod{})
		defer w.Stop()

		ginkgo.By("submitting the pod to kubernetes")
		podClient.Create(pod)

		ginkgo.By("verifying the pod is in kubernetes")
		selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
		options = metav1.ListOptions{LabelSelector: selector.String()}
		pods, err = podClient.List(options)
		framework.ExpectNoError(err, "failed to query for pods")
		gomega.Expect(len(pods.Items)).To(gomega.Equal(1))

		ginkgo.By("verifying pod creation was observed")
		select {
		case <-listCompleted:
			select {
			case event, _ := <-w.ResultChan():
				if event.Type != watch.Added {
					framework.Failf("Failed to observe pod creation: %v", event)
				}
			case <-time.After(framework.PodStartTimeout):
				framework.Failf("Timeout while waiting for pod creation")
			}
		case <-time.After(10 * time.Second):
			framework.Failf("Timeout while waiting to observe pod list")
		}

		// We need to wait for the pod to be running, otherwise the deletion
		// may be carried out immediately rather than gracefully.
		framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
		// save the running pod
		pod, err = podClient.Get(pod.Name, metav1.GetOptions{})
		framework.ExpectNoError(err, "failed to GET scheduled pod")

		ginkgo.By("deleting the pod gracefully")
		err = podClient.Delete(pod.Name, metav1.NewDeleteOptions(30))
		framework.ExpectNoError(err, "failed to delete pod")

		ginkgo.By("verifying the kubelet observed the termination notice")
		gomega.Expect(wait.Poll(time.Second*5, time.Second*30, func() (bool, error) {
			podList, err := framework.GetKubeletPods(f.ClientSet, pod.Spec.NodeName)
			if err != nil {
				e2elog.Logf("Unable to retrieve kubelet pods for node %v: %v", pod.Spec.NodeName, err)
				return false, nil
			}
			for _, kubeletPod := range podList.Items {
				if pod.Name != kubeletPod.Name {
					continue
				}
				if kubeletPod.ObjectMeta.DeletionTimestamp == nil {
					e2elog.Logf("deletion has not yet been observed")
					return false, nil
				}
				return true, nil
			}
			e2elog.Logf("no pod exists with the name we were looking for, assuming the termination request was observed and completed")
			return true, nil
		})).NotTo(gomega.HaveOccurred(), "kubelet never observed the termination notice")

		ginkgo.By("verifying pod deletion was observed")
		deleted := false
		var lastPod *v1.Pod
		timer := time.After(framework.DefaultPodDeletionTimeout)
		for !deleted {
			select {
			case event, _ := <-w.ResultChan():
				switch event.Type {
				case watch.Deleted:
					lastPod = event.Object.(*v1.Pod)
					deleted = true
				case watch.Error:
					e2elog.Logf("received a watch error: %v", event.Object)
					framework.Failf("watch closed with error")
				}
			case <-timer:
				framework.Failf("timed out waiting for pod deletion")
			}
		}
		if !deleted {
			framework.Failf("Failed to observe pod deletion")
		}

		gomega.Expect(lastPod.DeletionTimestamp).ToNot(gomega.BeNil())
		gomega.Expect(lastPod.Spec.TerminationGracePeriodSeconds).ToNot(gomega.BeZero())

		selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
		options = metav1.ListOptions{LabelSelector: selector.String()}
		pods, err = podClient.List(options)
		framework.ExpectNoError(err, "failed to query for pods")
		gomega.Expect(len(pods.Items)).To(gomega.Equal(0))
	})

	/*
		Release : v1.9
		Testname: Pods, update
		Description: Create a Pod with a unique label. Query for the Pod with the label as selector MUST be successful. Update the pod to change the value of the Label. Query for the Pod with the new value for the label MUST be successful.
	*/
	framework.ConformanceIt("should be updated [NodeConformance]", func() {
		ginkgo.By("creating the pod")
		name := "pod-update-" + string(uuid.NewUUID())
		value := strconv.Itoa(time.Now().Nanosecond())
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: name,
				Labels: map[string]string{
					"name": "foo",
					"time": value,
				},
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:  "nginx",
						Image: imageutils.GetE2EImage(imageutils.Nginx),
					},
				},
			},
		}

		ginkgo.By("submitting the pod to kubernetes")
		pod = podClient.CreateSync(pod)

		ginkgo.By("verifying the pod is in kubernetes")
		selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
		options := metav1.ListOptions{LabelSelector: selector.String()}
		pods, err := podClient.List(options)
		framework.ExpectNoError(err, "failed to query for pods")
		gomega.Expect(len(pods.Items)).To(gomega.Equal(1))

		ginkgo.By("updating the pod")
		podClient.Update(name, func(pod *v1.Pod) {
			value = strconv.Itoa(time.Now().Nanosecond())
			pod.Labels["time"] = value
		})

		framework.ExpectNoError(f.WaitForPodRunning(pod.Name))

		ginkgo.By("verifying the updated pod is in kubernetes")
		selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
		options = metav1.ListOptions{LabelSelector: selector.String()}
		pods, err = podClient.List(options)
		framework.ExpectNoError(err, "failed to query for pods")
		gomega.Expect(len(pods.Items)).To(gomega.Equal(1))
		e2elog.Logf("Pod update OK")
	})

	/*
		Release : v1.9
		Testname: Pods, ActiveDeadlineSeconds
		Description: Create a Pod with a unique label. Query for the Pod with the label as selector MUST be successful. The Pod is updated with ActiveDeadlineSeconds set on the Pod spec. Pod MUST terminate of the specified time elapses.
	*/
	framework.ConformanceIt("should allow activeDeadlineSeconds to be updated [NodeConformance]", func() {
		ginkgo.By("creating the pod")
		name := "pod-update-activedeadlineseconds-" + string(uuid.NewUUID())
		value := strconv.Itoa(time.Now().Nanosecond())
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: name,
				Labels: map[string]string{
					"name": "foo",
					"time": value,
				},
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:  "nginx",
						Image: imageutils.GetE2EImage(imageutils.Nginx),
					},
				},
			},
		}

		ginkgo.By("submitting the pod to kubernetes")
		podClient.CreateSync(pod)

		ginkgo.By("verifying the pod is in kubernetes")
		selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
		options := metav1.ListOptions{LabelSelector: selector.String()}
		pods, err := podClient.List(options)
		framework.ExpectNoError(err, "failed to query for pods")
		gomega.Expect(len(pods.Items)).To(gomega.Equal(1))

		ginkgo.By("updating the pod")
		podClient.Update(name, func(pod *v1.Pod) {
			newDeadline := int64(5)
			pod.Spec.ActiveDeadlineSeconds = &newDeadline
		})

		framework.ExpectNoError(f.WaitForPodTerminated(pod.Name, "DeadlineExceeded"))
	})

	/*
		Release : v1.9
		Testname: Pods, service environment variables
		Description: Create a server Pod listening on port 9376. A Service called fooservice is created for the server Pod listening on port 8765 targeting port 8080. If a new Pod is created in the cluster then the Pod MUST have the fooservice environment variables available from this new Pod. The new create Pod MUST have environment variables such as FOOSERVICE_SERVICE_HOST, FOOSERVICE_SERVICE_PORT, FOOSERVICE_PORT, FOOSERVICE_PORT_8765_TCP_PORT, FOOSERVICE_PORT_8765_TCP_PROTO, FOOSERVICE_PORT_8765_TCP and FOOSERVICE_PORT_8765_TCP_ADDR that are populated with proper values.
	*/
	framework.ConformanceIt("should contain environment variables for services [NodeConformance]", func() {
		// Make a pod that will be a service.
		// This pod serves its hostname via HTTP.
		serverName := "server-envvars-" + string(uuid.NewUUID())
		serverPod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name:   serverName,
				Labels: map[string]string{"name": serverName},
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:  "srv",
						Image: framework.ServeHostnameImage,
						Ports: []v1.ContainerPort{{ContainerPort: 9376}},
					},
				},
			},
		}
		podClient.CreateSync(serverPod)

		// This service exposes port 8080 of the test pod as a service on port 8765
		// TODO(filbranden): We would like to use a unique service name such as:
		//   svcName := "svc-envvars-" + randomSuffix()
		// However, that affects the name of the environment variables which are the capitalized
		// service name, so that breaks this test.  One possibility is to tweak the variable names
		// to match the service.  Another is to rethink environment variable names and possibly
		// allow overriding the prefix in the service manifest.
		svcName := "fooservice"
		svc := &v1.Service{
			ObjectMeta: metav1.ObjectMeta{
				Name: svcName,
				Labels: map[string]string{
					"name": svcName,
				},
			},
			Spec: v1.ServiceSpec{
				Ports: []v1.ServicePort{{
					Port:       8765,
					TargetPort: intstr.FromInt(8080),
				}},
				Selector: map[string]string{
					"name": serverName,
				},
			},
		}
		_, err := f.ClientSet.CoreV1().Services(f.Namespace.Name).Create(svc)
		framework.ExpectNoError(err, "failed to create service")

		// Make a client pod that verifies that it has the service environment variables.
		podName := "client-envvars-" + string(uuid.NewUUID())
		const containerName = "env3cont"
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name:   podName,
				Labels: map[string]string{"name": podName},
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:    containerName,
						Image:   imageutils.GetE2EImage(imageutils.BusyBox),
						Command: []string{"sh", "-c", "env"},
					},
				},
				RestartPolicy: v1.RestartPolicyNever,
			},
		}

		// It's possible for the Pod to be created before the Kubelet is updated with the new
		// service. In that case, we just retry.
		const maxRetries = 3
		expectedVars := []string{
			"FOOSERVICE_SERVICE_HOST=",
			"FOOSERVICE_SERVICE_PORT=",
			"FOOSERVICE_PORT=",
			"FOOSERVICE_PORT_8765_TCP_PORT=",
			"FOOSERVICE_PORT_8765_TCP_PROTO=",
			"FOOSERVICE_PORT_8765_TCP=",
			"FOOSERVICE_PORT_8765_TCP_ADDR=",
		}
		framework.ExpectNoErrorWithRetries(func() error {
			return f.MatchContainerOutput(pod, containerName, expectedVars, gomega.ContainSubstring)
		}, maxRetries, "Container should have service environment variables set")
	})

	/*
		Release : v1.13
		Testname: Pods, remote command execution over websocket
		Description: A Pod is created. Websocket is created to retrieve exec command output from this pod.
		Message retrieved form Websocket MUST match with expected exec command output.
	*/
	framework.ConformanceIt("should support remote command execution over websockets [NodeConformance]", func() {
		config, err := framework.LoadConfig()
		framework.ExpectNoError(err, "unable to get base config")

		ginkgo.By("creating the pod")
		name := "pod-exec-websocket-" + string(uuid.NewUUID())
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: name,
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:    "main",
						Image:   imageutils.GetE2EImage(imageutils.BusyBox),
						Command: []string{"/bin/sh", "-c", "echo container is alive; sleep 600"},
					},
				},
			},
		}

		ginkgo.By("submitting the pod to kubernetes")
		pod = podClient.CreateSync(pod)

		req := f.ClientSet.CoreV1().RESTClient().Get().
			Namespace(f.Namespace.Name).
			Resource("pods").
			Name(pod.Name).
			Suffix("exec").
			Param("stderr", "1").
			Param("stdout", "1").
			Param("container", pod.Spec.Containers[0].Name).
			Param("command", "echo").
			Param("command", "remote execution test")

		url := req.URL()
		ws, err := framework.OpenWebSocketForURL(url, config, []string{"channel.k8s.io"})
		if err != nil {
			framework.Failf("Failed to open websocket to %s: %v", url.String(), err)
		}
		defer ws.Close()

		buf := &bytes.Buffer{}
		gomega.Eventually(func() error {
			for {
				var msg []byte
				if err := websocket.Message.Receive(ws, &msg); err != nil {
					if err == io.EOF {
						break
					}
					framework.Failf("Failed to read completely from websocket %s: %v", url.String(), err)
				}
				if len(msg) == 0 {
					continue
				}
				if msg[0] != 1 {
					if len(msg) == 1 {
						// skip an empty message on stream other than stdout
						continue
					} else {
						framework.Failf("Got message from server that didn't start with channel 1 (STDOUT): %v", msg)
					}

				}
				buf.Write(msg[1:])
			}
			if buf.Len() == 0 {
				return fmt.Errorf("Unexpected output from server")
			}
			if !strings.Contains(buf.String(), "remote execution test") {
				return fmt.Errorf("Expected to find 'remote execution test' in %q", buf.String())
			}
			return nil
		}, time.Minute, 10*time.Second).Should(gomega.BeNil())
	})

	/*
		Release : v1.13
		Testname: Pods, logs from websockets
		Description: A Pod is created. Websocket is created to retrieve log of a container from this pod.
		Message retrieved form Websocket MUST match with container's output.
	*/
	framework.ConformanceIt("should support retrieving logs from the container over websockets [NodeConformance]", func() {
		config, err := framework.LoadConfig()
		framework.ExpectNoError(err, "unable to get base config")

		ginkgo.By("creating the pod")
		name := "pod-logs-websocket-" + string(uuid.NewUUID())
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: name,
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:    "main",
						Image:   imageutils.GetE2EImage(imageutils.BusyBox),
						Command: []string{"/bin/sh", "-c", "echo container is alive; sleep 10000"},
					},
				},
			},
		}

		ginkgo.By("submitting the pod to kubernetes")
		podClient.CreateSync(pod)

		req := f.ClientSet.CoreV1().RESTClient().Get().
			Namespace(f.Namespace.Name).
			Resource("pods").
			Name(pod.Name).
			Suffix("log").
			Param("container", pod.Spec.Containers[0].Name)

		url := req.URL()

		ws, err := framework.OpenWebSocketForURL(url, config, []string{"binary.k8s.io"})
		if err != nil {
			framework.Failf("Failed to open websocket to %s: %v", url.String(), err)
		}
		defer ws.Close()
		buf := &bytes.Buffer{}
		for {
			var msg []byte
			if err := websocket.Message.Receive(ws, &msg); err != nil {
				if err == io.EOF {
					break
				}
				framework.Failf("Failed to read completely from websocket %s: %v", url.String(), err)
			}
			if len(strings.TrimSpace(string(msg))) == 0 {
				continue
			}
			buf.Write(msg)
		}
		if buf.String() != "container is alive\n" {
			framework.Failf("Unexpected websocket logs:\n%s", buf.String())
		}
	})

	// Slow (~7 mins)
	ginkgo.It("should have their auto-restart back-off timer reset on image update [Slow][NodeConformance]", func() {
		podName := "pod-back-off-image"
		containerName := "back-off"
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name:   podName,
				Labels: map[string]string{"test": "back-off-image"},
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:    containerName,
						Image:   imageutils.GetE2EImage(imageutils.BusyBox),
						Command: []string{"/bin/sh", "-c", "sleep 5", "/crash/missing"},
					},
				},
			},
		}

		delay1, delay2 := startPodAndGetBackOffs(podClient, pod, buildBackOffDuration)

		ginkgo.By("updating the image")
		podClient.Update(podName, func(pod *v1.Pod) {
			pod.Spec.Containers[0].Image = imageutils.GetE2EImage(imageutils.Nginx)
		})

		time.Sleep(syncLoopFrequency)
		framework.ExpectNoError(f.WaitForPodRunning(pod.Name))

		ginkgo.By("get restart delay after image update")
		delayAfterUpdate, err := getRestartDelay(podClient, podName, containerName)
		if err != nil {
			framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
		}

		if delayAfterUpdate > 2*delay2 || delayAfterUpdate > 2*delay1 {
			framework.Failf("updating image did not reset the back-off value in pod=%s/%s d3=%s d2=%s d1=%s", podName, containerName, delayAfterUpdate, delay1, delay2)
		}
	})

	// Slow by design (~27 mins) issue #19027
	ginkgo.It("should cap back-off at MaxContainerBackOff [Slow][NodeConformance]", func() {
		podName := "back-off-cap"
		containerName := "back-off-cap"
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name:   podName,
				Labels: map[string]string{"test": "liveness"},
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:    containerName,
						Image:   imageutils.GetE2EImage(imageutils.BusyBox),
						Command: []string{"/bin/sh", "-c", "sleep 5", "/crash/missing"},
					},
				},
			},
		}

		podClient.CreateSync(pod)
		time.Sleep(2 * kubelet.MaxContainerBackOff) // it takes slightly more than 2*x to get to a back-off of x

		// wait for a delay == capped delay of MaxContainerBackOff
		ginkgo.By("getting restart delay when capped")
		var (
			delay1 time.Duration
			err    error
		)
		for i := 0; i < 3; i++ {
			delay1, err = getRestartDelay(podClient, podName, containerName)
			if err != nil {
				framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
			}

			if delay1 < kubelet.MaxContainerBackOff {
				continue
			}
		}

		if (delay1 < kubelet.MaxContainerBackOff) || (delay1 > maxBackOffTolerance) {
			framework.Failf("expected %s back-off got=%s in delay1", kubelet.MaxContainerBackOff, delay1)
		}

		ginkgo.By("getting restart delay after a capped delay")
		delay2, err := getRestartDelay(podClient, podName, containerName)
		if err != nil {
			framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
		}

		if delay2 < kubelet.MaxContainerBackOff || delay2 > maxBackOffTolerance { // syncloop cumulative drift
			framework.Failf("expected %s back-off got=%s on delay2", kubelet.MaxContainerBackOff, delay2)
		}
	})

	// TODO(freehan): label the test to be [NodeConformance] after tests are proven to be stable.
	ginkgo.It("should support pod readiness gates [NodeFeature:PodReadinessGate]", func() {
		podName := "pod-ready"
		readinessGate1 := "k8s.io/test-condition1"
		readinessGate2 := "k8s.io/test-condition2"
		patchStatusFmt := `{"status":{"conditions":[{"type":%q, "status":%q}]}}`
		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name:   podName,
				Labels: map[string]string{"test": "pod-readiness-gate"},
			},
			Spec: v1.PodSpec{
				Containers: []v1.Container{
					{
						Name:    "pod-readiness-gate",
						Image:   imageutils.GetE2EImage(imageutils.BusyBox),
						Command: []string{"/bin/sh", "-c", "echo container is alive; sleep 10000"},
					},
				},
				ReadinessGates: []v1.PodReadinessGate{
					{ConditionType: v1.PodConditionType(readinessGate1)},
					{ConditionType: v1.PodConditionType(readinessGate2)},
				},
			},
		}

		validatePodReadiness := func(expectReady bool) {
			err := wait.Poll(time.Second, maxReadyStatusUpdateTolerance, func() (bool, error) {
				podReady := podClient.PodIsReady(podName)
				res := expectReady == podReady
				if !res {
					e2elog.Logf("Expect the Ready condition of pod %q to be %v, but got %v", podName, expectReady, podReady)
				}
				return res, nil
			})
			framework.ExpectNoError(err)
		}

		ginkgo.By("submitting the pod to kubernetes")
		podClient.CreateSync(pod)
		gomega.Expect(podClient.PodIsReady(podName)).To(gomega.BeFalse(), "Expect pod's Ready condition to be false initially.")

		ginkgo.By(fmt.Sprintf("patching pod status with condition %q to true", readinessGate1))
		_, err := podClient.Patch(podName, types.StrategicMergePatchType, []byte(fmt.Sprintf(patchStatusFmt, readinessGate1, "True")), "status")
		framework.ExpectNoError(err)
		// Sleep for 10 seconds.
		time.Sleep(maxReadyStatusUpdateTolerance)
		gomega.Expect(podClient.PodIsReady(podName)).To(gomega.BeFalse(), "Expect pod's Ready condition to be false with only one condition in readinessGates equal to True")

		ginkgo.By(fmt.Sprintf("patching pod status with condition %q to true", readinessGate2))
		_, err = podClient.Patch(podName, types.StrategicMergePatchType, []byte(fmt.Sprintf(patchStatusFmt, readinessGate2, "True")), "status")
		framework.ExpectNoError(err)
		validatePodReadiness(true)

		ginkgo.By(fmt.Sprintf("patching pod status with condition %q to false", readinessGate1))
		_, err = podClient.Patch(podName, types.StrategicMergePatchType, []byte(fmt.Sprintf(patchStatusFmt, readinessGate1, "False")), "status")
		framework.ExpectNoError(err)
		validatePodReadiness(false)

	})
})


text:
// test.js
// This loads from the HTML page that is presented to the client when he/she enters,
// for example, http://localhost:16000. Since this application is, first and foremost,
// a service, we call that the "test page". This javascript populates the list of
// examples at the bottom, and then sets event handlers to wait for user input.

(function($) {

  // Sets the form's method to either 'GET' or 'POST', depending on the value of
  // the form's "method" control
  function setMethod() {
    $('#form').attr('method', $('#method').val());
  }

  // Handle any changes to the in-format select option.
  // Set the latex-style to enabled or disabled, according to the
  // currently selected value of math format

  function in_format_handler() {
    var val = $('#math-in-format-select').val();
    if (val == 'mml' || val == 'jats') {
      $('#latex-style-select').attr('disabled', 'disabled');
      $('#latex-style-label').attr('class', 'disabled');
    }
    else {
      $('#latex-style-select').removeAttr('disabled');
      $('#latex-style-label').attr('class', '');
    }
    //if (val == 'latex' || val == 'mml') {
    //  $('#out-format-select').val('svg');
    //}
  }

/*
  function out_format_handler() {
    var val = $('#out-format-select').val();
    if (val == 'client') {
      $('#math-in-format-select').val('jats');
    }
  }
*/

  // List of examples that will appear
  var test_examples = [
    'simple-tex',
    'simple-mml',
    'cauchy-integral',
    'cauchy-schwarz',
    'christoffel-symbols',
    'coins',
    'cosines',
    'cross-product',
    'curl-vector-field',
    'gauss-divergence',
    'sum-displaystyle',
    'lorentz',
    'maxwell',
    'quadratic',
    'ramanujan',
    'rogers-rmanujan',
    'standard-deviation',
    'jats-latex-two',
    'jats-mathml-many',
    'jats-3479416',
    'jats-2762331'
  ];

  // Populate the example list
  function make_example_list() {
    // Get the examples.yaml file
    var examples_ajax = $.ajax("examples/examples.yaml")
      .done(function(content) {
        var examples = jsyaml.load(content);
        var examples_by_name = {};
        examples.map(function(example) {
          examples_by_name[example.name] = example;
        });

        $('#examples-div ul').append(test_examples.map(function(te) {
          var example = examples_by_name[te];
          return "
" + example.description +
            "
";
        }));
        $('#examples-div a').on("click", function(event) {
          var example_ajax = $.ajax($(this).attr("href"))
            .done(function(content) {
              $('#q').val(content);
            })
            .fail(function() {
              // FIXME: do something here
            });
          return false;
        });
      })
      .fail(function() {
        // FIXME: do something here.
      });
  }

  $(document).ready(function() {
    // Check that browser supports the File API
    if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
      alert('Your browser doesn\'t seem to support the HTML File API, so you won\'t be able ' +
            'to upload files.');
    }

    // Event handlers
    $('#method').on('change', setMethod);
    $('#math-in-format-select').on('change', in_format_handler);
    $('#file').on('change', function(evt) {
      var file = evt.target.files[0];
      //console.log("file = %o", file);
      var reader = new FileReader();
      reader.onload = function(evt) {
        //console.log("finished reading the file");
        $('#q').val(evt.target.result);
      };
      reader.readAsText(file);
    });
    //$('#out-format-select').on('change', out_format_handler);

    // Page initialization
    setMethod();
    in_format_handler();
    make_example_list();
  });

})(jQuery);


text:
CREATE TABLE t1(a, b COLLATE string_compare);
INSERT INTO t1 VALUES(10, 'string');
INSERT INTO t1 VALUES(10, 'string2');


text:
import {spamEveryone} from '../bot/lips'
import tracker from '../tracking'

tracker.track('admin.spamEveryone')
spamEveryone()


text:
package commands

import "github.com/cloudfoundry/bosh-bootloader/storage"

const (
	CloudConfigCommand = "cloud-config"
)

type CloudConfig struct {
	logger             logger
	stateValidator     stateValidator
	cloudConfigManager cloudConfigManager
}

func NewCloudConfig(logger logger, stateValidator stateValidator, cloudConfigManager cloudConfigManager) CloudConfig {
	return CloudConfig{
		logger:             logger,
		stateValidator:     stateValidator,
		cloudConfigManager: cloudConfigManager,
	}
}

func (c CloudConfig) CheckFastFails(subcommandFlags []string, state storage.State) error {
	err := c.stateValidator.Validate()
	if err != nil {
		return err
	}

	return nil
}

func (c CloudConfig) Execute(args []string, state storage.State) error {
	if !c.cloudConfigManager.IsPresentCloudConfig() {
		err := c.cloudConfigManager.Initialize(state)
		if err != nil {
			return err
		}
	}
	if !c.cloudConfigManager.IsPresentCloudConfigVars() {
		err := c.cloudConfigManager.GenerateVars(state)
		if err != nil {
			return err
		}
	}
	contents, err := c.cloudConfigManager.Interpolate()
	if err != nil {
		return err
	}
	c.logger.Println(string(contents))
	return nil
}