text:
require 'fileutils'
require 'jar_dependencies'
require 'jars/version'
require 'jars/maven_factory'
require 'jars/gemspec_artifacts'

module Jars
  class LockDown

    attr_reader :debug, :verbose

    def initialize( debug, verbose )
      @debug = debug
      @verbose = verbose
    end

    def maven_new
      factory = MavenFactory.new( {}, @debug, @verbose )
      pom = File.expand_path( '../lock_down_pom.rb', __FILE__ )
      m = factory.maven_new( pom )
      m[ 'jruby.plugins.version' ] = Jars::JRUBY_PLUGINS_VERSION
      m[ 'dependency.plugin.version' ] = Jars::DEPENDENCY_PLUGIN_VERSION
      m[ 'jars.basedir' ] = File.expand_path( basedir )
      jarfile = File.expand_path( Jars.jarfile )
      m[ 'jars.jarfile' ] = jarfile if File.exists?( jarfile )
      attach_jar_coordinates_from_bundler_dependencies( m )
      m
    end
    private :maven_new

    def maven
      @maven ||= maven_new
    end

    def basedir
      File.expand_path( '.' )
    end

    def attach_jar_coordinates_from_bundler_dependencies( maven )
      load_path = $LOAD_PATH.dup
      require 'bundler'
      #TODO make this group a commandline option
      Bundler.setup( 'default' )
      done = []
      index = 0
      Gem.loaded_specs.each do |name, spec|
        deps = GemspecArtifacts.new( spec )
        deps.artifacts.each do |a|
          if !done.include?( a.key ) and a.scope != 'provided' and a.scope != 'test'
            maven.property( "jars.#{index}", a.to_coord )
            if a.exclusions
              jndex = 0
              a.exclusions.each do |ex|
                maven.property( "jars.#{index}.exclusions.#{jndex}", ex.to_s )
              end
            end
            maven.property( "jars.#{index}.scope", a.scope ) if a.scope
            index += 1
            done << a.key
          end
        end
      end
    rescue Gem::LoadError => e
      # not sure why to reraise the exception
      raise e
    rescue LoadError => e
      if Jars.verbose?
        warn e.message
        warn "no bundler found - ignore Gemfile if exists"
      end
    rescue Bundler::GemNotFound => e
      warn "can not setup bundler with #{Bundler.default_lockfile}"
      raise e
    ensure
      $LOAD_PATH.replace( load_path )
    end

    def lock_down( options = {} )
      vendor_dir = File.expand_path( options[ :vendor_dir ] ) if options[ :vendor_dir ]
      out = File.expand_path( '.jars.output' )
      tree = File.expand_path( '.jars.tree' )
      maven.property( 'jars.outputFile', out )
      maven.property( 'maven.repo.local', Jars.home )
      maven.property( 'jars.home', vendor_dir ) if vendor_dir
      maven.property( 'jars.lock', File.expand_path( Jars.lock ) )
      maven.property( 'jars.force', options[ :force ] == true )
      maven.property( 'jars.update', options[ :update ] ) if options[ :update ]

      args = [ 'gem:jars-lock' ]
      if options[ :tree ]
        args += [ 'dependency:tree', '-P -gemfile.lock', '-DoutputFile=' + tree ]
      end

      puts
      puts '-- jar root dependencies --'
      puts
      status = maven.exec( *args )
      exit 1 unless status
      if File.exists?( tree )
        puts
        puts '-- jar dependency tree --'
        puts
        puts File.read( tree )
        puts
      end
      puts
      puts File.read( out ).gsub( /#{File.dirname(out)}\//, '' )
      puts
    ensure
      FileUtils.rm_f out
      FileUtils.rm_f tree
    end
  end
end


text:
"""
Tests for GlusterFS backup driver.

"""
import os

import mock
from os_brick.remotefs import remotefs as remotefs_brick

from jacket.storage.backup.drivers import glusterfs
from jacket import context
from jacket.storage import exception
from jacket.storage import test
from jacket.storage import utils

FAKE_BACKUP_MOUNT_POINT_BASE = '/fake/mount-point-base'
FAKE_HOST = 'fake_host'
FAKE_VOL_NAME = 'backup_vol'
FAKE_BACKUP_SHARE = '%s:%s' % (FAKE_HOST, FAKE_VOL_NAME)
FAKE_BACKUP_PATH = os.path.join(FAKE_BACKUP_MOUNT_POINT_BASE,
                                'e51e43e3c63fd5770e90e58e2eafc709')

class BackupGlusterfsShareTestCase(test.TestCase):

    def setUp(self):
        super(BackupGlusterfsShareTestCase, self).setUp()
        self.ctxt = context.get_admin_context()

    def test_check_configuration(self):
        self.override_config('glusterfs_backup_share', FAKE_BACKUP_SHARE)
        self.mock_object(glusterfs.GlusterfsBackupDriver,
                         '_init_backup_repo_path',
                         mock.Mock(return_value=FAKE_BACKUP_PATH))

        with mock.patch.object(glusterfs.GlusterfsBackupDriver,
                               '_check_configuration'):
            driver = glusterfs.GlusterfsBackupDriver(self.ctxt)
        driver._check_configuration()

    def test_check_configuration_no_backup_share(self):
        self.override_config('glusterfs_backup_share', None)
        self.mock_object(glusterfs.GlusterfsBackupDriver,
                         '_init_backup_repo_path',
                         mock.Mock(return_value=FAKE_BACKUP_PATH))

        with mock.patch.object(glusterfs.GlusterfsBackupDriver,
                               '_check_configuration'):
            driver = glusterfs.GlusterfsBackupDriver(self.ctxt)
        self.assertRaises(exception.ConfigNotFound,
                          driver._check_configuration)

    def test_init_backup_repo_path(self):
        self.override_config('glusterfs_backup_share', FAKE_BACKUP_SHARE)
        self.override_config('glusterfs_backup_mount_point',
                             FAKE_BACKUP_MOUNT_POINT_BASE)
        mock_remotefsclient = mock.Mock()
        mock_remotefsclient.get_mount_point = mock.Mock(
            return_value=FAKE_BACKUP_PATH)
        self.mock_object(glusterfs.GlusterfsBackupDriver,
                         '_check_configuration')
        self.mock_object(remotefs_brick, 'RemoteFsClient',
                         mock.Mock(return_value=mock_remotefsclient))
        self.mock_object(os, 'getegid',
                         mock.Mock(return_value=333333))
        self.mock_object(utils, 'get_file_gid',
                         mock.Mock(return_value=333333))
        self.mock_object(utils, 'get_file_mode',
                         mock.Mock(return_value=00000))
        self.mock_object(utils, 'get_root_helper')

        with mock.patch.object(glusterfs.GlusterfsBackupDriver,
                               '_init_backup_repo_path'):
            driver = glusterfs.GlusterfsBackupDriver(self.ctxt)
        self.mock_object(driver, '_execute')
        path = driver._init_backup_repo_path()

        self.assertEqual(FAKE_BACKUP_PATH, path)
        utils.get_root_helper.called_once()
        mock_remotefsclient.mount.assert_called_once_with(FAKE_BACKUP_SHARE)
        mock_remotefsclient.get_mount_point.assert_called_once_with(
            FAKE_BACKUP_SHARE)

redpajama_set_name: RedPajamaGithub


text:
FactoryBot.define do
  factory :send_video, class: FantasticRobot::Request::SendVideo do
    chat_id { Faker::Number.number(10) }
    video { Faker::Lorem.word }
    duration { Faker::Number.number(3) }
    caption { Faker::Lorem.sentence }
    reply_to_message_id { Faker::Number.number(10) }
    reply_markup { nil }

    factory :send_video_without_optional_fields do
      duration { nil }
      caption { nil }
      reply_to_message_id { nil }
      reply_markup { nil }
    end
  end
end


text:
#include "py/mperrno.h"
#include "py/ioctl.h"
#include "py/objproperty.h"
#include "py/runtime.h"
#include "py/stream.h"

#include "shared-bindings/_bleio/__init__.h"
#include "shared-bindings/_bleio/PacketBuffer.h"
#include "shared-bindings/_bleio/UUID.h"
#include "shared-bindings/util.h"

//| class PacketBuffer:
//|     """Accumulates a Characteristic's incoming packets in a FIFO buffer and facilitates packet aware
//|     outgoing writes. A packet's size is either the characteristic length or the maximum transmission
//|     unit (MTU) minus overhead, whichever is smaller. The MTU can change so check `incoming_packet_length`
//|     and `outgoing_packet_length` before creating a buffer to store data.
//|
//|     When we're the server, we ignore all connections besides the first to subscribe to
//|     notifications."""
//|
//|     def __init__(self, characteristic: Characteristic, *, buffer_size: int):
//|         """Monitor the given Characteristic. Each time a new value is written to the Characteristic
//|         add the newly-written bytes to a FIFO buffer.
//|
//|         Monitor the given Characteristic. Each time a new value is written to the Characteristic
//|         add the newly-written packet of bytes to a FIFO buffer.
//|
//|         :param Characteristic characteristic: The Characteristic to monitor.
//|           It may be a local Characteristic provided by a Peripheral Service, or a remote Characteristic
//|           in a remote Service that a Central has connected to.
//|         :param int buffer_size: Size of ring buffer (in packets of the Characteristic's maximum
//|           length) that stores incoming packets coming from the peer."""
//|         ...
//|
STATIC mp_obj_t bleio_packet_buffer_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    enum { ARG_characteristic, ARG_buffer_size };
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_characteristic,  MP_ARG_REQUIRED | MP_ARG_OBJ },
        { MP_QSTR_buffer_size, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT },
    };

    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

    const mp_obj_t characteristic = args[ARG_characteristic].u_obj;

    const mp_int_t buffer_size = args[ARG_buffer_size].u_int;
    if (buffer_size < 1) {
        mp_raise_ValueError_varg(translate("%q must be >= 1"), MP_QSTR_buffer_size);
    }

    if (!MP_OBJ_IS_TYPE(characteristic, &bleio_characteristic_type)) {
        mp_raise_TypeError(translate("Expected a Characteristic"));
    }

    bleio_packet_buffer_obj_t *self = m_new_obj(bleio_packet_buffer_obj_t);
    self->base.type = &bleio_packet_buffer_type;

    common_hal_bleio_packet_buffer_construct(self, MP_OBJ_TO_PTR(characteristic), buffer_size);

    return MP_OBJ_FROM_PTR(self);
}

STATIC void check_for_deinit(bleio_packet_buffer_obj_t *self) {
    if (common_hal_bleio_packet_buffer_deinited(self)) {
        raise_deinited_error();
    }
}

