text:
package org.aikodi.chameleon.support.expression;

import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.oo.expression.Expression;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeReference;
import org.aikodi.chameleon.util.Util;

import java.util.Set;

/**
 * @author Marko van Dooren
 * @author Tim Laeremans
 */
public class ClassCastExpression extends ExprTypeRefContainingExpression {

	@Override
	public void disconnect() {
		super.disconnect();
	}

  public ClassCastExpression(TypeReference type, Expression expression) {
	  setTypeReference(type);
    setExpression(expression);
  }

  @Override
protected Type actualType() throws LookupException {
    Type result = getTypeReference().getElement();
//    if(result == null) {
//      getTypeReference().getElement();
//      throw new LookupException("Type reference of class cast expression returns null", getTypeReference());
//    }
    return result;
  }

  @Override
public ClassCastExpression cloneSelf() {
    return new ClassCastExpression(null, null);
  }

  public Set<Type> getDirectExceptions() throws LookupException {
    return Util.createNonNullSet(language(ObjectOrientedLanguage.class).classCastException(view().namespace()));
  }

}


text:
package com.tibco.streambase.contrib.jmsxml.test;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.streambase.sb.unittest.Expecter;
import com.streambase.sb.unittest.JSONSingleQuotesTupleMaker;
import com.streambase.sb.unittest.SBServerManager;
import com.streambase.sb.unittest.ServerManagerFactory;

public class TestJMSXML {

	private static SBServerManager server;

	@BeforeClass
	public static void setupServer() throws Exception {
		// create a StreamBase server and load applications once for all tests in this class
		server = ServerManagerFactory.getEmbeddedServer("sbd.sbconf");
		server.startServer();
		// this will run with the default JMS provider -- for this project, this is tibems
		server.loadApp("jms-xml-sample.sbapp");
	}

	@AfterClass
	public static void stopServer() throws Exception {
		if (server != null) {
			server.shutdownServer();
			server = null;
		}
	}

	@Before
	public void startContainers() throws Exception {
		// before each test, startup fresh container instances
		server.startContainers();
	}

	@Test
	public void testVRZN100() throws Exception {
		server.getEnqueuer("TestVRZN100XMLParse").enqueue(
				JSONSingleQuotesTupleMaker.MAKER, "{}");
		new Expecter(server.getDequeuer("XMLOut"))
				.expect(JSONSingleQuotesTupleMaker.MAKER,
						"{'text':'<quote><symbol>VRZN</symbol><bid>100.0</bid></quote>'}");
		new Expecter(server.getDequeuer("TupleOut")).expect(
				JSONSingleQuotesTupleMaker.MAKER,
				"{'quote':{'symbol':'VRZN','bid':100.0}}");
	}

	@After
	public void stopContainers() throws Exception {
		// after each test, dispose of the container instances
		server.stopContainers();
	}

}

redpajama_set_name: RedPajamaGithub


text:
	<#include "header.html" />

Hi ${user.firstName} ${user.lastName},

You have been successfully registered.

Click here to confirm your registration.

        This link will expire in <#if expireAfterSeconds gte 3600>${expireAfterSeconds / 3600} hour(s)<#else>${expireAfterSeconds / 60} minutes(s)</#if>.
        After that, you must submit a new request to your Administrators to resend a new account activation email.


text:
namespace CGAL {

template <class InputIterator, class Polyhedron>
void
convex_hull_incremental_3(InputIterator first, InputIterator beyond,
                          Polyhedron& P, bool test_correctness = false)
{
  typedef typename Polyhedron::Traits       PolyTraits;
  typedef typename PolyTraits::Kernel       K;
  typedef Convex_hull_d_traits_3<K>         ChullTraits;
  typedef Convex_hull_d< ChullTraits >      ChullType;

  ChullType CH(3);
  for ( ; first != beyond ; ++first)  CH.insert(*first);
  if ( test_correctness ) CGAL_ch_assertion(CH.is_valid());
  P.clear();
  CGAL::convex_hull_d_to_polyhedron_3(CH,P);
}

} //namespace CGAL

#endif // CGAL_CONVEX_HULL_INCREMENTAL_3_H


text:
package com.yalantis.ucrop.sample;

import android.Manifest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.yalantis.ucrop.view.UCropView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.Calendar;
import java.util.List;

import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;
import static android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

/**
 * Created by Oleksii Shliama (https://github.com/shliama).
 */
public class ResultActivity extends BaseActivity {

    private static final String TAG = "ResultActivity";
    private static final int DOWNLOAD_NOTIFICATION_ID_DONE = 911;

