package org.python.util;

import java.util.Properties;

import org.python.core.PySystemState;
import org.python.core.RegistryKey;

public class ProxyCompiler {

    /**
     * Compiles the python file by loading it
     *
     * FIXME: this is quite hackish right now. It basically starts a whole interpreter and sets
     * proxyDebugDirectory as the destination for the compiled proxy class
     *
     * @param filename python filename to exec
     * @param destDir destination directory for the proxy classes
     */
    public static void compile(String filename, String destDir) {
        Properties props = new Properties(System.getProperties());
        props.setProperty(RegistryKey.PYTHON_CACHEDIR_SKIP, "true");
        PySystemState.initialize(props, null);
        PythonInterpreter interp = new PythonInterpreter();

        String origProxyDir = org.python.core.Options.proxyDebugDirectory;
        try {
            org.python.core.Options.proxyDebugDirectory = destDir;
            interp.execfile(filename);
        } finally {
            org.python.core.Options.proxyDebugDirectory = origProxyDir;
        }
    }

}

{'repo_name': 'jython/frozen-mirror', 'stars': '539', 'repo_language': 'Python', 'file_name': 'test.xml', 'mime_type': 'text/plain', 'hash': -2097519895174891518, 'source_dataset': 'data'}


#import "EXPMatchers+endWith.h"

EXPMatcherImplementationBegin(endWith, (id expected)) {
  BOOL actualIsNil = (actual == nil);
  BOOL expectedIsNil = (expected == nil);
  //This condition allows the comparison of an immutable string or ordered collection to the mutable type of the same
  BOOL actualAndExpectedAreCompatible = (([actual isKindOfClass:[NSString class]] && [expected isKindOfClass:[NSString class]])
                                         || ([actual isKindOfClass:[NSArray class]] && [expected isKindOfClass:[NSArray class]])
                                         || ([actual isKindOfClass:[NSOrderedSet class]] && [expected isKindOfClass:[NSOrderedSet class]]));

  prerequisite(^BOOL {
    return actualAndExpectedAreCompatible;
  });

  match(^BOOL {
    if ([actual isKindOfClass:[NSString class]]) {
      return [actual hasSuffix:expected];
    } else if ([actual isKindOfClass:[NSArray class]]) {
      if ([expected count] > [actual count] || [expected count] == 0) {
        return NO;
      }
      NSArray *subArray = [actual subarrayWithRange:NSMakeRange([actual count] - [expected count], [expected count])];
      return [subArray isEqualToArray:expected];
    } else {
      if ([expected count] > [actual count] || [expected count] == 0) {
        return NO;
      }

      NSOrderedSet *subset = [NSOrderedSet orderedSetWithOrderedSet:actual range:NSMakeRange([actual count] - [expected count], [expected count]) copyItems:NO];
      return [subset isEqualToOrderedSet:expected];
    }
  });

  failureMessageForTo(^NSString *{
    if (actualIsNil) return @"the object is nil/null";
    if (expectedIsNil) return @"the expected value is nil/null";
    if (!actualAndExpectedAreCompatible) return [NSString stringWithFormat:@"%@ and %@ are not instances of one of %@, %@, or %@", EXPDescribeObject(actual), EXPDescribeObject(expected), [NSString class], [NSArray class], [NSOrderedSet class]];
    return [NSString stringWithFormat:@"expected: %@ to end with %@", EXPDescribeObject(actual), EXPDescribeObject(expected)];
  });

  failureMessageForNotTo(^NSString *{
    if (actualIsNil) return @"the object is nil/null";
    if (expectedIsNil) return @"the expected value is nil/null";
    if (!actualAndExpectedAreCompatible) return [NSString stringWithFormat:@"%@ and %@ are not instances of one of %@, %@, or %@", EXPDescribeObject(actual), EXPDescribeObject(expected), [NSString class], [NSArray class], [NSOrderedSet class]];

    return [NSString stringWithFormat:@"expected: %@ not to end with %@", EXPDescribeObject(actual), EXPDescribeObject(expected)];
  });
}
EXPMatcherImplementationEnd