//|     def readinto(self, buf: Any) -> Any:
//|         """Reads a single BLE packet into the ``buf``. Raises an exception if the next packet is longer
//|         than the given buffer. Use `packet_size` to read the maximum length of a single packet.
//|
//|         :return: number of bytes read and stored into ``buf``
//|         :rtype: int"""
//|         ...
//|
STATIC mp_obj_t bleio_packet_buffer_readinto(mp_obj_t self_in, mp_obj_t buffer_obj) {
    bleio_packet_buffer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    check_for_deinit(self);

    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(buffer_obj, &bufinfo, MP_BUFFER_WRITE);

    mp_int_t size = common_hal_bleio_packet_buffer_readinto(self, bufinfo.buf, bufinfo.len);
    if (size < 0) {
        mp_raise_ValueError_varg(translate("Buffer too short by %d bytes"), size * -1);
    }

    return MP_OBJ_NEW_SMALL_INT(size);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(bleio_packet_buffer_readinto_obj, bleio_packet_buffer_readinto);

//|     def write(self, data: Any, *, header: Any = None) -> Any:
//|         """Writes all bytes from data into the same outgoing packet. The bytes from header are included
//|         before data when the pending packet is currently empty.
//|
//|         This does not block until the data is sent. It only blocks until the data is pending.
//|
//|         :return: number of bytes written. May include header bytes when packet is empty.
//|         :rtype: int"""
//|         ...
//|
// TODO: Add a kwarg `merge=False` to dictate whether subsequent writes are merged into a pending
// one.
STATIC mp_obj_t bleio_packet_buffer_write(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    enum { ARG_data, ARG_header };
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_data,  MP_ARG_REQUIRED | MP_ARG_OBJ },
        { MP_QSTR_header, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}},
    };

    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

    bleio_packet_buffer_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
    check_for_deinit(self);

    mp_buffer_info_t data_bufinfo;
    mp_get_buffer_raise(args[ARG_data].u_obj, &data_bufinfo, MP_BUFFER_READ);

    mp_buffer_info_t header_bufinfo;
    header_bufinfo.len = 0;
    if (args[ARG_header].u_obj != MP_OBJ_NULL) {
        mp_get_buffer_raise(args[ARG_header].u_obj, &header_bufinfo, MP_BUFFER_READ);
    }

    mp_int_t num_bytes_written = common_hal_bleio_packet_buffer_write(
        self, data_bufinfo.buf, data_bufinfo.len, header_bufinfo.buf, header_bufinfo.len);
    if (num_bytes_written < 0) {
        // TODO: Raise an error if not connected. Right now the not-connected error
        // is unreliable, because common_hal_bleio_packet_buffer_write()
        // checks for conn_handle being set, but setting that
        // can be delayed because conn_handle is discovered by spying on
        // gatts write events, which may not have been sent yet.
        //
        // IDEAL:
        // mp_raise_bleio_ConnectionError(translate("Not connected"));
        // TEMPORARY:
        num_bytes_written = 0;
    }
    return MP_OBJ_NEW_SMALL_INT(num_bytes_written);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(bleio_packet_buffer_write_obj, 1, bleio_packet_buffer_write);

//|     def deinit(self) -> Any:
//|         """Disable permanently."""
//|         ...
STATIC mp_obj_t bleio_packet_buffer_deinit(mp_obj_t self_in) {
    bleio_packet_buffer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    common_hal_bleio_packet_buffer_deinit(self);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_packet_buffer_deinit_obj, bleio_packet_buffer_deinit);

//|     packet_size: int = ...
//|     """`packet_size` is the same as `incoming_packet_length`.
//|     The name `packet_size` is deprecated and
//|     will be removed in CircuitPython 6.0.0."""
//|
//|     incoming_packet_length: Any = ...
//|     """Maximum length in bytes of a packet we are reading."""
//|
STATIC mp_obj_t bleio_packet_buffer_get_incoming_packet_length(mp_obj_t self_in) {
    bleio_packet_buffer_obj_t *self = MP_OBJ_TO_PTR(self_in);

    mp_int_t size = common_hal_bleio_packet_buffer_get_incoming_packet_length(self);
    if (size < 0) {
        mp_raise_ValueError(translate("No connection: length cannot be determined"));
    }
    return MP_OBJ_NEW_SMALL_INT(size);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_packet_buffer_get_incoming_packet_length_obj, bleio_packet_buffer_get_incoming_packet_length);

const mp_obj_property_t bleio_packet_buffer_incoming_packet_length_obj = {
    .base.type = &mp_type_property,
    .proxy = { (mp_obj_t)&bleio_packet_buffer_get_incoming_packet_length_obj,
               (mp_obj_t)&mp_const_none_obj,
               (mp_obj_t)&mp_const_none_obj },
};

//|     outgoing_packet_length: int = ...
//|     """Maximum length in bytes of a packet we are writing."""
//|
STATIC mp_obj_t bleio_packet_buffer_get_outgoing_packet_length(mp_obj_t self_in) {
    bleio_packet_buffer_obj_t *self = MP_OBJ_TO_PTR(self_in);

    mp_int_t size = common_hal_bleio_packet_buffer_get_outgoing_packet_length(self);
    if (size < 0) {
        mp_raise_ValueError(translate("No connection: length cannot be determined"));
    }
    return MP_OBJ_NEW_SMALL_INT(size);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_packet_buffer_get_outgoing_packet_length_obj, bleio_packet_buffer_get_outgoing_packet_length);

const mp_obj_property_t bleio_packet_buffer_outgoing_packet_length_obj = {
    .base.type = &mp_type_property,
    .proxy = { (mp_obj_t)&bleio_packet_buffer_get_outgoing_packet_length_obj,
               (mp_obj_t)&mp_const_none_obj,
               (mp_obj_t)&mp_const_none_obj },
};

STATIC const mp_rom_map_elem_t bleio_packet_buffer_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_deinit),                     MP_ROM_PTR(&bleio_packet_buffer_deinit_obj) },

    // Standard stream methods.
    { MP_OBJ_NEW_QSTR(MP_QSTR_readinto),               MP_ROM_PTR(&bleio_packet_buffer_readinto_obj) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_write),                  MP_ROM_PTR(&bleio_packet_buffer_write_obj) },

    // .packet_size is now an alias for .incoming_packet_length
    // TODO: Remove in 6.0.0.
    { MP_OBJ_NEW_QSTR(MP_QSTR_packet_size),            MP_ROM_PTR(&bleio_packet_buffer_incoming_packet_length_obj) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_incoming_packet_length), MP_ROM_PTR(&bleio_packet_buffer_incoming_packet_length_obj) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_outgoing_packet_length), MP_ROM_PTR(&bleio_packet_buffer_outgoing_packet_length_obj) },
};

STATIC MP_DEFINE_CONST_DICT(bleio_packet_buffer_locals_dict, bleio_packet_buffer_locals_dict_table);

const mp_obj_type_t bleio_packet_buffer_type = {
    { &mp_type_type },
    .name = MP_QSTR_PacketBuffer,
    .make_new = bleio_packet_buffer_make_new,
    .locals_dict = (mp_obj_dict_t*)&bleio_packet_buffer_locals_dict
};


text:
package com.juwan.testmemoryleak;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import java.lang.ref.WeakReference;

public class AsyncActivity extends AppCompatActivity {

    private static final String TAG = AsyncActivity.class.getSimpleName();
    private TextView mContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async);
        mContent = (TextView)findViewById(R.id.content);
        new BackgroundTask(mContent).execute();
    }

    // Use static && WeakReference to solve
    private static class BackgroundTask extends AsyncTask<Void, Void, String> {

        private WeakReference<TextView> content;

        public BackgroundTask(TextView content) {
            this.content = new WeakReference<>(content);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                Log.e(TAG, e.getMessage());
            }
            return "do in background";
        }

        @Override
        protected void onPostExecute(String s) {
            if (content != null) {
                content.get().setText(s);
            }
        }
    }
}


text:
from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True

        return obj.payer == request.user

class AnonymousCanCreate(permissions.BasePermission):

    def has_permission(self, request, view):
        return view.action == 'create'


text:
layout: default
title: "Kaushik Rangadurai: Home Page"
include_header: true
nav_item: home
---

{% include about.html %}


text:
using namespace std;
using namespace IECore;

namespace IECore
{

/// \todo Move to Cortex. This `hash_value()` implementation differs from the existing
/// `std::hash` implementation that Cortex has in that it hashes the pointer and not
/// the string contents. I don't see any reason not to make `std::hash` use the faster
/// option as well.
/// Override `boost::hash_value()` to allow InternedString to be used
/// with `hashed_index`.
size_t hash_value( const IECore::InternedString &v )
{
	return boost::hash<const char *>()( v.c_str() );
}

} // namespace IECore

namespace GafferScene
{

namespace Private
{

// Override `boost::hash_value()` to allow Input to be used
/// with `hashed_index`.
size_t hash_value( const ChildNamesMap::Input &v )
{
	size_t s = 0;
	boost::hash_combine( s, v.name );
	boost::hash_combine( s, v.index );
	return s;
}

ChildNamesMap::ChildNamesMap( const std::vector<IECore::ConstInternedStringVectorDataPtr> &inputChildNames )
	:	m_childNames( new InternedStringVectorData() )
{
	vector<InternedString> &outputChildNames = m_childNames->writable();
	boost::format namePrefixSuffixFormatter( "%s%d" );

	unordered_set<InternedString> allNames;
	size_t index = 0;
	for( const auto &childNamesData : inputChildNames )
	{
		for( const auto &inputChildName : childNamesData->readable() )
		{
			InternedString outputChildName = inputChildName;
			if( allNames.find( inputChildName ) != allNames.end() )
			{
				// uniqueify the name
				string prefix;
				int suffix = IECore::StringAlgo::numericSuffix( inputChildName.string(), 1, &prefix );

				do
				{
					outputChildName = boost::str( namePrefixSuffixFormatter % prefix % suffix );
					suffix++;
				} while( allNames.find( outputChildName ) != allNames.end() );
			}

			allNames.insert( outputChildName );
			outputChildNames.push_back( outputChildName );

			m_map.insert( { { inputChildName, index }, outputChildName } );
		}
		index++;
	}
}

const IECore::InternedStringVectorData *ChildNamesMap::outputChildNames() const
{
	return m_childNames.get();
}

const ChildNamesMap::Input &ChildNamesMap::input( IECore::InternedString outputName ) const
{
	auto it = m_map.find( outputName );
	if( it == m_map.end() )
	{
		throw IECore::Exception(
			boost::str( boost::format( "Invalid child name \"%1%\"" ) % outputName )
		);
	}

	return it->input;
}

IECore::PathMatcher ChildNamesMap::set( const std::vector<IECore::ConstPathMatcherDataPtr> &inputSets ) const
{
	IECore::PathMatcher result;
	size_t inputIndex = 0;
	for( const auto &inputSetData : inputSets )
	{
		if( inputSetData )
		{
			const PathMatcher &inputSet = inputSetData->readable();
			// We want our outputSet to reference the data within inputSet rather
			// than do an expensive copy. But we may need to rename the children of
			// the root location according to m_map. Here we do that by taking subtrees
			// of the input and adding them to our output under a renamed prefix.
			for( PathMatcher::RawIterator pIt = inputSet.begin(), peIt = inputSet.end(); pIt != peIt; ++pIt )
			{
				const vector<InternedString> &inputPath = *pIt;
				if( !inputPath.size() )
				{
					// Skip root.
					continue;
				}
				assert( inputPath.size() == 1 );

				const auto &inputMap = m_map.get<1>();
				auto it = inputMap.find( Input{ inputPath[0], inputIndex } );
				if( it != inputMap.end() )
				{
					result.addPaths( inputSet.subTree( inputPath ), { it->output } );
				}
				else
				{
					// The set contains an invalid path that is not present in
					// the scene (as defined by the `inputChildNames` passed to our
					// constructor). We could throw an error, but since it's currently
					// relatively easy for a user to make an invalid set via
					// `Set::pathsPlug()`, we do the more helpful thing and just omit
					// the invalid path from the output set.
				}

				pIt.prune(); // We only want to visit the first level
			}
		}
	 	inputIndex++;
	}

	return result;
}

} // namespace Private

} // namespace GafferScene