    public static void startWithUri(@NonNull Context context, @NonNull Uri uri) {
        Intent intent = new Intent(context, ResultActivity.class);
        intent.setData(uri);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        try {
            UCropView uCropView = (UCropView) findViewById(R.id.ucrop);
            uCropView.getCropImageView().setImageUri(getIntent().getData(), null);
            uCropView.getOverlayView().setShowCropFrame(false);
            uCropView.getOverlayView().setShowCropGrid(false);
            uCropView.getOverlayView().setDimmedColor(Color.TRANSPARENT);
        } catch (Exception e) {
            Log.e(TAG, "setImageUri", e);
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(new File(getIntent().getData().getPath()).getAbsolutePath(), options);

        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle(getString(R.string.format_crop_result_d_d, options.outWidth, options.outHeight));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.menu_result, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_download) {
            saveCroppedImage();
        } else if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_STORAGE_WRITE_ACCESS_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    saveCroppedImage();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void saveCroppedImage() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    getString(R.string.permission_write_storage_rationale),
                    REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
        } else {
            Uri imageUri = getIntent().getData();
            if (imageUri != null && imageUri.getScheme().equals("file")) {
                try {
                    copyFileToDownloads(getIntent().getData());
                } catch (Exception e) {
                    Toast.makeText(ResultActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    Log.e(TAG, imageUri.toString(), e);
                }
            } else {
                Toast.makeText(ResultActivity.this, getString(R.string.toast_unexpected_error), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void copyFileToDownloads(Uri croppedFileUri) throws Exception {
        String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        String filename = String.format("%d_%s", Calendar.getInstance().getTimeInMillis(), croppedFileUri.getLastPathSegment());

        File saveFile = new File(downloadsDirectoryPath, filename);

        FileInputStream inStream = new FileInputStream(new File(croppedFileUri.getPath()));
        FileOutputStream outStream = new FileOutputStream(saveFile);
        FileChannel inChannel = inStream.getChannel();
        FileChannel outChannel = outStream.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
        inStream.close();
        outStream.close();

        showNotification(saveFile);
    }

    private void showNotification(@NonNull File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri fileUri = FileProvider.getUriForFile(
                this,
                getString(R.string.file_provider_authorities),
                file);

        intent.setDataAndType(fileUri, "image/*");

        List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(
                intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for(ResolveInfo info: resInfoList) {
            grantUriPermission(
                    info.activityInfo.packageName,
                    fileUri, FLAG_GRANT_WRITE_URI_PERMISSION | FLAG_GRANT_READ_URI_PERMISSION);
        }

        NotificationCompat.Builder mNotification = new NotificationCompat.Builder(this);

        mNotification
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_image_saved_click_to_preview))
                .setTicker(getString(R.string.notification_image_saved))
                .setSmallIcon(R.drawable.ic_done)
                .setOngoing(false)
                .setContentIntent(PendingIntent.getActivity(this, 0, intent, 0))
                .setAutoCancel(true);
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(DOWNLOAD_NOTIFICATION_ID_DONE, mNotification.build());
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/ringtoneitem_textview_header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="@string/ringtone"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@color/black" />

    <TextView
        android:id="@+id/ringtoneitem_textview_current"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/ringtoneitem_textview_header"
        android:text="@string/choose_ringtone"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="@color/black" />

</RelativeLayout>


text:
{% extends "base.html" %}
{% load main_extras %}

{% block title %}
API Uploader
{% endblock title %}

{% block content %}

Upload a code package

    {% if form %}
        <form action="{% url api.views.upload %}" method="post" enctype={% if form.is_multipart %}"multipart/form-data"{% else %}"application/x-www-form-urlencoded"{% endif %}>
		{% csrf_token %}

		{% if form.packageName.errors %}

			{{ form.packageName.errors }}
		{% else %}

		{% endif %}

Name:

		    {{ form.packageName }}

{{ form.packageName.help_text }}

                {% if form.package.errors %}

			{{ form.package.errors }}
		{% else %}

		{% endif %}

Package:

		    {{ form.package }}

{{ form.package.help_text }}

		{% if form.username.errors %}

			{{ username.file.errors }}
		{% else %}

		{% endif %}

Username:

		    {{ form.username }}

{{ form.username.help_text }}

		{% if form.password.errors %}

			{{ form.password.errors }}
		{% else %}

		{% endif %}

Password:

		    {{ form.password }}

{{ form.password.help_text }}

		<input id="code_package_submit" class="submit" type="submit" value="Submit Code Package" />
	    </form>
    {% else %}

Something when wrong while loading the form. Reload the page and try again

    {% endif %}
{% endblock content %}


text:
static int Close(SpiDevice *device) {
  int fd = device->Fd();
  device->SetFd(-1);
  return close(fd);
}

class CloseWorker : public SpiAsyncWorker {
public:
  CloseWorker(
    Nan::Callback *callback,
    SpiDevice *device
  ) : SpiAsyncWorker(callback), device_(device) {
  }

  ~CloseWorker() {}

  void Execute() {
    if (Close(device_) == -1) {
      SetErrorNo(errno);
      SetErrorSyscall("close");
    }
  }

  void HandleOKCallback() {
    Nan::HandleScope scope;

    v8::Local<v8::Value> argv[] = {
      Nan::Null()
    };

    callback->Call(1, argv, async_resource);
  }

private:
  SpiDevice *device_;
};

void Close(Nan::NAN_METHOD_ARGS_TYPE info) {
  SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());

  if (device->Fd() == -1) {
    return Nan::ThrowError(
      Nan::ErrnoException(
        EPERM, "close", "device closed, operation not permitted"
      )
    );
  }

  if (info.Length() < 1 || !info[0]->IsFunction()) {
    return Nan::ThrowError(
      Nan::ErrnoException(
        EINVAL, "close", "incorrect arguments passed to close(cb)"
      )
    );
  }

  Nan::Callback *callback = new Nan::Callback(info[0].As<v8::Function>());

  Nan::AsyncQueueWorker(new CloseWorker(callback, device));

  info.GetReturnValue().SetNull();
}

void CloseSync(Nan::NAN_METHOD_ARGS_TYPE info) {
  SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());

  if (device->Fd() == -1) {
    return Nan::ThrowError(
      Nan::ErrnoException(
        EPERM, "closeSync", "device closed, operation not permitted"
      )
    );
  }

  if (Close(device) == -1) {
    return Nan::ThrowError(Nan::ErrnoException(errno, "closeSync", ""));
  }

  info.GetReturnValue().SetNull();
}


text:
from datetime import datetime
from distutils import spawn
import argparse
import json
import os
import platform
import shutil
import socket
import sys
import urllib
import urllib2

__version__ = '5.9.1'

###############################################################################
# Options
###############################################################################
PARSER = argparse.ArgumentParser()
PARSER.add_argument(
  '-d', '--dependencies', dest='install_dependencies', action='store_true',
  help='install virtualenv and python dependencies',
)
PARSER.add_argument(
  '-s', '--start', dest='start', action='store_true',
  help='starts the dev_appserver.py with storage_path pointing to temp',
)
PARSER.add_argument(
  '-o', '--host', dest='host', action='store', default='127.0.0.1',
  help='the host to start the dev_appserver.py',
)
PARSER.add_argument(
  '-p', '--port', dest='port', action='store', default='8080',
  help='the port to start the dev_appserver.py',
)
PARSER.add_argument(
  '--appserver-args', dest='args', nargs=argparse.REMAINDER, default=[],
  help='all following args are passed to dev_appserver.py',
)
PARSER.add_argument(
  '-v', '--version', dest='show_version', action='store_true',
  help='Show gae-init version',
)
ARGS = PARSER.parse_args()

###############################################################################
# Globals
###############################################################################
BAD_ENDINGS = ['pyc', 'pyo', '~']
GAE_PATH = ''
IS_WINDOWS = platform.system() == 'Windows'

###############################################################################
# Directories
###############################################################################
DIR_MAIN = 'main'
DIR_TEMP = 'temp'
DIR_VENV = os.path.join(DIR_TEMP, 'venv')

DIR_LIB = os.path.join(DIR_MAIN, 'lib')
DIR_LIBX = os.path.join(DIR_MAIN, 'libx')
FILE_LIB = '%s.zip' % DIR_LIB
FILE_REQUIREMENTS = 'requirements.txt'
FILE_PIP_GUARD = os.path.join(DIR_TEMP, 'pip.guard')

FILE_VENV = os.path.join(DIR_VENV, 'Scripts', 'activate.bat') \
  if IS_WINDOWS \
  else os.path.join(DIR_VENV, 'bin', 'activate')

DIR_STORAGE = os.path.join(DIR_TEMP, 'storage')
FILE_UPDATE = os.path.join(DIR_TEMP, 'update.json')

###############################################################################
# Other global variables
###############################################################################
CORE_VERSION_URL = 'https://gae-init.appspot.com/_s/version/'
INTERNET_TEST_URL = 'https://www.google.com'
REQUIREMENTS_URL = 'http://docs.gae-init.appspot.com/requirement/'

###############################################################################
# Helpers
###############################################################################
def print_out(script, filename=''):
  timestamp = datetime.now().strftime('%H:%M:%S')
  if not filename:
    filename = '-' * 46
    script = script.rjust(12, '-')
  print '[%s] %12s %s' % (timestamp, script, filename)

def make_dirs(directory):
  if not os.path.exists(directory):
    os.makedirs(directory)

def listdir(directory, split_ext=False):
  try:
    if split_ext:
      return [os.path.splitext(dir_)[0] for dir_ in os.listdir(directory)]
    else:
      return os.listdir(directory)
  except OSError:
    return []

def site_packages_path():
  if IS_WINDOWS:
    return os.path.join(DIR_VENV, 'Lib', 'site-packages')
  py_version = 'python%s.%s' % sys.version_info[:2]
  return os.path.join(DIR_VENV, 'lib', py_version, 'site-packages')

def create_virtualenv():
  if not os.path.exists(FILE_VENV):
    os.system('virtualenv --no-site-packages %s' % DIR_VENV)
    os.system('echo %s >> %s' % (
      'set PYTHONPATH=' if IS_WINDOWS else 'unset PYTHONPATH', FILE_VENV
    ))
    pth_file = os.path.join(site_packages_path(), 'gae.pth')
    echo_to = 'echo %s >> {pth}'.format(pth=pth_file)
    os.system(echo_to % find_gae_path())
    os.system(echo_to % os.path.abspath(DIR_LIBX))
    fix_path_cmd = 'import dev_appserver; dev_appserver.fix_sys_path()'
    os.system(echo_to % (
      fix_path_cmd if IS_WINDOWS else '"%s"' % fix_path_cmd
    ))
  return True

def exec_pip_commands(command):
  script = []
  if create_virtualenv():
    activate_cmd = 'call %s' if IS_WINDOWS else 'source %s'
    activate_cmd %= FILE_VENV
    script.append(activate_cmd)

  script.append('echo %s' % command)
  script.append('%s SKIP_GOOGLEAPICLIENT_COMPAT_CHECK=1' %
                ('set' if IS_WINDOWS else 'export'))
  script.append(command)
  script = '&'.join(script) if IS_WINDOWS else \
    '/bin/bash -c "%s"' % ';'.join(script)
  os.system(script)

def make_guard(fname, cmd, spec):
  with open(fname, 'w') as guard:
    guard.write('Prevents %s execution if newer than %s' % (cmd, spec))

def guard_is_newer(guard, watched):
  if os.path.exists(guard):
    return os.path.getmtime(guard) > os.path.getmtime(watched)
  return False

def check_if_pip_should_run():
  return not guard_is_newer(FILE_PIP_GUARD, FILE_REQUIREMENTS)

def install_py_libs():
  if not check_if_pip_should_run() and os.path.exists(DIR_LIB):
    return

  exec_pip_commands('pip install -q -r %s' % FILE_REQUIREMENTS)

  exclude_ext = ['.pth', '.pyc', '.egg-info', '.dist-info', '.so']
  exclude_prefix = ['setuptools-', 'pip-', 'Pillow-']
  exclude = [
    'test', 'tests', 'pip', 'setuptools', '_markerlib', 'PIL',
    'easy_install.py', 'pkg_resources', 'pkg_resources.py'
  ]

  def _exclude_prefix(pkg):
    for prefix in exclude_prefix:
      if pkg.startswith(prefix):
        return True
    return False

  def _exclude_ext(pkg):
    for ext in exclude_ext:
      if pkg.endswith(ext):
        return True
    return False

  def _get_dest(pkg):
    make_dirs(DIR_LIB)
    return os.path.join(DIR_LIB, pkg)

  site_packages = site_packages_path()
  dir_libs = listdir(DIR_LIB)
  dir_libs.extend(listdir(DIR_LIBX))
  for dir_ in listdir(site_packages):
    if dir_ in dir_libs or dir_ in exclude:
      continue
    if _exclude_prefix(dir_) or _exclude_ext(dir_):
      continue
    src_path = os.path.join(site_packages, dir_)
    copy = shutil.copy if os.path.isfile(src_path) else shutil.copytree
    copy(src_path, _get_dest(dir_))

  make_guard(FILE_PIP_GUARD, 'pip', FILE_REQUIREMENTS)

def install_dependencies():
  make_dirs(DIR_TEMP)
  install_py_libs()

def check_for_update():
  if os.path.exists(FILE_UPDATE):
    mtime = os.path.getmtime(FILE_UPDATE)
    last = datetime.utcfromtimestamp(mtime).strftime('%Y-%m-%d')
    today = datetime.utcnow().strftime('%Y-%m-%d')
    if last == today:
      return
  try:
    with open(FILE_UPDATE, 'a'):
      os.utime(FILE_UPDATE, None)
    request = urllib2.Request(
      CORE_VERSION_URL,
      urllib.urlencode({'version': __version__}),
    )
    response = urllib2.urlopen(request)
    with open(FILE_UPDATE, 'w') as update_json:
      update_json.write(response.read())
  except (urllib2.HTTPError, urllib2.URLError):
    pass

def print_out_update(force_show=False):
  try:
    import pip
    SemVer = pip.util.version.SemanticVersion
  except AttributeError:
    import pip._vendor.distlib.version
    SemVer = pip._vendor.distlib.version.SemanticVersion

  try:
    with open(FILE_UPDATE, 'r') as update_json:
      data = json.load(update_json)
    if SemVer(__version__) < SemVer(data['version']) or force_show:
      print_out('UPDATE')
      print_out(data['version'], 'Latest version of gae-init')
      print_out(__version__, 'Your version is a bit behind')
      print_out('CHANGESET', data['changeset'])
  except (ValueError, KeyError):
    os.remove(FILE_UPDATE)
  except IOError:
    pass

###############################################################################
# Doctor
###############################################################################
def internet_on():
  try:
    urllib2.urlopen(INTERNET_TEST_URL, timeout=2)
    return True
  except (urllib2.URLError, socket.timeout):
    return False

def check_requirement(check_func):
  result, name, help_url_id = check_func()
  if not result:
    print_out('NOT FOUND', name)
    if help_url_id:
      print 'Please see %s%s' % (REQUIREMENTS_URL, help_url_id)
    return False
  return True

def find_gae_path():
  global GAE_PATH
  if GAE_PATH:
    return GAE_PATH
  if IS_WINDOWS:
    gae_path = None
    for path in os.environ['PATH'].split(os.pathsep):
      if os.path.isfile(os.path.join(path, 'dev_appserver.py')):
        gae_path = path
  else:
    gae_path = spawn.find_executable('dev_appserver.py')
    if gae_path:
      gae_path = os.path.dirname(os.path.realpath(gae_path))
  if not gae_path:
    return ''
  gcloud_exec = 'gcloud.cmd' if IS_WINDOWS else 'gcloud'
  if not os.path.isfile(os.path.join(gae_path, gcloud_exec)):
    GAE_PATH = gae_path
  else:
    gae_path = os.path.join(gae_path, '..', 'platform', 'google_appengine')
    if os.path.exists(gae_path):
      GAE_PATH = os.path.realpath(gae_path)
  return GAE_PATH

def check_internet():
  return internet_on(), 'Internet', ''

def check_gae():
  return bool(find_gae_path()), 'Google App Engine SDK', '#gae'

def check_git():
  return bool(spawn.find_executable('git')), 'Git', '#git'

def check_nodejs():
  return bool(spawn.find_executable('node')), 'Node.js', '#nodejs'

def check_pip():
  return bool(spawn.find_executable('pip')), 'pip', '#pip'

def check_virtualenv():
  return bool(spawn.find_executable('virtualenv')), 'virtualenv', '#virtualenv'

def doctor_says_ok():
  checkers = [check_gae, check_git, check_nodejs, check_pip, check_virtualenv]
  if False in [check_requirement(check) for check in checkers]:
    sys.exit(1)
  return check_requirement(check_internet)

###############################################################################
# Main
###############################################################################
def run_start():
  make_dirs(DIR_STORAGE)
  port = int(ARGS.port)
  run_command = ' '.join(map(str, [
    'dev_appserver.py',
    DIR_MAIN,
    '--host %s' % ARGS.host,
    '--port %s' % port,
    '--admin_port %s' % (port + 1),
    '--storage_path=%s' % DIR_STORAGE,
    '--skip_sdk_update_check',
  ] + ARGS.args))
  os.system(run_command)

def run():
  if len(sys.argv) == 1 or (ARGS.args and not ARGS.start):
    PARSER.print_help()
    sys.exit(1)

  os.chdir(os.path.dirname(os.path.realpath(__file__)))

  if doctor_says_ok():
    install_dependencies()
    check_for_update()

  if ARGS.show_version:
    print_out_update(force_show=True)
  else:
    print_out_update()

  if ARGS.start:
    run_start()

  if ARGS.install_dependencies:
    install_dependencies()

if __name__ == '__main__':
  run()


text:
MusicCodes
==========

A webapp for generating and managing download codes and serving the files.

![screenshot](screenshot.jpg)

## Usage ##

```
Usage:
    MusicCodes.py run
    MusicCodes.py create <number>
    MusicCodes.py add <number>
    MusicCodes.py show
    MusicCodes.py voucher --all
    MusicCodes.py voucher <from> <to>
    MusicCodes.py reset <code>
    MusicCodes.py -h | --help

Options:
    -h --help                   Show this screen.
    run                         Starts MusicCodes Web.
    create <number>             Creates DB with number of codes.
    add <number>                Adds number of codes to existing DB.
    show                        Show all DB entries.
    voucher --all               Creates a voucher PDF with all codes.
    voucher <from> <to>         Creates a voucher PDF with a range of codes.
    reset <code>                Resets the USED counter for a specific code.
```

### voucher ###
For using the voucher option you need to have latex installed. Needs `latexpdf`.


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Dashboard for /Users/ludo/Sites/3wasymfo-1mois/src/Troiswa/BackBundle/DataFixtures/ORM</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../../css/bootstrap.min.css" rel="stylesheet">
  <link href="../../css/nv.d3.css" rel="stylesheet">
  <link href="../../css/style.css" rel="stylesheet">

/Users/ludo/Sites/3wasymfo-1mois/src/Troiswa/BackBundle

DataFixtures

ORM

(Dashboard)

Classes

Coverage Distribution

       <svg></svg>

Complexity

       <svg></svg>

Insufficient Coverage

         Class
         Coverage

LoadProductData	0%

LoadCategoryData	0%

Project Risks

         Class
         CRAP

LoadProductData	12

LoadCategoryData	12

Methods

Coverage Distribution

       <svg></svg>

Complexity

       <svg></svg>

Insufficient Coverage

         Method
         Coverage

getOrder	0%

load	0%

getOrder	0%

load	0%

Project Risks

         Method
         CRAP

load	6

load	6

     Generated by PHP_CodeCoverage 2.0.16 using PHP 5.6.4 and PHPUnit 4.6.6 at Mon Oct 26 20:28:40 CET 2015.


text:
class RequisitesFromStatementsForServiceFatherFiliationMapper
  include XmlSchemaMapper
  schema File.expand_path('../../vendor/ezags-protocols/eZAGS/public/UploadService.xsd', File.dirname(__FILE__))
  type 'RequisitesFromStatementsForServiceFatherFiliation'

  # Дата заявления
  # @return [Date]
  # minOccurs: 1, maxOccurs: 1
  attr_accessor :statement_date
  # Номер заявления
  # @return [Int]
  # minOccurs: 0, maxOccurs: 1
  attr_accessor :statement_number
  # Реквизиты АЗ о смерти матери
  # @return [OldActRecordRequisitesMapper]
  # minOccurs: 0, maxOccurs: 1
  attr_accessor :death_reqs
  # Решение суда (при установлении отцовства)
  # @return [CourtActDecisionMapper]
  # minOccurs: 0, maxOccurs: 1
  attr_accessor :court_decision
  # Справка органа внутренних дел о том, что местонахождение матери не установлено
  # @return [RequisitesReferenceFromOVDMapper]
  # minOccurs: 0, maxOccurs: 1
  attr_accessor :ref_reqs

end


text:
<!DOCTYPE HTML>

		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<title>RadioButton - sap.m - qUnit test</title>

		<link rel="stylesheet" href="../../../../resources/sap/ui/thirdparty/qunit.css" type="text/css" media="screen">

qUnit Page for sap.m.RadioButton


text:
{# Display a success/error message after sending email #}
{# expects boolean email_sent and optional message_type for display #}
{% if email_sent %}

Your {% firstof message_type 'message' %} has been sent.  Thank you!

{% else %}

There was an error sending your {% firstof message_type 'message' %}.  Please try again later.

    {% if debug %}
        Exception generated when sending email: {{ err }}
    {% endif %}
{% endif %}


text:
package common

import (
	"context"
	"fmt"
	"path"

	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/kubernetes/test/e2e/framework"
	e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
	imageutils "k8s.io/kubernetes/test/utils/image"

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

var _ = ginkgo.Describe("[sig-storage] Projected secret", func() {
	f := framework.NewDefaultFramework("projected")

	/*
	   Release : v1.9
	   Testname: Projected Volume, Secrets, volume mode default
	   Description: A Pod is created with a projected volume source 'secret' to store a secret with a specified key with default permission mode. Pod MUST be able to read the content of the key successfully and the mode MUST be -rw-r--r-- by default.
	*/
	framework.ConformanceIt("should be consumable from pods in volume [NodeConformance]", func() {
		doProjectedSecretE2EWithoutMapping(f, nil /* default mode */, "projected-secret-test-"+string(uuid.NewUUID()), nil, nil)
	})

	/*
	   Release : v1.9
	   Testname: Projected Volume, Secrets, volume mode 0400
	   Description: A Pod is created with a projected volume source 'secret' to store a secret with a specified key with permission mode set to 0x400 on the Pod. Pod MUST be able to read the content of the key successfully and the mode MUST be -r--------.
	   This test is marked LinuxOnly since Windows does not support setting specific file permissions.
	*/
	framework.ConformanceIt("should be consumable from pods in volume with defaultMode set [LinuxOnly] [NodeConformance]", func() {
		defaultMode := int32(0400)
		doProjectedSecretE2EWithoutMapping(f, &defaultMode, "projected-secret-test-"+string(uuid.NewUUID()), nil, nil)
	})

	/*
	   Release : v1.9
	   Testname: Project Volume, Secrets, non-root, custom fsGroup
	   Description: A Pod is created with a projected volume source 'secret' to store a secret with a specified key. The volume has permission mode set to 0440, fsgroup set to 1001 and user set to non-root uid of 1000. Pod MUST be able to read the content of the key successfully and the mode MUST be -r--r-----.
	   This test is marked LinuxOnly since Windows does not support setting specific file permissions, or running as UID / GID.
	*/
	framework.ConformanceIt("should be consumable from pods in volume as non-root with defaultMode and fsGroup set [LinuxOnly] [NodeConformance]", func() {
		defaultMode := int32(0440) /* setting fsGroup sets mode to at least 440 */
		fsGroup := int64(1001)
		doProjectedSecretE2EWithoutMapping(f, &defaultMode, "projected-secret-test-"+string(uuid.NewUUID()), &fsGroup, &nonRootTestUserID)
	})

	/*
	   Release : v1.9
	   Testname: Projected Volume, Secrets, mapped
	   Description: A Pod is created with a projected volume source 'secret' to store a secret with a specified key with default permission mode. The secret is also mapped to a custom path. Pod MUST be able to read the content of the key successfully and the mode MUST be -r--------on the mapped volume.
	*/
	framework.ConformanceIt("should be consumable from pods in volume with mappings [NodeConformance]", func() {
		doProjectedSecretE2EWithMapping(f, nil)
	})

	/*
	   Release : v1.9
	   Testname: Projected Volume, Secrets, mapped, volume mode 0400
	   Description: A Pod is created with a projected volume source 'secret' to store a secret with a specified key with permission mode set to 0400. The secret is also mapped to a specific name. Pod MUST be able to read the content of the key successfully and the mode MUST be -r-------- on the mapped volume.
	   This test is marked LinuxOnly since Windows does not support setting specific file permissions.
	*/
	framework.ConformanceIt("should be consumable from pods in volume with mappings and Item Mode set [LinuxOnly] [NodeConformance]", func() {
		mode := int32(0400)
		doProjectedSecretE2EWithMapping(f, &mode)
	})

	ginkgo.It("should be able to mount in a volume regardless of a different secret existing with same name in different namespace [NodeConformance]", func() {
		var (
			namespace2  *v1.Namespace
			err         error
			secret2Name = "projected-secret-test-" + string(uuid.NewUUID())
		)

		if namespace2, err = f.CreateNamespace("secret-namespace", nil); err != nil {
			framework.Failf("unable to create new namespace %s: %v", namespace2.Name, err)
		}

		secret2 := secretForTest(namespace2.Name, secret2Name)
		secret2.Data = map[string][]byte{
			"this_should_not_match_content_of_other_secret": []byte("similarly_this_should_not_match_content_of_other_secret\n"),
		}
		if secret2, err = f.ClientSet.CoreV1().Secrets(namespace2.Name).Create(context.TODO(), secret2, metav1.CreateOptions{}); err != nil {
			framework.Failf("unable to create test secret %s: %v", secret2.Name, err)
		}
		doProjectedSecretE2EWithoutMapping(f, nil /* default mode */, secret2.Name, nil, nil)
	})

	/*
	   Release : v1.9
	   Testname: Projected Volume, Secrets, mapped, multiple paths
	   Description: A Pod is created with a projected volume source 'secret' to store a secret with a specified key. The secret is mapped to two different volume mounts. Pod MUST be able to read the content of the key successfully from the two volume mounts and the mode MUST be -r-------- on the mapped volumes.
	*/
	framework.ConformanceIt("should be consumable in multiple volumes in a pod [NodeConformance]", func() {
		// This test ensures that the same secret can be mounted in multiple
		// volumes in the same pod.  This test case exists to prevent
		// regressions that break this use-case.
		var (
			name             = "projected-secret-test-" + string(uuid.NewUUID())
			volumeName       = "projected-secret-volume"
			volumeMountPath  = "/etc/projected-secret-volume"
			volumeName2      = "projected-secret-volume-2"
			volumeMountPath2 = "/etc/projected-secret-volume-2"
			secret           = secretForTest(f.Namespace.Name, name)
		)

		ginkgo.By(fmt.Sprintf("Creating secret with name %s", secret.Name))
		var err error
		if secret, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Create(context.TODO(), secret, metav1.CreateOptions{}); err != nil {
			framework.Failf("unable to create test secret %s: %v", secret.Name, err)
		}

		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: "pod-projected-secrets-" + string(uuid.NewUUID()),
			},
			Spec: v1.PodSpec{
				Volumes: []v1.Volume{
					{
						Name: volumeName,
						VolumeSource: v1.VolumeSource{
							Projected: &v1.ProjectedVolumeSource{
								Sources: []v1.VolumeProjection{
									{
										Secret: &v1.SecretProjection{
											LocalObjectReference: v1.LocalObjectReference{
												Name: name,
											},
										},
									},
								},
							},
						},
					},
					{
						Name: volumeName2,
						VolumeSource: v1.VolumeSource{
							Projected: &v1.ProjectedVolumeSource{
								Sources: []v1.VolumeProjection{
									{
										Secret: &v1.SecretProjection{
											LocalObjectReference: v1.LocalObjectReference{
												Name: name,
											},
										},
									},
								},
							},
						},
					},
				},
				Containers: []v1.Container{
					{
						Name:  "secret-volume-test",
						Image: imageutils.GetE2EImage(imageutils.Mounttest),
						Args: []string{
							"--file_content=/etc/projected-secret-volume/data-1",
							"--file_mode=/etc/projected-secret-volume/data-1"},
						VolumeMounts: []v1.VolumeMount{
							{
								Name:      volumeName,
								MountPath: volumeMountPath,
								ReadOnly:  true,
							},
							{
								Name:      volumeName2,
								MountPath: volumeMountPath2,
								ReadOnly:  true,
							},
						},
					},
				},
				RestartPolicy: v1.RestartPolicyNever,
			},
		}

		fileModeRegexp := getFileModeRegex("/etc/projected-secret-volume/data-1", nil)
		f.TestContainerOutputRegexp("consume secrets", pod, 0, []string{
			"content of file \"/etc/projected-secret-volume/data-1\": value-1",
			fileModeRegexp,
		})
	})

	/*
	   Release : v1.9
	   Testname: Projected Volume, Secrets, create, update delete
	   Description: Create a Pod with three containers with secrets namely a create, update and delete container. Create Container when started MUST no have a secret, update and delete containers MUST be created with a secret value. Create a secret in the create container, the Pod MUST be able to read the secret from the create container. Update the secret in the update container, Pod MUST be able to read the updated secret value. Delete the secret in the delete container. Pod MUST fail to read the secret from the delete container.
	*/
	framework.ConformanceIt("optional updates should be reflected in volume [NodeConformance]", func() {
		podLogTimeout := e2epod.GetPodSecretUpdateTimeout(f.ClientSet)
		containerTimeoutArg := fmt.Sprintf("--retry_time=%v", int(podLogTimeout.Seconds()))
		trueVal := true
		volumeMountPath := "/etc/projected-secret-volumes"

		deleteName := "s-test-opt-del-" + string(uuid.NewUUID())
		deleteContainerName := "dels-volume-test"
		deleteVolumeName := "deletes-volume"
		deleteSecret := &v1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: f.Namespace.Name,
				Name:      deleteName,
			},
			Data: map[string][]byte{
				"data-1": []byte("value-1"),
			},
		}

		updateName := "s-test-opt-upd-" + string(uuid.NewUUID())
		updateContainerName := "upds-volume-test"
		updateVolumeName := "updates-volume"
		updateSecret := &v1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: f.Namespace.Name,
				Name:      updateName,
			},
			Data: map[string][]byte{
				"data-1": []byte("value-1"),
			},
		}

		createName := "s-test-opt-create-" + string(uuid.NewUUID())
		createContainerName := "creates-volume-test"
		createVolumeName := "creates-volume"
		createSecret := &v1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: f.Namespace.Name,
				Name:      createName,
			},
			Data: map[string][]byte{
				"data-1": []byte("value-1"),
			},
		}

		ginkgo.By(fmt.Sprintf("Creating secret with name %s", deleteSecret.Name))
		var err error
		if deleteSecret, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Create(context.TODO(), deleteSecret, metav1.CreateOptions{}); err != nil {
			framework.Failf("unable to create test secret %s: %v", deleteSecret.Name, err)
		}

		ginkgo.By(fmt.Sprintf("Creating secret with name %s", updateSecret.Name))
		if updateSecret, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Create(context.TODO(), updateSecret, metav1.CreateOptions{}); err != nil {
			framework.Failf("unable to create test secret %s: %v", updateSecret.Name, err)
		}

		pod := &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: "pod-projected-secrets-" + string(uuid.NewUUID()),
			},
			Spec: v1.PodSpec{
				Volumes: []v1.Volume{
					{
						Name: deleteVolumeName,
						VolumeSource: v1.VolumeSource{
							Projected: &v1.ProjectedVolumeSource{
								Sources: []v1.VolumeProjection{
									{
										Secret: &v1.SecretProjection{
											LocalObjectReference: v1.LocalObjectReference{
												Name: deleteName,
											},
											Optional: &trueVal,
										},
									},
								},
							},
						},
					},
					{
						Name: updateVolumeName,
						VolumeSource: v1.VolumeSource{
							Projected: &v1.ProjectedVolumeSource{
								Sources: []v1.VolumeProjection{
									{
										Secret: &v1.SecretProjection{
											LocalObjectReference: v1.LocalObjectReference{
												Name: updateName,
											},
											Optional: &trueVal,
										},
									},
								},
							},
						},
					},
					{
						Name: createVolumeName,
						VolumeSource: v1.VolumeSource{
							Projected: &v1.ProjectedVolumeSource{
								Sources: []v1.VolumeProjection{
									{
										Secret: &v1.SecretProjection{
											LocalObjectReference: v1.LocalObjectReference{
												Name: createName,
											},
											Optional: &trueVal,
										},
									},
								},
							},
						},
					},
				},
				Containers: []v1.Container{
					{
						Name:    deleteContainerName,
						Image:   imageutils.GetE2EImage(imageutils.Mounttest),
						Command: []string{"/mounttest", "--break_on_expected_content=false", containerTimeoutArg, "--file_content_in_loop=/etc/projected-secret-volumes/delete/data-1"},
						VolumeMounts: []v1.VolumeMount{
							{
								Name:      deleteVolumeName,
								MountPath: path.Join(volumeMountPath, "delete"),
								ReadOnly:  true,
							},
						},
					},
					{
						Name:    updateContainerName,
						Image:   imageutils.GetE2EImage(imageutils.Mounttest),
						Command: []string{"/mounttest", "--break_on_expected_content=false", containerTimeoutArg, "--file_content_in_loop=/etc/projected-secret-volumes/update/data-3"},
						VolumeMounts: []v1.VolumeMount{
							{
								Name:      updateVolumeName,
								MountPath: path.Join(volumeMountPath, "update"),
								ReadOnly:  true,
							},
						},
					},
					{
						Name:    createContainerName,
						Image:   imageutils.GetE2EImage(imageutils.Mounttest),
						Command: []string{"/mounttest", "--break_on_expected_content=false", containerTimeoutArg, "--file_content_in_loop=/etc/projected-secret-volumes/create/data-1"},
						VolumeMounts: []v1.VolumeMount{
							{
								Name:      createVolumeName,
								MountPath: path.Join(volumeMountPath, "create"),
								ReadOnly:  true,
							},
						},
					},
				},
				RestartPolicy: v1.RestartPolicyNever,
			},
		}
		ginkgo.By("Creating the pod")
		f.PodClient().CreateSync(pod)

		pollCreateLogs := func() (string, error) {
			return e2epod.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, createContainerName)
		}
		gomega.Eventually(pollCreateLogs, podLogTimeout, framework.Poll).Should(gomega.ContainSubstring("Error reading file /etc/projected-secret-volumes/create/data-1"))

		pollUpdateLogs := func() (string, error) {
			return e2epod.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, updateContainerName)
		}
		gomega.Eventually(pollUpdateLogs, podLogTimeout, framework.Poll).Should(gomega.ContainSubstring("Error reading file /etc/projected-secret-volumes/update/data-3"))

		pollDeleteLogs := func() (string, error) {
			return e2epod.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, deleteContainerName)
		}
		gomega.Eventually(pollDeleteLogs, podLogTimeout, framework.Poll).Should(gomega.ContainSubstring("value-1"))

		ginkgo.By(fmt.Sprintf("Deleting secret %v", deleteSecret.Name))
		err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Delete(context.TODO(), deleteSecret.Name, metav1.DeleteOptions{})
		framework.ExpectNoError(err, "Failed to delete secret %q in namespace %q", deleteSecret.Name, f.Namespace.Name)

		ginkgo.By(fmt.Sprintf("Updating secret %v", updateSecret.Name))
		updateSecret.ResourceVersion = "" // to force update
		delete(updateSecret.Data, "data-1")
		updateSecret.Data["data-3"] = []byte("value-3")
		_, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Update(context.TODO(), updateSecret, metav1.UpdateOptions{})
		framework.ExpectNoError(err, "Failed to update secret %q in namespace %q", updateSecret.Name, f.Namespace.Name)

		ginkgo.By(fmt.Sprintf("Creating secret with name %s", createSecret.Name))
		if createSecret, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Create(context.TODO(), createSecret, metav1.CreateOptions{}); err != nil {
			framework.Failf("unable to create test secret %s: %v", createSecret.Name, err)
		}

		ginkgo.By("waiting to observe update in volume")

		gomega.Eventually(pollCreateLogs, podLogTimeout, framework.Poll).Should(gomega.ContainSubstring("value-1"))
		gomega.Eventually(pollUpdateLogs, podLogTimeout, framework.Poll).Should(gomega.ContainSubstring("value-3"))
		gomega.Eventually(pollDeleteLogs, podLogTimeout, framework.Poll).Should(gomega.ContainSubstring("Error reading file /etc/projected-secret-volumes/delete/data-1"))
	})

	//The secret is in pending during volume creation until the secret objects are available
	//or until mount the secret volume times out. There is no secret object defined for the pod, so it should return timeout exception unless it is marked optional.
	//Slow (~5 mins)
	ginkgo.It("Should fail non-optional pod creation due to secret object does not exist [Slow]", func() {
		volumeMountPath := "/etc/projected-secret-volumes"
		podName := "pod-secrets-" + string(uuid.NewUUID())
		err := createNonOptionalSecretPod(f, volumeMountPath, podName)
		framework.ExpectError(err, "created pod %q with non-optional secret in namespace %q", podName, f.Namespace.Name)
	})

	//Secret object defined for the pod, If a key is specified which is not present in the secret,
	// the volume setup will error unless it is marked optional, during the pod creation.
	//Slow (~5 mins)
	ginkgo.It("Should fail non-optional pod creation due to the key in the secret object does not exist [Slow]", func() {
		volumeMountPath := "/etc/secret-volumes"
		podName := "pod-secrets-" + string(uuid.NewUUID())
		err := createNonOptionalSecretPodWithSecret(f, volumeMountPath, podName)
		framework.ExpectError(err, "created pod %q with non-optional secret in namespace %q", podName, f.Namespace.Name)
	})
})