{'repo_name': 'bfeher/BFPaperButton', 'stars': '856', 'repo_language': 'Objective-C', 'file_name': 'BFPaperButton.xccheckout', 'mime_type': 'text/xml', 'hash': -4071761320366603178, 'source_dataset': 'data'}


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInstance: {fileID: 0}
  m_PrefabAsset: {fileID: 0}
  m_GameObject: {fileID: 0}
  m_Enabled: 1
  m_EditorHideFlags: 0
  m_Script: {fileID: 11500000, guid: 9d1de2691495b304e9843ac3335b626d, type: 3}
  m_Name: uniform_plaid_purple_d
  m_EditorClassIdentifier:
  Variance:
  - Frames:
    - sprite: {fileID: 21300000, guid: 2f81117539d9f87478ec7f709a4b34a4, type: 3}
      secondDelay: 0
  - Frames:
    - sprite: {fileID: 21300002, guid: 2f81117539d9f87478ec7f709a4b34a4, type: 3}
      secondDelay: 0
  - Frames:
    - sprite: {fileID: 21300004, guid: 2f81117539d9f87478ec7f709a4b34a4, type: 3}
      secondDelay: 0
  - Frames:
    - sprite: {fileID: 21300006, guid: 2f81117539d9f87478ec7f709a4b34a4, type: 3}
      secondDelay: 0
  IsPalette: 0
  setID: 21650

{'repo_name': 'unitystation/unitystation', 'stars': '507', 'repo_language': 'C#', 'file_name': 'misc.meta', 'mime_type': 'text/plain', 'hash': -7113327025372899774, 'source_dataset': 'data'}