text:
import * as ts from "typescript";

import * as Lint from "../lint";

const OPTION_ALLOW_DECLARATIONS = "allow-declarations";

export class Rule extends Lint.Rules.AbstractRule {
    /* tslint:disable:object-literal-sort-keys */
    public static metadata: Lint.IRuleMetadata = {
        ruleName: "only-arrow-functions",
        description: "Disallows traditional (non-arrow) function expressions.",
        rationale: "Traditional functions don't bind lexical scope, which can lead to unexpected behavior when accessing 'this'.",
        optionsDescription: Lint.Utils.dedent`
            One argument may be optionally provided:

            * \`"${OPTION_ALLOW_DECLARATIONS}"\` allows standalone function declarations.
        `,
        options: {
            type: "array",
            items: {
                type: "string",
                enum: [OPTION_ALLOW_DECLARATIONS],
            },
            minLength: 0,
            maxLength: 1,
        },
        optionExamples: ["true", `[true, "${OPTION_ALLOW_DECLARATIONS}"]`],
        type: "typescript",
    };
    /* tslint:enable:object-literal-sort-keys */

    public static FAILURE_STRING = "non-arrow functions are forbidden";

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return this.applyWithWalker(new OnlyArrowFunctionsWalker(sourceFile, this.getOptions()));
    }
}

class OnlyArrowFunctionsWalker extends Lint.RuleWalker {
    public visitFunctionDeclaration(node: ts.FunctionDeclaration) {
        if (!this.hasOption(OPTION_ALLOW_DECLARATIONS)) {
            this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING));
        }
        super.visitFunctionDeclaration(node);
    }

    public visitFunctionExpression(node: ts.FunctionExpression) {
        this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING));
        super.visitFunctionExpression(node);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Microsoft.Build.Framework;
using Mono.Cecil;
using Mono.Cecil.Cil;

public class ModuleWeaver
{
    // Will contain the full element XML from FodyWeavers.xml. OPTIONAL
    public XElement Config { get; set; }

    // Will log an MessageImportance.Normal message to MSBuild. OPTIONAL
    public Action<string> LogDebug { get; set; }

    // Will log an MessageImportance.High message to MSBuild. OPTIONAL
    public Action<string> LogInfo  { get; set; }

    // Will log a message to MSBuild. OPTIONAL
    public Action<string, MessageImportance> LogMessage  { get; set; }

    // Will log an warning message to MSBuild. OPTIONAL
    public Action<string> LogWarning  { get; set; }

    // Will log an warning message to MSBuild at a specific point in the code. OPTIONAL
    public Action<string, SequencePoint> LogWarningPoint { get; set; }

    // Will log an error message to MSBuild. OPTIONAL
    public Action<string> LogError { get; set; }

    // Will log an error message to MSBuild at a specific point in the code. OPTIONAL
    public Action<string, SequencePoint> LogErrorPoint { get; set; }

    // An instance of Mono.Cecil.IAssemblyResolver for resolving assembly references. OPTIONAL
    public IAssemblyResolver AssemblyResolver { get; set; }

    // An instance of Mono.Cecil.ModuleDefinition for processing. REQUIRED
    public ModuleDefinition ModuleDefinition { get; set; }

    // Will contain the full path of the target assembly. OPTIONAL
    public string AssemblyFilePath { get; set; }

    // Will contain the full directory path of the target project.
    // A copy of $(ProjectDir). OPTIONAL
    public string ProjectDirectoryPath { get; set; }

    // Will contain the full directory path of the current weaver. OPTIONAL
    public string AddinDirectoryPath { get; set; }

    // Will contain the full directory path of the current solution.
    // A copy of `$(SolutionDir)` or, if it does not exist, a copy of `$(MSBuildProjectDirectory)..\..\..\`. OPTIONAL
    public string SolutionDirectoryPath { get; set; }

    // Will contain a semicomma delimetered string that contains
    // all the references for the target project.
    // A copy of the contents of the @(ReferencePath). OPTIONAL
    public string References { get; set; }

    // Will a list of all the references marked as copy-local.
    // A copy of the contents of the @(ReferenceCopyLocalPaths). OPTIONAL
    public List<string> ReferenceCopyLocalPaths { get; set; }

    // Will a list of all the msbuild constants.
    // A copy of the contents of the $(DefineConstants). OPTIONAL
    public List<string> DefineConstants { get; set; }

    // Init logging delegates to make testing easier
    public ModuleWeaver()
    {
        LogDebug = m => { };
        LogInfo = m => { };
        LogWarning = m => { };
        LogWarningPoint = (m,p) => { };
        LogError = m => { };
        LogErrorPoint = (m, p) => { };
    }

    public void Execute()
    {
        ModuleDefinition.Types.Add(new TypeDefinition("MyNamespace", "MyType", TypeAttributes.Public));
    }

    // Will be called when a request to cancel the build occurs. OPTIONAL
    public void Cancel()
    {
    }

    // Will be called after all weaving has occurred and the module has been saved. OPTIONAL
    public void AfterWeaving()
    {
    }
}


text:
/**
 * @private
 */
IonicModule

.controller('$ionicScroll', [
  '$scope',
  'scrollViewOptions',
  '$timeout',
  '$window',
  '$location',
  '$document',
  '$ionicScrollDelegate',
  '$ionicHistory',
function($scope, scrollViewOptions, $timeout, $window, $location, $document, $ionicScrollDelegate, $ionicHistory) {

  var self = this;
  // for testing
  self.__timeout = $timeout;

  self._scrollViewOptions = scrollViewOptions; //for testing

  var element = self.element = scrollViewOptions.el;
  var $element = self.$element = jqLite(element);
  var scrollView = self.scrollView = new ionic.views.Scroll(scrollViewOptions);

  //Attach self to element as a controller so other directives can require this controller
  //through `require: '$ionicScroll'
  //Also attach to parent so that sibling elements can require this
  ($element.parent().length ? $element.parent() : $element)
    .data('$$ionicScrollController', self);

  var deregisterInstance = $ionicScrollDelegate._registerInstance(
    self, scrollViewOptions.delegateHandle, function() {
      return $ionicHistory.isActiveScope($scope);
    }
  );

  if (!angular.isDefined(scrollViewOptions.bouncing)) {
    ionic.Platform.ready(function() {
      if (scrollView.options) {
        scrollView.options.bouncing = true;
        if (ionic.Platform.isAndroid()) {
          // No bouncing by default on Android
          scrollView.options.bouncing = false;
          // Faster scroll decel
          scrollView.options.deceleration = 0.95;
        }
      }
    });
  }

  var resize = angular.bind(scrollView, scrollView.resize);
  ionic.on('resize', resize, $window);

  var scrollFunc = function(e) {
    var detail = (e.originalEvent || e).detail || {};
    $scope.$onScroll && $scope.$onScroll({
      event: e,
      scrollTop: detail.scrollTop || 0,
      scrollLeft: detail.scrollLeft || 0
    });
  };

  $element.on('scroll', scrollFunc);

  $scope.$on('$destroy', function() {
    deregisterInstance();
    //Windows: make sure the scrollView.__cleanup exists before calling it
    if (scrollView.__cleanup) {
        scrollView.__cleanup();
    }
    ionic.off('resize', resize, $window);
    $window.removeEventListener('resize', resize);
    scrollViewOptions = null;
    self._scrollViewOptions.el = null;
    self._scrollViewOptions = null;
    $element.off('scroll', scrollFunc);
    $element = null;
    self.$element = null;
    element = null;
    self.element = null;
    self.scrollView = null;
    scrollView = null;
  });

  $timeout(function() {
    scrollView && scrollView.run && scrollView.run();
  });

  self.getScrollView = function() {
    return self.scrollView;
  };

  self.getScrollPosition = function() {
    return self.scrollView.getValues();
  };

  self.resize = function() {
    return $timeout(resize).then(function() {
      $element && $element.triggerHandler('scroll.resize');
    });
  };

  self.scrollTop = function(shouldAnimate) {
    ionic.DomUtil.blurAll();
    self.resize().then(function() {
      scrollView.scrollTo(0, 0, !!shouldAnimate);
    });
  };

  self.scrollBottom = function(shouldAnimate) {
    ionic.DomUtil.blurAll();
    self.resize().then(function() {
      var max = scrollView.getScrollMax();
      scrollView.scrollTo(max.left, max.top, !!shouldAnimate);
    });
  };

  self.scrollTo = function(left, top, shouldAnimate) {
    ionic.DomUtil.blurAll();
    self.resize().then(function() {
      scrollView.scrollTo(left, top, !!shouldAnimate);
    });
  };

  self.zoomTo = function(zoom, shouldAnimate, originLeft, originTop) {
    ionic.DomUtil.blurAll();
    self.resize().then(function() {
      scrollView.zoomTo(zoom, !!shouldAnimate, originLeft, originTop);
    });
  };

  self.zoomBy = function(zoom, shouldAnimate, originLeft, originTop) {
    ionic.DomUtil.blurAll();
    self.resize().then(function() {
      scrollView.zoomBy(zoom, !!shouldAnimate, originLeft, originTop);
    });
  };

  self.scrollBy = function(left, top, shouldAnimate) {
    ionic.DomUtil.blurAll();
    self.resize().then(function() {
      scrollView.scrollBy(left, top, !!shouldAnimate);
    });
  };

  self.anchorScroll = function(shouldAnimate) {
    ionic.DomUtil.blurAll();
    self.resize().then(function() {
      var hash = $location.hash();
      var elm = hash && $document[0].getElementById(hash);
      if (!(hash && elm)) {
        scrollView.scrollTo(0,0, !!shouldAnimate);
        return;
      }
      var curElm = elm;
      var scrollLeft = 0, scrollTop = 0, levelsClimbed = 0;
      do {
        if (curElm !== null) scrollLeft += curElm.offsetLeft;
        if (curElm !== null) scrollTop += curElm.offsetTop;
        curElm = curElm.offsetParent;
        levelsClimbed++;
      } while (curElm.attributes != self.element.attributes && curElm.offsetParent);
      scrollView.scrollTo(scrollLeft, scrollTop, !!shouldAnimate);
    });
  };

  /**
   * @private
   */
  self._setRefresher = function(refresherScope, refresherElement) {
    var refresher = self.refresher = refresherElement;
    var refresherHeight = self.refresher.clientHeight || 60;
    scrollView.activatePullToRefresh(refresherHeight, function() {
      // activateCallback
      refresher.classList.add('active');
      refresherScope.$onPulling();
      onPullProgress(1);
    }, function() {
      // deactivateCallback
      refresher.classList.remove('active');
      refresher.classList.remove('refreshing');
      refresher.classList.remove('refreshing-tail');
    }, function() {
      // startCallback
      refresher.classList.add('refreshing');
      refresherScope.$onRefresh();
    }, function() {
      // showCallback
      refresher.classList.remove('invisible');
    }, function() {
      // hideCallback
      refresher.classList.add('invisible');
    }, function() {
      // tailCallback
      refresher.classList.add('refreshing-tail');
    }, onPullProgress);

    function onPullProgress(progress) {
      $scope.$broadcast('$ionicRefresher.pullProgress', progress);
      refresherScope.$onPullProgress && refresherScope.$onPullProgress(progress);
    }
  };

}]);