func doProjectedSecretE2EWithoutMapping(f *framework.Framework, defaultMode *int32,
	secretName string, fsGroup *int64, uid *int64) {
	var (
		volumeName      = "projected-secret-volume"
		volumeMountPath = "/etc/projected-secret-volume"
		secret          = secretForTest(f.Namespace.Name, secretName)
	)

	ginkgo.By(fmt.Sprintf("Creating projection with secret that has name %s", secret.Name))
	var err error
	if secret, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Create(context.TODO(), secret, metav1.CreateOptions{}); err != nil {
		framework.Failf("unable to create test secret %s: %v", secret.Name, err)
	}

	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "pod-projected-secrets-" + string(uuid.NewUUID()),
			Namespace: f.Namespace.Name,
		},
		Spec: v1.PodSpec{
			Volumes: []v1.Volume{
				{
					Name: volumeName,
					VolumeSource: v1.VolumeSource{
						Projected: &v1.ProjectedVolumeSource{
							Sources: []v1.VolumeProjection{
								{
									Secret: &v1.SecretProjection{
										LocalObjectReference: v1.LocalObjectReference{
											Name: secretName,
										},
									},
								},
							},
						},
					},
				},
			},
			Containers: []v1.Container{
				{
					Name:  "projected-secret-volume-test",
					Image: imageutils.GetE2EImage(imageutils.Mounttest),
					Args: []string{
						"--file_content=/etc/projected-secret-volume/data-1",
						"--file_mode=/etc/projected-secret-volume/data-1"},
					VolumeMounts: []v1.VolumeMount{
						{
							Name:      volumeName,
							MountPath: volumeMountPath,
						},
					},
				},
			},
			RestartPolicy: v1.RestartPolicyNever,
		},
	}

	if defaultMode != nil {
		//pod.Spec.Volumes[0].VolumeSource.Projected.Sources[0].Secret.DefaultMode = defaultMode
		pod.Spec.Volumes[0].VolumeSource.Projected.DefaultMode = defaultMode
	}

	if fsGroup != nil || uid != nil {
		pod.Spec.SecurityContext = &v1.PodSecurityContext{
			FSGroup:   fsGroup,
			RunAsUser: uid,
		}
	}

	fileModeRegexp := getFileModeRegex("/etc/projected-secret-volume/data-1", defaultMode)
	expectedOutput := []string{
		"content of file \"/etc/projected-secret-volume/data-1\": value-1",
		fileModeRegexp,
	}

	f.TestContainerOutputRegexp("consume secrets", pod, 0, expectedOutput)
}