/*
 * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
 *
 * 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 com.hazelcast.internal.util;

import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class ThreadLocalRandomProviderTest extends HazelcastTestSupport {

    @Test
    public void testConstructor() {
        assertUtilityConstructor(ThreadLocalRandomProvider.class);
    }
}

{'repo_name': 'hazelcast/hazelcast', 'stars': '3823', 'repo_language': 'Java', 'file_name': 'ClassHeader.txt', 'mime_type': 'text/plain', 'hash': 918764491001815379, 'source_dataset': 'data'}


# #-- fwd_oneport.test --#
# source the master var file when it's there
[ -f ../.tpkg.var.master ] && source ../.tpkg.var.master
# use .tpkg.var.test for in test variable passing
[ -f .tpkg.var.test ] && source .tpkg.var.test

PRE="../.."
# do the test

# skip the single query test
# so that all three queries get timeouts during the later test.
#
#echo "> dig www1.example.com."
#dig @localhost -p $UNBOUND_PORT www1.example.com. | tee outfile
#echo "> cat logfiles"
#cat fwd.log
#cat unbound.log
#echo "> check answer for single query"
#if grep "10.20.30.40" outfile; then
	#echo "OK"
#else
	#echo "Not OK"
	#exit 1
#fi

echo "> do queries"
dig @localhost -p $UNBOUND_PORT www1.example.com. >outfile1 &
digpid1=$!
dig @localhost -p $UNBOUND_PORT www2.example.com. >outfile2 &
digpid2=$!
dig @localhost -p $UNBOUND_PORT www3.example.com. >outfile3 &
digpid3=$!
dig @localhost -p $UNBOUND_PORT www4.example.com. >outfile4 &
digpid4=$!
dig @localhost -p $UNBOUND_PORT www5.example.com. >outfile5 &
digpid5=$!
dig @localhost -p $UNBOUND_PORT www6.example.com. >outfile6 &
digpid6=$!
sleep 12
kill -9 $digpid1
kill -9 $digpid2
kill -9 $digpid3
kill -9 $digpid4
kill -9 $digpid5
kill -9 $digpid6

echo "> cat outfile1"
cat outfile1
echo "> cat outfile2"
cat outfile2
echo "> cat outfile3"
cat outfile3
echo "> cat outfile4"
cat outfile4
echo "> cat outfile5"
cat outfile5
echo "> cat outfile6"
cat outfile6
echo "> cat logfiles"
cat fwd.log
cat unbound.log

echo "> check for ID bit collisions"
grep "pending reply" unbound.log > ids
numsend=`cat ids | wc -l`
cat ids | awk '{print $8};' | sort -u > ids2
numuniq=`cat ids2 | wc -l`
if test $numuniq -ne $numsend; then
	echo "got a ID number clash. could not do test, sorry"
	exit 0
fi

echo "> check answers for queries"
if grep "10.20.30.40" outfile1; then
	echo "1 is OK"
else
	echo "1 is not OK"
	exit 1
fi
if grep "10.20.30.50" outfile2; then
	echo "2 is OK"
else
	echo "2 is not OK"
	exit 1
fi
if grep "10.20.30.60" outfile3; then
	echo "3 is OK"
else
	echo "3 is not OK"
	exit 1
fi
if grep "10.20.30.70" outfile4; then
	echo "4 is OK"
else
	echo "4 is not OK"
	exit 1
fi
if grep "10.20.30.80" outfile5; then
	echo "5 is OK"
else
	echo "5 is not OK"
	exit 1
fi
if grep "10.20.30.90" outfile6; then
	echo "6 is OK"
else
	echo "6 is not OK"
	exit 1
fi

exit 0

{'repo_name': 'sumoprojects/sumokoin', 'stars': '125', 'repo_language': 'C++', 'file_name': 'FindBacktrace.cmake', 'mime_type': 'text/plain', 'hash': 3341609652911857192, 'source_dataset': 'data'}


# frozen_string_literal: true

#
=begin
original source is
https://github.com/termtter/termtter/blob/master/lib/termtter/system_extensions/windows.rb

customed by whiteleaf

(The MIT License)

Copyright (c) 2008-2012 The Termtter Development Team

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=end

$hStdOut = WinAPI.GetStdHandle(0xFFFFFFF5)
lpBuffer = ' ' * 22
WinAPI.GetConsoleScreenBufferInfo($hStdOut, lpBuffer)
$oldColor = lpBuffer.unpack('SSSSSssssSS')[4]
$default_foreground = $oldColor & 0x0f
$default_background = $oldColor & 0xf0

$colorMap = {
   0 => 0x07|0x00|0x00|0x00, # black/white
   1 => 0x08               , # foreground_intensity
   4 => 0x8000             , # underline
   7 => 0x4000             , # reverse
  30 => 0x00|0x00|0x00|0x00, # black
  31 => 0x04|0x00|0x00|0x00, # red/red
  32 => 0x02|0x00|0x00|0x00, # green/green
  33 => 0x06|0x00|0x00|0x00, # yellow/yellow
  34 => 0x01|0x00|0x00|0x00, # blue/blue
  35 => 0x05|0x00|0x00|0x00, # magenta/purple
  36 => 0x03|0x00|0x00|0x00, # cyan/aqua
  37 => 0x07|0x00|0x00|0x00, # white/gray
  39 => $default_foreground, # default
  40 => 0x00|0x00|0x00|0x00, # background:black
  41 => 0x00|0x00|0x40|0x00, # background:red
  42 => 0x00|0x00|0x20|0x00, # background:green
  43 => 0x00|0x00|0x60|0x00, # background:yellow
  44 => 0x00|0x00|0x10|0x00, # background:blue
  45 => 0x00|0x00|0x50|0x00, # background:magenta
  46 => 0x00|0x00|0x30|0x00, # background:cyan
  47 => 0x00|0x00|0x70|0x00, # background:white
  49 => $default_background, # default
  90 => 0x07|0x00|0x00|0x00, # erase/white
}

def write_color(str, console = STDOUT)
  @decoration ||= 0
  @foreground ||= $default_foreground
  @background ||= $default_background
  @reverse ||= false
  str.gsub("\xef\xbd\x9e", "\xe3\x80\x9c").split(/(\e\[\d*[a-zA-Z])/).each do |token|
    case token
    when /\e\[(\d+)m/
      code = $1.to_i
      code = code > 90 ? (code % 60) : code
      case code
      when 0
        @decoration = 0
        @foreground = $default_foreground
        @background = $default_background
        @reverse = false
      when 1
        @decoration |= $colorMap[1]
      when 4
        @decoration |= $colorMap[4]
      when 7
        @reverse = true
      when 30..39
        @foreground = $colorMap[code].to_i
      when 40..49
        @background = $colorMap[code].to_i
      end
      foreground = @foreground
      background = @background
      if @reverse
        foreground <<= 4
        background >>= 4
        # reverse では intensity 情報も文字と背景で入れ替わるでの、
        # 下位4bitと上位4bitをスワップ
        @decoration = @decoration & 0xff00 | @decoration >> 4 & 0xf | (@decoration & 0xf) << 4
      end
      loop do
        error_code = WinAPI.SetConsoleTextAttribute $hStdOut, @decoration | foreground | background
        if error_code == 0
          if WinAPI.GetLastError == 6
            $hStdOut = WinAPI.GetStdHandle(0xFFFFFFF5)
            redo
          end
        end
        break
      end
    when /\e\[\d*[a-zA-Z]/, ""
      # do nothing
    else
      console.write token
    end
  end
  WinAPI.SetConsoleTextAttribute $hStdOut, $oldColor
end

{'repo_name': 'whiteleaf7/narou', 'stars': '224', 'repo_language': 'Ruby', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 4987384750601859539, 'source_dataset': 'data'}


<meta charset="UTF-8">
<title>CardValidCallback.Fields.Number - stripe</title>
<link rel="stylesheet" href="../../../../style.css">

stripe / com.stripe.android.view / CardValidCallback / Fields / Number

Number

Number

{'repo_name': 'stripe/stripe-android', 'stars': '664', 'repo_language': 'Kotlin', 'file_name': 'copy.html', 'mime_type': 'text/html', 'hash': 4330921264373993282, 'source_dataset': 'data'}


// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "quaternion_demo.h"
#include "icosphere.h"

#include <Eigen/Geometry>
#include <Eigen/QR>
#include <Eigen/LU>

#include <iostream>
#include <QEvent>
#include <QMouseEvent>
#include <QInputDialog>
#include <QGridLayout>
#include <QButtonGroup>
#include <QRadioButton>
#include <QDockWidget>
#include <QPushButton>
#include <QGroupBox>

using namespace Eigen;

class FancySpheres
{
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    FancySpheres()
    {
      const int levels = 4;
      const float scale = 0.33;
      float radius = 100;
      std::vector<int> parents;

      // leval 0
      mCenters.push_back(Vector3f::Zero());
      parents.push_back(-1);
      mRadii.push_back(radius);

      // generate level 1 using icosphere vertices
      radius *= 0.45;
      {
        float dist = mRadii[0]*0.9;
        for (int i=0; i<12; ++i)
        {
          mCenters.push_back(mIcoSphere.vertices()[i] * dist);
          mRadii.push_back(radius);
          parents.push_back(0);
        }
      }

      static const float angles [10] = {
        0, 0,
        M_PI, 0.*M_PI,
        M_PI, 0.5*M_PI,
        M_PI, 1.*M_PI,
        M_PI, 1.5*M_PI
      };

      // generate other levels
      int start = 1;
      for (int l=1; l<levels; l++)
      {
        radius *= scale;
        int end = mCenters.size();
        for (int i=start; i<end; ++i)
        {
          Vector3f c = mCenters[i];
          Vector3f ax0 = (c - mCenters[parents[i]]).normalized();
          Vector3f ax1 = ax0.unitOrthogonal();
          Quaternionf q;
          q.setFromTwoVectors(Vector3f::UnitZ(), ax0);
          Affine3f t = Translation3f(c) * q * Scaling(mRadii[i]+radius);
          for (int j=0; j<5; ++j)
          {
            Vector3f newC = c + ( (AngleAxisf(angles[j*2+1], ax0)
                                * AngleAxisf(angles[j*2+0] * (l==1 ? 0.35 : 0.5), ax1)) * ax0)
                                * (mRadii[i] + radius*0.8);
            mCenters.push_back(newC);
            mRadii.push_back(radius);
            parents.push_back(i);
          }
        }
        start = end;
      }
    }

    void draw()
    {
      int end = mCenters.size();
      glEnable(GL_NORMALIZE);
      for (int i=0; i<end; ++i)
      {
        Affine3f t = Translation3f(mCenters[i]) * Scaling(mRadii[i]);
        gpu.pushMatrix(GL_MODELVIEW);
        gpu.multMatrix(t.matrix(),GL_MODELVIEW);
        mIcoSphere.draw(2);
        gpu.popMatrix(GL_MODELVIEW);
      }
      glDisable(GL_NORMALIZE);
    }
  protected:
    std::vector<Vector3f> mCenters;
    std::vector<float> mRadii;
    IcoSphere mIcoSphere;
};

// generic linear interpolation method
template<typename T> T lerp(float t, const T& a, const T& b)
{
  return a*(1-t) + b*t;
}

// quaternion slerp
template<> Quaternionf lerp(float t, const Quaternionf& a, const Quaternionf& b)
{ return a.slerp(t,b); }

// linear interpolation of a frame using the type OrientationType
// to perform the interpolation of the orientations
template<typename OrientationType>
inline static Frame lerpFrame(float alpha, const Frame& a, const Frame& b)
{
  return Frame(lerp(alpha,a.position,b.position),
               Quaternionf(lerp(alpha,OrientationType(a.orientation),OrientationType(b.orientation))));
}

template<typename _Scalar> class EulerAngles
{
public:
  enum { Dim = 3 };
  typedef _Scalar Scalar;
  typedef Matrix<Scalar,3,3> Matrix3;
  typedef Matrix<Scalar,3,1> Vector3;
  typedef Quaternion<Scalar> QuaternionType;

protected:

  Vector3 m_angles;

public:

  EulerAngles() {}
  inline EulerAngles(Scalar a0, Scalar a1, Scalar a2) : m_angles(a0, a1, a2) {}
  inline EulerAngles(const QuaternionType& q) { *this = q; }

  const Vector3& coeffs() const { return m_angles; }
  Vector3& coeffs() { return m_angles; }

  EulerAngles& operator=(const QuaternionType& q)
  {
    Matrix3 m = q.toRotationMatrix();
    return *this = m;
  }

  EulerAngles& operator=(const Matrix3& m)
  {
    // mat =  cy*cz          -cy*sz           sy
    //        cz*sx*sy+cx*sz  cx*cz-sx*sy*sz -cy*sx
    //       -cx*cz*sy+sx*sz  cz*sx+cx*sy*sz  cx*cy
    m_angles.coeffRef(1) = std::asin(m.coeff(0,2));
    m_angles.coeffRef(0) = std::atan2(-m.coeff(1,2),m.coeff(2,2));
    m_angles.coeffRef(2) = std::atan2(-m.coeff(0,1),m.coeff(0,0));
    return *this;
  }

  Matrix3 toRotationMatrix(void) const
  {
    Vector3 c = m_angles.array().cos();
    Vector3 s = m_angles.array().sin();
    Matrix3 res;
    res <<  c.y()*c.z(),                    -c.y()*s.z(),                   s.y(),
            c.z()*s.x()*s.y()+c.x()*s.z(),  c.x()*c.z()-s.x()*s.y()*s.z(),  -c.y()*s.x(),
            -c.x()*c.z()*s.y()+s.x()*s.z(), c.z()*s.x()+c.x()*s.y()*s.z(),  c.x()*c.y();
    return res;
  }

  operator QuaternionType() { return QuaternionType(toRotationMatrix()); }
};

// Euler angles slerp
template<> EulerAngles<float> lerp(float t, const EulerAngles<float>& a, const EulerAngles<float>& b)
{
  EulerAngles<float> res;
  res.coeffs() = lerp(t, a.coeffs(), b.coeffs());
  return res;
}

RenderingWidget::RenderingWidget()
{
  mAnimate = false;
  mCurrentTrackingMode = TM_NO_TRACK;
  mNavMode = NavTurnAround;
  mLerpMode = LerpQuaternion;
  mRotationMode = RotationStable;
  mTrackball.setCamera(&mCamera);

  // required to capture key press events
  setFocusPolicy(Qt::ClickFocus);
}

void RenderingWidget::grabFrame(void)
{
    // ask user for a time
    bool ok = false;
    double t = 0;
    if (!m_timeline.empty())
      t = (--m_timeline.end())->first + 1.;
    t = QInputDialog::getDouble(this, "Eigen's RenderingWidget", "time value: ",
      t, 0, 1e3, 1, &ok);
    if (ok)
    {
      Frame aux;
      aux.orientation = mCamera.viewMatrix().linear();
      aux.position = mCamera.viewMatrix().translation();
      m_timeline[t] = aux;
    }
}

void RenderingWidget::drawScene()
{
  static FancySpheres sFancySpheres;
  float length = 50;
  gpu.drawVector(Vector3f::Zero(), length*Vector3f::UnitX(), Color(1,0,0,1));
  gpu.drawVector(Vector3f::Zero(), length*Vector3f::UnitY(), Color(0,1,0,1));
  gpu.drawVector(Vector3f::Zero(), length*Vector3f::UnitZ(), Color(0,0,1,1));

  // draw the fractal object
  float sqrt3 = std::sqrt(3.);
  glLightfv(GL_LIGHT0, GL_AMBIENT, Vector4f(0.5,0.5,0.5,1).data());
  glLightfv(GL_LIGHT0, GL_DIFFUSE, Vector4f(0.5,1,0.5,1).data());
  glLightfv(GL_LIGHT0, GL_SPECULAR, Vector4f(1,1,1,1).data());
  glLightfv(GL_LIGHT0, GL_POSITION, Vector4f(-sqrt3,-sqrt3,sqrt3,0).data());

  glLightfv(GL_LIGHT1, GL_AMBIENT, Vector4f(0,0,0,1).data());
  glLightfv(GL_LIGHT1, GL_DIFFUSE, Vector4f(1,0.5,0.5,1).data());
  glLightfv(GL_LIGHT1, GL_SPECULAR, Vector4f(1,1,1,1).data());
  glLightfv(GL_LIGHT1, GL_POSITION, Vector4f(-sqrt3,sqrt3,-sqrt3,0).data());

  glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, Vector4f(0.7, 0.7, 0.7, 1).data());
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, Vector4f(0.8, 0.75, 0.6, 1).data());
  glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Vector4f(1, 1, 1, 1).data());
  glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 64);

  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);
  glEnable(GL_LIGHT1);

  sFancySpheres.draw();
  glVertexPointer(3, GL_FLOAT, 0, mVertices[0].data());
  glNormalPointer(GL_FLOAT, 0, mNormals[0].data());
  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_NORMAL_ARRAY);
  glDrawArrays(GL_TRIANGLES, 0, mVertices.size());
  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_NORMAL_ARRAY);

  glDisable(GL_LIGHTING);
}

void RenderingWidget::animate()
{
  m_alpha += double(m_timer.interval()) * 1e-3;

  TimeLine::const_iterator hi = m_timeline.upper_bound(m_alpha);
  TimeLine::const_iterator lo = hi;
  --lo;

  Frame currentFrame;

  if(hi==m_timeline.end())
  {
    // end
    currentFrame = lo->second;
    stopAnimation();
  }
  else if(hi==m_timeline.begin())
  {
    // start
    currentFrame = hi->second;
  }
  else
  {
    float s = (m_alpha - lo->first)/(hi->first - lo->first);
    if (mLerpMode==LerpEulerAngles)
      currentFrame = ::lerpFrame<EulerAngles<float> >(s, lo->second, hi->second);
    else if (mLerpMode==LerpQuaternion)
      currentFrame = ::lerpFrame<Eigen::Quaternionf>(s, lo->second, hi->second);
    else
    {
      std::cerr << "Invalid rotation interpolation mode (abort)\n";
      exit(2);
    }
    currentFrame.orientation.coeffs().normalize();
  }

  currentFrame.orientation = currentFrame.orientation.inverse();
  currentFrame.position = - (currentFrame.orientation * currentFrame.position);
  mCamera.setFrame(currentFrame);

  updateGL();
}

void RenderingWidget::keyPressEvent(QKeyEvent * e)
{
    switch(e->key())
    {
      case Qt::Key_Up:
        mCamera.zoom(2);
        break;
      case Qt::Key_Down:
        mCamera.zoom(-2);
        break;
      // add a frame
      case Qt::Key_G:
        grabFrame();
        break;
      // clear the time line
      case Qt::Key_C:
        m_timeline.clear();
        break;
      // move the camera to initial pos
      case Qt::Key_R:
        resetCamera();
        break;
      // start/stop the animation
      case Qt::Key_A:
        if (mAnimate)
        {
          stopAnimation();
        }
        else
        {
          m_alpha = 0;
          connect(&m_timer, SIGNAL(timeout()), this, SLOT(animate()));
          m_timer.start(1000/30);
          mAnimate = true;
        }
        break;
      default:
        break;
    }

    updateGL();
}

void RenderingWidget::stopAnimation()
{
  disconnect(&m_timer, SIGNAL(timeout()), this, SLOT(animate()));
  m_timer.stop();
  mAnimate = false;
  m_alpha = 0;
}

void RenderingWidget::mousePressEvent(QMouseEvent* e)
{
  mMouseCoords = Vector2i(e->pos().x(), e->pos().y());
  bool fly = (mNavMode==NavFly) || (e->modifiers()&Qt::ControlModifier);
  switch(e->button())
  {
    case Qt::LeftButton:
      if(fly)
      {
        mCurrentTrackingMode = TM_LOCAL_ROTATE;
        mTrackball.start(Trackball::Local);
      }
      else
      {
        mCurrentTrackingMode = TM_ROTATE_AROUND;
        mTrackball.start(Trackball::Around);
      }
      mTrackball.track(mMouseCoords);
      break;
    case Qt::MidButton:
      if(fly)
        mCurrentTrackingMode = TM_FLY_Z;
      else
        mCurrentTrackingMode = TM_ZOOM;
      break;
    case Qt::RightButton:
        mCurrentTrackingMode = TM_FLY_PAN;
      break;
    default:
      break;
  }
}
void RenderingWidget::mouseReleaseEvent(QMouseEvent*)
{
    mCurrentTrackingMode = TM_NO_TRACK;
    updateGL();
}

void RenderingWidget::mouseMoveEvent(QMouseEvent* e)
{
    // tracking
    if(mCurrentTrackingMode != TM_NO_TRACK)
    {
        float dx =   float(e->x() - mMouseCoords.x()) / float(mCamera.vpWidth());
        float dy = - float(e->y() - mMouseCoords.y()) / float(mCamera.vpHeight());

        // speedup the transformations
        if(e->modifiers() & Qt::ShiftModifier)
        {
          dx *= 10.;
          dy *= 10.;
        }

        switch(mCurrentTrackingMode)
        {
          case TM_ROTATE_AROUND:
          case TM_LOCAL_ROTATE:
            if (mRotationMode==RotationStable)
            {
              // use the stable trackball implementation mapping
              // the 2D coordinates to 3D points on a sphere.
              mTrackball.track(Vector2i(e->pos().x(), e->pos().y()));
            }
            else
            {
              // standard approach mapping the x and y displacements as rotations
              // around the camera's X and Y axes.
              Quaternionf q = AngleAxisf( dx*M_PI, Vector3f::UnitY())
                            * AngleAxisf(-dy*M_PI, Vector3f::UnitX());
              if (mCurrentTrackingMode==TM_LOCAL_ROTATE)
                mCamera.localRotate(q);
              else
                mCamera.rotateAroundTarget(q);
            }
            break;
          case TM_ZOOM :
            mCamera.zoom(dy*100);
            break;
          case TM_FLY_Z :
            mCamera.localTranslate(Vector3f(0, 0, -dy*200));
            break;
          case TM_FLY_PAN :
            mCamera.localTranslate(Vector3f(dx*200, dy*200, 0));
            break;
          default:
            break;
        }

        updateGL();
    }

    mMouseCoords = Vector2i(e->pos().x(), e->pos().y());
}

void RenderingWidget::paintGL()
{
  glEnable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
  glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
  glDisable(GL_COLOR_MATERIAL);
  glDisable(GL_BLEND);
  glDisable(GL_ALPHA_TEST);
  glDisable(GL_TEXTURE_1D);
  glDisable(GL_TEXTURE_2D);
  glDisable(GL_TEXTURE_3D);

  // Clear buffers
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  mCamera.activateGL();

  drawScene();
}

void RenderingWidget::initializeGL()
{
  glClearColor(1., 1., 1., 0.);
  glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  glDepthMask(GL_TRUE);
  glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

  mCamera.setPosition(Vector3f(-200, -200, -200));
  mCamera.setTarget(Vector3f(0, 0, 0));
  mInitFrame.orientation = mCamera.orientation().inverse();
  mInitFrame.position = mCamera.viewMatrix().translation();
}

void RenderingWidget::resizeGL(int width, int height)
{
    mCamera.setViewport(width,height);
}

void RenderingWidget::setNavMode(int m)
{
  mNavMode = NavMode(m);
}

void RenderingWidget::setLerpMode(int m)
{
  mLerpMode = LerpMode(m);
}

void RenderingWidget::setRotationMode(int m)
{
  mRotationMode = RotationMode(m);
}

void RenderingWidget::resetCamera()
{
  if (mAnimate)
    stopAnimation();
  m_timeline.clear();
  Frame aux0 = mCamera.frame();
  aux0.orientation = aux0.orientation.inverse();
  aux0.position = mCamera.viewMatrix().translation();
  m_timeline[0] = aux0;

  Vector3f currentTarget = mCamera.target();
  mCamera.setTarget(Vector3f::Zero());

  // compute the rotation duration to move the camera to the target
  Frame aux1 = mCamera.frame();
  aux1.orientation = aux1.orientation.inverse();
  aux1.position = mCamera.viewMatrix().translation();
  float duration = aux0.orientation.angularDistance(aux1.orientation) * 0.9;
  if (duration<0.1) duration = 0.1;

  // put the camera at that time step:
  aux1 = aux0.lerp(duration/2,mInitFrame);
  // and make it look at the target again
  aux1.orientation = aux1.orientation.inverse();
  aux1.position = - (aux1.orientation * aux1.position);
  mCamera.setFrame(aux1);
  mCamera.setTarget(Vector3f::Zero());

  // add this camera keyframe
  aux1.orientation = aux1.orientation.inverse();
  aux1.position = mCamera.viewMatrix().translation();
  m_timeline[duration] = aux1;

  m_timeline[2] = mInitFrame;
  m_alpha = 0;
  animate();
  connect(&m_timer, SIGNAL(timeout()), this, SLOT(animate()));
  m_timer.start(1000/30);
  mAnimate = true;
}

QWidget* RenderingWidget::createNavigationControlWidget()
{
  QWidget* panel = new QWidget();
  QVBoxLayout* layout = new QVBoxLayout();

  {
    QPushButton* but = new QPushButton("reset");
    but->setToolTip("move the camera to initial position (with animation)");
    layout->addWidget(but);
    connect(but, SIGNAL(clicked()), this, SLOT(resetCamera()));
  }
  {
    // navigation mode
    QGroupBox* box = new QGroupBox("navigation mode");
    QVBoxLayout* boxLayout = new QVBoxLayout;
    QButtonGroup* group = new QButtonGroup(panel);
    QRadioButton* but;
    but = new QRadioButton("turn around");
    but->setToolTip("look around an object");
    group->addButton(but, NavTurnAround);
    boxLayout->addWidget(but);
    but = new QRadioButton("fly");
    but->setToolTip("free navigation like a spaceship\n(this mode can also be enabled pressing the \"shift\" key)");
    group->addButton(but, NavFly);
    boxLayout->addWidget(but);
    group->button(mNavMode)->setChecked(true);
    connect(group, SIGNAL(buttonClicked(int)), this, SLOT(setNavMode(int)));
    box->setLayout(boxLayout);
    layout->addWidget(box);
  }
  {
    // track ball, rotation mode
    QGroupBox* box = new QGroupBox("rotation mode");
    QVBoxLayout* boxLayout = new QVBoxLayout;
    QButtonGroup* group = new QButtonGroup(panel);
    QRadioButton* but;
    but = new QRadioButton("stable trackball");
    group->addButton(but, RotationStable);
    boxLayout->addWidget(but);
    but->setToolTip("use the stable trackball implementation mapping\nthe 2D coordinates to 3D points on a sphere");
    but = new QRadioButton("standard rotation");
    group->addButton(but, RotationStandard);
    boxLayout->addWidget(but);
    but->setToolTip("standard approach mapping the x and y displacements\nas rotations around the camera's X and Y axes");
    group->button(mRotationMode)->setChecked(true);
    connect(group, SIGNAL(buttonClicked(int)), this, SLOT(setRotationMode(int)));
    box->setLayout(boxLayout);
    layout->addWidget(box);
  }
  {
    // interpolation mode
    QGroupBox* box = new QGroupBox("spherical interpolation");
    QVBoxLayout* boxLayout = new QVBoxLayout;
    QButtonGroup* group = new QButtonGroup(panel);
    QRadioButton* but;
    but = new QRadioButton("quaternion slerp");
    group->addButton(but, LerpQuaternion);
    boxLayout->addWidget(but);
    but->setToolTip("use quaternion spherical interpolation\nto interpolate orientations");
    but = new QRadioButton("euler angles");
    group->addButton(but, LerpEulerAngles);
    boxLayout->addWidget(but);
    but->setToolTip("use Euler angles to interpolate orientations");
    group->button(mNavMode)->setChecked(true);
    connect(group, SIGNAL(buttonClicked(int)), this, SLOT(setLerpMode(int)));
    box->setLayout(boxLayout);
    layout->addWidget(box);
  }
  layout->addItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding));
  panel->setLayout(layout);
  return panel;
}

QuaternionDemo::QuaternionDemo()
{
  mRenderingWidget = new RenderingWidget();
  setCentralWidget(mRenderingWidget);

  QDockWidget* panel = new QDockWidget("navigation", this);
  panel->setAllowedAreas((QFlags<Qt::DockWidgetArea>)(Qt::RightDockWidgetArea | Qt::LeftDockWidgetArea));
  addDockWidget(Qt::RightDockWidgetArea, panel);
  panel->setWidget(mRenderingWidget->createNavigationControlWidget());
}

int main(int argc, char *argv[])
{
  std::cout << "Navigation:\n";
  std::cout << "  left button:           rotate around the target\n";
  std::cout << "  middle button:         zoom\n";
  std::cout << "  left button + ctrl     quake rotate (rotate around camera position)\n";
  std::cout << "  middle button + ctrl   walk (progress along camera's z direction)\n";
  std::cout << "  left button:           pan (translate in the XY camera's plane)\n\n";
  std::cout << "R : move the camera to initial position\n";
  std::cout << "A : start/stop animation\n";
  std::cout << "C : clear the animation\n";
  std::cout << "G : add a key frame\n";

  QApplication app(argc, argv);
  QuaternionDemo demo;
  demo.resize(600,500);
  demo.show();
  return app.exec();
}

#include "quaternion_demo.moc"

{'repo_name': 'biometrics/openbr', 'stars': '2620', 'repo_language': 'C++', 'file_name': 'BioID.xml', 'mime_type': 'text/xml', 'hash': -3686547929427532844, 'source_dataset': 'data'}


#ifndef _Demo_LocalCubemapsManualProbesGameState_H_
#define _Demo_LocalCubemapsManualProbesGameState_H_

#include "OgrePrerequisites.h"
#include "TutorialGameState.h"

namespace Ogre
{
    class ParallaxCorrectedCubemap;
    class ParallaxCorrectedCubemapAuto;
    class ParallaxCorrectedCubemapBase;
    class HlmsPbsDatablock;
}

namespace Demo
{
    class LocalCubemapsManualProbesGameState : public TutorialGameState
    {
        Ogre::SceneNode     *mLightNodes[3];

        Ogre::ParallaxCorrectedCubemapBase  *mParallaxCorrectedCubemap;
        Ogre::ParallaxCorrectedCubemapAuto  *mParallaxCorrectedCubemapAuto;
        Ogre::ParallaxCorrectedCubemap      *mParallaxCorrectedCubemapOrig;
        Ogre::HlmsPbsDatablock          *mMaterials[4*4];
        bool                            mPerPixelReflections;
        /// True if we were using manual probes before mPerPixelReflections became true
        bool                            mWasManualProbe;

        virtual void generateDebugText( float timeSinceLast, Ogre::String &outText );

        void setupParallaxCorrectCubemaps(void);

    public:
        LocalCubemapsManualProbesGameState( const Ogre::String &helpDescription );

        virtual void createScene01(void);
        virtual void destroyScene(void);

        virtual void update( float timeSinceLast );

        virtual void keyReleased( const SDL_KeyboardEvent &arg );
    };
}

#endif

{'repo_name': 'OGRECave/ogre-next', 'stars': '278', 'repo_language': 'C++', 'file_name': 'UniqueModel.MESH.material', 'mime_type': 'text/plain', 'hash': 8015280523471127483, 'source_dataset': 'data'}