text:
// See LICENSE.txt for license information.

namespace VictorBush.Ego.NefsLib.Item
{
    using System;

    /// <summary>
    /// Additional attributes that describe an item.
    /// </summary>
    public struct NefsItemAttributes
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NefsItemAttributes"/> struct.
        /// </summary>
        /// <param name="isCacheable">Indicates if item is cacheable.</param>
        /// <param name="isDirectory">Indicates if item is directory.</param>
        /// <param name="isDuplicated">Indicates if item has duplicates.</param>
        /// <param name="isPatched">Indicates if item is patched.</param>
        /// <param name="v16IsTransformed">Indicates if item's data has transformations applied.</param>
        /// <param name="v16Unknown0x10">Unknown flag 0x10 (v1.6).</param>
        /// <param name="v16Unknown0x40">Unknown flag 0x40 (v1.6).</param>
        /// <param name="v16Unknown0x80">Unknown flag 0x80 (v1.6).</param>
        /// <param name="v20IsZlib">Version 2.0 - Indicates if item's data is zlib compressed.</param>
        /// <param name="v20IsAes">Version 2.0 - Indicates if item's data is AES encrypted.</param>
        /// <param name="v20Unknown0x10">Unknown flag 0x10.</param>
        /// <param name="v20Unknown0x20">Unknown flag 0x20.</param>
        /// <param name="v20Unknown0x40">Unknown flag 0x40.</param>
        /// <param name="v20Unknown0x80">Unknown flag 0x80.</param>
        /// <param name="part6Volume">Item volume.</param>
        /// <param name="part6Unknown0x3">Unknown value.</param>
        public NefsItemAttributes(
            bool isCacheable = false,
            bool isDirectory = false,
            bool isDuplicated = false,
            bool isPatched = false,
            bool v16IsTransformed = false,
            bool v16Unknown0x10 = false,
            bool v16Unknown0x40 = false,
            bool v16Unknown0x80 = false,
            bool v20IsZlib = false,
            bool v20IsAes = false,
            bool v20Unknown0x10 = false,
            bool v20Unknown0x20 = false,
            bool v20Unknown0x40 = false,
            bool v20Unknown0x80 = false,
            UInt16 part6Volume = 0,
            byte part6Unknown0x3 = 0)
        {
            this.IsCacheable = isCacheable;
            this.IsDirectory = isDirectory;
            this.IsDuplicated = isDuplicated;
            this.IsPatched = isPatched;
            this.V16IsTransformed = v16IsTransformed;
            this.V16Unknown0x10 = v16Unknown0x10;
            this.V16Unknown0x40 = v16Unknown0x40;
            this.V16Unknown0x80 = v16Unknown0x80;
            this.V20IsZlib = v20IsZlib;
            this.V20IsAes = v20IsAes;
            this.V20Unknown0x10 = v20Unknown0x10;
            this.V20Unknown0x20 = v20Unknown0x20;
            this.V20Unknown0x40 = v20Unknown0x40;
            this.V20Unknown0x80 = v20Unknown0x80;
            this.Part6Volume = part6Volume;
            this.Part6Unknown0x3 = part6Unknown0x3;
        }

        /// <summary>
        /// A flag indicating whether this item is cacheable (presumably by the game engine).
        /// </summary>
        public bool IsCacheable { get; }

        /// <summary>
        /// A flag indicating whether this item is a directory.
        /// </summary>
        public bool IsDirectory { get; }

        /// <summary>
        /// A flag indicating whether this item is duplicated.
        /// </summary>
        public bool IsDuplicated { get; }

        /// <summary>
        /// A flag indicating whether this item is patched (meaning unknown).
        /// </summary>
        public bool IsPatched { get; }

        /// <summary>
        /// Unknown data (from part 6).
        /// </summary>
        public byte Part6Unknown0x3 { get; }

        /// <summary>
        /// Meaning unknown (from part 6).
        /// </summary>
        public UInt16 Part6Volume { get; }

        /// <summary>
        /// Version 1.6 - A flag indicating whether the item's data has transforms applied
        /// (compressed, encrypted, etc).
        /// </summary>
        public bool V16IsTransformed { get; }

        /// <summary>
        /// Version 1.6 unknown flag.
        /// </summary>
        public bool V16Unknown0x10 { get; }

        /// <summary>
        /// Version 1.6 unknown flag.
        /// </summary>
        public bool V16Unknown0x40 { get; }

        /// <summary>
        /// Version 1.6 unknown flag.
        /// </summary>
        public bool V16Unknown0x80 { get; }

        /// <summary>
        /// Version 2.0 - indicates whether the item's data is AES encrypted.
        /// </summary>
        public bool V20IsAes { get; }

        /// <summary>
        /// Version 2.0 - indicates whether the item's data is zlib compressed.
        /// </summary>
        public bool V20IsZlib { get; }

        /// <summary>
        /// Version 2.0 unknown flag.
        /// </summary>
        public bool V20Unknown0x10 { get; }

        /// <summary>
        /// Version 2.0 unknown flag.
        /// </summary>
        public bool V20Unknown0x20 { get; }

        /// <summary>
        /// Version 2.0 unknown flag.
        /// </summary>
        public bool V20Unknown0x40 { get; }

        /// <summary>
        /// Version 2.0 unknown flag.
        /// </summary>
        public bool V20Unknown0x80 { get; }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>App Engine Python SDK: google.appengine._internal.antlr3.exceptions.BacktrackingFailed Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="common.css" rel="stylesheet" type="text/css"/>

App Engine Python SDK
    v1.6.9 rev.445

The Python runtime is available as an experimental Preview feature.

google

appengine

_internal

antlr3

exceptions

BacktrackingFailed

google.appengine._internal.antlr3.exceptions.BacktrackingFailed Class Reference

Inheritance diagram for google.appengine._internal.antlr3.exceptions.BacktrackingFailed:

  <map id="google.appengine._internal.antlr3.exceptions.BacktrackingFailed_map" name="google.appengine._internal.antlr3.exceptions.BacktrackingFailed_map">
</map>

Detailed Description

@brief Raised to signal failed backtrack attempt

The documentation for this class was generated from the following file:

code/googleappengine-read-only/python/google/appengine/_internal/antlr3/exceptions.py

<address class="footer">
    Maintained by tzmartin
</address>


text:
package com.jaquadro.minecraft.gardenstuff.integration;

import com.jaquadro.minecraft.gardenapi.api.GardenAPI;
import com.jaquadro.minecraft.gardenapi.api.component.ILanternSource;
import com.jaquadro.minecraft.gardenstuff.GardenStuff;
import com.jaquadro.minecraft.gardenstuff.core.ClientProxy;
import com.jaquadro.minecraft.gardenstuff.integration.twilightforest.EntityFireflyWrapper;
import com.jaquadro.minecraft.gardenstuff.integration.lantern.FireflyLanternSource;
import com.jaquadro.minecraft.gardenstuff.integration.twilightforest.RenderFireflyWrapper;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.entity.effect.EntityWeatherEffect;
import net.minecraft.world.World;

import java.lang.reflect.Constructor;
import java.util.Random;

public class TwilightForestIntegration
{
    public static final String MOD_ID = "TwilightForest";

    static Class classEntityFirefly;
    static Class classRenderFirefly;

    public static Constructor constEntityFirefly;
    public static Constructor constRenderFirefly;

    private static boolean initialized;

    public static void init () {
        if (!Loader.isModLoaded(MOD_ID))
            return;

        try {
            classEntityFirefly = Class.forName("twilightforest.entity.passive.EntityTFTinyFirefly");
            classRenderFirefly = Class.forName("twilightforest.client.renderer.entity.RenderTFTinyFirefly");

            constEntityFirefly = classEntityFirefly.getConstructor(World.class, double.class, double.class, double.class);
            constRenderFirefly = classRenderFirefly.getConstructor();

            if (GardenStuff.proxy instanceof ClientProxy)
                registerEntity();

            Block blockFirefly = GameRegistry.findBlock(MOD_ID, "tile.TFFirefly");
            ILanternSource fireflySource = new FireflyLanternSource(blockFirefly);

            GardenAPI.instance().registries().lanternSources().registerLanternSource(fireflySource);

            initialized = true;
        }
        catch (Throwable t) { }
    }

    @SideOnly(Side.CLIENT)
    private static void registerEntity () {
        RenderingRegistry.registerEntityRenderingHandler(EntityFireflyWrapper.class, new RenderFireflyWrapper());
    }

    public static boolean isLoaded () {
        return initialized;
    }