func doProjectedSecretE2EWithMapping(f *framework.Framework, mode *int32) {
	var (
		name            = "projected-secret-test-map-" + string(uuid.NewUUID())
		volumeName      = "projected-secret-volume"
		volumeMountPath = "/etc/projected-secret-volume"
		secret          = secretForTest(f.Namespace.Name, name)
	)

	ginkgo.By(fmt.Sprintf("Creating projection with secret that has name %s", secret.Name))
	var err error
	if secret, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Create(context.TODO(), secret, metav1.CreateOptions{}); err != nil {
		framework.Failf("unable to create test secret %s: %v", secret.Name, err)
	}

	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name: "pod-projected-secrets-" + string(uuid.NewUUID()),
		},
		Spec: v1.PodSpec{
			Volumes: []v1.Volume{
				{
					Name: volumeName,
					VolumeSource: v1.VolumeSource{
						Projected: &v1.ProjectedVolumeSource{
							Sources: []v1.VolumeProjection{
								{
									Secret: &v1.SecretProjection{
										LocalObjectReference: v1.LocalObjectReference{
											Name: name,
										},
										Items: []v1.KeyToPath{
											{
												Key:  "data-1",
												Path: "new-path-data-1",
											},
										},
									},
								},
							},
						},
					},
				},
			},
			Containers: []v1.Container{
				{
					Name:  "projected-secret-volume-test",
					Image: imageutils.GetE2EImage(imageutils.Mounttest),
					Args: []string{
						"--file_content=/etc/projected-secret-volume/new-path-data-1",
						"--file_mode=/etc/projected-secret-volume/new-path-data-1"},
					VolumeMounts: []v1.VolumeMount{
						{
							Name:      volumeName,
							MountPath: volumeMountPath,
						},
					},
				},
			},
			RestartPolicy: v1.RestartPolicyNever,
		},
	}

	if mode != nil {
		//pod.Spec.Volumes[0].VolumeSource.Projected.Sources[0].Secret.Items[0].Mode = mode
		pod.Spec.Volumes[0].VolumeSource.Projected.DefaultMode = mode
	}

	fileModeRegexp := getFileModeRegex("/etc/projected-secret-volume/new-path-data-1", mode)
	expectedOutput := []string{
		"content of file \"/etc/projected-secret-volume/new-path-data-1\": value-1",
		fileModeRegexp,
	}

	f.TestContainerOutputRegexp("consume secrets", pod, 0, expectedOutput)
}