    public static void doFireflyEffect (World world, int x, int y, int z, Random rand) {
        try {
            EntityWeatherEffect tinyfly;
            double dx, dy, dz;

            for (int i = 0; i < 2; i++) {
                dx = x + ((rand.nextFloat() - rand.nextFloat()) * 0.3F + 0.5F);
                dy = y + ((rand.nextFloat() - rand.nextFloat()) * 0.4F - .05f);
                dz = z + ((rand.nextFloat() - rand.nextFloat()) * 0.3F + 0.5F);

                tinyfly = (EntityWeatherEffect) constEntityFirefly.newInstance(world, dx, dy, dz);
                //tinyfly = new EntityFireflyWrapper(world, dx, dy, dz);
                world.spawnEntityInWorld(tinyfly);
            }
        }
        catch (Throwable t) {

        }
    }
}


text:
using namespace Framework::Vulkan;

CCommandBufferPool::CCommandBufferPool(CDevice& device, uint32_t queueFamilyIndex)
: m_device(&device)
{
	Create(queueFamilyIndex);
}

CCommandBufferPool::~CCommandBufferPool()
{
	Reset();
}

bool CCommandBufferPool::IsEmpty() const
{
	return (m_handle == VK_NULL_HANDLE);
}

void CCommandBufferPool::Reset()
{
	if(m_handle != VK_NULL_HANDLE)
	{
		assert(m_device != nullptr);
		m_device->vkFreeCommandBuffers(*m_device, m_handle, m_buffers.size(), m_buffers.data());
		m_buffers.clear();
		m_bufferIndex = 0;
		m_device->vkDestroyCommandPool(*m_device, m_handle, nullptr);
		m_device = nullptr;
		m_handle = VK_NULL_HANDLE;
	}
}

CCommandBufferPool& CCommandBufferPool::operator =(CCommandBufferPool&& rhs)
{
	Reset();

	std::swap(m_device, rhs.m_device);
	std::swap(m_handle, rhs.m_handle);

	std::swap(m_buffers, rhs.m_buffers);
	std::swap(m_bufferIndex, rhs.m_bufferIndex);

	return (*this);
}

VkCommandBuffer CCommandBufferPool::AllocateBuffer()
{
	VkCommandBuffer buffer = VK_NULL_HANDLE;
	if(m_bufferIndex < m_buffers.size())
	{
		buffer = m_buffers[m_bufferIndex++];
		auto result = m_device->vkResetCommandBuffer(buffer, VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
		CHECKVULKANERROR(result);
	}
	else
	{
		auto bufferAllocateInfo = Framework::Vulkan::CommandBufferAllocateInfo();
		bufferAllocateInfo.commandPool        = m_handle;
		bufferAllocateInfo.level              = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
		bufferAllocateInfo.commandBufferCount = 1;

		auto result = m_device->vkAllocateCommandBuffers(*m_device, &bufferAllocateInfo, &buffer);
		CHECKVULKANERROR(result);

		m_buffers.push_back(buffer);
		m_bufferIndex++;
	}
	return buffer;
}

void CCommandBufferPool::ResetBuffers()
{
	m_bufferIndex = 0;
}

void CCommandBufferPool::Create(uint32_t queueFamilyIndex)
{
	auto commandPoolCreateInfo = Framework::Vulkan::CommandPoolCreateInfo();
	commandPoolCreateInfo.queueFamilyIndex = queueFamilyIndex;
	commandPoolCreateInfo.flags            = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;

	auto result = m_device->vkCreateCommandPool(*m_device, &commandPoolCreateInfo, nullptr, &m_handle);
	CHECKVULKANERROR(result);
}


text:
require 'test/unit'
require 'logger'
require File.dirname(__FILE__) + '/../lib/ruby-mythtv'


text:
import os
import datetime
import json
import webapp2
import jinja2
import urllib

from google.appengine.api import users

from poker.models import *
from poker.firebase import create_custom_token, send_firebase_message

JINJA_ENVIRONMENT = jinja2.Environment(
    loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '../templates')),
    extensions = [
        'jinja2.ext.autoescape',
    ],
    autoescape = True
)

__all__ = [
    'MainPage',
    'NewGame',
    'GameList',
    'DeleteGame',
    'GamePage',
    'GameOpened',
    'ToggleCompleteGame',
    'NewStory',
    'SkipStory',
    'CompleteStory',
    'NewRound',
    'CompleteRound',
    'EstimateRound',
    'ToggleGameObserver',
    'DeleteParticipant',
    'GameClosed',
]

class Player():
    user = None
    profile = None

    def __init__(self):
        user = users.get_current_user()
        if user:
            self.user = user

    def get_user(self):
        return self.user

    def get_url(self, dest_url):
        if self.user:
            return users.create_logout_url('/')
        return users.create_login_url(dest_url)

    def get_games(self):
        return Game.all().filter("user =", self.user)

    def get_profile(self):
        return None

    def get_name(self):
        profile = self.get_profile()
        if profile and 'displayName' in profile:
            return profile['displayName']
        return None

    def get_photo(self):
        profile = self.get_profile()
        if profile and 'image' in profile:
            return profile['image']['url']
        return None

class PokerRequestHandler(webapp2.RequestHandler):
    player = None

    def get_player(self):
        if self.player is None:
            player = Player()
        return player

    def get_user(self, abort = True):
        user = self.get_player().get_user()
        if abort:
            if not user:
                self.abort(401)
        return user

    def get_game(self, game_id, check_user = False):
        game = Game.get_by_id(int(game_id))
        if not game:
            self.abort(404)
        if check_user:
            user = self.get_player().get_user()
            if game.user != user:
                self.abort(403)
        return game

    def get_story(self, game_id, story_id, check_user = False):
        game = self.get_game(game_id, check_user)
        story = Story.get_by_id(int(story_id), game)
        if not story:
            self.abort(404)
        return story

    def get_round(self, game_id, story_id, round_id, check_user = False):
        story = self.get_story(game_id, story_id, check_user)
        round = Round.get_by_id(int(round_id), story)
        if not round:
            self.abort(404)
        return round

    def get_participant(self, game_id, participant_key, check_user = False):
        game = self.get_game(game_id, check_user)
        participant = Participant.get_by_key_name(str(participant_key), game)
        if not participant:
            self.abort(404)
        return participant

class MainPage(PokerRequestHandler):
    def get(self):
        player = self.get_player()
        user = player.get_user()
        if user:
            return self.redirect('/game/list')
        url = player.get_url(self.request.uri)
        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render({
            'user': user,
            'url': url,
            'now': datetime.datetime.now(),
        }))

class NewGame(PokerRequestHandler):
    def post(self):
        user = self.get_user()
        try:
            game = Game(
                name = self.request.get('name'),
                deck = int(self.request.get('deck')),
                user = user
            )
        except:
            return self.redirect('/')
        game.put()
        game_url = game.get_url()
        return self.redirect(game_url)

class GameList(PokerRequestHandler):

    def get(self):
        player = self.get_player()
        user = player.get_user()
        url = player.get_url(self.request.uri)
        games = player.get_games().order("-created")
        template = JINJA_ENVIRONMENT.get_template('list.html')
        self.response.write(template.render({
            'user': user,
            'player_name': player.get_name(),
            'player_photo': player.get_photo(),
            'url': url,
            'games': games,
            'decks': Game.DECK_CHOICES,
            'now': datetime.datetime.now(),
        }))

class DeleteGame(PokerRequestHandler):
    def get(self, game_id):
        game = self.get_game(game_id, check_user = True)
        game.delete()
        return self.redirect('/')

class GamePage(PokerRequestHandler):

    def get(self, game_id):
        user = self.get_user()
        player = self.get_player()
        url = player.get_url(self.request.uri)
        game = self.get_game(game_id)
        deck = json.dumps(game.get_deck())
        participant_key = str(game.key().id()) + str(user.user_id())
        participant = Participant.get_or_insert(
            participant_key,
            parent = game,
            user = user
        )
        if not participant.name or not participant.photo:
            participant.name = player.get_name()
            participant.photo = player.get_photo()
            participant.put()
        template = JINJA_ENVIRONMENT.get_template('game.html')
        channel_id = participant_key
        client_auth_token = create_custom_token(channel_id)
        message = game.get_message()
        initial_message = urllib.unquote(json.dumps(message))
        self.response.write(template.render({
            'user': user,
            'player_name': player.get_name(),
            'player_photo': player.get_photo(),
            'game': game,
            'deck': deck,
            'url': url,
            'now': datetime.datetime.now(),
            'request_url': self.request.url,
            'token': client_auth_token,
            'channel_id': channel_id,
            'initial_message': initial_message,
        }))

class GameOpened(PokerRequestHandler):
    def post(self, game_id):
        user = self.get_user()
        game = self.get_game(game_id)
        game.send_update()
        response = {
            'estimates': game.get_user_estimates(user),
        }
        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(response))

class ToggleCompleteGame(PokerRequestHandler):
    def get(self, game_id, toggle):
        self.post(game_id, toggle)
        return self.redirect('/game/list')

    def post(self, game_id, toggle):
        game = self.get_game(game_id, check_user = True)
        game.completed = toggle == 'complete'
        if game.completed:
            for story in game.get_stories():
                for round in story.get_rounds():
                    round.completed = True
                    round.put()
                if story.estimate is None:
                    story.estimate = Story.SKIPPED
                    story.put()
        game.current_story_id = None
        game.put()
        game.send_update()

class NewStory(PokerRequestHandler):
    def post(self, game_id):
        game = self.get_game(game_id, check_user = True)
        current_story = game.get_current_story()
        if game.completed or current_story:
            self.abort(403)
        try:
            story = Story(
                parent = game,
                name = self.request.get('name')
            )
        except:
            self.abort(400)
        story.put()
        story.new_round()
        game.current_story_id = story.key().id()
        game.put()
        game.send_update()

class SkipStory(PokerRequestHandler):
    def post(self, game_id, story_id):
        story = self.get_story(game_id, story_id, check_user = True)
        rounds = story.get_rounds()
        for round in rounds:
            round.completed = True
            round.put()
        story.estimate = Story.SKIPPED
        story.put()
        game = story.parent()
        game.current_story_id = None
        game.put()
        game.send_update()

class CompleteStory(PokerRequestHandler):
    def post(self, game_id, story_id):
        story = self.get_story(game_id, story_id, check_user = True)
        game = story.parent()
        if game.completed or not story.is_current():
            self.abort(403)
        deck = game.get_deck()
        card = self.request.get('card')
        try:
            card = int(card)
        except ValueError:
            self.abort(400)
        try:
            estimate = deck[card]
        except IndexError:
            self.abort(400)
        rounds = story.get_rounds()
        for round in rounds:
            round.completed = True
            round.put()
        story.estimate = card
        story.put()
        game.current_story_id = None
        game.put()
        game.send_update()

class NewRound(PokerRequestHandler):
    def post(self, game_id, story_id):
        story = self.get_story(game_id, story_id, check_user = True)
        game = story.parent()
        if game.completed or not story.is_current():
            self.abort(403)
        story.new_round()
        game.send_update()