text:
CREATE PROCEDURE [dbo].[GetCountNotes]
AS
	Select Count(*) From Notes
GO


text:
include(CMakeFindDependencyMacro)
find_dependency(Threads)

# Work out the set of components to load
if(${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS)
    set(${CMAKE_FIND_PACKAGE_NAME}_comps ${${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS})
endif()

# Check all required components are available before trying to load any
foreach(comp IN LISTS ${CMAKE_FIND_PACKAGE_NAME}_comps)
    if(${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED_${comp} AND NOT EXISTS ${CMAKE_CURRENT_LIST_DIR}/Sqlpp17${comp}Config.cmake)
        set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "Sqlpp17 missing required component: ${comp}")
        set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
        return()
    endif()
endforeach()

# Add the target file
include(${CMAKE_CURRENT_LIST_DIR}/Sqlpp17Targets.cmake)

# Load any optional components
foreach(comp IN LISTS ${CMAKE_FIND_PACKAGE_NAME}_comps)
    include(${CMAKE_CURRENT_LIST_DIR}/Sqlpp17${comp}Config.cmake OPTIONAL)
endforeach()


text:
"""
.. module: security_monkey.common.sts_connect
    :platform: Unix

.. version:: $$VERSION$$
.. moduleauthor:: Patrick Kelley <pkelley@netflix.com> @monkeysecurity

"""
from security_monkey.datastore import Account
import boto
import boto.ec2
import boto.ses
import boto.iam
import boto.sns
import boto.sqs
import boto.rds
import boto.redshift
import botocore.session

def connect(account_name, connection_type, **args):
    """

    Examples of use:
    ec2 = sts_connect.connect(environment, 'ec2', region=region, validate_certs=False)
    ec2 = sts_connect.connect(environment, 'ec2', validate_certs=False, debug=1000)
    ec2 = sts_connect.connect(environment, 'ec2')
    where environment is ( test, prod, dev )
    s3  = sts_connect.connect(environment, 's3')
    ses = sts_connect.connect(environment, 'ses')

    :param account: Account to connect with (i.e. test, prod, dev)

    :raises Exception: RDS Region not valid
                       AWS Tech not supported.

    :returns: STS Connection Object for given tech

    :note: To use this method a SecurityMonkey role must be created
            in the target account with full read only privledges.
    """
    account = Account.query.filter(Account.name == account_name).first()
    sts = boto.connect_sts()
    role = sts.assume_role('arn:aws:iam::' + account.number + ':role/SecurityMonkey', 'secmonkey')

    if connection_type == 'botocore':
        botocore_session = botocore.session.get_session()
        botocore_session.set_credentials(role.credentials.access_key, role.credentials.secret_key, token=role.credentials.session_token)
        return botocore_session

    if connection_type == 'ec2':
        return boto.connect_ec2(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'elb':
        if 'region' in args:
            region = args['region']
            del args['region']
        else:
            region = 'us-east-1'

        return boto.ec2.elb.connect_to_region(
            region,
            aws_access_key_id=role.credentials.access_key,
            aws_secret_access_key=role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 's3':
        if 'region' in args:
            region = args['region']
            # drop region key-val pair from args or you'll get an exception
            del args['region']
            return boto.s3.connect_to_region(
                region,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token,
                **args)

        return boto.connect_s3(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'ses':
        if 'region' in args:
            region = args['region']
            del args['region']
            return boto.ses.connect_to_region(
                region,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token,
                **args)

        return boto.connect_ses(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'iam':
        if 'region' in args:
            region = args['region']
            # drop region key-val pair from args or you'll get an exception
            del args['region']
            return boto.iam.connect_to_region(
                region,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token,
                **args)

        return boto.connect_iam(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'route53':
        return boto.connect_route53(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'sns':
        if 'region' in args:
            region = args['region']
            del args['region']
            return boto.sns.connect_to_region(
                region.name,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token,
                **args)

        return boto.connect_sns(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'sqs':
        if 'region' in args:
            region = args['region']
            del args['region']
            return boto.sqs.connect_to_region(
                region.name,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token,
                **args)

        return boto.connect_sqs(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'vpc':
        return boto.connect_vpc(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'rds':
        if 'region' in args:
            reg = args['region']
            rds_region = None
            for boto_region in boto.rds.regions():
                if reg.name == boto_region.name:
                    rds_region = boto_region

            if rds_region is None:
                raise Exception('The supplied region {0} is not in boto.rds.regions. {1}'.format(reg, boto.rds.regions()))

        return boto.connect_rds(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    if connection_type == 'redshift':
        if 'region' in args:
            region = args['region']
            del args['region']
            return boto.redshift.connect_to_region(
                region.name,
                aws_access_key_id=role.credentials.access_key,
                aws_secret_access_key=role.credentials.secret_key,
                security_token=role.credentials.session_token,
                **args)

        return boto.connect_redshift(
            role.credentials.access_key,
            role.credentials.secret_key,
            security_token=role.credentials.session_token,
            **args)

    err_msg = 'The connection_type supplied (%s) is not implemented.' % connection_type
    raise Exception(err_msg)


text:
"use strict";
var Engine;
(function (Engine) {
    var Player;
    (function (_Player) {
        var Util = Engine.Util;
        var MOVEMENT_SPEED = 2.4;
        var HORIZONTAL_VIEW_SPEED = 1.2;
        var VERTICAL_VIEW_SPEED = 1000;
        var CROUCH_SPEED = 500;
        var JUMP_HEIGHT = 50;
        var JUMP_SPEED = 2;
        var MAX_CROUCH_MOD = 0;
        var MIN_CROUCH_MOD = -25;
        var MAX_JUMP_MOD = Infinity;
        var MIN_JUMP_MOD = 0;
        var MAX_VIEW_MOD = 1000;
        var MIN_VIEW_MOD = -1000;
        var Direction;
        (function (Direction) {
            Direction[Direction["FORWARD"] = 1] = "FORWARD";
            Direction[Direction["RIGHT"] = 2] = "RIGHT";
            Direction[Direction["BACKWARD"] = 4] = "BACKWARD";
            Direction[Direction["LEFT"] = 8] = "LEFT";
        })(Direction || (Direction = {}));
        var DIRECTION_STATE_TABLE = {};
        DIRECTION_STATE_TABLE[8 /* LEFT */] = 'left';
        DIRECTION_STATE_TABLE[2 /* RIGHT */] = 'right';
        DIRECTION_STATE_TABLE[1 /* FORWARD */] = 'forward';
        DIRECTION_STATE_TABLE[4 /* BACKWARD */] = 'backward';
        var DIRECTION_TABLE = {
            0: Infinity,
            1: (0 / 8) * Util.CIRCLE,
            2: (2 / 8) * Util.CIRCLE,
            3: (1 / 8) * Util.CIRCLE,
            4: (4 / 8) * Util.CIRCLE,
            5: Infinity,
            6: (3 / 8) * Util.CIRCLE,
            7: (2 / 8) * Util.CIRCLE,
            8: (6 / 8) * Util.CIRCLE,
            9: (7 / 8) * Util.CIRCLE,
            10: Infinity,
            11: (0 / 8) * Util.CIRCLE,
            12: (5 / 8) * Util.CIRCLE,
            13: (6 / 8) * Util.CIRCLE,
            14: (4 / 8) * Util.CIRCLE,
            15: Infinity
        };
        var Player = (function () {
            function Player(x, y, direction) {
                this.x = x;
                this.y = y;
                this.direction = direction;
                this.crouchModifier = 0;
                this.jumpModifier = 0;
                this.viewAngle = 0;
                this.verticalVelocity = 0;
                this.moveWhileJumping = false;
            }
            Player.prototype.rotate = function (angle) {
                this.direction = (this.direction + angle + Util.CIRCLE) % (Util.CIRCLE);
            };
            Player.prototype.walk = function (distance, map, direction) {
                this.move(distance, map, this.direction + direction);
            };
            Player.prototype.move = function (distance, map, direction) {
                var dx = Math.cos(direction) * distance;
                var dy = Math.sin(direction) * distance;
                if (map.get(this.x + dx, this.y) <= 0) {
                    this.x += dx;
                }
                if (map.get(this.x, this.y + dy) <= 0) {
                    this.y += dy;
                }
            };
            //Modularize these methods
            Player.prototype.changeCrouchModifier = function (delta) {
                this.crouchModifier = Util.clamp(this.crouchModifier + delta, MIN_CROUCH_MOD, MAX_CROUCH_MOD);
            };
            Player.prototype.changeJumpModifier = function (delta) {
                this.jumpModifier = Util.clamp(this.jumpModifier + delta, MIN_JUMP_MOD, MAX_JUMP_MOD);
            };
            Player.prototype.changeViewAngle = function (delta) {
                this.viewAngle = Util.clamp(this.viewAngle + delta, MIN_VIEW_MOD, MAX_VIEW_MOD);
            };
            Player.prototype.update = function (states, map, timestep) {
                var jumpDirection = 0;
                var moveWhileJumping = false;
                for (var direction in Direction) {
                    if (states[DIRECTION_STATE_TABLE[direction]] && this.onGround()) {
                        this.walk(MOVEMENT_SPEED * timestep, map, DIRECTION_TABLE[direction]);
                        moveWhileJumping = true;
                        jumpDirection += +direction;
                    }
                }
                if (states['turnLeft']) {
                    this.rotate(-1 * HORIZONTAL_VIEW_SPEED * Math.PI * timestep);
                }
                if (states['turnRight']) {
                    this.rotate(HORIZONTAL_VIEW_SPEED * Math.PI * timestep);
                }
                if (states['lookUp']) {
                    this.changeViewAngle(VERTICAL_VIEW_SPEED * timestep);
                }
                if (states['lookDown']) {
                    this.changeViewAngle(-1 * VERTICAL_VIEW_SPEED * timestep);
                }
                if (states['crouch']) {
                    this.changeCrouchModifier(-1 * CROUCH_SPEED * timestep);
                }
                else {
                    this.changeCrouchModifier(CROUCH_SPEED * timestep);
                }
                if (states['jump']) {
                    if (this.onGround()) {
                        this.verticalVelocity = 5;
                        console.log(jumpDirection);
                        console.log(typeof jumpDirection);
                        jumpDirection = DIRECTION_TABLE[jumpDirection];
                        this.jumpDirection = jumpDirection + this.direction;
                        this.moveWhileJumping = (jumpDirection !== Infinity) ? moveWhileJumping : false;
                    }
                }
                if (!this.onGround()) {
                    if (this.moveWhileJumping) {
                        this.move(JUMP_SPEED * timestep, map, this.jumpDirection);
                    }
                }
                this.verticalVelocity -= timestep * 15;
                this.changeJumpModifier(JUMP_HEIGHT * timestep * this.verticalVelocity);
            };
            Player.prototype.getHeightInformation = function () {
                return {
                    heightModifier: this.crouchModifier + this.jumpModifier,
                    viewAngle: this.viewAngle
                };
            };
            Player.prototype.onGround = function () {
                return this.jumpModifier === MIN_JUMP_MOD;
            };
            return Player;
        })();
        _Player.Player = Player;
    })(Player = Engine.Player || (Engine.Player = {}));
})(Engine || (Engine = {}));


text:
package org.jolokia.docker.maven.util;

import java.io.File;
import java.io.FilenameFilter;

/**
 * @author roland
 * @since 19.10.14
 */
public class SuffixFileFilter implements FilenameFilter {

    final public static FilenameFilter PEM_FILTER = new SuffixFileFilter(".pem");

    private String suffix;

    public SuffixFileFilter(String suffix) {
        this.suffix = suffix;
    }

    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(suffix);
    }
}


text:
package operation

import (
	"context"
	"errors"
	"fmt"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/event"
	"go.mongodb.org/mongo-driver/mongo/description"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
	"go.mongodb.org/mongo-driver/x/mongo/driver"
	"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)

// ListDatabases performs a listDatabases operation.
type ListDatabases struct {
	filter              bsoncore.Document
	authorizedDatabases *bool
	nameOnly            *bool
	session             *session.Client
	clock               *session.ClusterClock
	monitor             *event.CommandMonitor
	database            string
	deployment          driver.Deployment
	readPreference      *readpref.ReadPref
	retry               *driver.RetryMode
	selector            description.ServerSelector
	crypt               *driver.Crypt

	result ListDatabasesResult
}

type ListDatabasesResult struct {
	// An array of documents, one document for each database
	Databases []databaseRecord
	// The sum of the size of all the database files on disk in bytes.
	TotalSize int64
}

type databaseRecord struct {
	Name       string
	SizeOnDisk int64 `bson:"sizeOnDisk"`
	Empty      bool
}

func buildListDatabasesResult(response bsoncore.Document, srvr driver.Server) (ListDatabasesResult, error) {
	elements, err := response.Elements()
	if err != nil {
		return ListDatabasesResult{}, err
	}
	ir := ListDatabasesResult{}
	for _, element := range elements {
		switch element.Key() {

		case "totalSize":
			var ok bool
			ir.TotalSize, ok = element.Value().AsInt64OK()
			if !ok {
				err = fmt.Errorf("response field 'totalSize' is type int64, but received BSON type %s: %s", element.Value().Type, element.Value())
			}

		case "databases":
			// TODO: Make operationgen handle array results.
			arr, ok := element.Value().ArrayOK()
			if !ok {
				err = fmt.Errorf("response field 'databases' is type array, but received BSON type %s", element.Value().Type)
				continue
			}

			var tmp bsoncore.Document
			marshalErr := bson.Unmarshal(arr, &tmp)
			if marshalErr != nil {
				err = marshalErr
				continue
			}
			records, marshalErr := tmp.Elements()
			if marshalErr != nil {
				err = marshalErr
				continue
			}

			ir.Databases = make([]databaseRecord, len(records))
			for i, val := range records {
				valueDoc, ok := val.Value().DocumentOK()
				if !ok {
					err = fmt.Errorf("'databases' element is type document, but received BSON type %s", val.Value().Type)
					continue
				}

				elems, marshalErr := valueDoc.Elements()
				if marshalErr != nil {
					err = marshalErr
					continue
				}
				for _, elem := range elems {
					switch elem.Key() {

					case "name":
						ir.Databases[i].Name, ok = elem.Value().StringValueOK()
						if !ok {
							err = fmt.Errorf("response field 'name' is type string, but received BSON type %s", elem.Value().Type)
							continue
						}

					case "sizeOnDisk":
						ir.Databases[i].SizeOnDisk, ok = elem.Value().AsInt64OK()
						if !ok {
							err = fmt.Errorf("response field 'sizeOnDisk' is type int64, but received BSON type %s", elem.Value().Type)
							continue
						}

					case "empty":
						ir.Databases[i].Empty, ok = elem.Value().BooleanOK()
						if !ok {
							err = fmt.Errorf("response field 'empty' is type bool, but received BSON type %s", elem.Value().Type)
							continue
						}
					}
				}
			}
		}
	}
	return ir, err
}

// NewListDatabases constructs and returns a new ListDatabases.
func NewListDatabases(filter bsoncore.Document) *ListDatabases {
	return &ListDatabases{
		filter: filter,
	}
}

// Result returns the result of executing this operation.
func (ld *ListDatabases) Result() ListDatabasesResult { return ld.result }

func (ld *ListDatabases) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server, _ int) error {
	var err error

	ld.result, err = buildListDatabasesResult(response, srvr)
	return err

}

// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (ld *ListDatabases) Execute(ctx context.Context) error {
	if ld.deployment == nil {
		return errors.New("the ListDatabases operation must have a Deployment set before Execute can be called")
	}

	return driver.Operation{
		CommandFn:         ld.command,
		ProcessResponseFn: ld.processResponse,

		Client:         ld.session,
		Clock:          ld.clock,
		CommandMonitor: ld.monitor,
		Database:       ld.database,
		Deployment:     ld.deployment,
		ReadPreference: ld.readPreference,
		RetryMode:      ld.retry,
		Type:           driver.Read,
		Selector:       ld.selector,
		Crypt:          ld.crypt,
	}.Execute(ctx, nil)

}

func (ld *ListDatabases) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
	dst = bsoncore.AppendInt32Element(dst, "listDatabases", 1)
	if ld.filter != nil {

		dst = bsoncore.AppendDocumentElement(dst, "filter", ld.filter)
	}
	if ld.nameOnly != nil {

		dst = bsoncore.AppendBooleanElement(dst, "nameOnly", *ld.nameOnly)
	}
	if ld.authorizedDatabases != nil {

		dst = bsoncore.AppendBooleanElement(dst, "authorizedDatabases", *ld.authorizedDatabases)
	}

	return dst, nil
}

// Filter determines what results are returned from listDatabases.
func (ld *ListDatabases) Filter(filter bsoncore.Document) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.filter = filter
	return ld
}

// NameOnly specifies whether to only return database names.
func (ld *ListDatabases) NameOnly(nameOnly bool) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.nameOnly = &nameOnly
	return ld
}

// AuthorizedDatabases specifies whether to only return databases which the user is authorized to use."
func (ld *ListDatabases) AuthorizedDatabases(authorizedDatabases bool) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.authorizedDatabases = &authorizedDatabases
	return ld
}

// Session sets the session for this operation.
func (ld *ListDatabases) Session(session *session.Client) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.session = session
	return ld
}

// ClusterClock sets the cluster clock for this operation.
func (ld *ListDatabases) ClusterClock(clock *session.ClusterClock) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.clock = clock
	return ld
}

// CommandMonitor sets the monitor to use for APM events.
func (ld *ListDatabases) CommandMonitor(monitor *event.CommandMonitor) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.monitor = monitor
	return ld
}

// Database sets the database to run this operation against.
func (ld *ListDatabases) Database(database string) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.database = database
	return ld
}

// Deployment sets the deployment to use for this operation.
func (ld *ListDatabases) Deployment(deployment driver.Deployment) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.deployment = deployment
	return ld
}

// ReadPreference set the read prefernce used with this operation.
func (ld *ListDatabases) ReadPreference(readPreference *readpref.ReadPref) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.readPreference = readPreference
	return ld
}

// ServerSelector sets the selector used to retrieve a server.
func (ld *ListDatabases) ServerSelector(selector description.ServerSelector) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.selector = selector
	return ld
}

// Retry enables retryable mode for this operation. Retries are handled automatically in driver.Operation.Execute based
// on how the operation is set.
func (ld *ListDatabases) Retry(retry driver.RetryMode) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.retry = &retry
	return ld
}

// Crypt sets the Crypt object to use for automatic encryption and decryption.
func (ld *ListDatabases) Crypt(crypt *driver.Crypt) *ListDatabases {
	if ld == nil {
		ld = new(ListDatabases)
	}

	ld.crypt = crypt
	return ld
}


text:
from unittest import TestCase
from constants import LOW, HIGH, MAX_LOW, MIN_HIGH, MAX_CURRENT, INPUT_RESISTANCE
from scoville.signal import GenericSignal, DelayedSignal
from aluTest import ALUTest

class ShiftTests(ALUTest):

  def testLeftShiftShouldTakeLeftInput(self):
    self.runShiftCombinations(LOW, LOW, LOW, MAX_LOW)
    self.runShiftCombinations(HIGH, LOW, LOW, MIN_HIGH)

  def testRightShiftShouldTakeRightInput(self):
    self.runShiftCombinations(LOW, LOW, HIGH, MAX_LOW)
    self.runShiftCombinations(LOW, HIGH, HIGH, MIN_HIGH)

  def testShiftShouldIgnoreOtherInput(self):
    self.runShiftCombinations(LOW, HIGH, LOW, MAX_LOW)
    self.runShiftCombinations(HIGH, LOW, HIGH, MAX_LOW)

  def runShiftCombinations(self, leftIn, rightIn, shiftDirection, expectedResult):
    for a in [LOW, HIGH]:
      for b in  [LOW, HIGH]:
        circuit = self.initCircuit("S_SHIFT")

        circuit.setSignal(GenericSignal('A', a))
        circuit.setSignal(GenericSignal('B', b))

        circuit.setSignal(GenericSignal('SUBTRACT', shiftDirection))
        circuit.setSignal(GenericSignal('LEFT_A', leftIn))
        circuit.setSignal(GenericSignal('RIGHT_A', rightIn))

        circuit.run()
        self.checkCurrent(circuit)
        self.expect(circuit,"RESULT", expectedResult)