class CompleteRound(PokerRequestHandler):
    def post(self, game_id, story_id, round_id):
        round = self.get_round(game_id, story_id, round_id, check_user = True)
        story = round.parent()
        game = story.parent()
        if game.completed or not story.is_current():
            self.abort(403)
        round.completed = True
        round.put()
        game.send_update()

class EstimateRound(PokerRequestHandler):
    def post(self, game_id, story_id, round_id):
        round = self.get_round(game_id, story_id, round_id)
        user = self.get_user()
        story = round.parent()
        game = story.parent()
        if game.completed or not story.is_current() or round.completed:
            self.abort(403)
        deck = game.get_deck()
        card = self.request.get('card')
        try:
            card = int(card)
        except ValueError:
            self.abort(400)
        try:
            estimate = deck[card]
        except IndexError:
            self.abort(400)
        estimate_key = str(round.key().id()) + str(user.user_id())
        estimate = Estimate.get_or_insert(
            estimate_key,
            parent = round,
            user = user,
            card = card
        )
        estimate.put()
        count_participants = game.get_participants().filter('observer =', False).count()
        count_estimates = round.get_estimates().count()
        if count_participants == count_estimates:
            round.completed = True
            round.put()
        game.send_update(force = round.completed, user = user)

class ToggleGameObserver(PokerRequestHandler):
    def post(self, game_id, participant_key, observer):
        participant = self.get_participant(game_id, participant_key, check_user = True)
        participant.observer = observer == 'observer'
        participant.put()
        game = participant.parent()
        game.send_update()

class DeleteParticipant(PokerRequestHandler):
    def post(self, game_id, participant_key):
        participant = self.get_participant(game_id, participant_key, check_user = True)
        game = participant.parent()
        if game.user == participant.user:
            self.abort(403)
        participant.delete()
        game.send_update()

class GameClosed(PokerRequestHandler):
    def post(self, game_id):
        game = self.get_game(game_id)
        user = self.get_user()
        participant_key = str(game.key().id()) + str(user.user_id())
        channel_id = participant_key
        send_firebase_message(channel_id, None)


text:
import numpy as np
import discretize
from discretize.utils import example_simplex_mesh

class TestInterpolation2d(discretize.tests.OrderTest):
    name = "Interpolation 2D"
    meshSizes = [8, 16, 32, 64]
    meshTypes = ["uniform simplex mesh"]
    interp_points = np.stack(np.mgrid[0.25:0.75:32j, 0.25:0.75:32j], axis=-1).reshape(
        -1, 2
    )
    meshDimension = 2
    expectedOrders = 1

    def setupMesh(self, n):
        points, simplices = example_simplex_mesh((n, n))
        self.M = discretize.SimplexMesh(points, simplices)
        return 1.0 / n

    def getError(self):
        funX = lambda x, y: -(y ** 2)
        funY = lambda x, y: x ** 2

        if "x" in self.type:
            ana = funX(*self.interp_points.T)
        elif "y" in self.type:
            ana = funY(*self.interp_points.T)
        else:
            ana = funX(*self.interp_points.T) + funY(*self.interp_points.T)

        mesh = self.M
        if "F" in self.type:
            Fc = np.c_[funX(*mesh.faces.T), funY(*mesh.faces.T)]
            grid = mesh.project_face_vector(Fc)
        elif "E" in self.type:
            Ec = np.c_[funX(*mesh.edges.T), funY(*mesh.edges.T)]
            grid = mesh.project_edge_vector(Ec)
        elif "CC" == self.type:
            grid = funX(*mesh.cell_centers.T) + funY(*mesh.cell_centers.T)
        elif "N" == self.type:
            grid = funX(*mesh.nodes.T) + funY(*mesh.nodes.T)

        comp = mesh.get_interpolation_matrix(self.interp_points, self.type) * grid

        err = np.linalg.norm((comp - ana), np.inf)
        return err

    def test_orderCC(self):
        self.type = "CC"
        self.expectedOrders = 2
        self.name = "Interpolation 2D: CC"
        self.expectedOrders = 1
        self.orderTest()

    def test_orderN(self):
        self.type = "N"
        self.expectedOrders = 2
        self.name = "Interpolation 2D: N"
        self.orderTest()
        self.expectedOrders = 1

    def test_orderFx(self):
        self.type = "Fx"
        self.name = "Interpolation 2D: Fx"
        self.orderTest()

    def test_orderFy(self):
        self.type = "Fy"
        self.name = "Interpolation 2D: Fy"
        self.orderTest()

    def test_orderEx(self):
        self.type = "Ex"
        self.name = "Interpolation 2D: Ex"
        self.orderTest()

    def test_orderEy(self):
        self.type = "Ey"
        self.name = "Interpolation 2D: Ey"
        self.orderTest()

class TestInterpolation3d(discretize.tests.OrderTest):
    name = "Interpolation 3D"
    meshSizes = [5, 10, 20, 40]
    meshTypes = ["uniform simplex mesh"]
    interp_points = np.stack(
        np.mgrid[0.25:0.75:32j, 0.25:0.75:32j, 0.25:0.75:32j], axis=-1
    ).reshape(-1, 3)
    meshDimension = 3
    expectedOrders = 1

    def setupMesh(self, n):
        points, simplices = example_simplex_mesh((n, n, n))
        self.M = discretize.SimplexMesh(points, simplices)
        return 1.0 / n

    def getError(self):
        funX = lambda x, y, z: np.cos(2 * np.pi * y)
        funY = lambda x, y, z: np.cos(2 * np.pi * z)
        funZ = lambda x, y, z: np.cos(2 * np.pi * x)

        if "x" in self.type:
            ana = funX(*self.interp_points.T)
        elif "y" in self.type:
            ana = funY(*self.interp_points.T)
        elif "z" in self.type:
            ana = funZ(*self.interp_points.T)
        else:
            ana = (
                funX(*self.interp_points.T)
                + funY(*self.interp_points.T)
                + funZ(*self.interp_points.T)
            )

        mesh = self.M
        if "F" in self.type:
            Fc = np.c_[funX(*mesh.faces.T), funY(*mesh.faces.T), funZ(*mesh.faces.T)]
            grid = mesh.project_face_vector(Fc)
        elif "E" in self.type:
            Ec = np.c_[funX(*mesh.edges.T), funY(*mesh.edges.T), funZ(*mesh.edges.T)]
            grid = mesh.project_edge_vector(Ec)
        elif "CC" == self.type:
            grid = (
                funX(*mesh.cell_centers.T)
                + funY(*mesh.cell_centers.T)
                + funZ(*mesh.cell_centers.T)
            )
        elif "N" == self.type:
            grid = funX(*mesh.nodes.T) + funY(*mesh.nodes.T) + funZ(*mesh.nodes.T)

        comp = mesh.get_interpolation_matrix(self.interp_points, self.type) * grid

        err = np.linalg.norm((comp - ana), np.inf)
        return err

    def test_orderCC(self):
        self.type = "CC"
        self.expectedOrders = 2
        self.name = "Interpolation 3D: CC"
        self.orderTest()
        self.expectedOrders = 1

    def test_orderN(self):
        self.type = "N"
        self.expectedOrders = 2
        self.name = "Interpolation 3D: N"
        self.orderTest()
        self.expectedOrders = 1

    def test_orderFx(self):
        self.type = "Fx"
        self.name = "Interpolation 3D: Fx"
        self.orderTest()

    def test_orderFy(self):
        self.type = "Fy"
        self.name = "Interpolation 3D: Fy"
        self.orderTest()

    def test_orderFz(self):
        self.type = "Fz"
        self.name = "Interpolation 3D: Fz"
        self.orderTest()

    def test_orderEx(self):
        self.type = "Ex"
        self.name = "Interpolation 3D: Ex"
        self.orderTest()

    def test_orderEy(self):
        self.type = "Ey"
        self.name = "Interpolation 3D: Ey"
        self.orderTest()

    def test_orderEz(self):
        self.type = "Ez"
        self.name = "Interpolation 3D: Ez"
        self.orderTest()

class TestAveraging(discretize.tests.OrderTest):
    meshSizes = [8, 16, 32]
    meshTypes = ["uniform simplex mesh"]

    def setupMesh(self, n):
        dim = self.meshDimension
        points, simplices = example_simplex_mesh(dim * (n,))
        self.M = discretize.SimplexMesh(points, simplices)
        return 1.0 / n

    def getError(self):
        mesh = self.M
        if mesh.dim == 2:
            func = lambda x, y: np.cos(x ** 2) - np.sin(y ** 2) + 2 * x * y
        else:
            func = (
                lambda x, y, z: np.cos(x ** 2)
                - np.sin(y ** 2)
                + 2 * x * y
                + np.cos(2 * z) ** 2
                + z ** 3
            )

        if self.target_type == "CC":
            interp_points = mesh.cell_centers
        elif self.target_type == "N":
            interp_points = mesh.nodes
        elif self.target_type == "E":
            interp_points = mesh.edges
        elif self.target_type == "F":
            interp_points = mesh.faces
        ana = func(*interp_points.T)

        if self.source_type == "CC":
            source_points = mesh.cell_centers
        elif self.source_type == "N":
            source_points = mesh.nodes
        elif self.source_type == "E":
            source_points = mesh.edges
        elif self.source_type == "F":
            source_points = mesh.faces

        v = func(*source_points.T)

        if self.source_type == "N":
            if self.target_type == "CC":
                avg_mat = mesh.average_node_to_cell
            elif self.target_type == "E":
                avg_mat = mesh.average_node_to_edge
            elif self.target_type == "F":
                avg_mat = mesh.average_node_to_face
        elif self.source_type == "CC":
            if self.target_type == "N":
                avg_mat = mesh.average_cell_to_node
            elif self.target_type == "E":
                avg_mat = mesh.average_cell_to_edge
            elif self.target_type == "F":
                avg_mat = mesh.average_cell_to_face
        elif self.source_type == "E":
            if self.target_type == "CC":
                avg_mat = mesh.average_edge_to_cell
            elif self.target_type == "F":
                avg_mat = mesh.average_edge_to_face
        elif self.source_type == "F":
            if self.target_type == "CC":
                avg_mat = mesh.average_face_to_cell

        comp = avg_mat @ v

        err = np.linalg.norm((comp - ana), np.inf)
        return err

    # 2D
    def test_AvgN2CC_2D(self):
        self.source_type = "N"
        self.target_type = "CC"
        self.name = "average_node_to_cell 2D"
        self.meshDimension = 2
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgN2F_2D(self):
        self.source_type = "N"
        self.target_type = "F"
        self.name = "average_node_to_face 2D"
        self.meshDimension = 2
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgN2E_2D(self):
        self.source_type = "N"
        self.target_type = "E"
        self.name = "average_node_to_edge 2D"
        self.meshDimension = 2
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgCC2E_2D(self):
        self.source_type = "CC"
        self.target_type = "E"
        self.name = "average_cell_to_edge 2D"
        self.meshDimension = 2
        self.expectedOrders = 1
        self.orderTest()

    def test_AvgE2CC_2D(self):
        self.source_type = "E"
        self.target_type = "CC"
        self.name = "average_edge_to_cell 2D"
        self.meshDimension = 2
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgF2CC_2D(self):
        self.source_type = "F"
        self.target_type = "CC"
        self.name = "average_face_to_cell 2D"
        self.meshDimension = 2
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgCC2F_2D(self):
        self.source_type = "CC"
        self.target_type = "F"
        self.name = "average_cell_to_face 2D"
        self.meshDimension = 2
        self.expectedOrders = 1
        self.orderTest()

    # 3D
    def test_AvgN2CC_3D(self):
        self.source_type = "N"
        self.target_type = "CC"
        self.name = "average_node_to_cell 3D"
        self.meshDimension = 3
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgN2F_3D(self):
        self.source_type = "N"
        self.target_type = "F"
        self.name = "average_node_to_face 3D"
        self.meshDimension = 3
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgN2E_3D(self):
        self.source_type = "N"
        self.target_type = "E"
        self.name = "average_node_to_edge 3D"
        self.meshDimension = 3
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgCC2N_3D(self):
        self.source_type = "CC"
        self.target_type = "N"
        self.name = "average_cell_to_node 3D"
        self.meshDimension = 3
        self.expectedOrders = 1
        self.orderTest()

    def test_AvgE2CC_3D(self):
        self.source_type = "E"
        self.target_type = "CC"
        self.name = "average_edge_to_cell 3D"
        self.meshDimension = 3
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgF2CC_3D(self):
        self.source_type = "F"
        self.target_type = "CC"
        self.name = "average_face_to_cell 3D"
        self.meshDimension = 3
        self.expectedOrders = 2
        self.orderTest()

    def test_AvgCC2F_3D(self):
        self.source_type = "CC"
        self.target_type = "F"
        self.name = "average_cell_to_face 3D"
        self.meshDimension = 3
        self.expectedOrders = 1
        self.orderTest()