text:
package org.apache.river.test.spec.renewalservice;

import java.util.logging.Level;

// java.rmi
import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;

//
import org.apache.river.qa.harness.TestException;
import org.apache.river.qa.harness.Test;

// net.jini
import net.jini.core.lease.Lease;
import net.jini.core.lease.UnknownLeaseException;
import net.jini.lease.LeaseRenewalService;
import net.jini.lease.LeaseRenewalSet;

// org.apache.river
import org.apache.river.qa.harness.QATestEnvironment;
import org.apache.river.test.share.OpCountingOwner;
import org.apache.river.test.share.TestLease;
import org.apache.river.test.share.TestLeaseProvider;

/**
 * ExpireSetSleepTest asserts that a lease renewal set is nullified when
 * its lease expires but including that any leases in the set are not
 * renewed after the set expires.
 *
 */
public class ExpireSetSleepTest extends AbstractLeaseRenewalServiceTest {

    /**
     * Provides leases for this test.
     */
    protected TestLeaseProvider leaseProvider = null;

    /**
     * The "land lord" for the leases. Defines lease method behavior.
     */
    protected OpCountingOwner owner = null;

    /**
     * The maximum time granted for a lease by a renew operation.
     */
    protected long renewGrant = 0;

    /**
     * The default value for renewGrant
     */
    protected final long DEFAULT_RENEW_GRANT = 150 * 1000; // 2.5 minutes

    /**
     * grants for each of the three leases used in this test
     */
    protected long grant1 = 0;
    protected long grant2 = 0;
    protected long grant3 = 0;

    /**
     * grant for the renewal set lease
     */
    protected long setLeaseGrant = 0;

    /**
     * Sets up the testing environment.
     */
    public Test construct(org.apache.river.qa.harness.QAConfig sysConfig) throws Exception {

       // mandatory call to parent
       super.construct(sysConfig);

       // Announce where we are in the test
       logger.log(Level.FINE, "ExpireSetSleepTest: In setup() method.");

       // instantiate a lease provider
       leaseProvider = new TestLeaseProvider(4);

       // capture the renewal time
       String property = "org.apache.river.test.spec.renewalservice.renewGrant";
       renewGrant = getConfig().getLongConfigVal(property, DEFAULT_RENEW_GRANT);

       // calculate (hopefully) sane grant times for each lease
       grant1 = getConfig().getLongConfigVal(property, renewGrant);

       grant2 = getConfig().getLongConfigVal(property, renewGrant) * 2;

       grant3 = getConfig().getLongConfigVal(property, renewGrant) * 3;

       // create an owner for the lease
       owner = new OpCountingOwner(renewGrant);
       return this;
    }

    /**
     * This method asserts that a lease renewal set is nullified when
     * its lease expires but including that any leases in the set are not
     * renewed after the set expires.
     *
     *
Notes:
For more information see the LRS specification
     * section 9.3 page 108.

     */
    public void run() throws Exception {

	// Announce where we are in the test
	logger.log(Level.FINE, "ExpireSetSleepTest: In run() method.");

	// get a lease renewal set w/ duration of 1/5 the max grant time
	logger.log(Level.FINE, "Creating the lease renewal set.");
	setLeaseGrant = renewGrant / 5;
	logger.log(Level.FINE, "Lease duration == " + setLeaseGrant);
	LeaseRenewalService lrs = getLRS();
	LeaseRenewalSet set = lrs.createLeaseRenewalSet(setLeaseGrant);
	set = prepareSet(set);

	// get three leases with their repective durations
	logger.log(Level.FINE, "Creating the leases to be managed.");

	logger.log(Level.FINE, "Duration (lease #1) == " + grant1);
	TestLease testLease1 =
	    leaseProvider.createNewLease(owner, rstUtil.durToExp(grant1));

	logger.log(Level.FINE, "Duration (lease #2) == " + grant2);
	TestLease testLease2 =
	    leaseProvider.createNewLease(owner, rstUtil.durToExp(grant2));

	logger.log(Level.FINE, "Duration (lease #3) == " + grant3);
	TestLease testLease3 =
	    leaseProvider.createNewLease(owner, rstUtil.durToExp(grant3));

	// start managing the leases for as long as we can
	logger.log(Level.FINE, "Adding managed leases to lease renewal set.");
	set.renewFor(testLease1, Lease.FOREVER);
	set.renewFor(testLease2, Lease.FOREVER);
	set.renewFor(testLease3, Lease.FOREVER);

	// allow the lease of the renewal set to expire
	logger.log(Level.FINE, "Getting the renewal set lease.");
	Lease setLease = prepareLease(set.getRenewalSetLease());
	boolean success = expireRenewalSetLease(setLease);
	if (success == false) {
	    String message = "Lease did not expire as expected.\n";
	    throw new TestException(message);
	}

	// assert that any attempt to use the set results in an exception
	try {
	    Lease managedLease = set.remove(testLease1);
	    String message = "Performed successful remove operation on\n";
	    message += " renewal set after its lease had expired.";
	    throw new TestException(message);
	} catch (NoSuchObjectException ex) {
	    // we passed so just keep on going ...
	}

	try {
	    Lease managedLease = leaseProvider.createNewLease(owner,
							      renewGrant);
	    set.renewFor(managedLease, Lease.FOREVER);
	    managedLease.cancel();
	    String message = "Performed successful add operation on\n";
	    message += " renewal set after its lease had expired.";
	    throw new TestException(message);
	} catch (NoSuchObjectException ex) {
	    // we passed so just keep on going ...
	}

	// Wait for the lease we put into the set to expire.
	// Note, we picked expiration times for the leases which
	// we know the renewal service won't renew before the set
	// expires so the expiration time are copies of the lease
	// object have should be the actual expiration times of
	// the lease

	String rslt = expireClientLease(testLease1, "lease #1");
	if (null != rslt) {
	    throw new TestException(rslt);
	}

	rslt = expireClientLease(testLease2, "lease #2");
	if (null != rslt) {
	    throw new TestException(rslt);
	}

	rslt = expireClientLease(testLease3, "lease #3");
	if (null != rslt) {
	    throw new TestException(rslt);
	}

	// assert that no calls have been made to renew or cancel
	long renewCalls = owner.getRenewCalls();
	long batchRenewCalls = owner.getBatchRenewCalls();
	long cancelCalls = owner.getCancelCalls();
	long batchCancelCalls = owner.getBatchCancelCalls();

	// there should be no renewal attempts
	if (renewCalls > 0 || batchRenewCalls > 0) {
	    String message = "The LRS called renew on the leases in " +
		" error.";
	    throw new TestException(message);
	}

	// cancel is strictly forbidden anytime
	if (cancelCalls > 0 || batchCancelCalls > 0) {
	    String message = "The LRS called cancel on the leases in " +
		" error.";
	    throw new TestException(message);
	}
    }

    /**
     * This method determines how the renewal set lease is canceled.
     *
     *
Notes:

     * This method is sort of a template method to support reuse of test code.
     *
     * @param lease the lease to expire
     *
     */
    protected boolean expireRenewalSetLease(Lease lease)
                       throws UnknownLeaseException, RemoteException,
                              InterruptedException   {

	return rstUtil.waitForLeaseExpiration(lease,
					      "for set lease to expire.");
    }

    /**
     * Utiltity method that waits on the given lease expiring. Returns
     * null if the lease expires and an error message
     * otherwise.
     * @param lease The lease we are waiting on
     * @param name  The name of the lease we are waiting on
     */
    private String expireClientLease(Lease lease, String name)
        throws UnknownLeaseException, RemoteException, InterruptedException
    {
	final boolean success = rstUtil.waitForLeaseExpiration(lease,
				    "Waiting for " + name + " to expire");
	if (success == false) {
	    return name + " did not expire as expected\n";
	}

	return null;
    }

} // ExpireSetSleepTest


text:
package faygo

import (
	"encoding/json"
	"errors"
	"fmt"
	"math"
	"mime/multipart"
	"net/http"
	"net/http/httputil"
	"net/url"
	"path"
	"sync"

	"github.com/henrylee2cn/faygo/logging"
	"github.com/henrylee2cn/faygo/session"
)

// Headers
const (
	HeaderAccept                        = "Accept"
	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAuthorization                 = "Authorization"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"
	HeaderContentDescription            = "Content-Description"
	HeaderContentTransferEncoding       = "Content-Transfer-Encoding"
	HeaderCookie                        = "Cookie"
	HeaderSetCookie                     = "Set-Cookie"
	HeaderIfModifiedSince               = "If-Modified-Since"
	HeaderLastModified                  = "Last-Modified"
	HeaderLocation                      = "Location"
	HeaderReferer                       = "Referer"
	HeaderUserAgent                     = "User-Agent"
	HeaderUpgrade                       = "Upgrade"
	HeaderVary                          = "Vary"
	HeaderWWWAuthenticate               = "WWW-Authenticate"
	HeaderXForwardedProto               = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride           = "X-HTTP-Method-Override"
	HeaderXForwardedFor                 = "X-Forwarded-For"
	HeaderXRealIP                       = "X-Real-IP"
	HeaderXRequestedWith                = "X-Requested-With"
	HeaderServer                        = "Server"
	HeaderOrigin                        = "Origin"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderExpires                       = "Expires"
	HeaderCacheControl                  = "Cache-Control"
	HeaderPragma                        = "Pragma"

	// Security
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

// MIME types
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

const (
	charsetUTF8 = "charset=utf-8"
	nosniff     = "nosniff" // Security
)

const (
	// stopExecutionposition used inside the Context,
	// is the number which shows us that the context's handlerChain manualy stop the execution
	stopExecutionposition int16 = math.MaxInt16 - 1
)

type (
	// Map is just a conversion for a map[string]interface{}
	// should not be used inside Render when PongoEngine is used.
	Map map[string]interface{}

	// Context is resetting every time a ruest is coming to the server
	// it is not good practice to use this object in goroutines, for these cases use the .Clone()
	Context struct {
		R                  *http.Request // the *http.Request
		W                  *Response     // the *Response cooked by the http.ResponseWriter
		curSession         session.Store
		limitedRequestBody []byte // the copy of requset body(Limited by maximum length)
		frame              *Framework
		handlerChain       HandlerChain                // keep track all registed handlers
		pathParams         PathParams                  // The parameter values on the URL path
		queryParams        url.Values                  // URL query string values
		data               map[interface{}]interface{} // Used to transfer variables between Handler-chains
		handlerChainLen    int16
		pos                int16 // pos is the position number of the Context, look .Next to understand
		enableGzip         bool  // Note: Never reset!
		enableSession      bool  // Note: Never reset!
		enableXSRF         bool  // Note: Never reset!
		xsrfExpire         int
		_xsrfToken         string
		_xsrfTokenReset    bool
	}
)

// Log used by the user bissness
func (ctx *Context) Log() *logging.Logger {
	return ctx.frame.bizlog
}

// XSRFToken creates a xsrf token string and returns.
// If specifiedExpiration is empty, the value in the configuration is used.
func (ctx *Context) XSRFToken(specifiedExpiration ...int) string {
	if ctx._xsrfToken == "" {
		token, ok := ctx.SecureCookieParam(ctx.frame.config.XSRF.Key, "_xsrf")
		if !ok {
			ctx._xsrfTokenReset = true
			token = RandomString(32)
			if len(specifiedExpiration) > 0 && specifiedExpiration[0] > 0 {
				ctx.xsrfExpire = specifiedExpiration[0]
			} else if ctx.xsrfExpire == 0 {
				ctx.xsrfExpire = ctx.frame.config.XSRF.ExpireSecond
			}
		}
		ctx._xsrfToken = token
	}
	return ctx._xsrfToken
}

// XSRFFormHTML writes an input field contains xsrf token value.
func (ctx *Context) XSRFFormHTML() string {
	return `<input type="hidden" name="_xsrf" value="` +
		ctx.XSRFToken() + `" />`
}

// checkXSRFCookie checks xsrf token in this request is valid or not.
// the token can provided in request cookie "_xsrf",
// or in header "X-Xsrftoken" and "X-CsrfToken",
// or in form field value named as "_xsrf".
func (ctx *Context) checkXSRFCookie() bool {
	if !ctx.enableXSRF {
		return true
	}
	token := ctx.BizParam("_xsrf")
	if token == "" {
		token = ctx.R.Header.Get("X-Xsrftoken")
	}
	if token == "" {
		token = ctx.R.Header.Get("X-Csrftoken")
	}
	// default cookie value
	if token == "" {
		token, _ = ctx.SecureCookieParam(ctx.frame.config.XSRF.Key, "_xsrf")
	}
	if token == "" {
		ctx.Error(403, "'_xsrf' argument missing from POST")
		return false
	}
	if ctx._xsrfToken != token {
		ctx.Error(403, "XSRF cookie does not match POST argument")
		return false
	}
	return true
}

var errNotEnableSession = errors.New("before using the session, must set config `session::enable = true`...")

// startSession starts session and load old session data info this controller.
func (ctx *Context) startSession() (session.Store, error) {
	if ctx.curSession != nil {
		return ctx.curSession, nil
	}
	if !ctx.enableSession {
		return nil, errNotEnableSession
	}
	ctx.makeSureParseMultipartForm()
	var err error
	ctx.curSession, err = ctx.frame.sessionManager.SessionStart(ctx.W, ctx.R)
	return ctx.curSession, err
}

// getSessionStore return SessionStore.
func (ctx *Context) getSessionStore() (session.Store, error) {
	if ctx.curSession != nil {
		return ctx.curSession, nil
	}
	if !ctx.enableSession {
		return nil, errNotEnableSession
	}
	var err error
	ctx.curSession, err = ctx.frame.sessionManager.GetSessionStore(ctx.W, ctx.R)
	return ctx.curSession, err
}

// SetSession puts value into session.
func (ctx *Context) SetSession(key interface{}, value interface{}) {
	if _, err := ctx.startSession(); err != nil {
		ctx.Log().Warningf("start session fail: %s", err.Error())
		return
	}
	ctx.curSession.Set(key, value)
}

// GetSession gets value from session.
func (ctx *Context) GetSession(key interface{}) interface{} {
	if _, err := ctx.getSessionStore(); err != nil {
		return nil
	}
	return ctx.curSession.Get(key)
}

// DelSession removes value from session.
func (ctx *Context) DelSession(key interface{}) {
	if _, err := ctx.getSessionStore(); err != nil {
		return
	}
	ctx.curSession.Delete(key)
}

// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
func (ctx *Context) SessionRegenerateID() {
	if _, err := ctx.getSessionStore(); err != nil {
		return
	}
	ctx.curSession.SessionRelease(ctx.W)
	ctx.curSession = ctx.frame.sessionManager.SessionRegenerateID(ctx.W, ctx.R)
}

// DestroySession cleans session data and session cookie.
func (ctx *Context) DestroySession() {
	if _, err := ctx.getSessionStore(); err != nil {
		return
	}
	ctx.curSession.Flush()
	ctx.curSession = nil
	ctx.frame.sessionManager.SessionDestroy(ctx.W, ctx.R)
}

// Redirect replies to the request with a redirect to url,
// which may be a path relative to the request path.
//
// The provided status code should be in the 3xx range and is usually
// StatusMovedPermanently, StatusFound or StatusSeeOther.
func (ctx *Context) Redirect(status int, urlStr string) error {
	if status < http.StatusMultipleChoices || status > http.StatusPermanentRedirect {
		return fmt.Errorf("The provided status code should be in the 3xx range and is usually 301, 302 or 303, yours: %d", status)
	}
	http.Redirect(ctx.W, ctx.R, urlStr, status)
	return nil
}

var proxyList = &struct {
	m map[string]*httputil.ReverseProxy
	sync.RWMutex
}{
	m: map[string]*httputil.ReverseProxy{},
}

// ReverseProxy routes URLs to the scheme, host, and base path provided in targetUrlBase.
// If pathAppend is "true" and the targetUrlBase's path is "/base" and the incoming ruest was for "/dir",
// the target ruest will be for /base/dir.
func (ctx *Context) ReverseProxy(targetUrlBase string, pathAppend bool) error {
	proxyList.RLock()
	var rp = proxyList.m[targetUrlBase]
	proxyList.RUnlock()
	if rp == nil {
		proxyList.Lock()
		defer proxyList.Unlock()
		rp = proxyList.m[targetUrlBase]
		if rp == nil {
			target, err := url.Parse(targetUrlBase)
			if err != nil {
				return err
			}
			targetQuery := target.RawQuery
			rp = &httputil.ReverseProxy{
				Director: func(r *http.Request) {
					r.Host = target.Host
					r.URL.Scheme = target.Scheme
					r.URL.Host = target.Host
					r.URL.Path = path.Join(target.Path, r.URL.Path)
					if targetQuery == "" || r.URL.RawQuery == "" {
						r.URL.RawQuery = targetQuery + r.URL.RawQuery
					} else {
						r.URL.RawQuery = targetQuery + "&" + r.URL.RawQuery
					}
				},
			}
			proxyList.m[targetUrlBase] = rp
		}
	}

	if !pathAppend {
		ctx.R.URL.Path = ""
	}
	rp.ServeHTTP(ctx.W, ctx.R)
	return nil
}

func (ctx *Context) doFilter() bool {
	if count := len(ctx.frame.filter); count > 0 {
		ctx.handlerChain = ctx.frame.filter
		ctx.handlerChainLen = int16(count)
		ctx.posReset()
		ctx.Next()
		if ctx.IsBreak() {
			if !ctx.W.Committed() {
				ctx.Error(http.StatusForbidden, http.StatusText(http.StatusForbidden))
			}
			return false
		}
	}
	return true
}

// doHandler calls the first handler only, it's like Next with negative pos, used only on Router&MemoryRouter
func (ctx *Context) doHandler(handlerChain HandlerChain, pathParams PathParams) {
	ctx.pathParams = pathParams
	ctx.handlerChain = handlerChain
	ctx.handlerChainLen = int16(len(handlerChain))
	ctx.posReset()
	if !ctx.prepare() {
		return
	}
	ctx.Next()
}

// Called before the start
func (ctx *Context) prepare() bool {
	var pass = true
	//if XSRF is Enable then check cookie where there has any cookie in the request's cookie _csrf
	if ctx.enableXSRF {
		ctx.XSRFToken()
		switch ctx.R.Method {
		case "POST", "DELETE", "PUT":
			pass = ctx.checkXSRFCookie()
		default:
			switch ctx.BizParam("_method") {
			case "POST", "DELETE", "PUT":
				pass = ctx.checkXSRFCookie()
			}
		}
	}
	return pass
}

// reset the cursor
func (ctx *Context) posReset() {
	ctx.pos = -1
}

// Next calls all the next handler from the middleware stack, it used inside a middleware.
// Notes: Non-concurrent security.
func (ctx *Context) Next() {
	//set position to the next
	ctx.pos++
	//run the next
	if ctx.pos < ctx.handlerChainLen {
		if err := ctx.handlerChain[ctx.pos].Serve(ctx); err != nil {
			global.errorFunc(ctx, err.Error(), http.StatusInternalServerError)
			ctx.Stop()
			return
		}
		// If the next one exists, it is executed automatically.
		ctx.Next()
		return
	}
	ctx.pos--
}

func (ctx *Context) beforeWriteHeader() {
	if ctx._xsrfTokenReset {
		ctx.SetSecureCookie(ctx.frame.config.XSRF.Key, "_xsrf", ctx._xsrfToken, ctx.xsrfExpire)
	}
	if ctx.enableSession {
		if ctx.curSession != nil {
			ctx.curSession.SessionRelease(ctx.W)
			ctx.curSession = nil
		}
	}
}

// Stop just sets the .pos to 32766 in order to  not move to the next handlers(if any)
func (ctx *Context) Stop() {
	ctx.pos = stopExecutionposition
}

// Stopped returns whether the operation has stopped.
func (ctx *Context) Stopped() bool {
	return ctx.pos >= ctx.handlerChainLen
}

// IsBreak returns whether the operation is stopped halfway.
func (ctx *Context) IsBreak() bool {
	return ctx.pos == stopExecutionposition
}

func (ctx *Context) recordBody() []byte {
	if !ctx.frame.config.PrintBody {
		return nil
	}
	var b []byte
	formValues := ctx.FormParamAll()
	if len(formValues) > 0 || ctx.IsUpload() {
		v := multipart.Form{
			Value: formValues,
		}
		if ctx.R.MultipartForm != nil {
			v.File = ctx.R.MultipartForm.File
		}
		b, _ = json.Marshal(v)
	} else {
		b = ctx.LimitedBodyBytes()
	}
	if len(b) > 0 {
		bb := make([]byte, len(b)+2)
		bb[0] = '\n'
		copy(bb[1:], b)
		bb[len(bb)-1] = '\n'
		return bb
	}
	return b
}

func (frame *Framework) getContext(w http.ResponseWriter, r *http.Request) *Context {
	ctx := frame.contextPool.Get().(*Context)
	ctx.R = r
	ctx.W.reset(w)
	ctx.data = make(map[interface{}]interface{})
	if frame.config.PrintBody && !ctx.IsUpload() {
		ctx.LimitedBodyBytes()
	}
	return ctx
}

func (frame *Framework) putContext(ctx *Context) {
	if ctx.R.Body != nil {
		ctx.R.Body.Close()
	}
	ctx.R = nil
	ctx.W.writer = nil
	ctx.limitedRequestBody = nil
	ctx.data = nil
	ctx.queryParams = nil
	ctx._xsrfToken = ""
	ctx._xsrfTokenReset = false
	frame.contextPool.Put(ctx)
}