class TestVectorAveraging2D(discretize.tests.OrderTest):
    name = "Averaging 2D"
    meshSizes = [8, 16, 32, 64]
    meshTypes = ["uniform simplex mesh"]
    meshDimension = 2
    expectedOrders = 1

    def setupMesh(self, n):
        points, simplices = example_simplex_mesh((n, n))
        self.M = discretize.SimplexMesh(points, simplices)
        return 1.0 / n

    def getError(self):
        funX = lambda x, y: -(y ** 2)
        funY = lambda x, y: x ** 2
        mesh = self.M
        ana = np.c_[funX(*mesh.cell_centers.T), funY(*mesh.cell_centers.T)].reshape(
            -1, order="F"
        )

        if self.source_type == "F":
            Fc = np.c_[funX(*mesh.faces.T), funY(*mesh.faces.T)]
            grid = mesh.project_face_vector(Fc)
            comp = mesh.average_face_to_cell_vector @ grid
        elif self.source_type == "E":
            Ec = np.c_[funX(*mesh.edges.T), funY(*mesh.edges.T)]
            grid = mesh.project_edge_vector(Ec)
            comp = mesh.average_edge_to_cell_vector @ grid

        err = np.linalg.norm((comp - ana), np.inf)
        return err

    def test_AvgE2CCV(self):
        self.source_type = "E"
        self.name = "average_edge_to_cell_vector 2D"
        self.orderTest()

    def test_AvgF2CCV(self):
        self.source_type = "F"
        self.name = "average_face_to_cell_vector 2D"
        self.orderTest()

class TestVectorAveraging3D(discretize.tests.OrderTest):
    name = "Averaging 3D"
    meshSizes = [8, 16, 32]
    meshTypes = ["uniform simplex mesh"]
    meshDimension = 3
    expectedOrders = 1

    def setupMesh(self, n):
        points, simplices = example_simplex_mesh((n, n, n))
        self.M = discretize.SimplexMesh(points, simplices)
        return 1.0 / n

    def getError(self):
        funX = lambda x, y, z: np.cos(2 * np.pi * y)
        funY = lambda x, y, z: np.cos(2 * np.pi * z)
        funZ = lambda x, y, z: np.cos(2 * np.pi * x)
        mesh = self.M
        ana = np.c_[
            funX(*mesh.cell_centers.T),
            funY(*mesh.cell_centers.T),
            funZ(*mesh.cell_centers.T),
        ].reshape(-1, order="F")

        if self.source_type == "F":
            Fc = np.c_[funX(*mesh.faces.T), funY(*mesh.faces.T), funZ(*mesh.faces.T)]
            grid = mesh.project_face_vector(Fc)
            comp = mesh.average_face_to_cell_vector @ grid
        elif self.source_type == "E":
            Ec = np.c_[funX(*mesh.edges.T), funY(*mesh.edges.T), funZ(*mesh.edges.T)]
            grid = mesh.project_edge_vector(Ec)
            comp = mesh.average_edge_to_cell_vector @ grid

        err = np.linalg.norm((comp - ana), np.inf)
        return err

    def test_AvgE2CCV(self):
        self.source_type = "E"
        self.name = "average_edge_to_cell_vector 2D"
        self.expectedOrders = 1
        self.orderTest()

    def test_AvgF2CCV(self):
        self.source_type = "F"
        self.name = "average_face_to_cell_vector 2D"
        self.expectedOrders = 1
        self.orderTest()

def test_cell_to_face_extrap():
    # 2D
    points, simplices = example_simplex_mesh((10, 10))
    mesh = discretize.SimplexMesh(points, simplices)

    v = np.ones(len(mesh))

    Fv = mesh.average_cell_to_face @ v

    np.testing.assert_equal(1.0, Fv)

    # 3D
    points, simplices = example_simplex_mesh((4, 4, 4))
    mesh = discretize.SimplexMesh(points, simplices)

    v = np.ones(len(mesh))

    Fv = mesh.average_cell_to_face @ v

    np.testing.assert_equal(1.0, Fv)


text:
#ifndef SVGInlineFlowBox_h
#define SVGInlineFlowBox_h

#include "core/rendering/InlineFlowBox.h"

namespace WebCore {

class RenderSVGInlineText;

class SVGInlineFlowBox FINAL : public InlineFlowBox {
public:
    SVGInlineFlowBox(RenderObject* obj)
        : InlineFlowBox(obj)
        , m_logicalHeight(0)
    {
    }

    virtual bool isSVGInlineFlowBox() const { return true; }
    virtual float virtualLogicalHeight() const { return m_logicalHeight; }
    void setLogicalHeight(float h) { m_logicalHeight = h; }

    void paintSelectionBackground(PaintInfo&);
    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom);

    virtual FloatRect calculateBoundaries() const;

    static void computeTextMatchMarkerRectForRenderer(RenderSVGInlineText*);

private:
    float m_logicalHeight;
};

inline SVGInlineFlowBox* toSVGInlineFlowBox(InlineBox* box)
{
    ASSERT_WITH_SECURITY_IMPLICATION(!box || box->isSVGInlineFlowBox());
    return static_cast<SVGInlineFlowBox*>(box);
}

} // namespace WebCore

#endif // SVGInlineFlowBox_h


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

import java.util.Iterator;
import java.util.List;
import net.sf.cglib.core.*;

class NoOpGenerator
implements CallbackGenerator
{
    public static final NoOpGenerator INSTANCE = new NoOpGenerator();

    public void generate(ClassEmitter ce, Context context, List methods) {
        for (Iterator it = methods.iterator(); it.hasNext();) {
            MethodInfo method = (MethodInfo)it.next();
            if (TypeUtils.isBridge(method.getModifiers()) || (
                    TypeUtils.isProtected(context.getOriginalModifiers(method)) &&
                    TypeUtils.isPublic(method.getModifiers()))) {
                CodeEmitter e = EmitUtils.begin_method(ce, method);
                e.load_this();
                e.load_args();
                context.emitInvoke(e, method);
                e.return_value();
                e.end_method();
            }
        }
    }

    public void generateStatic(CodeEmitter e, Context context, List methods) { }
}


text:
<?php

class CSVLog{
	public $handler;

	/**
	* init log
	*
	* @param $root String root folder for saving log
	* @param $date String string with date format yyyy-mm-dd for generating folder and file
	*/
	public function __construct($root, $date){
		$year = date('Y', strtotime($date));
		$month = date('F', strtotime($date));
		$day = date('d', strtotime($date));

		if(!is_dir($root . '/' . $year . '/' . $month)){
			mkdir($root . '/' . $year . '/' . $month, 0775, true);
		}

		$this->handler = fopen($root . '/' . $year . '/' . $month . '/' . $day . '.csv', 'a+');
	}

	/**
	* write data to csv file
	*
	* @param $data Array data to be written on csv
	*/
	public function write($data){
		fputcsv($this->handler, $data);
	}

	/**
	* close file
	*
	*/
	public function close(){
		fclose($this->handler);
	}
}


text:
				 ตั้งค่าสิทธิ์การใช้งาน

จัดการตั้งค่าสิทธิ์การใช้งาน

			 จัดการตั้งค่าสิทธิ์การใช้งาน

							 ข้อมูลผู้ใช้ระบบ

								 ชื่อ - นามสกุล

							{{ entryUserData.firstname }} {{ entryUserData.lastname }}

								 อีเมล์

							{{ entryUserData.email }}

								 หน่วยงาน

							{{ entryUserData.department_name }}

								 ตำแหน่ง

							{{ entryUserData.position }}

								 เบอร์โทรศัพท์

							{{ entryUserData.phone }}

								 เบอร์ติดต่อภายใน

							{{ entryUserData.local_phone }}

			<form name="permissionManageForm" novalidate data-ng-if="entryUserPermissionData.length != 0">

							เมนูหลัก
							เมนูย่อย
							ตั้งค่าสิทธิ์การใช้งาน

								รายงานการจองห้องประชุม

								{{ permissionItem.menu_sub_name }}

									<select class="form-control next-focus" required
										data-ng-model="entryUserPermissionData[$index].permission_status_id">
										<option value="" selected disabled>เลือกสิทธิ์การใช้งาน</option>
										<option data-ng-repeat="item in permissionStatusList"
											value="{{ item.permission_status_id }}">{{ item.permission_status_name }}</option>
									</select>

								เกี่ยวกับห้องประชุม

= 5">
								{{ permissionItem.menu_sub_name }}

									<select class="form-control next-focus" required
										data-ng-model="entryUserPermissionData[$index].permission_status_id">
										<option value="" selected disabled>เลือกสิทธิ์การใช้งาน</option>
										<option data-ng-repeat="item in permissionStatusList"
											value="{{ item.permission_status_id }}">{{ item.permission_status_name }}</option>
									</select>

								ผู้ใช้ระบบ

= 7">
								{{ permissionItem.menu_sub_name }}

									<select class="form-control next-focus" required
										data-ng-model="entryUserPermissionData[$index].permission_status_id">
										<option value="" selected disabled>เลือกสิทธิ์การใช้งาน</option>
										<option data-ng-repeat="item in permissionStatusList"
											value="{{ item.permission_status_id }}">{{ item.permission_status_name }}</option>
									</select>

					<button class="btn btn-warning next-focus" type="button"
						data-ng-show="userPermission[10].perm_status == 'ADMIN'"
						data-ng-disabled="permissionManageForm.$invalid"
						data-ng-click="updateUserPermission()">
						 บันทึกการเปลี่ยนแปลง
					</button>

			</form>


text:
from __future__ import unicode_literals
from decorators import on_command
from run_code import run_code

@on_command(['py2'])
def run(robot, channel, user, tokens):
    ''' Run Python2 script'''
    code = tokens[0]
    tokens[0] = '#!/usr/bin/env python2\n\n' + code
    return channel, run_code(tokens)


text:
Template.weddings.created = function () {
  this.autorun(function () {
    this.subscription = Meteor.subscribe('weddings');
  }.bind(this));
};

Template.weddings.rendered = function () {
  this.autorun(function () {
    if (!this.subscription.ready()) {
      IonLoading.show();
    } else {
      IonLoading.hide();
    }
  }.bind(this));
};

Template.weddings.helpers({
  weddings: function () {
    return Weddings.find({}, {sort: {createdAt: -1, name: -1}});
  }
});


text:
package glisp

func IsArray(expr Sexp) bool {
	switch expr.(type) {
	case SexpArray:
		return true
	}
	return false
}

func IsList(expr Sexp) bool {
	if expr == SexpNull {
		return true
	}
	switch list := expr.(type) {
	case SexpPair:
		return IsList(list.tail)
	}
	return false
}

func IsFloat(expr Sexp) bool {
	switch expr.(type) {
	case SexpFloat:
		return true
	}
	return false
}

func IsInt(expr Sexp) bool {
	switch expr.(type) {
	case SexpInt:
		return true
	}
	return false
}

func IsString(expr Sexp) bool {
	switch expr.(type) {
	case SexpStr:
		return true
	}
	return false
}

func IsChar(expr Sexp) bool {
	switch expr.(type) {
	case SexpChar:
		return true
	}
	return false
}

func IsNumber(expr Sexp) bool {
	switch expr.(type) {
	case SexpFloat:
		return true
	case SexpInt:
		return true
	case SexpChar:
		return true
	}
	return false
}

func IsSymbol(expr Sexp) bool {
	switch expr.(type) {
	case SexpSymbol:
		return true
	}
	return false
}

func IsHash(expr Sexp) bool {
	switch expr.(type) {
	case SexpHash:
		return true
	}
	return false
}

func IsZero(expr Sexp) bool {
	switch e := expr.(type) {
	case SexpInt:
		return int(e) == 0
	case SexpChar:
		return int(e) == 0
	case SexpFloat:
		return float64(e) == 0.0
	}
	return false
}

func IsEmpty(expr Sexp) bool {
	if expr == SexpNull {
		return true
	}

	switch e := expr.(type) {
	case SexpArray:
		return len(e) == 0
	case SexpHash:
		return HashIsEmpty(e)
	}

	return false
}


text:
local Prefs =
{
	XStyledMusicSelect =
	{
		Default = "Wide Style",
		Choices = { "X Style", "Wide Style" },
		Values = { "X Style", "Wide Style" }
	},
	XDifficultyList =
	{
		Default = "SN Style",
		Choices = { "X Style", "SN Style"},
		Values = { "X Style", "SN Style"}
	},
	EndlessLevel =
	{
		Default = 1,
		Choices = { "Lv. 1", "Lv. 2", "Lv. 3", "Lv. 4", "All", "Lv. 5" },
		Values = {1, 2, 3, 4, 5, 6}
	},
	JudgmentHeight =
	{
		Default = "Standard",
		Choices = {"Standard", "Old"},
		Values = {"Standard", "Old"}
	},
	MenuBG =
	{
		Default = "SuperNOVA 3",
		Choices = { "SuperNOVA", "SuperNOVA 2", "SuperNOVA 3", "SuperNOVA 3 v2", "IIDX SIRIUS" },
		Values = { "SuperNOVA", "SuperNOVA 2", "SuperNOVA 3", "SuperNOVA 3 v2", "IIDX SIRIUS" }
	},
	MenuMusic =
	{
		Default = "SuperNOVA 3",
		Choices = { "DDRMAX", "DDRMAX 2", "EXTREME", "SuperNOVA", "SuperNOVA 2", "SuperNOVA 3", "IIDX SIRIUS", "aston crowe", "dj vortivask" },
		Values = { "DDRMAX", "DDRMAX 2", "EXTREME", "SuperNOVA", "SuperNOVA 2", "SuperNOVA 3", "IIDX SIRIUS", "aston crowe", "dj vortivask" }
	},
	LightMode =
	{
		Default = false,
		Choices = {"No", "Yes"},
		Values = {false, true}
	},
	ComboColorMode =
	{
		Default = "arcade",
		Choices = {"Arcade Style", "Wii Style", "Waiei Style"},
		Values = {"arcade", "wii", "waiei"}
	},
	SpeedModSource =
	{
		Default = "internal",
		Choices = {"Standard", "From File", "SM5 Default"},
		Values = {"internal", "custom", "arbitrary"}
	},
	ConvertScoresAndGrades =
	{
		Default = false,
		Choices = {"No", "Yes"},
		Values = {false, true}
	},
}

ThemePrefs.InitAll(Prefs)

function ScreenGameplay_P1X()
	local st = GAMESTATE:GetCurrentStyle():GetStepsType();
	if st == "StepsType_Dance_Solo" then
		return SCREEN_CENTER_X;
	elseif st == "StepsType_Dance_Couple" then
		return WideScale(SCREEN_CENTER_X-175,SCREEN_CENTER_X-160);
	else
		return WideScale(SCREEN_CENTER_X-175,SCREEN_CENTER_X-240);
	end
end
function ScreenGameplay_P2X()
	local st = GAMESTATE:GetCurrentStyle():GetStepsType();
	if st == "StepsType_Dance_Solo" then
		return SCREEN_CENTER_X;
	elseif st == "StepsType_Dance_Couple" then
		return WideScale(SCREEN_CENTER_X+175,SCREEN_CENTER_X+160);
	else
		return WideScale(SCREEN_CENTER_X+175,SCREEN_CENTER_X+240);
	end
end

function OptionRowScreenFilter()
	--we use integers equivalent to the alpha value multiplied by 10
	--to work around float precision issues
	local choiceToAlpha = {0, 3, 6, 9}
	local alphaToChoice = {[0]=1, [3]=2, [6]=3, [9]=4}
	local t = {
		Name="Filter",
		LayoutType = "ShowAllInRow",
		SelectType = "SelectOne",
		OneChoiceForAllPlayers = false,
		ExportOnChange = true,
		Choices = { THEME:GetString('OptionNames','Off'),
			THEME:GetString('OptionTitles', 'FilterDark'),
			THEME:GetString('OptionTitles', 'FilterDarker'),
			THEME:GetString('OptionTitles', 'FilterDarkest'),
		 },
		LoadSelections = function(self, list, pn)
			local pName = ToEnumShortString(pn)
			local filterValue = getenv("ScreenFilter"..pName)

			if filterValue ~= nil then
				local val = alphaToChoice[filterValue] or 1
				list[val] = true
			else
				setenv("ScreenFilter"..pName,0)
				list[1] = true
			end
		end,
		SaveSelections = function(self, list, pn)
			local pName = ToEnumShortString(pn)
			local found = false
			for i=1,#list do
				if not found then
					if list[i] == true then
						setenv("ScreenFilter"..pName,choiceToAlpha[i])
						found = true
					end
				end
			end
		end,
	};
	setmetatable(t, t)
	return t
end
local judgmentTransformYs = {
	Standard={normal=-76, reverse=67},
	Old={normal=-30, reverse=30}
}
setmetatable(judgmentTransformYs, {__index=function(this, _) return this.Standard end})

function JudgmentTransformCommand( self, params )
	self:x( 0 )
	self:y( judgmentTransformYs
		[ThemePrefs.Get("JudgmentHeight")]
		[params.bReverse and "reverse" or "normal"] )
end

function PlayerOptionsLines()
	local fixedLines = "2,3,4,5,6,7,10,8,9,11,12,13"
	local speedLine = "1,"
	local modSetting = ThemePrefs.Get "SpeedModSource"
	if modSetting == "custom" then
		speedLine = "1C,"
	elseif modSetting == "arbitrary" then
		speedLine = "1A,"
	end
	return speedLine..fixedLines
end

do
	local function speed_str(name, ...)
		return THEME:GetString("OptionItemExplanations", "Speed"..name):format(...)
	end

	function GetSpeedExplanation(pn)
		local modSetting = ThemePrefs.Get "SpeedModSource"
		if modSetting == "custom" then
			return speed_str("Fallback")
		elseif modSetting == "internal" then
			return nil
		end

		local mmod, cmod, xmod
		local sc = (GAMESTATE:Env()).SpeedChoice

		if sc then
			local our_sc = sc[pn]
			local speed = our_sc.speed
			if our_sc.mode ~= 'x' then
				xmod = 1
				if our_sc.mode == 'm' then
					mmod = speed
					cmod = nil
				else
					cmod = speed
					mmod = nil
				end
			else
				xmod = our_sc.speed/100
				mmod = nil
				cmod = nil
			end
		else
			local po = GAMESTATE:GetPlayerState(pn):GetPlayerOptions('ModsLevel_Current')
			mmod = po:MMod()
			cmod = po:CMod()
			xmod = po:XMod()
		end

		if mmod then
			return speed_str('M', mmod)
		elseif cmod then
			return speed_str('C', cmod)
		else
			if xmod == 1 then
				return speed_str('1x')
			elseif xmod < 1 then
				return speed_str('Lowx',xmod*100)
			else
				local formatted_speed
				if math.floor(xmod) == xmod then
					formatted_speed = tostring(math.floor(xmod))
				elseif math.floor(xmod*10)/10 == xmod then
					formatted_speed = tostring(math.floor(xmod*10)/10)
				else
					formatted_speed = string.format(xmod, "%.2f")
				end
				return speed_str('Highx', formatted_speed)
			end
		end
		return nil
	end
end