repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Linuxbrew/homebrew-core | Formula/pdf2svg.rb | 1165 | class Pdf2svg < Formula
desc "PDF converter to SVG"
homepage "https://cityinthesky.co.uk/opensource/pdf2svg"
url "https://github.com/db9052/pdf2svg/archive/v0.2.3.tar.gz"
sha256 "4fb186070b3e7d33a51821e3307dce57300a062570d028feccd4e628d50dea8a"
license "GPL-2.0"
revision 6
bottle do
sha256 cellar: :any, arm64_big_sur: "dc5018cf8ccb7b474fe5c575d562c59e361c3c251ce88d9e36b7636d1f77ef3b"
sha256 cellar: :any, big_sur: "3a8d825e70e419c4f7cc783d472eec8cd384764c351c131780c2a0b691cda24d"
sha256 cellar: :any, catalina: "a2af2e44c752994638edbd3aa7684290d116d20f1da2fe3e4490527be5b23bac"
sha256 cellar: :any, mojave: "b0cf8046c13335a16496cc5601af7a82f14b45c866cf9f3ae9072075ccc867fe"
sha256 cellar: :any, x86_64_linux: "98a0e701b595abda653f23e02b7247c858b3ad8290ae70d4c562a1aa6f247e8f"
end
depends_on "pkg-config" => :build
depends_on "cairo"
depends_on "poppler"
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
system "#{bin}/pdf2svg", test_fixtures("test.pdf"), "test.svg"
end
end
| bsd-2-clause |
praekelt/mc2 | mc2/controllers/base/tests/base.py | 4651 | import json
import responses
from django.test import TransactionTestCase
from django.conf import settings
from mc2.controllers.base.models import Controller, EnvVariable, MarathonLabel
class ControllerBaseTestCase(TransactionTestCase):
def mk_controller(self, controller={}):
controller_defaults = {
'owner': getattr(self, 'user', None),
'name': 'Test App',
'marathon_cmd': 'ping'
}
controller_defaults.update(controller)
return Controller.objects.create(**controller_defaults)
def mk_labels_variable(self, controller, **env):
env_defaults = {
'controller': controller,
'name': 'TEST_LABELS_NAME',
'value': 'a test label value'
}
env_defaults.update(env)
return MarathonLabel.objects.create(**env_defaults)
def mk_env_variable(self, controller, **env):
env_defaults = {
'controller': controller,
'key': 'TEST_KEY',
'value': 'a test value'
}
env_defaults.update(env)
return EnvVariable.objects.create(**env_defaults)
def mock_create_marathon_app(self, status=201):
responses.add(
responses.POST, '%s/v2/apps' % settings.MESOS_MARATHON_HOST,
body=json.dumps({}),
content_type="application/json",
status=status)
def mock_create_postgres_db(self, status=200, data={}):
responses.add(
responses.POST, '%s/queues/postgres/wait/create_database'
% settings.SEED_XYLEM_API_HOST,
body=json.dumps(data),
content_type="application/json",
status=status)
def mock_update_marathon_app(self, app_id, status=200):
responses.add(
responses.PUT, '%s/v2/apps/%s' % (
settings.MESOS_MARATHON_HOST, app_id),
body=json.dumps({}),
content_type="application/json",
status=status)
def mock_restart_marathon_app(self, app_id, status=200):
responses.add(
responses.POST, '%s/v2/apps/%s/restart' % (
settings.MESOS_MARATHON_HOST, app_id),
body=json.dumps({}),
content_type="application/json",
status=status)
def mock_delete_marathon_app(self, app_id, status=200):
responses.add(
responses.DELETE, '%s/v2/apps/%s' % (
settings.MESOS_MARATHON_HOST, app_id),
body=json.dumps({}),
content_type="application/json",
status=status)
def mock_exists_on_marathon(self, app_id, status=200):
responses.add(
responses.GET, '%s/v2/apps/%s' % (
settings.MESOS_MARATHON_HOST, app_id),
body=json.dumps({}),
content_type="application/json",
status=status)
def mock_get_vhost(self, vhost_name, status=200):
responses.add(
responses.GET, '%s/vhosts/%s' % (
settings.RABBITMQ_API_HOST, vhost_name),
body=json.dumps({'name': vhost_name}),
content_type="application/json",
status=status)
def mock_put_vhost(self, vhost_name, status=204):
responses.add(
responses.PUT, '%s/vhosts/%s' % (
settings.RABBITMQ_API_HOST, vhost_name),
body=json.dumps({}),
content_type="application/json",
status=status)
def mock_get_user(self, name, status=200):
responses.add(
responses.GET, '%s/users/%s' % (
settings.RABBITMQ_API_HOST, name),
body=json.dumps({'name': name}),
content_type="application/json",
status=status)
def mock_put_user(self, name, status=200):
responses.add(
responses.PUT, '%s/users/%s' % (
settings.RABBITMQ_API_HOST, name),
body=json.dumps({}),
content_type="application/json",
status=status)
def mock_put_vhost_permissions(self, vhost, username, status=200):
responses.add(
responses.PUT, '%s/permissions/%s/%s' % (
settings.RABBITMQ_API_HOST, vhost, username),
body=json.dumps({}),
content_type="application/json",
status=status)
def mock_successful_new_vhost(self, vhost_name, vhost_user):
self.mock_get_vhost(vhost_name, status=404)
self.mock_put_vhost(vhost_name)
self.mock_get_user(vhost_user, status=404)
self.mock_put_user(vhost_user)
self.mock_put_vhost_permissions(vhost_name, vhost_user)
| bsd-2-clause |
KosherBacon/homebrew-cask | Casks/gitkraken.rb | 892 | cask 'gitkraken' do
version '2.4.0'
sha256 '1afe9a5071aeb477a2e299e2e58c84a51f729884d629fa1962c56ce9faf45e6a'
url "https://release.gitkraken.com/darwin/v#{version}.zip"
appcast 'https://release.gitkraken.com/darwin/RELEASES',
checkpoint: '84bf3052b449f63c13e95dbec666dbdd53dad08137aff7bfb45119b93075c9cb'
name 'GitKraken'
homepage 'https://www.gitkraken.com/'
auto_updates true
app 'GitKraken.app'
zap delete: [
'~/Library/Application Support/com.axosoft.gitkraken.ShipIt',
'~/Library/Application Support/GitKraken',
'~/Library/Caches/GitKraken',
'~/Library/Caches/com.axosoft.gitkraken',
'~/Library/Preferences/com.axosoft.gitkraken.plist',
'~/Library/Saved Application State/com.axosoft.gitkraken.savedState',
'~/.gitkraken',
]
end
| bsd-2-clause |
ahamez/pnmc | support/pn/place.cc | 1270 | /// @file
/// @copyright The code is licensed under the BSD License
/// <http://opensource.org/licenses/BSD-2-Clause>,
/// Copyright (c) 2013-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#include <ostream>
#include "support/pn/place.hh"
namespace pnmc { namespace pn {
/*------------------------------------------------------------------------------------------------*/
place::place(std::size_t id, std::string n, valuation_type m)
: uid{id}, name{std::move(n)}, marking{m}, pre{}, post{}
{}
/*------------------------------------------------------------------------------------------------*/
bool
place::connected()
const noexcept
{
return not(pre.empty() and post.empty());
}
/*------------------------------------------------------------------------------------------------*/
bool
operator<(const pn::place& lhs, const pn::place& rhs)
noexcept
{
return lhs.uid < rhs.uid;
}
/*------------------------------------------------------------------------------------------------*/
std::ostream&
operator<<(std::ostream& os, const pn::place& p)
{
return os << "pl " << p.name << " (" << p.marking << ")";
}
/*------------------------------------------------------------------------------------------------*/
}} // pnmc::pn
| bsd-2-clause |
jacoblusk/SAEA-HTTPD | SAEA-HTTPD/HttpServer.cs | 9744 | using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ServiceModel.Channels;
using System.Timers;
using log4net;
namespace SAEAHTTPD {
public class HttpServer {
private readonly List<SocketAsyncEventArgs> connections = new List<SocketAsyncEventArgs>();
private readonly ConcurrentStack<SocketAsyncEventArgs> readWritePool = new ConcurrentStack<SocketAsyncEventArgs> ();
private readonly ConcurrentStack<SocketAsyncEventArgs> acceptPool = new ConcurrentStack<SocketAsyncEventArgs> ();
private bool running = true;
private int maxAccept, maxConnections, bufferSize;
private const int Timeout = 10 * 1000;
private readonly Semaphore enforceMaxClients;
private readonly Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private readonly BufferManager bufferManager;
private System.Timers.Timer timeoutTimer;
private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public delegate void HttpRequestHandler(object sender, HttpRequestArgs e);
public event HttpRequestHandler OnHttpRequest;
public HttpServer (int maxAccept, int maxConnections, int bufferSize) {
timeoutTimer = new System.Timers.Timer(Timeout);
timeoutTimer.Elapsed += timeoutTimer_Elapsed;
this.maxAccept = maxAccept;
this.maxConnections = maxConnections;
this.bufferSize = bufferSize;
this.enforceMaxClients = new Semaphore (maxConnections, maxConnections);
this.bufferManager = BufferManager.CreateBufferManager (maxConnections, maxConnections * bufferSize * 2);
for (int i = 0; i < maxAccept; i++) {
var acceptArgs = new SocketAsyncEventArgs ();
acceptArgs.Completed += HandleAcceptCompleted;
this.acceptPool.Push (acceptArgs);
}
for (int i = 0; i < maxConnections; i++) {
var readWriteArgs = new SocketAsyncEventArgs ();
var client = new HttpClient ();
readWriteArgs.UserToken = client;
readWriteArgs.SetBuffer (this.bufferManager.TakeBuffer (bufferSize), 0, bufferSize);
readWriteArgs.Completed += HandleReadWriteCompleted;
this.readWritePool.Push (readWriteArgs);
}
timeoutTimer.Start();
}
void timeoutTimer_Elapsed(object sender, ElapsedEventArgs e) {
lock (this.connections) {
List<SocketAsyncEventArgs> removed = new List<SocketAsyncEventArgs>();
foreach (SocketAsyncEventArgs conn in connections) {
var client = conn.UserToken as HttpClient;
int remaining = Environment.TickCount - client.LastActive;
log.Debug(string.Format("Remaining time for {0} is {1}", client.Socket.RemoteEndPoint, remaining));
if (remaining > Timeout) {
removed.Add(conn);
}
}
foreach (SocketAsyncEventArgs conn in removed) {
CloseSocket(conn);
}
}
}
void client_OnFinishedRequest(object sender, HttpRequestArgs args) {
if (OnHttpRequest != null) {
OnHttpRequest(this, args);
}
}
public void Start(IPEndPoint local) {
this.listener.Bind (local);
this.listener.Listen (this.maxAccept);
SocketAsyncEventArgs acceptArgs;
while (this.running) {
if (acceptPool.TryPop(out acceptArgs)) {
if (!this.listener.AcceptAsync(acceptArgs)) {
HandleAccept(acceptArgs);
}
}
this.enforceMaxClients.WaitOne();
}
}
public void Stop(bool force) {
this.running = false;
}
private void HandleAccept(SocketAsyncEventArgs acceptArgs) {
log.Debug(string.Format("Accept, {0}", acceptArgs.AcceptSocket.RemoteEndPoint));
if (acceptArgs.SocketError != SocketError.Success) {
acceptArgs.AcceptSocket.Close ();
} else {
SocketAsyncEventArgs readWriteArgs;
if (this.readWritePool.TryPop (out readWriteArgs)) {
var client = (HttpClient)readWriteArgs.UserToken;
client.Socket = acceptArgs.AcceptSocket;
client.LastActive = Environment.TickCount;
readWriteArgs.AcceptSocket = acceptArgs.AcceptSocket;
acceptArgs.AcceptSocket = null;
lock (this.connections) {
this.connections.Add(readWriteArgs);
}
if (!client.Socket.ReceiveAsync (readWriteArgs)) {
HandleReadWrite (readWriteArgs);
}
}
}
this.acceptPool.Push (acceptArgs);
}
private void HandleReadWrite(SocketAsyncEventArgs readWriteArgs) {
var client = (HttpClient)readWriteArgs.UserToken;
if (readWriteArgs.SocketError != SocketError.Success) {
log.Warn(string.Format("Socket error {0}", readWriteArgs.SocketError));
//Socket was already removed
if (readWriteArgs.SocketError != SocketError.OperationAborted) {
CloseSocket(readWriteArgs);
}
return;
}
switch (readWriteArgs.LastOperation) {
case SocketAsyncOperation.Receive:
HandleRecieve(readWriteArgs);
break;
case SocketAsyncOperation.Send:
HandleSend(readWriteArgs);
break;
default:
throw new ArgumentException("Unknown last operation!");
}
}
private void StartSend(SocketAsyncEventArgs sendArgs) {
var client = sendArgs.UserToken as HttpClient;
client.ResponseBytesRemaining = client.ResponseBytes.Length;
bufferManager.ReturnBuffer(sendArgs.Buffer);
sendArgs.SetBuffer(client.ResponseBytes, 0, client.ResponseBytes.Length);
if (!client.Socket.SendAsync(sendArgs)) {
HandleReadWrite(sendArgs);
}
}
private void HandleSend(SocketAsyncEventArgs sendArgs) {
var client = sendArgs.UserToken as HttpClient;
client.ResponseBytesRemaining -= sendArgs.BytesTransferred;
if (client.ResponseBytesRemaining > 0) {
client.ResponseBytesOffset += sendArgs.BytesTransferred;
if (!client.Socket.SendAsync(sendArgs)) {
HandleReadWrite(sendArgs);
}
} else {
log.Debug("Finished sending response");
sendArgs.SetBuffer(bufferManager.TakeBuffer(this.bufferSize), 0, this.bufferSize);
CloseSocket(sendArgs);
}
}
private void HandleRecieve(SocketAsyncEventArgs readArgs) {
var client = readArgs.UserToken as HttpClient;
client.LastActive = Environment.TickCount;
if (readArgs.BytesTransferred == 0) {
CloseSocket(readArgs);
return;
}
client.RequestStream.Write(readArgs.Buffer, readArgs.Offset, readArgs.BytesTransferred);
try {
client.ProcessHTTP();
} catch(HttpProcessException ex) {
//The request is said to be faulty here
CloseSocket(readArgs);
log.Warn(ex);
return;
}
if (client.State == HttpState.Finished) {
if (OnHttpRequest != null) {
OnHttpRequest(this, new HttpRequestArgs(client.Request, client.Response));
client.ResponseBytes = client.Response.BuildResponse();
log.Debug(Encoding.UTF8.GetString(client.ResponseBytes));
StartSend(readArgs);
return;
}
}
if (!client.Socket.ReceiveAsync(readArgs)) {
HandleReadWrite(readArgs);
}
}
private void CloseSocket(SocketAsyncEventArgs args) {
lock (this.connections) {
if(!this.connections.Contains(args)) {
log.Debug("We already closed this socket");
return;
}
this.connections.Remove(args);
}
log.Debug(string.Format("Closing socket {0}", args.AcceptSocket.RemoteEndPoint));
try {
args.AcceptSocket.Shutdown(SocketShutdown.Both);
} catch (SocketException) {
log.Debug("Socket must already be closed");
}
args.AcceptSocket.Close();
((HttpClient)args.UserToken).Reset();
this.readWritePool.Push(args);
this.enforceMaxClients.Release();
}
private void HandleReadWriteCompleted (object sender, SocketAsyncEventArgs e) {
HandleReadWrite (e);
}
private void HandleAcceptCompleted (object sender, SocketAsyncEventArgs e) {
HandleAccept (e);
}
}
}
| bsd-2-clause |
NARKOZ/gitlab | lib/gitlab/help.rb | 2690 | # frozen_string_literal: true
require 'gitlab'
require 'gitlab/cli_helpers'
module Gitlab::Help
extend Gitlab::CLI::Helpers
class << self
# Returns the (modified) help from the 'ri' command or returns an error.
#
# @return [String]
def get_help(cmd)
cmd_namespace = namespace cmd
if cmd_namespace
ri_output = `#{ri_cmd} -T #{cmd_namespace} 2>&1`.chomp
if $CHILD_STATUS == 0
change_help_output! cmd, ri_output
yield ri_output if block_given?
ri_output
else
"Ri docs not found for #{cmd}, please install the docs to use 'help'."
end
else
"Unknown command: #{cmd}."
end
end
# Finds the location of 'ri' on a system.
#
# @return [String]
def ri_cmd
which_ri = `which ri`.chomp
raise "'ri' tool not found in $PATH. Please install it to use the help." if which_ri.empty?
which_ri
end
# A hash map that contains help topics (Branches, Groups, etc.)
# and a list of commands that are defined under a topic (create_branch,
# branches, protect_branch, etc.).
#
# @return [Hash<Array>]
def help_map
@help_map ||=
actions.each_with_object({}) do |action, hsh|
key = client.method(action)
.owner.to_s.gsub(/Gitlab::(?:Client::)?/, '')
hsh[key] ||= []
hsh[key] << action.to_s
end
end
# Table with available commands.
#
# @return [Terminal::Table]
def actions_table(topic = nil)
rows = topic ? help_map[topic] : help_map.keys
table do |t|
t.title = topic || 'Help Topics'
# add_row expects an array and we have strings hence the map.
rows.sort.map { |r| [r] }.each_with_index do |row, index|
t.add_row row
t.add_separator unless rows.size - 1 == index
end
end
end
# Returns full namespace of a command (e.g. Gitlab::Client::Branches.cmd)
def namespace(cmd)
method_owners.select { |method| method[:name] == cmd }
.map { |method| "#{method[:owner]}.#{method[:name]}" }
.shift
end
# Massage output from 'ri'.
def change_help_output!(cmd, output_str)
output_str = +output_str
output_str.gsub!(/#{cmd}(\(.*?\))/m, "#{cmd}\\1")
output_str.gsub!(/,\s*/, ', ')
# Ensure @option descriptions are on a single line
output_str.gsub!(/\n\[/, " \[")
output_str.gsub!(/\s(@)/, "\n@")
output_str.gsub!(/(\])\n(:)/, '\\1 \\2')
output_str.gsub!(/(:.*)(\n)(.*\.)/, '\\1 \\3')
output_str.gsub!(/\{(.+)\}/, '"{\\1}"')
end
end
end
| bsd-2-clause |
mwkm/pbrt-v3 | src/shapes/triangle.cpp | 26411 |
/*
pbrt source code is Copyright(c) 1998-2015
Matt Pharr, Greg Humphreys, and Wenzel Jakob.
This file is part of pbrt.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
// shapes/triangle.cpp*
#include "shapes/triangle.h"
#include "texture.h"
#include "textures/constant.h"
#include "paramset.h"
#include "sampling.h"
#include "efloat.h"
#include "ext/rply.h"
STAT_PERCENT("Intersections/Ray-triangle intersection tests", nHits, nTests);
// Triangle Local Definitions
static void PlyErrorCallback(p_ply, const char *message) {
Error("PLY writing error: %s", message);
}
// Triangle Method Definitions
STAT_RATIO("Scene/Triangles per triangle mesh", nTris, nMeshes);
TriangleMesh::TriangleMesh(
const Transform &ObjectToWorld, int nTriangles, const int *vertexIndices,
int nVertices, const Point3f *P, const Vector3f *S, const Normal3f *N,
const Point2f *UV, const std::shared_ptr<Texture<Float>> &alphaMask,
const std::shared_ptr<Texture<Float>> &shadowAlphaMask)
: nTriangles(nTriangles),
nVertices(nVertices),
vertexIndices(vertexIndices, vertexIndices + 3 * nTriangles),
alphaMask(alphaMask),
shadowAlphaMask(shadowAlphaMask) {
++nMeshes;
nTris += nTriangles;
triMeshBytes += sizeof(*this) + (3 * nTriangles * sizeof(int)) +
nVertices * (sizeof(*P) + (N ? sizeof(*N) : 0) +
(S ? sizeof(*S) : 0) + (UV ? sizeof(*UV) : 0));
// Transform mesh vertices to world space
p.reset(new Point3f[nVertices]);
for (int i = 0; i < nVertices; ++i) p[i] = ObjectToWorld(P[i]);
// Copy _UV_, _N_, and _S_ vertex data, if present
if (UV) {
uv.reset(new Point2f[nVertices]);
memcpy(uv.get(), UV, nVertices * sizeof(Point2f));
}
if (N) {
n.reset(new Normal3f[nVertices]);
for (int i = 0; i < nVertices; ++i) n[i] = ObjectToWorld(N[i]);
}
if (S) {
s.reset(new Vector3f[nVertices]);
for (int i = 0; i < nVertices; ++i) s[i] = ObjectToWorld(S[i]);
}
}
std::vector<std::shared_ptr<Shape>> CreateTriangleMesh(
const Transform *ObjectToWorld, const Transform *WorldToObject,
bool reverseOrientation, int nTriangles, const int *vertexIndices,
int nVertices, const Point3f *p, const Vector3f *s, const Normal3f *n,
const Point2f *uv, const std::shared_ptr<Texture<Float>> &alphaMask,
const std::shared_ptr<Texture<Float>> &shadowAlphaMask) {
std::shared_ptr<TriangleMesh> mesh = std::make_shared<TriangleMesh>(
*ObjectToWorld, nTriangles, vertexIndices, nVertices, p, s, n, uv,
alphaMask, shadowAlphaMask);
std::vector<std::shared_ptr<Shape>> tris;
tris.reserve(nTriangles);
for (int i = 0; i < nTriangles; ++i)
tris.push_back(std::make_shared<Triangle>(ObjectToWorld, WorldToObject,
reverseOrientation, mesh, i));
return tris;
}
bool WritePlyFile(const std::string &filename, int nTriangles,
const int *vertexIndices, int nVertices, const Point3f *P,
const Vector3f *S, const Normal3f *N, const Point2f *UV) {
p_ply plyFile =
ply_create(filename.c_str(), PLY_DEFAULT, PlyErrorCallback, 0, nullptr);
if (plyFile != nullptr) {
ply_add_element(plyFile, "vertex", nVertices);
ply_add_scalar_property(plyFile, "x", PLY_FLOAT);
ply_add_scalar_property(plyFile, "y", PLY_FLOAT);
ply_add_scalar_property(plyFile, "z", PLY_FLOAT);
if (N != nullptr) {
ply_add_scalar_property(plyFile, "nx", PLY_FLOAT);
ply_add_scalar_property(plyFile, "ny", PLY_FLOAT);
ply_add_scalar_property(plyFile, "nz", PLY_FLOAT);
}
if (UV != nullptr) {
ply_add_scalar_property(plyFile, "u", PLY_FLOAT);
ply_add_scalar_property(plyFile, "v", PLY_FLOAT);
}
if (S != nullptr)
Warning("PLY mesh in \"%s\" will be missing tangent vectors \"S\".",
filename.c_str());
ply_add_element(plyFile, "face", nTriangles);
ply_add_list_property(plyFile, "vertex_indices", PLY_UINT8, PLY_INT);
ply_write_header(plyFile);
for (int i = 0; i < nVertices; ++i) {
ply_write(plyFile, P[i].x);
ply_write(plyFile, P[i].y);
ply_write(plyFile, P[i].z);
if (N) {
ply_write(plyFile, N[i].x);
ply_write(plyFile, N[i].y);
ply_write(plyFile, N[i].z);
}
if (UV) {
ply_write(plyFile, UV[i].x);
ply_write(plyFile, UV[i].y);
}
}
for (int i = 0; i < nTriangles; ++i) {
ply_write(plyFile, 3);
ply_write(plyFile, vertexIndices[3 * i]);
ply_write(plyFile, vertexIndices[3 * i + 1]);
ply_write(plyFile, vertexIndices[3 * i + 2]);
}
ply_close(plyFile);
return true;
}
return false;
}
Bounds3f Triangle::ObjectBound() const {
// Get triangle vertices in _p0_, _p1_, and _p2_
const Point3f &p0 = mesh->p[v[0]];
const Point3f &p1 = mesh->p[v[1]];
const Point3f &p2 = mesh->p[v[2]];
return Union(Bounds3f((*WorldToObject)(p0), (*WorldToObject)(p1)),
(*WorldToObject)(p2));
}
Bounds3f Triangle::WorldBound() const {
// Get triangle vertices in _p0_, _p1_, and _p2_
const Point3f &p0 = mesh->p[v[0]];
const Point3f &p1 = mesh->p[v[1]];
const Point3f &p2 = mesh->p[v[2]];
return Union(Bounds3f(p0, p1), p2);
}
bool Triangle::Intersect(const Ray &ray, Float *tHit, SurfaceInteraction *isect,
bool testAlphaTexture) const {
ProfilePhase p(Prof::TriIntersect);
++nTests;
// Get triangle vertices in _p0_, _p1_, and _p2_
const Point3f &p0 = mesh->p[v[0]];
const Point3f &p1 = mesh->p[v[1]];
const Point3f &p2 = mesh->p[v[2]];
// Perform ray--triangle intersection test
// Transform triangle vertices to ray coordinate space
// Translate vertices based on ray origin
Point3f p0t = p0 - Vector3f(ray.o);
Point3f p1t = p1 - Vector3f(ray.o);
Point3f p2t = p2 - Vector3f(ray.o);
// Permute components of triangle vertices and ray direction
int kz = MaxDimension(Abs(ray.d));
int kx = kz + 1;
if (kx == 3) kx = 0;
int ky = kx + 1;
if (ky == 3) ky = 0;
Vector3f d = Permute(ray.d, kx, ky, kz);
p0t = Permute(p0t, kx, ky, kz);
p1t = Permute(p1t, kx, ky, kz);
p2t = Permute(p2t, kx, ky, kz);
// Apply shear transformation to translated vertex positions
Float Sx = -d.x / d.z;
Float Sy = -d.y / d.z;
Float Sz = 1.f / d.z;
p0t.x += Sx * p0t.z;
p0t.y += Sy * p0t.z;
p1t.x += Sx * p1t.z;
p1t.y += Sy * p1t.z;
p2t.x += Sx * p2t.z;
p2t.y += Sy * p2t.z;
// Compute edge function coefficients _e0_, _e1_, and _e2_
Float e0 = p1t.x * p2t.y - p1t.y * p2t.x;
Float e1 = p2t.x * p0t.y - p2t.y * p0t.x;
Float e2 = p0t.x * p1t.y - p0t.y * p1t.x;
// Fall back to double precision test at triangle edges
if (sizeof(Float) == sizeof(float) &&
(e0 == 0.0f || e1 == 0.0f || e2 == 0.0f)) {
double p2txp1ty = (double)p2t.x * (double)p1t.y;
double p2typ1tx = (double)p2t.y * (double)p1t.x;
e0 = (float)(p2typ1tx - p2txp1ty);
double p0txp2ty = (double)p0t.x * (double)p2t.y;
double p0typ2tx = (double)p0t.y * (double)p2t.x;
e1 = (float)(p0typ2tx - p0txp2ty);
double p1txp0ty = (double)p1t.x * (double)p0t.y;
double p1typ0tx = (double)p1t.y * (double)p0t.x;
e2 = (float)(p1typ0tx - p1txp0ty);
}
// Perform triangle edge and determinant tests
if ((e0 < 0 || e1 < 0 || e2 < 0) && (e0 > 0 || e1 > 0 || e2 > 0))
return false;
Float det = e0 + e1 + e2;
if (det == 0) return false;
// Compute scaled hit distance to triangle and test against ray $t$ range
p0t.z *= Sz;
p1t.z *= Sz;
p2t.z *= Sz;
Float tScaled = e0 * p0t.z + e1 * p1t.z + e2 * p2t.z;
if (det < 0 && (tScaled >= 0 || tScaled < ray.tMax * det))
return false;
else if (det > 0 && (tScaled <= 0 || tScaled > ray.tMax * det))
return false;
// Compute barycentric coordinates and $t$ value for triangle intersection
Float invDet = 1 / det;
Float b0 = e0 * invDet;
Float b1 = e1 * invDet;
Float b2 = e2 * invDet;
Float t = tScaled * invDet;
// Ensure that computed triangle $t$ is conservatively greater than zero
// Compute $\delta_z$ term for triangle $t$ error bounds
Float maxZt = MaxComponent(Abs(Vector3f(p0t.z, p1t.z, p2t.z)));
Float deltaZ = gamma(3) * maxZt;
// Compute $\delta_x$ and $\delta_y$ terms for triangle $t$ error bounds
Float maxXt = MaxComponent(Abs(Vector3f(p0t.x, p1t.x, p2t.x)));
Float maxYt = MaxComponent(Abs(Vector3f(p0t.y, p1t.y, p2t.y)));
Float deltaX = gamma(5) * (maxXt + maxZt);
Float deltaY = gamma(5) * (maxYt + maxZt);
// Compute $\delta_e$ term for triangle $t$ error bounds
Float deltaE =
2 * (gamma(2) * maxXt * maxYt + deltaY * maxXt + deltaX * maxYt);
// Compute $\delta_t$ term for triangle $t$ error bounds and check _t_
Float maxE = MaxComponent(Abs(Vector3f(e0, e1, e2)));
Float deltaT = 3 *
(gamma(3) * maxE * maxZt + deltaE * maxZt + deltaZ * maxE) *
std::abs(invDet);
if (t <= deltaT) return false;
// Compute triangle partial derivatives
Vector3f dpdu, dpdv;
Point2f uv[3];
GetUVs(uv);
// Compute deltas for triangle partial derivatives
Vector2f duv02 = uv[0] - uv[2], duv12 = uv[1] - uv[2];
Vector3f dp02 = p0 - p2, dp12 = p1 - p2;
Float determinant = duv02[0] * duv12[1] - duv02[1] * duv12[0];
if (determinant == 0) {
// Handle zero determinant for triangle partial derivative matrix
CoordinateSystem(Normalize(Cross(p2 - p0, p1 - p0)), &dpdu, &dpdv);
} else {
Float invdet = 1 / determinant;
dpdu = (duv12[1] * dp02 - duv02[1] * dp12) * invdet;
dpdv = (-duv12[0] * dp02 + duv02[0] * dp12) * invdet;
}
// Compute error bounds for triangle intersection
Float xAbsSum =
(std::abs(b0 * p0.x) + std::abs(b1 * p1.x) + std::abs(b2 * p2.x));
Float yAbsSum =
(std::abs(b0 * p0.y) + std::abs(b1 * p1.y) + std::abs(b2 * p2.y));
Float zAbsSum =
(std::abs(b0 * p0.z) + std::abs(b1 * p1.z) + std::abs(b2 * p2.z));
Vector3f pError = gamma(7) * Vector3f(xAbsSum, yAbsSum, zAbsSum);
// Interpolate $(u,v)$ parametric coordinates and hit point
Point3f pHit = b0 * p0 + b1 * p1 + b2 * p2;
Point2f uvHit = b0 * uv[0] + b1 * uv[1] + b2 * uv[2];
// Test intersection against alpha texture, if present
if (testAlphaTexture && mesh->alphaMask) {
SurfaceInteraction isectLocal(pHit, Vector3f(0, 0, 0), uvHit, -ray.d,
dpdu, dpdv, Normal3f(0, 0, 0),
Normal3f(0, 0, 0), ray.time, this);
if (mesh->alphaMask->Evaluate(isectLocal) == 0) return false;
}
// Fill in _SurfaceInteraction_ from triangle hit
*isect = SurfaceInteraction(pHit, pError, uvHit, -ray.d, dpdu, dpdv,
Normal3f(0, 0, 0), Normal3f(0, 0, 0), ray.time,
this);
// Override surface normal in _isect_ for triangle
isect->n = isect->shading.n = Normal3f(Normalize(Cross(dp02, dp12)));
if (mesh->n || mesh->s) {
// Initialize _Triangle_ shading geometry
// Compute shading normal _ns_ for triangle
Normal3f ns;
if (mesh->n) {
ns = (b0 * mesh->n[v[0]] + b1 * mesh->n[v[1]] +
b2 * mesh->n[v[2]]);
if (ns.LengthSquared() > 0)
ns = Normalize(ns);
else
ns = isect->n;
} else
ns = isect->n;
// Compute shading tangent _ss_ for triangle
Vector3f ss;
if (mesh->s) {
ss = (b0 * mesh->s[v[0]] + b1 * mesh->s[v[1]] +
b2 * mesh->s[v[2]]);
if (ss.LengthSquared() > 0)
ss = Normalize(ss);
else
ss = Normalize(isect->dpdu);
}
else
ss = Normalize(isect->dpdu);
// Compute shading bitangent _ts_ for triangle and adjust _ss_
Vector3f ts = Cross(ss, ns);
if (ts.LengthSquared() > 0.f) {
ts = Normalize(ts);
ss = Cross(ts, ns);
} else
CoordinateSystem((Vector3f)ns, &ss, &ts);
// Compute $\dndu$ and $\dndv$ for triangle shading geometry
Normal3f dndu, dndv;
if (mesh->n) {
// Compute deltas for triangle partial derivatives of normal
Vector2f duv02 = uv[0] - uv[2];
Vector2f duv12 = uv[1] - uv[2];
Normal3f dn1 = mesh->n[v[0]] - mesh->n[v[2]];
Normal3f dn2 = mesh->n[v[1]] - mesh->n[v[2]];
Float determinant = duv02[0] * duv12[1] - duv02[1] * duv12[0];
if (determinant == 0)
dndu = dndv = Normal3f(0, 0, 0);
else {
Float invDet = 1 / determinant;
dndu = (duv12[1] * dn1 - duv02[1] * dn2) * invDet;
dndv = (-duv12[0] * dn1 + duv02[0] * dn2) * invDet;
}
} else
dndu = dndv = Normal3f(0, 0, 0);
isect->SetShadingGeometry(ss, ts, dndu, dndv, true);
}
// Ensure correct orientation of the geometric normal
if (mesh->n)
isect->n = Faceforward(isect->n, isect->shading.n);
else if (reverseOrientation ^ transformSwapsHandedness)
isect->n = isect->shading.n = -isect->n;
*tHit = t;
++nHits;
return true;
}
bool Triangle::IntersectP(const Ray &ray, bool testAlphaTexture) const {
ProfilePhase p(Prof::TriIntersectP);
++nTests;
// Get triangle vertices in _p0_, _p1_, and _p2_
const Point3f &p0 = mesh->p[v[0]];
const Point3f &p1 = mesh->p[v[1]];
const Point3f &p2 = mesh->p[v[2]];
// Perform ray--triangle intersection test
// Transform triangle vertices to ray coordinate space
// Translate vertices based on ray origin
Point3f p0t = p0 - Vector3f(ray.o);
Point3f p1t = p1 - Vector3f(ray.o);
Point3f p2t = p2 - Vector3f(ray.o);
// Permute components of triangle vertices and ray direction
int kz = MaxDimension(Abs(ray.d));
int kx = kz + 1;
if (kx == 3) kx = 0;
int ky = kx + 1;
if (ky == 3) ky = 0;
Vector3f d = Permute(ray.d, kx, ky, kz);
p0t = Permute(p0t, kx, ky, kz);
p1t = Permute(p1t, kx, ky, kz);
p2t = Permute(p2t, kx, ky, kz);
// Apply shear transformation to translated vertex positions
Float Sx = -d.x / d.z;
Float Sy = -d.y / d.z;
Float Sz = 1.f / d.z;
p0t.x += Sx * p0t.z;
p0t.y += Sy * p0t.z;
p1t.x += Sx * p1t.z;
p1t.y += Sy * p1t.z;
p2t.x += Sx * p2t.z;
p2t.y += Sy * p2t.z;
// Compute edge function coefficients _e0_, _e1_, and _e2_
Float e0 = p1t.x * p2t.y - p1t.y * p2t.x;
Float e1 = p2t.x * p0t.y - p2t.y * p0t.x;
Float e2 = p0t.x * p1t.y - p0t.y * p1t.x;
// Fall back to double precision test at triangle edges
if (sizeof(Float) == sizeof(float) &&
(e0 == 0.0f || e1 == 0.0f || e2 == 0.0f)) {
double p2txp1ty = (double)p2t.x * (double)p1t.y;
double p2typ1tx = (double)p2t.y * (double)p1t.x;
e0 = (float)(p2typ1tx - p2txp1ty);
double p0txp2ty = (double)p0t.x * (double)p2t.y;
double p0typ2tx = (double)p0t.y * (double)p2t.x;
e1 = (float)(p0typ2tx - p0txp2ty);
double p1txp0ty = (double)p1t.x * (double)p0t.y;
double p1typ0tx = (double)p1t.y * (double)p0t.x;
e2 = (float)(p1typ0tx - p1txp0ty);
}
// Perform triangle edge and determinant tests
if ((e0 < 0 || e1 < 0 || e2 < 0) && (e0 > 0 || e1 > 0 || e2 > 0))
return false;
Float det = e0 + e1 + e2;
if (det == 0) return false;
// Compute scaled hit distance to triangle and test against ray $t$ range
p0t.z *= Sz;
p1t.z *= Sz;
p2t.z *= Sz;
Float tScaled = e0 * p0t.z + e1 * p1t.z + e2 * p2t.z;
if (det < 0 && (tScaled >= 0 || tScaled < ray.tMax * det))
return false;
else if (det > 0 && (tScaled <= 0 || tScaled > ray.tMax * det))
return false;
// Compute barycentric coordinates and $t$ value for triangle intersection
Float invDet = 1 / det;
Float b0 = e0 * invDet;
Float b1 = e1 * invDet;
Float b2 = e2 * invDet;
Float t = tScaled * invDet;
// Ensure that computed triangle $t$ is conservatively greater than zero
// Compute $\delta_z$ term for triangle $t$ error bounds
Float maxZt = MaxComponent(Abs(Vector3f(p0t.z, p1t.z, p2t.z)));
Float deltaZ = gamma(3) * maxZt;
// Compute $\delta_x$ and $\delta_y$ terms for triangle $t$ error bounds
Float maxXt = MaxComponent(Abs(Vector3f(p0t.x, p1t.x, p2t.x)));
Float maxYt = MaxComponent(Abs(Vector3f(p0t.y, p1t.y, p2t.y)));
Float deltaX = gamma(5) * (maxXt + maxZt);
Float deltaY = gamma(5) * (maxYt + maxZt);
// Compute $\delta_e$ term for triangle $t$ error bounds
Float deltaE =
2 * (gamma(2) * maxXt * maxYt + deltaY * maxXt + deltaX * maxYt);
// Compute $\delta_t$ term for triangle $t$ error bounds and check _t_
Float maxE = MaxComponent(Abs(Vector3f(e0, e1, e2)));
Float deltaT = 3 *
(gamma(3) * maxE * maxZt + deltaE * maxZt + deltaZ * maxE) *
std::abs(invDet);
if (t <= deltaT) return false;
// Test shadow ray intersection against alpha texture, if present
if (testAlphaTexture && (mesh->alphaMask || mesh->shadowAlphaMask)) {
// Compute triangle partial derivatives
Vector3f dpdu, dpdv;
Point2f uv[3];
GetUVs(uv);
// Compute deltas for triangle partial derivatives
Vector2f duv02 = uv[0] - uv[2], duv12 = uv[1] - uv[2];
Vector3f dp02 = p0 - p2, dp12 = p1 - p2;
Float determinant = duv02[0] * duv12[1] - duv02[1] * duv12[0];
if (determinant == 0) {
// Handle zero determinant for triangle partial derivative matrix
CoordinateSystem(Normalize(Cross(p2 - p0, p1 - p0)), &dpdu, &dpdv);
} else {
Float invdet = 1 / determinant;
dpdu = (duv12[1] * dp02 - duv02[1] * dp12) * invdet;
dpdv = (-duv12[0] * dp02 + duv02[0] * dp12) * invdet;
}
// Interpolate $(u,v)$ parametric coordinates and hit point
Point3f pHit = b0 * p0 + b1 * p1 + b2 * p2;
Point2f uvHit = b0 * uv[0] + b1 * uv[1] + b2 * uv[2];
SurfaceInteraction isectLocal(pHit, Vector3f(0, 0, 0), uvHit, -ray.d,
dpdu, dpdv, Normal3f(0, 0, 0),
Normal3f(0, 0, 0), ray.time, this);
if (mesh->alphaMask && mesh->alphaMask->Evaluate(isectLocal) == 0)
return false;
if (mesh->shadowAlphaMask &&
mesh->shadowAlphaMask->Evaluate(isectLocal) == 0)
return false;
}
++nHits;
return true;
}
Float Triangle::Area() const {
// Get triangle vertices in _p0_, _p1_, and _p2_
const Point3f &p0 = mesh->p[v[0]];
const Point3f &p1 = mesh->p[v[1]];
const Point3f &p2 = mesh->p[v[2]];
return 0.5 * Cross(p1 - p0, p2 - p0).Length();
}
Interaction Triangle::Sample(const Point2f &u) const {
Point2f b = UniformSampleTriangle(u);
// Get triangle vertices in _p0_, _p1_, and _p2_
const Point3f &p0 = mesh->p[v[0]];
const Point3f &p1 = mesh->p[v[1]];
const Point3f &p2 = mesh->p[v[2]];
Interaction it;
it.p = b[0] * p0 + b[1] * p1 + (1 - b[0] - b[1]) * p2;
// Compute surface normal for sampled point on triangle
if (mesh->n)
it.n = Normalize(b[0] * mesh->n[v[0]] + b[1] * mesh->n[v[1]] +
(1 - b[0] - b[1]) * mesh->n[v[2]]);
else
it.n = Normalize(Normal3f(Cross(p1 - p0, p2 - p0)));
if (reverseOrientation) it.n *= -1;
// Compute error bounds for sampled point on triangle
Point3f pAbsSum =
Abs(b[0] * p0) + Abs(b[1] * p1) + Abs((1 - b[0] - b[1]) * p2);
it.pError = gamma(6) * Vector3f(pAbsSum.x, pAbsSum.y, pAbsSum.z);
return it;
}
std::vector<std::shared_ptr<Shape>> CreateTriangleMeshShape(
const Transform *o2w, const Transform *w2o, bool reverseOrientation,
const ParamSet ¶ms,
std::map<std::string, std::shared_ptr<Texture<Float>>> *floatTextures) {
int nvi, npi, nuvi, nsi, nni;
const int *vi = params.FindInt("indices", &nvi);
const Point3f *P = params.FindPoint3f("P", &npi);
const Point2f *uvs = params.FindPoint2f("uv", &nuvi);
if (!uvs) uvs = params.FindPoint2f("st", &nuvi);
std::vector<Point2f> tempUVs;
if (!uvs) {
const Float *fuv = params.FindFloat("uv", &nuvi);
if (!fuv) fuv = params.FindFloat("st", &nuvi);
if (fuv) {
nuvi /= 2;
tempUVs.reserve(nuvi);
for (int i = 0; i < nuvi; ++i)
tempUVs.push_back(Point2f(fuv[2 * i], fuv[2 * i + 1]));
uvs = &tempUVs[0];
}
}
bool discardDegenerateUVs =
params.FindOneBool("discarddegenerateUVs", false);
if (uvs) {
if (nuvi < npi) {
Error(
"Not enough of \"uv\"s for triangle mesh. Expencted %d, "
"found %d. Discarding.",
npi, nuvi);
uvs = nullptr;
} else if (nuvi > npi)
Warning(
"More \"uv\"s provided than will be used for triangle "
"mesh. (%d expcted, %d found)",
npi, nuvi);
}
if (!vi) {
Error(
"Vertex indices \"indices\" not provided with triangle mesh shape");
return std::vector<std::shared_ptr<Shape>>();
}
if (!P) {
Error("Vertex positions \"P\" not provided with triangle mesh shape");
return std::vector<std::shared_ptr<Shape>>();
}
const Vector3f *S = params.FindVector3f("S", &nsi);
if (S && nsi != npi) {
Error("Number of \"S\"s for triangle mesh must match \"P\"s");
S = nullptr;
}
const Normal3f *N = params.FindNormal3f("N", &nni);
if (N && nni != npi) {
Error("Number of \"N\"s for triangle mesh must match \"P\"s");
N = nullptr;
}
if (discardDegenerateUVs && uvs && N) {
// if there are normals, check for bad uv's that
// give degenerate mappings; discard them if so
const int *vp = vi;
for (int i = 0; i < nvi; i += 3, vp += 3) {
Float area =
.5f * Cross(P[vp[0]] - P[vp[1]], P[vp[2]] - P[vp[1]]).Length();
if (area < 1e-7) continue; // ignore degenerate tris.
if ((uvs[vp[0]].x == uvs[vp[1]].x &&
uvs[vp[0]].y == uvs[vp[1]].y) ||
(uvs[vp[1]].x == uvs[vp[2]].x &&
uvs[vp[1]].y == uvs[vp[2]].y) ||
(uvs[vp[2]].x == uvs[vp[0]].x &&
uvs[vp[2]].y == uvs[vp[0]].y)) {
Warning(
"Degenerate uv coordinates in triangle mesh. Discarding "
"all uvs.");
uvs = nullptr;
break;
}
}
}
for (int i = 0; i < nvi; ++i)
if (vi[i] >= npi) {
Error(
"trianglemesh has out of-bounds vertex index %d (%d \"P\" "
"values were given",
vi[i], npi);
return std::vector<std::shared_ptr<Shape>>();
}
std::shared_ptr<Texture<Float>> alphaTex;
std::string alphaTexName = params.FindTexture("alpha");
if (alphaTexName != "") {
if (floatTextures->find(alphaTexName) != floatTextures->end())
alphaTex = (*floatTextures)[alphaTexName];
else
Error("Couldn't find float texture \"%s\" for \"alpha\" parameter",
alphaTexName.c_str());
} else if (params.FindOneFloat("alpha", 1.f) == 0.f)
alphaTex.reset(new ConstantTexture<Float>(0.f));
std::shared_ptr<Texture<Float>> shadowAlphaTex;
std::string shadowAlphaTexName = params.FindTexture("shadowalpha");
if (shadowAlphaTexName != "") {
if (floatTextures->find(shadowAlphaTexName) != floatTextures->end())
shadowAlphaTex = (*floatTextures)[shadowAlphaTexName];
else
Error(
"Couldn't find float texture \"%s\" for \"shadowalpha\" "
"parameter",
shadowAlphaTexName.c_str());
} else if (params.FindOneFloat("shadowalpha", 1.f) == 0.f)
shadowAlphaTex.reset(new ConstantTexture<Float>(0.f));
return CreateTriangleMesh(o2w, w2o, reverseOrientation, nvi / 3, vi, npi, P,
S, N, uvs, alphaTex, shadowAlphaTex);
}
| bsd-2-clause |
kajiki/mahjong-scoring | lib/mahjong_scoring/rules/all_honors.rb | 176 | module Rules
class AllHonors < StandardHand
def self.score() 64 end
def self.match?(hand)
super and
hand.tiles.all? { |t| t.honor? }
end
end
end
| bsd-2-clause |
alexg0/homebrew-cask | Casks/beekeeper-studio.rb | 1033 | cask "beekeeper-studio" do
version "1.9.1"
sha256 "a753bff4336f4c9d75db74e181149cc5e07727fb9bb512cdf6e37c0b0d36cc2c"
url "https://github.com/beekeeper-studio/beekeeper-studio/releases/download/v#{version}/Beekeeper-Studio-#{version}.dmg",
verified: "github.com/beekeeper-studio/beekeeper-studio/"
name "Beekeeper Studio"
desc "Cross platform SQL editor and database management app"
homepage "https://www.beekeeperstudio.io/"
livecheck do
url :url
strategy :github_latest
end
auto_updates true
app "Beekeeper Studio.app"
zap trash: [
"~/Library/Application Support/Caches/beekeeper-studio-updater",
"~/Library/Application Support/beekeeper-studio",
"~/Library/Caches/io.beekeeperstudio.desktop",
"~/Library/Caches/io.beekeeperstudio.desktop.ShipIt",
"~/Library/Preferences/ByHost/io.beekeeperstudio.desktop.ShipIt.*.plist",
"~/Library/Preferences/io.beekeeperstudio.desktop.plist",
"~/Library/Saved Application State/io.beekeeperstudio.desktop.savedState",
]
end
| bsd-2-clause |
kaufmo/koala-framework | Kwf_js/EyeCandy/List/Plugins/StateChanger/Hover.js | 432 | var kwfExtend = require('kwf/extend');
Kwf.EyeCandy.List.Plugins.StateChanger.Hover = kwfExtend(Kwf.EyeCandy.List.Plugins.Abstract, {
state: 'large',
init: function() {
this.list.on('childMouseEnter', function(item) {
item.pushState(this.state, this);
}, this);
this.list.on('childMouseLeave', function(item) {
item.removeState(this.state, this);
}, this);
}
});
| bsd-2-clause |
hightower70/CygnusGroundStationDev | Modules/FlightGearInterface/FlightGearThread.cs | 5519 | ///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2013 Laszlo Arvai. All rights reserved.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License,
// or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301 USA
///////////////////////////////////////////////////////////////////////////////
// File description
// ----------------
// FlightGear main data conversion thread
///////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace FlightGearInterface
{
class FlightGearThread
{
#region · Private data ·
private FlightGearSettings m_settings;
private UdpClient m_udp_client;
private IPEndPoint m_endpoint;
#endregion
#region · Public members ·
/// <summary>
/// Sets up this interface module
/// </summary>
public void Configure(FlightGearSettings in_settings)
{
m_settings = in_settings;
}
/// <summary>
/// Starts module operation
/// </summary>
public void Open()
{
// starts flight gear
StartFlightGear();
// create endpoint
m_endpoint = new IPEndPoint(m_settings.IPAddress, m_settings.Port);
// Open UDP connection
m_udp_client = new UdpClient(m_endpoint);
// start data reception
IAsyncResult res = m_udp_client.BeginReceive(new AsyncCallback(ReceiveCallback), null);
}
/// <summary>
/// Stops module operation
/// </summary>
public void Close()
{
if (m_udp_client != null)
m_udp_client.Close();
m_udp_client = null;
}
#endregion
#region · Private members ·
private void ReceiveCallback(IAsyncResult res)
{
try
{
if (m_udp_client != null)
{
byte[] data = m_udp_client.EndReceive(res, ref m_endpoint);
string receiveString = Encoding.ASCII.GetString(data);
ProcessReceivedLine(receiveString);
// get next packet
m_udp_client.BeginReceive(ReceiveCallback, null);
}
}
catch
{
// do nothing
}
}
private void ProcessReceivedLine(string in_line)
{
double value;
string[] chunks = in_line.Substring(0, in_line.Length - 1).Split(',');
//////////////////////
// Raw "sensor" values
// Gyro
// /orientation/roll-rate-degps
value = Convert.ToSingle(chunks[0], CultureInfo.InvariantCulture);
// /orientation/pitch-rate-degps
value = Convert.ToSingle(chunks[1], CultureInfo.InvariantCulture);
// /orientation/yaw-rate-degps
value = Convert.ToSingle(chunks[2], CultureInfo.InvariantCulture);
// Acceleration
// /accelerations/pilot/x-accel-fps_sec
value = Convert.ToSingle(chunks[3], CultureInfo.InvariantCulture);
// /accelerations/pilot/y-accel-fps_sec
value = Convert.ToSingle(chunks[4], CultureInfo.InvariantCulture);
// /accelerations/pilot/z-accel-fps_sec
value = Convert.ToSingle(chunks[5], CultureInfo.InvariantCulture);
///////////
// Attitude
// /orientation/roll-deg
value = Convert.ToSingle(chunks[6], CultureInfo.InvariantCulture);
// /orientation/pitch-deg</node>
value = Convert.ToSingle(chunks[7], CultureInfo.InvariantCulture);
// /orientation/heading-deg</node>
value = Convert.ToSingle(chunks[8], CultureInfo.InvariantCulture);
///////////////
// GPS Position
// /position/latitude-deg
value = Convert.ToSingle(chunks[9], CultureInfo.InvariantCulture);
// /position/longitude-deg
value = Convert.ToSingle(chunks[10], CultureInfo.InvariantCulture);
// /position/altitude-ft
value = Convert.ToSingle(chunks[11], CultureInfo.InvariantCulture);
///////////
// Airspeed
// /velocities/airspeed-kt
value = Convert.ToSingle(chunks[12], CultureInfo.InvariantCulture);
}
/// <summary>
/// Starts FlightGear program
/// </summary>
/// <param name="in_settings">Settings class for parameters</param>
private void StartFlightGear()
{
// check if start is required
if (!m_settings.Autostart)
return;
// Check whether FlightGear is already running
Process[] processes = Process.GetProcessesByName("fgfs");
if (processes == null || processes.Length <= 0)
{
string flight_gear_bin = Path.Combine(m_settings.Path, "bin\\fgfs.exe");
string flight_gear_dir = Path.Combine(m_settings.Path, "bin");
// Create process start information
ProcessStartInfo startInfo = new ProcessStartInfo(flight_gear_bin, m_settings.Options);
startInfo.WorkingDirectory = flight_gear_dir;
// Start FlightGear
try
{
Process.Start(startInfo);
}
catch
{
}
}
}
#endregion
}
}
| bsd-2-clause |
milot-mirdita/GeMuDB | Vendor/NCBI eutils/src/gov/nih/nlm/ncbi/www/soap/eutils/efetch_gene/CitPat_class_type0.java | 24797 |
/**
* CitPat_class_type0.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST)
*/
package gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene;
/**
* CitPat_class_type0 bean class
*/
@SuppressWarnings({"unchecked","unused"})
public class CitPat_class_type0
implements org.apache.axis2.databinding.ADBBean{
/* This type was generated from the piece of schema that had
name = Cit-pat_class_type0
Namespace URI = http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene
Namespace Prefix = ns1
*/
/**
* field for CitPat_classSequence
* This was an Array!
*/
protected gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[] localCitPat_classSequence ;
/* This tracker boolean wil be used to detect whether the user called the set method
* for this attribute. It will be used to determine whether to include this field
* in the serialized XML
*/
protected boolean localCitPat_classSequenceTracker = false ;
public boolean isCitPat_classSequenceSpecified(){
return localCitPat_classSequenceTracker;
}
/**
* Auto generated getter method
* @return gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[]
*/
public gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[] getCitPat_classSequence(){
return localCitPat_classSequence;
}
/**
* validate the array for CitPat_classSequence
*/
protected void validateCitPat_classSequence(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[] param){
}
/**
* Auto generated setter method
* @param param CitPat_classSequence
*/
public void setCitPat_classSequence(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[] param){
validateCitPat_classSequence(param);
localCitPat_classSequenceTracker = param != null;
this.localCitPat_classSequence=param;
}
/**
* Auto generated add method for the array for convenience
* @param param gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence
*/
public void addCitPat_classSequence(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence param){
if (localCitPat_classSequence == null){
localCitPat_classSequence = new gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[]{};
}
//update the setting tracker
localCitPat_classSequenceTracker = true;
java.util.List list =
org.apache.axis2.databinding.utils.ConverterUtil.toList(localCitPat_classSequence);
list.add(param);
this.localCitPat_classSequence =
(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[])list.toArray(
new gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[list.size()]);
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,parentQName);
return factory.createOMElement(dataSource,parentQName);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":Cit-pat_class_type0",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"Cit-pat_class_type0",
xmlWriter);
}
}
if (localCitPat_classSequenceTracker){
if (localCitPat_classSequence!=null){
for (int i = 0;i < localCitPat_classSequence.length;i++){
if (localCitPat_classSequence[i] != null){
localCitPat_classSequence[i].serialize(null,xmlWriter);
} else {
// we don't have to do any thing since minOccures is zero
}
}
} else {
throw new org.apache.axis2.databinding.ADBException("Cit-pat_classSequence cannot be null!!");
}
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene")){
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
if (localCitPat_classSequenceTracker){
if (localCitPat_classSequence!=null) {
for (int i = 0;i < localCitPat_classSequence.length;i++){
if (localCitPat_classSequence[i] != null){
elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene",
"Cit-pat_classSequence"));
elementList.add(localCitPat_classSequence[i]);
} else {
// nothing to do
}
}
} else {
throw new org.apache.axis2.databinding.ADBException("Cit-pat_classSequence cannot be null!!");
}
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static CitPat_class_type0 parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
CitPat_class_type0 object =
new CitPat_class_type0();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"Cit-pat_class_type0".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (CitPat_class_type0)gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
java.util.ArrayList list1 = new java.util.ArrayList();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
try{
if (reader.isStartElement() ){
// Process the array and step past its final element's end.
list1.add(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence.Factory.parse(reader));
//loop until we find a start element that is not part of this array
boolean loopDone1 = false;
while(!loopDone1){
// Step to next element event.
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isEndElement()){
//two continuous end elements means we are exiting the xml structure
loopDone1 = true;
} else {
list1.add(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence.Factory.parse(reader));
}
}
// call the converter utility to convert and set the array
object.setCitPat_classSequence((gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence[])
org.apache.axis2.databinding.utils.ConverterUtil.convertToArray(
gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.CitPat_classSequence.class,
list1));
} // End of if for expected property start element
else {
}
} catch (java.lang.Exception e) {}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
| bsd-2-clause |
nickraptis/fidibot | src/fidibot.py | 7614 | #! /usr/bin/env python
#
# Author: Nick Raptis <airscorp@gmail.com>
import argparse
import irc.bot
from irc.strings import lower
from logsetup import setup_logging, setup_client_logging
from introspect import build_index
from modules import activate_modules
from alternatives import alternatives, read_files, _
import tools, auth
import logging
log = logging.getLogger(__name__)
# set unicode decoding to replace errors
from irc.buffer import DecodingLineBuffer as DLB
DLB.errors = 'replace'
class FidiBot(irc.bot.SingleServerIRCBot):
def __init__(self, channel, nickname, server, port=6667,
realname=None, password='', callsign='fidi',
admin_pass=None, google_api_key=None):
if channel[0] != "#":
# make sure channel starts with a #
channel = "#" + channel
self.nickname = self._nickname_wanted = nickname
self.channel = channel
self.realname = realname if realname else nickname
self.password = password
self.callsign = callsign
self.identified = False
self.alternatives = alternatives
self.google_api_key = google_api_key
# setup admins
#self.admin_pass = admin_pass
self.admins = auth.AdminAuth(admin_pass)
# load modules
active_modules, active_alternatives = activate_modules()
self.modules = [m(self) for m in active_modules]
self.alternatives.merge_with(active_alternatives)
# add alternatives from directory
self.alternatives.merge_with(read_files())
self.alternatives.clean_duplicates()
# build help index
self.help_index = build_index(self.modules)
super(FidiBot, self).__init__([(server, port)], nickname, realname)
# set up rate limiting after 5 seconds to one message per second
self.connection.execute_delayed(5,
self.connection.set_rate_limit, (1,))
# set up throttles
self.join_throttle = tools.Throttle(10 * 60)
self.duh_throttle = tools.Throttle(60)
# set up keepalive
self._pings_pending = 0
self._last_kicker = ''
self.connection.execute_every(300, self._keepalive)
def _keepalive(self):
if self._pings_pending >= 2:
log.warning("Connection timed out. Will try to reconnect!")
self.disconnect()
self._pings_pending = 0
return
try:
self.connection.ping('keep-alive')
self._pings_pending += 1
except irc.client.ServerNotConnectedError:
pass
def on_pong(self, c, e):
self._pings_pending = 0
def on_kick(self, c, e):
nick = e.arguments[0]
channel = e.target
if nick == c.get_nickname():
self._last_kicker = e.source.nick
c.execute_delayed(10, c.join, (channel,))
def on_nicknameinuse(self, c, e):
new_nick = self.nickname + "_"
c.nick(new_nick)
c.execute_delayed(10, self.changeback_nickname)
self.nickname = new_nick
def changeback_nickname(self):
if self.nickname.endswith('_'):
new_nick = self._nickname_wanted
self.connection.nick(new_nick)
self.nickname = new_nick
def on_welcome(self, c, e):
c.join(self.channel)
def on_privnotice(self, c, e):
if e.source.nick == "NickServ":
if "NickServ identify" in e.arguments[0]:
log.debug("NickServ asks us to identify")
if self.password:
log.info("Sending password to NickServ")
c.privmsg("NickServ", "identify " + self.password)
else:
log.warning("We were asked to identify but we have no password")
elif "You are now identified" in e.arguments[0]:
log.debug("We are now identified with NickServ")
self.identified = True
elif "Invalid password" in e.arguments[0]:
log.error("Invalid password! Check your settings!")
def on_privmsg(self, c, e):
# first try to defer the message to the active modules
for m in self.modules:
if m.on_privmsg(c, e):
return
# default behaviour if no module processes the message.
command = lower(e.arguments[0].split(" ", 1)[0])
if self.callsign in command:
# maybe someone is calling us by name?
c.privmsg(e.source.nick, _("You don't have to call me by name in private"))
return
log.debug("Failed to understand private message '%s' from user %s",
e.arguments[0], e.source.nick)
c.privmsg(e.source.nick, _("I don't understand %s") % command)
def on_pubmsg(self, c, e):
# first try to defer the message to the active modules
for m in self.modules:
if m.on_pubmsg(c, e):
return
# don't do default behaviour for the GitHub bots
if 'github' in e.source.nick.lower():
return
# default behaviour if no module processes the message.
if self.callsign in lower(e.arguments[0]):
log.debug("Failed to understand public message '%s' from user %s",
e.arguments[0], e.source.nick)
if not self.duh_throttle.is_throttled(e.source.nick):
c.privmsg(e.target, _("Someone talking about me? Duh!"))
def on_join(self, c, e):
nick = e.source.nick
# ignore the commings and goings of the GitHub bots
if 'github' in nick.lower():
return
if not nick == c.get_nickname():
if not self.join_throttle.is_throttled(nick):
c.privmsg(e.target, _("Welcome %s") % nick)
elif self._last_kicker:
c.privmsg(e.target, _("Why did you kick me, %s?") % self._last_kicker)
self._last_kicker = ''
def on_bannedfromchan(self, c, e):
c.execute_delayed(10, c.join, (e.arguments[0],))
def get_version(self):
return "fidibot https://github.com/nickraptis/fidibot"
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('server', help="Server to connect to")
parser.add_argument('channel', help="Channel to join. Prepending with # is optional")
parser.add_argument('nickname', help="Nickname to use")
parser.add_argument('-r', '--realname', help="Real name to use. Defaults to nickname")
parser.add_argument('-x', '--password', help="Password to authenticate with NickServ")
parser.add_argument('-p', '--port', default=6667, type=int, help="Connect to port")
parser.add_argument('-c', '--callsign', default="fidi", help="Callsign for commands")
parser.add_argument('-s', '--admin-pass', help="Password for admin commands")
parser.add_argument('-g', '--google-api-key', help="Google API key for url shortener")
return parser.parse_args()
def main():
args = get_args()
setup_logging()
bot = FidiBot(args.channel, args.nickname, args.server, args.port,
realname= args.realname, password=args.password, callsign=args.callsign,
admin_pass = args.admin_pass, google_api_key = args.google_api_key)
setup_client_logging(bot)
try:
bot.start()
except KeyboardInterrupt:
bot.disconnect(_("Someone closed me!"))
except Exception as e:
log.exception(e)
bot.disconnect(_("I crashed damn it!"))
raise SystemExit(4)
if __name__ == "__main__":
main()
| bsd-2-clause |
titon/test | src/Titon/Test/Stub/Model/Order.php | 192 | <?php
namespace Titon\Test\Stub\Model;
class Order extends TestModel {
protected $table = 'orders';
protected $belongsTo = [
'User' => 'Titon\Test\Stub\Model\User'
];
} | bsd-2-clause |
mmoening/MatterControl | MatterControlLib/SlicerConfiguration/MappingClasses/InjectGCodeCommands.cs | 2359 | /*
Copyright (c) 2016, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System.Collections.Generic;
namespace MatterHackers.MatterControl.SlicerConfiguration.MappingClasses
{
public class InjectGCodeCommands : UnescapeNewlineCharacters
{
public InjectGCodeCommands(PrinterConfig printer, string canonicalSettingsName, string exportedName)
: base(printer, canonicalSettingsName, exportedName)
{
}
protected void AddDefaultIfNotPresent(List<string> linesAdded, string commandToAdd, string[] linesToCheckIfAlreadyPresent, string comment)
{
string command = commandToAdd.Split(' ')[0].Trim();
bool foundCommand = false;
foreach (string line in linesToCheckIfAlreadyPresent)
{
if (line.StartsWith(command))
{
foundCommand = true;
break;
}
}
if (!foundCommand)
{
linesAdded.Add(string.Format("{0} ; {1}", commandToAdd, comment));
}
}
}
} | bsd-2-clause |
stephen-turner/xenadmin | XenAdmin/Wizards/ImportWizard/ImportSourcePage.cs | 17896 | /* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using DiscUtils;
using DiscUtils.Wim;
using XenAdmin.Controls;
using XenCenterLib;
using XenAdmin.Dialogs;
using XenAdmin.Controls.Common;
using XenCenterLib.Archive;
using XenOvf;
using XenOvf.Definitions;
using XenOvf.Definitions.VMC;
using XenOvf.Utilities;
namespace XenAdmin.Wizards.ImportWizard
{
internal partial class ImportSourcePage : XenTabPage
{
#region Private fields
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly string[] m_supportedImageTypes = new[] { ".vhd", ".vmdk" };//CA-61385: remove ".vdi", ".wim" support for Boston
private readonly string[] m_supportedApplianceTypes = new[] { ".ovf", ".ova", ".ova.gz" };
private readonly string[] m_supportedXvaTypes = new[] {".xva", "ova.xml"};
/// <summary>
/// Stores the last valid selected appliance
/// </summary>
private string m_lastValidAppliance;
private EnvelopeType m_selectedOvfEnvelope;
private bool m_buttonNextEnabled;
#endregion
public ImportSourcePage()
{
InitializeComponent();
m_ctrlError.HideError();
m_tlpEncryption.Visible = false;
}
#region Base class (XenTabPage) overrides
/// <summary>
/// Gets the page's title (headline)
/// </summary>
public override string PageTitle { get { return Messages.IMPORT_SOURCE_PAGE_TITLE; } }
/// <summary>
/// Gets the page's label in the (left hand side) wizard progress panel
/// </summary>
public override string Text { get { return Messages.IMPORT_SOURCE_PAGE_TEXT; } }
/// <summary>
/// Gets the value by which the help files section for this page is identified
/// </summary>
public override string HelpID { get { return "Source"; } }
protected override bool ImplementsIsDirty()
{
return true;
}
public override void PageLeave(PageLoadedDirection direction, ref bool cancel)
{
if (direction == PageLoadedDirection.Forward && IsDirty)
{
if (IsUri() && !PerformCheck(CheckDownloadFromUri))
{
cancel = true;
base.PageLeave(direction, ref cancel);
return;
}
if (!PerformCheck(CheckIsSupportedType, CheckPathExists))
{
cancel = true;
base.PageLeave(direction, ref cancel);
return;
}
if (!PerformCheck(CheckIsCompressed))
{
cancel = true;
base.PageLeave(direction, ref cancel);
return;
}
var checks = new List<CheckDelegate>();
switch (TypeOfImport)
{
case ImportWizard.ImportType.Xva:
checks.Add(GetDiskCapacityXva);
break;
case ImportWizard.ImportType.Ovf:
checks.Add(LoadAppliance);
break;
case ImportWizard.ImportType.Vhd:
checks.Add(GetDiskCapacityImage);
break;
}
if (!PerformCheck(checks.ToArray()))
{
cancel = true;
base.PageLeave(direction, ref cancel);
return;
}
if (TypeOfImport == ImportWizard.ImportType.Ovf && OVF.HasEncryption(SelectedOvfEnvelope))
{
cancel = true;
m_tlpEncryption.Visible = true;
m_buttonNextEnabled = false;
OnPageUpdated();
}
}
base.PageLeave(direction, ref cancel);
}
public override void PopulatePage()
{
lblIntro.Text = OvfModeOnly ? Messages.IMPORT_SOURCE_PAGE_INTRO_OVF_ONLY : Messages.IMPORT_SOURCE_PAGE_INTRO;
}
public override bool EnableNext()
{
return m_buttonNextEnabled;
}
#endregion
#region Accessors
public bool OvfModeOnly { private get; set; }
public ImportWizard.ImportType TypeOfImport { get; private set; }
public string FilePath { get { return m_textBoxFile.Text.Trim(); } }
/// <summary>
/// Maybe null if no valid ovf has been found
/// </summary>
public EnvelopeType SelectedOvfEnvelope
{
get { return m_selectedOvfEnvelope; }
private set
{
m_selectedOvfEnvelope = value;
if (m_selectedOvfEnvelope == null)
_SelectedOvfPackage = null;
else
_SelectedOvfPackage = XenOvf.Package.Create(FilePath);
}
}
/// <summary>
/// XenOvf.Package is the proper abstraction for the wizard to use for most cases instead of just OVF.
/// Maintain it along side SelectedOvf until it can be phased out.
/// </summary>
public XenOvf.Package SelectedOvfPackage
{
get
{
if (m_selectedOvfEnvelope == null)
return null;
return _SelectedOvfPackage;
}
}
XenOvf.Package _SelectedOvfPackage;
public ulong ImageLength { get; private set; }
public bool IsWIM { get; private set; }
public bool IsXvaVersion1 { get; private set; }
public ulong DiskCapacity { get; private set; }
#endregion
public void SetFileName(string fileName)
{
m_textBoxFile.Text = fileName;
}
#region Private methods
/// <summary>
/// Performs certain checks on the pages's input data and shows/hides an error accordingly
/// </summary>
/// <param name="checks">The checks to perform</param>
private bool PerformCheck(params CheckDelegate[] checks)
{
m_buttonNextEnabled = m_ctrlError.PerformCheck(checks);
OnPageUpdated();
return m_buttonNextEnabled;
}
private bool GetDiskCapacityXva(out string error)
{
error = string.Empty;
try
{
FileInfo info = new FileInfo(FilePath);
ImageLength = info.Length > 0 ? (ulong)info.Length : 0;
DiskCapacity = IsXvaVersion1
? GetTotalSizeFromXmlGeneva() //Geneva style
: GetTotalSizeFromXmlXva(GetXmlStringFromTarXVA()); //xva style
}
catch (Exception)
{
DiskCapacity = ImageLength;
}
return true;
}
private ulong GetTotalSizeFromXmlGeneva()
{
ulong totalSize = 0;
XmlDocument xmlMetadata = new XmlDocument();
xmlMetadata.Load(FilePath);
XPathNavigator nav = xmlMetadata.CreateNavigator();
XPathNodeIterator nodeIterator = nav.Select(".//vdi");
while (nodeIterator.MoveNext())
totalSize += UInt64.Parse(nodeIterator.Current.GetAttribute("size", ""));
return totalSize;
}
private string GetXmlStringFromTarXVA()
{
using (Stream stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
{
ArchiveIterator iterator = ArchiveFactory.Reader(ArchiveFactory.Type.Tar, stream);
if( iterator.HasNext() )
{
Stream ofs = new MemoryStream();
iterator.ExtractCurrentFile(ofs);
return new StreamReader(ofs).ReadToEnd();
}
return String.Empty;
}
}
private ulong GetTotalSizeFromXmlXva(string xmlString)
{
ulong totalSize = 0;
XmlDocument xmlMetadata = new XmlDocument();
xmlMetadata.LoadXml(xmlString);
XPathNavigator nav = xmlMetadata.CreateNavigator();
XPathNodeIterator nodeIterator = nav.Select(".//name[. = \"virtual_size\"]");
while (nodeIterator.MoveNext())
{
XPathNavigator vdiNavigator = nodeIterator.Current;
if (vdiNavigator.MoveToNext())
totalSize += UInt64.Parse(vdiNavigator.Value);
}
return totalSize;
}
private bool GetDiskCapacityImage(out string error)
{
error = string.Empty;
string filename = FilePath;
FileInfo info = new FileInfo(filename);
ImageLength = info.Length > 0 ? (ulong)info.Length : 0;
if (IsWIM)
{
try
{
using (FileStream wimstream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
WimFile wimDisk = new WimFile(wimstream);
string manifest = wimDisk.Manifest;
Wim_Manifest wimManifest = (Wim_Manifest)Tools.Deserialize(manifest, typeof(Wim_Manifest));
DiskCapacity = wimManifest.Image[wimDisk.BootImage].TotalBytes; //image data size
return true;
}
}
catch (Exception)
{
error = Messages.IMAGE_SELECTION_PAGE_ERROR_CORRUPT_FILE;
return false;
}
}
try
{
using (VirtualDisk vd = VirtualDisk.OpenDisk(filename, FileAccess.Read))
{
DiskCapacity = (ulong)vd.Capacity;
return true;
}
}
catch (IOException ioe)
{
error = ioe.Message.Contains("Invalid VMDK descriptor file")
? Messages.IMAGE_SELECTION_PAGE_ERROR_INVALID_VMDK_DESCRIPTOR
: Messages.IMAGE_SELECTION_PAGE_ERROR_INVALID_FILE_TYPE;
return false;
}
catch (Exception)
{
error = Messages.IMAGE_SELECTION_PAGE_ERROR_CORRUPT_FILE;
return false;
}
}
private bool LoadAppliance(out string error)
{
error = string.Empty;
if (m_lastValidAppliance == FilePath)
return true;
SelectedOvfEnvelope = GetOvfEnvelope(out error);
if (SelectedOvfEnvelope != null)
{
m_lastValidAppliance = FilePath;
return true;
}
return false;
}
private EnvelopeType GetOvfEnvelope(out string error)
{
error = string.Empty;
string path = FilePath;
string extension = Path.GetExtension(path).ToLower();
if (extension == ".ovf")
{
EnvelopeType env = null;
try
{
env = OVF.Load(path);
}
catch(OutOfMemoryException ex)
{
log.ErrorFormat("Failed to load OVF {0} as we ran out of memory: {1}", path, ex.Message);
env = null;
}
if (env == null)
{
error = Messages.INVALID_OVF;
return null;
}
return env;
}
if (extension == ".ova")
{
if (!CheckSourceIsWritable(out error))
return null;
try
{
string x = OVF.ExtractOVFXml(path);
var env = Tools.DeserializeOvfXml(x);
if (env == null)
{
error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_CORRUPT_OVA;
return null;
}
return env;
}
catch (Exception)
{
error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_CORRUPT_OVA;
return null;
}
}
return null;
}
private bool IsUri()
{
Regex regex = new Regex(Messages.URI_REGEX, RegexOptions.IgnoreCase);
return regex.Match(FilePath).Success;
}
/// <summary>
/// Check on the fly
/// </summary>
private bool CheckPathValid(out string error)
{
error = string.Empty;
if (String.IsNullOrEmpty(FilePath))
return false;
//if it's URI ignore
if (IsUri())
return true;
if (!PathValidator.IsPathValid(FilePath))
{
error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_INVALID_PATH;
return false;
}
return true;
}
/// <summary>
/// Check when we leave the page
/// </summary>
private bool CheckIsSupportedType(out string error)
{
error = string.Empty;
IsWIM = false;
string filepath = FilePath;
foreach (var ext in m_supportedXvaTypes)
{
if (filepath.ToLower().EndsWith(ext))
{
if (OvfModeOnly)
{
error = Messages.IMPORT_SOURCE_PAGE_ERROR_OVF_ONLY;
return false;
}
if (ext == "ova.xml")
IsXvaVersion1 = true;
TypeOfImport = ImportWizard.ImportType.Xva;
return true;
}
}
foreach (var ext in m_supportedApplianceTypes)
{
if (filepath.ToLower().EndsWith(ext))
{
TypeOfImport = ImportWizard.ImportType.Ovf;
return true;
}
}
foreach (var ext in m_supportedImageTypes)
{
if (filepath.ToLower().EndsWith(ext))
{
if (OvfModeOnly)
{
error = Messages.IMPORT_SOURCE_PAGE_ERROR_OVF_ONLY;
return false;
}
if (ext == ".wim")
IsWIM = true;
TypeOfImport = ImportWizard.ImportType.Vhd;
return true;
}
}
error = Messages.ERROR_UNSUPPORTED_FILE_TYPE;
return false;
}
/// <summary>
/// Check when we leave the page
/// </summary>
private bool CheckPathExists(out string error)
{
error = string.Empty;
if (File.Exists(FilePath))
return true;
error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_NONE_EXIST_PATH;
return false;
}
/// <summary>
/// Check the source folder is writable
/// </summary>
private bool CheckSourceIsWritable(out string error)
{
error = string.Empty;
var directory = Path.GetDirectoryName(FilePath);
var touchFile = Path.Combine(directory, "_");
try
{
//attempt writing in the destination directory
using (FileStream fs = File.OpenWrite(touchFile))
{
//it works
}
File.Delete(touchFile);
return true;
}
catch (UnauthorizedAccessException)
{
error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_SOURCE_IS_READONLY;
return false;
}
}
/// <summary>
/// Check when we leave the page
/// </summary>
private bool CheckIsCompressed(out string error)
{
error = string.Empty;
string fileName = FilePath;
string extension = Path.GetExtension(fileName).ToLower();
if (extension == ".gz")
{
if (!CheckSourceIsWritable(out error))
return false;
string outfile = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName));
using (var dlog = new DecompressApplianceDialog(fileName, outfile))
{
if (dlog.ShowDialog(ParentForm) == DialogResult.Yes)
{
m_textBoxFile.Text = outfile;
return true;
}
return false; //user cancelled or error
}
}
return true;//it's not compressed, ok to continue
}
private bool CheckDownloadFromUri(out string error)
{
error = string.Empty;
Uri uri;
try
{
uri = new Uri(FilePath);
}
catch (ArgumentNullException)
{
error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_INVALID_URI;
return false;
}
catch (UriFormatException)
{
error = Messages.IMPORT_SELECT_APPLIANCE_PAGE_ERROR_INVALID_URI;
return false;
}
using (var dlog = new DownloadApplianceDialog(uri))
{
if (dlog.ShowDialog(ParentForm) == DialogResult.Yes && !string.IsNullOrEmpty(dlog.DownloadedPath))
{
m_textBoxFile.Text = dlog.DownloadedPath;
return true;
}
return false; //an error happened during download or the user cancelled
}
}
#endregion
#region Control event handlers
private void m_buttonBrowse_Click(object sender, EventArgs e)
{
using (FileDialog ofd = new OpenFileDialog
{
CheckFileExists = true,
CheckPathExists = true,
DereferenceLinks = true,
Filter = OvfModeOnly ? Messages.IMPORT_SOURCE_PAGE_FILETYPES_OVF_ONLY : Messages.IMPORT_SOURCE_PAGE_FILETYPES,
RestoreDirectory = true,
Multiselect = false,
})
{
if (ofd.ShowDialog() == DialogResult.OK)
m_textBoxFile.Text = ofd.FileName;
}
}
private void m_textBoxImage_TextChanged(object sender, EventArgs e)
{
m_tlpEncryption.Visible = false;
PerformCheck(CheckPathValid);
IsDirty = true;
}
#endregion
}
}
| bsd-2-clause |
cfvbaibai/CardFantasy | workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/skill/WeaponSummon.java | 865 | package cfvbaibai.cardfantasy.engine.skill;
import cfvbaibai.cardfantasy.data.Skill;
import cfvbaibai.cardfantasy.engine.*;
public final class WeaponSummon extends PreAttackCardSkill {
public static void apply(SkillResolver resolver, SkillUseInfo skillUseInfo, CardInfo attacker, EntityInfo defender, int min, int max) {
if (attacker.getStatus().containsStatus(CardStatusType.迷惑)) {
// 迷魂状态下不发动英雄杀手
return;
}
Skill skill = skillUseInfo.getSkill();
int adjAT = resolver.getStage().getRandomizer().next(min, max);
//resolver.getStage().getUI().useSkill(attacker, skill, true);
resolver.getStage().getUI().adjustAT(attacker, attacker, adjAT, skill);
attacker.addEffect(new SkillEffect(SkillEffectType.ATTACK_CHANGE, skillUseInfo, adjAT, false));
}
}
| bsd-2-clause |
PopCap/GameIdea | Engine/Source/Runtime/Renderer/Private/SceneOcclusion.cpp | 50556 | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
SceneRendering.cpp: Scene rendering.
=============================================================================*/
#include "RendererPrivate.h"
#include "ScenePrivate.h"
#include "RefCounting.h"
#include "SceneOcclusion.h"
#include "ScreenRendering.h"
#include "SceneFilterRendering.h"
#include "SceneUtils.h"
#include "PostProcessing.h"
/*-----------------------------------------------------------------------------
Globals
-----------------------------------------------------------------------------*/
int32 GAllowPrecomputedVisibility = 1;
static FAutoConsoleVariableRef CVarAllowPrecomputedVisibility(
TEXT("r.AllowPrecomputedVisibility"),
GAllowPrecomputedVisibility,
TEXT("If zero, precomputed visibility will not be used to cull primitives."),
ECVF_RenderThreadSafe
);
static int32 GShowPrecomputedVisibilityCells = 0;
static FAutoConsoleVariableRef CVarShowPrecomputedVisibilityCells(
TEXT("r.ShowPrecomputedVisibilityCells"),
GShowPrecomputedVisibilityCells,
TEXT("If not zero, draw all precomputed visibility cells."),
ECVF_RenderThreadSafe
);
static int32 GShowRelevantPrecomputedVisibilityCells = 0;
static FAutoConsoleVariableRef CVarShowRelevantPrecomputedVisibilityCells(
TEXT("r.ShowRelevantPrecomputedVisibilityCells"),
GShowRelevantPrecomputedVisibilityCells,
TEXT("If not zero, draw relevant precomputed visibility cells only."),
ECVF_RenderThreadSafe
);
#define NUM_CUBE_VERTICES 36
/** Random table for occlusion **/
FOcclusionRandomStream GOcclusionRandomStream;
int32 FOcclusionQueryHelpers::GetNumBufferedFrames()
{
#if WITH_SLI
// If we're running with SLI, assume throughput is more important than latency, and buffer an extra frame
check(GNumActiveGPUsForRendering <= (int32)FOcclusionQueryHelpers::MaxBufferedOcclusionFrames);
return FMath::Min<int32>(GNumActiveGPUsForRendering, (int32)FOcclusionQueryHelpers::MaxBufferedOcclusionFrames);
#else
static const auto NumBufferedQueriesVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.NumBufferedOcclusionQueries"));
return FMath::Clamp<int32>(NumBufferedQueriesVar->GetValueOnAnyThread(), 1, (int32)FOcclusionQueryHelpers::MaxBufferedOcclusionFrames);
#endif
}
// default, non-instanced shader implementation
IMPLEMENT_SHADER_TYPE(,FOcclusionQueryVS,TEXT("OcclusionQueryVertexShader"),TEXT("Main"),SF_Vertex);
FRenderQueryPool::~FRenderQueryPool()
{
Release();
}
void FRenderQueryPool::Release()
{
Queries.Empty();
}
FRenderQueryRHIRef FRenderQueryPool::AllocateQuery()
{
// Are we out of available render queries?
if ( Queries.Num() == 0 )
{
// Create a new render query.
return RHICreateRenderQuery(QueryType);
}
return Queries.Pop(/*bAllowShrinking=*/ false);
}
void FRenderQueryPool::ReleaseQuery(FRHICommandListImmediate& RHICmdList, FRenderQueryRHIRef &Query)
{
if ( IsValidRef(Query) )
{
// Is no one else keeping a refcount to the query?
if ( Query.GetRefCount() == 1 )
{
// Return it to the pool.
Queries.Add( Query );
}
// De-ref without deleting.
Query = NULL;
}
}
FGlobalBoundShaderState FDeferredShadingSceneRenderer::OcclusionTestBoundShaderState;
/**
* Returns an array of visibility data for the given view position, or NULL if none exists.
* The data bits are indexed by VisibilityId of each primitive in the scene.
* This method decompresses data if necessary and caches it based on the bucket and chunk index in the view state.
*/
const uint8* FSceneViewState::GetPrecomputedVisibilityData(FViewInfo& View, const FScene* Scene)
{
const uint8* PrecomputedVisibilityData = NULL;
if (Scene->PrecomputedVisibilityHandler && GAllowPrecomputedVisibility && View.Family->EngineShowFlags.PrecomputedVisibility)
{
const FPrecomputedVisibilityHandler& Handler = *Scene->PrecomputedVisibilityHandler;
FViewElementPDI VisibilityCellsPDI(&View, NULL);
// Draw visibility cell bounds for debugging if enabled
if ((GShowPrecomputedVisibilityCells || View.Family->EngineShowFlags.PrecomputedVisibilityCells) && !GShowRelevantPrecomputedVisibilityCells)
{
for (int32 BucketIndex = 0; BucketIndex < Handler.PrecomputedVisibilityCellBuckets.Num(); BucketIndex++)
{
for (int32 CellIndex = 0; CellIndex < Handler.PrecomputedVisibilityCellBuckets[BucketIndex].Cells.Num(); CellIndex++)
{
const FPrecomputedVisibilityCell& CurrentCell = Handler.PrecomputedVisibilityCellBuckets[BucketIndex].Cells[CellIndex];
// Construct the cell's bounds
const FBox CellBounds(CurrentCell.Min, CurrentCell.Min + FVector(Handler.PrecomputedVisibilityCellSizeXY, Handler.PrecomputedVisibilityCellSizeXY, Handler.PrecomputedVisibilityCellSizeZ));
if (View.ViewFrustum.IntersectBox(CellBounds.GetCenter(), CellBounds.GetExtent()))
{
DrawWireBox(&VisibilityCellsPDI, CellBounds, FColor(50, 50, 255), SDPG_World);
}
}
}
}
// Calculate the bucket that ViewOrigin falls into
// Cells are hashed into buckets to reduce search time
const float FloatOffsetX = (View.ViewMatrices.ViewOrigin.X - Handler.PrecomputedVisibilityCellBucketOriginXY.X) / Handler.PrecomputedVisibilityCellSizeXY;
// FMath::TruncToInt rounds toward 0, we want to always round down
const int32 BucketIndexX = FMath::Abs((FMath::TruncToInt(FloatOffsetX) - (FloatOffsetX < 0.0f ? 1 : 0)) / Handler.PrecomputedVisibilityCellBucketSizeXY % Handler.PrecomputedVisibilityNumCellBuckets);
const float FloatOffsetY = (View.ViewMatrices.ViewOrigin.Y -Handler.PrecomputedVisibilityCellBucketOriginXY.Y) / Handler.PrecomputedVisibilityCellSizeXY;
const int32 BucketIndexY = FMath::Abs((FMath::TruncToInt(FloatOffsetY) - (FloatOffsetY < 0.0f ? 1 : 0)) / Handler.PrecomputedVisibilityCellBucketSizeXY % Handler.PrecomputedVisibilityNumCellBuckets);
const int32 PrecomputedVisibilityBucketIndex = BucketIndexY * Handler.PrecomputedVisibilityCellBucketSizeXY + BucketIndexX;
check(PrecomputedVisibilityBucketIndex < Handler.PrecomputedVisibilityCellBuckets.Num());
const FPrecomputedVisibilityBucket& CurrentBucket = Handler.PrecomputedVisibilityCellBuckets[PrecomputedVisibilityBucketIndex];
for (int32 CellIndex = 0; CellIndex < CurrentBucket.Cells.Num(); CellIndex++)
{
const FPrecomputedVisibilityCell& CurrentCell = CurrentBucket.Cells[CellIndex];
// Construct the cell's bounds
const FBox CellBounds(CurrentCell.Min, CurrentCell.Min + FVector(Handler.PrecomputedVisibilityCellSizeXY, Handler.PrecomputedVisibilityCellSizeXY, Handler.PrecomputedVisibilityCellSizeZ));
// Check if ViewOrigin is inside the current cell
if (CellBounds.IsInside(View.ViewMatrices.ViewOrigin))
{
// Reuse a cached decompressed chunk if possible
if (CachedVisibilityChunk
&& CachedVisibilityHandlerId == Scene->PrecomputedVisibilityHandler->GetId()
&& CachedVisibilityBucketIndex == PrecomputedVisibilityBucketIndex
&& CachedVisibilityChunkIndex == CurrentCell.ChunkIndex)
{
checkSlow(CachedVisibilityChunk->Num() >= CurrentCell.DataOffset + CurrentBucket.CellDataSize);
PrecomputedVisibilityData = &(*CachedVisibilityChunk)[CurrentCell.DataOffset];
}
else
{
const FCompressedVisibilityChunk& CompressedChunk = Handler.PrecomputedVisibilityCellBuckets[PrecomputedVisibilityBucketIndex].CellDataChunks[CurrentCell.ChunkIndex];
CachedVisibilityBucketIndex = PrecomputedVisibilityBucketIndex;
CachedVisibilityChunkIndex = CurrentCell.ChunkIndex;
CachedVisibilityHandlerId = Scene->PrecomputedVisibilityHandler->GetId();
if (CompressedChunk.bCompressed)
{
// Decompress the needed visibility data chunk
DecompressedVisibilityChunk.Reset();
DecompressedVisibilityChunk.AddUninitialized(CompressedChunk.UncompressedSize);
verify(FCompression::UncompressMemory(
COMPRESS_ZLIB,
DecompressedVisibilityChunk.GetData(),
CompressedChunk.UncompressedSize,
CompressedChunk.Data.GetData(),
CompressedChunk.Data.Num()));
CachedVisibilityChunk = &DecompressedVisibilityChunk;
}
else
{
CachedVisibilityChunk = &CompressedChunk.Data;
}
checkSlow(CachedVisibilityChunk->Num() >= CurrentCell.DataOffset + CurrentBucket.CellDataSize);
// Return a pointer to the cell containing ViewOrigin's decompressed visibility data
PrecomputedVisibilityData = &(*CachedVisibilityChunk)[CurrentCell.DataOffset];
}
if (GShowRelevantPrecomputedVisibilityCells)
{
// Draw the currently used visibility cell with green wireframe for debugging
DrawWireBox(&VisibilityCellsPDI, CellBounds, FColor(50, 255, 50), SDPG_Foreground);
}
else
{
break;
}
}
else if (GShowRelevantPrecomputedVisibilityCells)
{
// Draw all cells in the current visibility bucket as blue wireframe
DrawWireBox(&VisibilityCellsPDI, CellBounds, FColor(50, 50, 255), SDPG_World);
}
}
}
return PrecomputedVisibilityData;
}
void FSceneViewState::TrimOcclusionHistory(FRHICommandListImmediate& RHICmdList, float MinHistoryTime, float MinQueryTime, int32 FrameNumber)
{
// Only trim every few frames, since stale entries won't cause problems
if (FrameNumber % 6 == 0)
{
int32 NumBufferedFrames = FOcclusionQueryHelpers::GetNumBufferedFrames();
for(TSet<FPrimitiveOcclusionHistory,FPrimitiveOcclusionHistoryKeyFuncs>::TIterator PrimitiveIt(PrimitiveOcclusionHistorySet);
PrimitiveIt;
++PrimitiveIt
)
{
// If the primitive has an old pending occlusion query, release it.
if(PrimitiveIt->LastConsideredTime < MinQueryTime)
{
PrimitiveIt->ReleaseQueries(RHICmdList, OcclusionQueryPool, NumBufferedFrames);
}
// If the primitive hasn't been considered for visibility recently, remove its history from the set.
if(PrimitiveIt->LastConsideredTime < MinHistoryTime)
{
PrimitiveIt.RemoveCurrent();
}
}
}
}
bool FSceneViewState::IsShadowOccluded(FRHICommandListImmediate& RHICmdList, FPrimitiveComponentId PrimitiveId, const ULightComponent* Light, int32 InShadowSplitIndex, bool bTranslucentShadow, int32 NumBufferedFrames) const
{
// Find the shadow's occlusion query from the previous frame.
const FSceneViewState::FProjectedShadowKey Key(PrimitiveId, Light, InShadowSplitIndex, bTranslucentShadow);
// Get the oldest occlusion query
const uint32 QueryIndex = FOcclusionQueryHelpers::GetQueryLookupIndex(PendingPrevFrameNumber, NumBufferedFrames);
const FSceneViewState::ShadowKeyOcclusionQueryMap& ShadowOcclusionQueryMap = ShadowOcclusionQueryMaps[QueryIndex];
const FRenderQueryRHIRef* Query = ShadowOcclusionQueryMap.Find(Key);
// Read the occlusion query results.
uint64 NumSamples = 0;
// Only block on the query if not running SLI
const bool bWaitOnQuery = GNumActiveGPUsForRendering == 1;
if (Query && RHICmdList.GetRenderQueryResult(*Query, NumSamples, bWaitOnQuery))
{
// If the shadow's occlusion query didn't have any pixels visible the previous frame, it's occluded.
return NumSamples == 0;
}
else
{
// If the shadow wasn't queried the previous frame, it isn't occluded.
return false;
}
}
void FSceneViewState::Destroy()
{
if ( IsInGameThread() )
{
// Release the occlusion query data.
BeginReleaseResource(this);
// Defer deletion of the view state until the rendering thread is done with it.
BeginCleanup(this);
}
else
{
ReleaseResource();
FinishCleanup();
}
}
SIZE_T FSceneViewState::GetSizeBytes() const
{
uint32 ShadowOcclusionQuerySize = ShadowOcclusionQueryMaps.GetAllocatedSize();
for (int32 i = 0; i < ShadowOcclusionQueryMaps.Num(); ++i)
{
ShadowOcclusionQuerySize += ShadowOcclusionQueryMaps[i].GetAllocatedSize();
}
return sizeof(*this)
+ ShadowOcclusionQuerySize
+ ParentPrimitives.GetAllocatedSize()
+ PrimitiveFadingStates.GetAllocatedSize()
+ PrimitiveOcclusionHistorySet.GetAllocatedSize();
}
class FOcclusionQueryIndexBuffer : public FIndexBuffer
{
public:
virtual void InitRHI() override
{
const uint32 MaxBatchedPrimitives = FOcclusionQueryBatcher::OccludedPrimitiveQueryBatchSize;
const uint32 Stride = sizeof(uint16);
const uint32 SizeInBytes = MaxBatchedPrimitives * NUM_CUBE_VERTICES * Stride;
FRHIResourceCreateInfo CreateInfo;
void* BufferData;
IndexBufferRHI = RHICreateAndLockIndexBuffer(Stride, SizeInBytes, BUF_Static, CreateInfo, BufferData);
uint16* RESTRICT Indices = (uint16*)BufferData;
for(uint32 PrimitiveIndex = 0;PrimitiveIndex < MaxBatchedPrimitives;PrimitiveIndex++)
{
for(int32 Index = 0;Index < NUM_CUBE_VERTICES;Index++)
{
Indices[PrimitiveIndex * NUM_CUBE_VERTICES + Index] = PrimitiveIndex * 8 + GCubeIndices[Index];
}
}
RHIUnlockIndexBuffer(IndexBufferRHI);
}
};
TGlobalResource<FOcclusionQueryIndexBuffer> GOcclusionQueryIndexBuffer;
FOcclusionQueryBatcher::FOcclusionQueryBatcher(class FSceneViewState* ViewState,uint32 InMaxBatchedPrimitives)
: CurrentBatchOcclusionQuery(NULL)
, MaxBatchedPrimitives(InMaxBatchedPrimitives)
, NumBatchedPrimitives(0)
, OcclusionQueryPool(ViewState ? &ViewState->OcclusionQueryPool : NULL)
{}
FOcclusionQueryBatcher::~FOcclusionQueryBatcher()
{
check(!BatchOcclusionQueries.Num());
}
void FOcclusionQueryBatcher::Flush(FRHICommandListImmediate& RHICmdList)
{
if(BatchOcclusionQueries.Num())
{
FMemMark MemStackMark(FMemStack::Get());
// Create the indices for MaxBatchedPrimitives boxes.
FIndexBufferRHIParamRef IndexBufferRHI = GOcclusionQueryIndexBuffer.IndexBufferRHI;
// Draw the batches.
for(int32 BatchIndex = 0, NumBatches = BatchOcclusionQueries.Num();BatchIndex < NumBatches;BatchIndex++)
{
FOcclusionBatch& Batch = BatchOcclusionQueries[BatchIndex];
FRenderQueryRHIParamRef BatchOcclusionQuery = Batch.Query;
FVertexBufferRHIParamRef VertexBufferRHI = Batch.VertexAllocation.VertexBuffer->VertexBufferRHI;
uint32 VertexBufferOffset = Batch.VertexAllocation.VertexOffset;
const int32 NumPrimitivesThisBatch = (BatchIndex != (NumBatches-1)) ? MaxBatchedPrimitives : NumBatchedPrimitives;
RHICmdList.BeginRenderQuery(BatchOcclusionQuery);
RHICmdList.SetStreamSource(0, VertexBufferRHI, sizeof(FVector), VertexBufferOffset);
RHICmdList.DrawIndexedPrimitive(
IndexBufferRHI,
PT_TriangleList,
/*BaseVertexIndex=*/ 0,
/*MinIndex=*/ 0,
/*NumVertices=*/ 8 * NumPrimitivesThisBatch,
/*StartIndex=*/ 0,
/*NumPrimitives=*/ 12 * NumPrimitivesThisBatch,
/*NumInstances=*/ 1
);
RHICmdList.EndRenderQuery(BatchOcclusionQuery);
}
INC_DWORD_STAT_BY(STAT_OcclusionQueries,BatchOcclusionQueries.Num());
// Reset the batch state.
BatchOcclusionQueries.Empty(BatchOcclusionQueries.Num());
CurrentBatchOcclusionQuery = NULL;
}
}
FRenderQueryRHIParamRef FOcclusionQueryBatcher::BatchPrimitive(const FVector& BoundsOrigin,const FVector& BoundsBoxExtent)
{
// Check if the current batch is full.
if(CurrentBatchOcclusionQuery == NULL || NumBatchedPrimitives >= MaxBatchedPrimitives)
{
check(OcclusionQueryPool);
CurrentBatchOcclusionQuery = new(BatchOcclusionQueries) FOcclusionBatch;
CurrentBatchOcclusionQuery->Query = OcclusionQueryPool->AllocateQuery();
CurrentBatchOcclusionQuery->VertexAllocation = FGlobalDynamicVertexBuffer::Get().Allocate(MaxBatchedPrimitives * 8 * sizeof(FVector));
check(CurrentBatchOcclusionQuery->VertexAllocation.IsValid());
NumBatchedPrimitives = 0;
}
// Add the primitive's bounding box to the current batch's vertex buffer.
const FVector PrimitiveBoxMin = BoundsOrigin - BoundsBoxExtent;
const FVector PrimitiveBoxMax = BoundsOrigin + BoundsBoxExtent;
float* RESTRICT Vertices = (float*)CurrentBatchOcclusionQuery->VertexAllocation.Buffer;
Vertices[ 0] = PrimitiveBoxMin.X; Vertices[ 1] = PrimitiveBoxMin.Y; Vertices[ 2] = PrimitiveBoxMin.Z;
Vertices[ 3] = PrimitiveBoxMin.X; Vertices[ 4] = PrimitiveBoxMin.Y; Vertices[ 5] = PrimitiveBoxMax.Z;
Vertices[ 6] = PrimitiveBoxMin.X; Vertices[ 7] = PrimitiveBoxMax.Y; Vertices[ 8] = PrimitiveBoxMin.Z;
Vertices[ 9] = PrimitiveBoxMin.X; Vertices[10] = PrimitiveBoxMax.Y; Vertices[11] = PrimitiveBoxMax.Z;
Vertices[12] = PrimitiveBoxMax.X; Vertices[13] = PrimitiveBoxMin.Y; Vertices[14] = PrimitiveBoxMin.Z;
Vertices[15] = PrimitiveBoxMax.X; Vertices[16] = PrimitiveBoxMin.Y; Vertices[17] = PrimitiveBoxMax.Z;
Vertices[18] = PrimitiveBoxMax.X; Vertices[19] = PrimitiveBoxMax.Y; Vertices[20] = PrimitiveBoxMin.Z;
Vertices[21] = PrimitiveBoxMax.X; Vertices[22] = PrimitiveBoxMax.Y; Vertices[23] = PrimitiveBoxMax.Z;
// Bump the batches buffer pointer.
Vertices += 24;
CurrentBatchOcclusionQuery->VertexAllocation.Buffer = (uint8*)Vertices;
NumBatchedPrimitives++;
return CurrentBatchOcclusionQuery->Query;
}
static void IssueProjectedShadowOcclusionQuery(FRHICommandListImmediate& RHICmdList, FViewInfo& View, const FProjectedShadowInfo& ProjectedShadowInfo, FOcclusionQueryVS* VertexShader, int32 NumBufferedFrames)
{
FSceneViewState* ViewState = (FSceneViewState*)View.State;
const uint32 QueryIndex = FOcclusionQueryHelpers::GetQueryIssueIndex(ViewState->PendingPrevFrameNumber, NumBufferedFrames);
FSceneViewState::ShadowKeyOcclusionQueryMap& ShadowOcclusionQueryMap = ViewState->ShadowOcclusionQueryMaps[QueryIndex];
// The shadow transforms and view transforms are relative to different origins, so the world coordinates need to
// be translated.
const FVector4 PreShadowToPreViewTranslation(View.ViewMatrices.PreViewTranslation - ProjectedShadowInfo.PreShadowTranslation,0);
// If the shadow frustum is farther from the view origin than the near clipping plane,
// it can't intersect the near clipping plane.
const bool bIntersectsNearClippingPlane = ProjectedShadowInfo.ReceiverFrustum.IntersectSphere(
View.ViewMatrices.ViewOrigin + ProjectedShadowInfo.PreShadowTranslation,
View.NearClippingDistance * FMath::Sqrt(3.0f)
);
if( !bIntersectsNearClippingPlane )
{
// Allocate an occlusion query for the primitive from the occlusion query pool.
const FRenderQueryRHIRef ShadowOcclusionQuery = ViewState->OcclusionQueryPool.AllocateQuery();
VertexShader->SetParameters(RHICmdList, View);
// Draw the primitive's bounding box, using the occlusion query.
RHICmdList.BeginRenderQuery(ShadowOcclusionQuery);
void* VerticesPtr;
void* IndicesPtr;
// preallocate memory to fill out with vertices and indices
RHICmdList.BeginDrawIndexedPrimitiveUP(PT_TriangleList, 12, 8, sizeof(FVector), VerticesPtr, 0, NUM_CUBE_VERTICES, sizeof(uint16), IndicesPtr);
FVector* Vertices = (FVector*)VerticesPtr;
uint16* Indices = (uint16*)IndicesPtr;
// Generate vertices for the shadow's frustum.
for(uint32 Z = 0;Z < 2;Z++)
{
for(uint32 Y = 0;Y < 2;Y++)
{
for(uint32 X = 0;X < 2;X++)
{
const FVector4 UnprojectedVertex = ProjectedShadowInfo.InvReceiverMatrix.TransformFVector4(
FVector4(
(X ? -1.0f : 1.0f),
(Y ? -1.0f : 1.0f),
(Z ? 1.0f : 0.0f),
1.0f
)
);
const FVector ProjectedVertex = UnprojectedVertex / UnprojectedVertex.W + PreShadowToPreViewTranslation;
Vertices[GetCubeVertexIndex(X,Y,Z)] = ProjectedVertex;
}
}
}
// we just copy the indices right in
FMemory::Memcpy(Indices, GCubeIndices, sizeof(GCubeIndices));
FSceneViewState::FProjectedShadowKey Key(ProjectedShadowInfo);
checkSlow(ShadowOcclusionQueryMap.Find(Key) == NULL);
ShadowOcclusionQueryMap.Add(Key, ShadowOcclusionQuery);
RHICmdList.EndDrawIndexedPrimitiveUP();
RHICmdList.EndRenderQuery(ShadowOcclusionQuery);
}
}
FHZBOcclusionTester::FHZBOcclusionTester()
: ResultsBuffer( NULL )
{
SetInvalidFrameNumber();
}
bool FHZBOcclusionTester::IsValidFrame(uint32 FrameNumber) const
{
return (FrameNumber & FrameNumberMask) == ValidFrameNumber;
}
void FHZBOcclusionTester::SetValidFrameNumber(uint32 FrameNumber)
{
ValidFrameNumber = FrameNumber & FrameNumberMask;
checkSlow(!IsInvalidFrame());
}
bool FHZBOcclusionTester::IsInvalidFrame() const
{
return ValidFrameNumber == InvalidFrameNumber;
}
void FHZBOcclusionTester::SetInvalidFrameNumber()
{
// this number cannot be set by SetValidFrameNumber()
ValidFrameNumber = InvalidFrameNumber;
checkSlow(IsInvalidFrame());
}
void FHZBOcclusionTester::InitDynamicRHI()
{
if (GetFeatureLevel() >= ERHIFeatureLevel::SM4)
{
#if PLATFORM_MAC // Workaround radr://16096028 Texture Readback via glReadPixels + PBOs stalls on Nvidia GPUs
FPooledRenderTargetDesc Desc( FPooledRenderTargetDesc::Create2DDesc( FIntPoint( SizeX, SizeY ), PF_R8G8B8A8, FClearValueBinding::None, TexCreate_CPUReadback | TexCreate_HideInVisualizeTexture, TexCreate_None, false ) );
#else
FPooledRenderTargetDesc Desc( FPooledRenderTargetDesc::Create2DDesc( FIntPoint( SizeX, SizeY ), PF_B8G8R8A8, FClearValueBinding::None, TexCreate_CPUReadback | TexCreate_HideInVisualizeTexture, TexCreate_None, false ) );
#endif
GRenderTargetPool.FindFreeElement( Desc, ResultsTextureCPU, TEXT("HZBResultsCPU") );
}
}
void FHZBOcclusionTester::ReleaseDynamicRHI()
{
if (GetFeatureLevel() >= ERHIFeatureLevel::SM4)
{
GRenderTargetPool.FreeUnusedResource( ResultsTextureCPU );
}
}
uint32 FHZBOcclusionTester::AddBounds( const FVector& BoundsCenter, const FVector& BoundsExtent )
{
uint32 Index = Primitives.AddUninitialized();
check( Index < SizeX * SizeY );
Primitives[ Index ].Center = BoundsCenter;
Primitives[ Index ].Extent = BoundsExtent;
return Index;
}
void FHZBOcclusionTester::MapResults(FRHICommandListImmediate& RHICmdList)
{
check( !ResultsBuffer );
if( !IsInvalidFrame() )
{
uint32 IdleStart = FPlatformTime::Cycles();
int32 Width = 0;
int32 Height = 0;
RHICmdList.MapStagingSurface(ResultsTextureCPU->GetRenderTargetItem().ShaderResourceTexture, (void*&)ResultsBuffer, Width, Height);
// RHIMapStagingSurface will block until the results are ready (from the previous frame) so we need to consider this RT idle time
GRenderThreadIdle[ERenderThreadIdleTypes::WaitingForGPUQuery] += FPlatformTime::Cycles() - IdleStart;
GRenderThreadNumIdle[ERenderThreadIdleTypes::WaitingForGPUQuery]++;
}
// Can happen because of device removed, we might crash later but this occlusion culling system can behave gracefully.
if( ResultsBuffer == NULL )
{
// First frame
static uint8 FirstFrameBuffer[] = { 255 };
ResultsBuffer = FirstFrameBuffer;
SetInvalidFrameNumber();
}
}
void FHZBOcclusionTester::UnmapResults(FRHICommandListImmediate& RHICmdList)
{
check( ResultsBuffer );
if(!IsInvalidFrame())
{
RHICmdList.UnmapStagingSurface(ResultsTextureCPU->GetRenderTargetItem().ShaderResourceTexture);
}
ResultsBuffer = NULL;
}
bool FHZBOcclusionTester::IsVisible( uint32 Index ) const
{
checkSlow( ResultsBuffer );
checkSlow( Index < SizeX * SizeY );
// TODO shader compress to bits
#if 0
return ResultsBuffer[ 4 * Index ] != 0;
#elif 0
uint32 x = FMath::ReverseMortonCode2( Index >> 0 );
uint32 y = FMath::ReverseMortonCode2( Index >> 1 );
uint32 m = x + y * SizeX;
return ResultsBuffer[ 4 * m ] != 0;
#else
// TODO put block constants in class
// TODO optimize
const uint32 BlockSize = 8;
const uint32 SizeInBlocksX = SizeX / BlockSize;
const uint32 SizeInBlocksY = SizeY / BlockSize;
const int32 BlockIndex = Index / (BlockSize * BlockSize);
const int32 BlockX = BlockIndex % SizeInBlocksX;
const int32 BlockY = BlockIndex / SizeInBlocksY;
const int32 b = Index % (BlockSize * BlockSize);
const int32 x = BlockX * BlockSize + b % BlockSize;
const int32 y = BlockY * BlockSize + b / BlockSize;
return ResultsBuffer[ 4 * (x + y * SizeY) ] != 0;
#endif
}
class FHZBTestPS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FHZBTestPS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform, OutEnvironment);
}
FHZBTestPS() {}
public:
FShaderParameter HZBUvFactor;
FShaderParameter HZBSize;
FShaderResourceParameter HZBTexture;
FShaderResourceParameter HZBSampler;
FShaderResourceParameter BoundsCenterTexture;
FShaderResourceParameter BoundsCenterSampler;
FShaderResourceParameter BoundsExtentTexture;
FShaderResourceParameter BoundsExtentSampler;
FHZBTestPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
HZBUvFactor.Bind( Initializer.ParameterMap, TEXT("HZBUvFactor") );
HZBSize.Bind( Initializer.ParameterMap, TEXT("HZBSize") );
HZBTexture.Bind( Initializer.ParameterMap, TEXT("HZBTexture") );
HZBSampler.Bind( Initializer.ParameterMap, TEXT("HZBSampler") );
BoundsCenterTexture.Bind( Initializer.ParameterMap, TEXT("BoundsCenterTexture") );
BoundsCenterSampler.Bind( Initializer.ParameterMap, TEXT("BoundsCenterSampler") );
BoundsExtentTexture.Bind( Initializer.ParameterMap, TEXT("BoundsExtentTexture") );
BoundsExtentSampler.Bind( Initializer.ParameterMap, TEXT("BoundsExtentSampler") );
}
void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View, FTextureRHIParamRef BoundsCenter, FTextureRHIParamRef BoundsExtent )
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View );
/*
* Defines the maximum number of mipmaps the HZB test is considering
* to avoid memory cache trashing when rendering on high resolution.
*/
const float kHZBTestMaxMipmap = 9.0f;
const float HZBMipmapCounts = FMath::Log2(FMath::Max(View.HZBMipmap0Size.X, View.HZBMipmap0Size.Y));
const FVector HZBUvFactorValue(
float(View.ViewRect.Width()) / float(2 * View.HZBMipmap0Size.X),
float(View.ViewRect.Height()) / float(2 * View.HZBMipmap0Size.Y),
FMath::Max(HZBMipmapCounts - kHZBTestMaxMipmap, 0.0f)
);
const FVector4 HZBSizeValue(
View.HZBMipmap0Size.X,
View.HZBMipmap0Size.Y,
1.0f / float(View.HZBMipmap0Size.X),
1.0f / float(View.HZBMipmap0Size.Y)
);
SetShaderValue(RHICmdList, ShaderRHI, HZBUvFactor, HZBUvFactorValue);
SetShaderValue(RHICmdList, ShaderRHI, HZBSize, HZBSizeValue);
SetTextureParameter(RHICmdList, ShaderRHI, HZBTexture, HZBSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), View.HZB->GetRenderTargetItem().ShaderResourceTexture );
SetTextureParameter(RHICmdList, ShaderRHI, BoundsCenterTexture, BoundsCenterSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), BoundsCenter );
SetTextureParameter(RHICmdList, ShaderRHI, BoundsExtentTexture, BoundsExtentSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), BoundsExtent );
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << HZBUvFactor;
Ar << HZBSize;
Ar << HZBTexture;
Ar << HZBSampler;
Ar << BoundsCenterTexture;
Ar << BoundsCenterSampler;
Ar << BoundsExtentTexture;
Ar << BoundsExtentSampler;
return bShaderHasOutdatedParameters;
}
};
IMPLEMENT_SHADER_TYPE(,FHZBTestPS,TEXT("HZBOcclusion"),TEXT("HZBTestPS"),SF_Pixel);
void FHZBOcclusionTester::Submit(FRHICommandListImmediate& RHICmdList, const FViewInfo& View)
{
SCOPED_DRAW_EVENT(RHICmdList, SubmitHZB);
FSceneViewState* ViewState = (FSceneViewState*)View.State;
if( !ViewState )
{
return;
}
TRefCountPtr< IPooledRenderTarget > BoundsCenterTexture;
TRefCountPtr< IPooledRenderTarget > BoundsExtentTexture;
{
uint32 Flags = TexCreate_ShaderResource | TexCreate_Dynamic;
FPooledRenderTargetDesc Desc( FPooledRenderTargetDesc::Create2DDesc( FIntPoint( SizeX, SizeY ), PF_A32B32G32R32F, FClearValueBinding::None, Flags, TexCreate_None, false ) );
GRenderTargetPool.FindFreeElement( Desc, BoundsCenterTexture, TEXT("HZBBoundsCenter") );
GRenderTargetPool.FindFreeElement( Desc, BoundsExtentTexture, TEXT("HZBBoundsExtent") );
}
TRefCountPtr< IPooledRenderTarget > ResultsTextureGPU;
{
#if PLATFORM_MAC // Workaround radr://16096028 Texture Readback via glReadPixels + PBOs stalls on Nvidia GPUs
FPooledRenderTargetDesc Desc( FPooledRenderTargetDesc::Create2DDesc( FIntPoint( SizeX, SizeY ), PF_R8G8B8A8, FClearValueBinding::None, TexCreate_None, TexCreate_RenderTargetable, false ) );
#else
FPooledRenderTargetDesc Desc( FPooledRenderTargetDesc::Create2DDesc( FIntPoint( SizeX, SizeY ), PF_B8G8R8A8, FClearValueBinding::None, TexCreate_None, TexCreate_RenderTargetable, false ) );
#endif
GRenderTargetPool.FindFreeElement( Desc, ResultsTextureGPU, TEXT("HZBResultsGPU") );
}
{
#if 0
static float CenterBuffer[ SizeX * SizeY ][4];
static float ExtentBuffer[ SizeX * SizeY ][4];
FMemory::Memset( CenterBuffer, 0, sizeof( CenterBuffer ) );
FMemory::Memset( ExtentBuffer, 0, sizeof( ExtentBuffer ) );
const uint32 NumPrimitives = Primitives.Num();
for( uint32 i = 0; i < NumPrimitives; i++ )
{
const FOcclusionPrimitive& Primitive = Primitives[i];
CenterBuffer[i][0] = Primitive.Center.X;
CenterBuffer[i][1] = Primitive.Center.Y;
CenterBuffer[i][2] = Primitive.Center.Z;
CenterBuffer[i][3] = 0.0f;
ExtentBuffer[i][0] = Primitive.Extent.X;
ExtentBuffer[i][1] = Primitive.Extent.Y;
ExtentBuffer[i][2] = Primitive.Extent.Z;
ExtentBuffer[i][3] = 1.0f;
}
FUpdateTextureRegion2D Region( 0, 0, 0, 0, SizeX, SizeY );
RHIUpdateTexture2D( (FTexture2DRHIRef&)BoundsCenterTexture->GetRenderTargetItem().ShaderResourceTexture, 0, Region, SizeX * 4 * sizeof( float ), (uint8*)CenterBuffer );
RHIUpdateTexture2D( (FTexture2DRHIRef&)BoundsExtentTexture->GetRenderTargetItem().ShaderResourceTexture, 0, Region, SizeX * 4 * sizeof( float ), (uint8*)ExtentBuffer );
#elif 0
static float CenterBuffer[ SizeX * SizeY ][4];
static float ExtentBuffer[ SizeX * SizeY ][4];
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_HZBPackPrimitiveData);
FMemory::Memset( CenterBuffer, 0, sizeof( CenterBuffer ) );
FMemory::Memset( ExtentBuffer, 0, sizeof( ExtentBuffer ) );
const uint32 NumPrimitives = Primitives.Num();
for( uint32 i = 0; i < NumPrimitives; i++ )
{
const FOcclusionPrimitive& Primitive = Primitives[i];
uint32 x = FMath::ReverseMortonCode2( i >> 0 );
uint32 y = FMath::ReverseMortonCode2( i >> 1 );
uint32 m = x + y * SizeX;
CenterBuffer[m][0] = Primitive.Center.X;
CenterBuffer[m][1] = Primitive.Center.Y;
CenterBuffer[m][2] = Primitive.Center.Z;
CenterBuffer[m][3] = 0.0f;
ExtentBuffer[m][0] = Primitive.Extent.X;
ExtentBuffer[m][1] = Primitive.Extent.Y;
ExtentBuffer[m][2] = Primitive.Extent.Z;
ExtentBuffer[m][3] = 1.0f;
}
}
QUICK_SCOPE_CYCLE_COUNTER(STAT_HZBUpdateTextures);
FUpdateTextureRegion2D Region( 0, 0, 0, 0, SizeX, SizeY );
RHIUpdateTexture2D( (FTexture2DRHIRef&)BoundsCenterTexture->GetRenderTargetItem().ShaderResourceTexture, 0, Region, SizeX * 4 * sizeof( float ), (uint8*)CenterBuffer );
RHIUpdateTexture2D( (FTexture2DRHIRef&)BoundsExtentTexture->GetRenderTargetItem().ShaderResourceTexture, 0, Region, SizeX * 4 * sizeof( float ), (uint8*)ExtentBuffer );
#else
// Update in blocks to avoid large update
const uint32 BlockSize = 8;
const uint32 SizeInBlocksX = SizeX / BlockSize;
const uint32 SizeInBlocksY = SizeY / BlockSize;
const uint32 BlockStride = BlockSize * 4 * sizeof( float );
float CenterBuffer[ BlockSize * BlockSize ][4];
float ExtentBuffer[ BlockSize * BlockSize ][4];
const uint32 NumPrimitives = Primitives.Num();
for( uint32 i = 0; i < NumPrimitives; i += BlockSize * BlockSize )
{
const uint32 BlockEnd = FMath::Min( BlockSize * BlockSize, NumPrimitives - i );
for( uint32 b = 0; b < BlockEnd; b++ )
{
const FOcclusionPrimitive& Primitive = Primitives[ i + b ];
CenterBuffer[b][0] = Primitive.Center.X;
CenterBuffer[b][1] = Primitive.Center.Y;
CenterBuffer[b][2] = Primitive.Center.Z;
CenterBuffer[b][3] = 0.0f;
ExtentBuffer[b][0] = Primitive.Extent.X;
ExtentBuffer[b][1] = Primitive.Extent.Y;
ExtentBuffer[b][2] = Primitive.Extent.Z;
ExtentBuffer[b][3] = 1.0f;
}
// Clear rest of block
if( BlockEnd < BlockSize * BlockSize )
{
FMemory::Memset( (float*)CenterBuffer + BlockEnd * 4, 0, sizeof( CenterBuffer ) - BlockEnd * 4 * sizeof(float) );
FMemory::Memset( (float*)ExtentBuffer + BlockEnd * 4, 0, sizeof( ExtentBuffer ) - BlockEnd * 4 * sizeof(float) );
}
const int32 BlockIndex = i / (BlockSize * BlockSize);
const int32 BlockX = BlockIndex % SizeInBlocksX;
const int32 BlockY = BlockIndex / SizeInBlocksY;
FUpdateTextureRegion2D Region( BlockX * BlockSize, BlockY * BlockSize, 0, 0, BlockSize, BlockSize );
RHIUpdateTexture2D( (FTexture2DRHIRef&)BoundsCenterTexture->GetRenderTargetItem().ShaderResourceTexture, 0, Region, BlockStride, (uint8*)CenterBuffer );
RHIUpdateTexture2D( (FTexture2DRHIRef&)BoundsExtentTexture->GetRenderTargetItem().ShaderResourceTexture, 0, Region, BlockStride, (uint8*)ExtentBuffer );
}
#endif
Primitives.Empty();
}
// Draw test
{
SCOPED_DRAW_EVENT(RHICmdList, TestHZB);
SetRenderTarget(RHICmdList, ResultsTextureGPU->GetRenderTargetItem().TargetableTexture, NULL);
RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
RHICmdList.SetDepthStencilState(TStaticDepthStencilState< false, CF_Always >::GetRHI());
TShaderMapRef< FScreenVS > VertexShader(View.ShaderMap);
TShaderMapRef< FHZBTestPS > PixelShader(View.ShaderMap);
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
PixelShader->SetParameters(RHICmdList, View, BoundsCenterTexture->GetRenderTargetItem().ShaderResourceTexture, BoundsExtentTexture->GetRenderTargetItem().ShaderResourceTexture );
RHICmdList.SetViewport(0, 0, 0.0f, SizeX, SizeY, 1.0f);
// TODO draw quads covering blocks added above
DrawRectangle(
RHICmdList,
0, 0,
SizeX, SizeY,
0, 0,
SizeX, SizeY,
FIntPoint( SizeX, SizeY ),
FIntPoint( SizeX, SizeY ),
*VertexShader,
EDRF_UseTriangleOptimization);
}
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, ResultsTextureGPU);
// Transfer memory GPU -> CPU
RHICmdList.CopyToResolveTarget(ResultsTextureGPU->GetRenderTargetItem().TargetableTexture, ResultsTextureCPU->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams());
}
template< uint32 Stage >
class THZBBuildPS : public FGlobalShader
{
DECLARE_SHADER_TYPE(THZBBuildPS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform, OutEnvironment);
OutEnvironment.SetDefine( TEXT("STAGE"), Stage );
OutEnvironment.SetRenderTargetOutputFormat(0, PF_R32_FLOAT);
}
THZBBuildPS() {}
public:
FShaderParameter InvSizeParameter;
FShaderParameter InputUvFactorAndOffsetParameter;
FShaderParameter InputViewportMaxBoundParameter;
FSceneTextureShaderParameters SceneTextureParameters;
FShaderResourceParameter TextureParameter;
FShaderResourceParameter TextureParameterSampler;
THZBBuildPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
InvSizeParameter.Bind( Initializer.ParameterMap, TEXT("InvSize") );
InputUvFactorAndOffsetParameter.Bind( Initializer.ParameterMap, TEXT("InputUvFactorAndOffset") );
InputViewportMaxBoundParameter.Bind( Initializer.ParameterMap, TEXT("InputViewportMaxBound") );
SceneTextureParameters.Bind( Initializer.ParameterMap );
TextureParameter.Bind( Initializer.ParameterMap, TEXT("Texture") );
TextureParameterSampler.Bind( Initializer.ParameterMap, TEXT("TextureSampler") );
}
void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View );
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
const FIntPoint GBufferSize = SceneContext.GetBufferSizeXY();
const FVector2D InvSize( 1.0f / float(GBufferSize.X), 1.0f / float(GBufferSize.Y) );
const FVector4 InputUvFactorAndOffset (
float(2 * View.HZBMipmap0Size.X) / float(GBufferSize.X),
float(2 * View.HZBMipmap0Size.Y) / float(GBufferSize.Y),
float(View.ViewRect.Min.X) / float(GBufferSize.X),
float(View.ViewRect.Min.Y) / float(GBufferSize.Y)
);
const FVector2D InputViewportMaxBound (
float(View.ViewRect.Max.X) / float(GBufferSize.X) - 0.5f * InvSize.X,
float(View.ViewRect.Max.Y) / float(GBufferSize.Y) - 0.5f * InvSize.Y
);
SetShaderValue(RHICmdList, ShaderRHI, InvSizeParameter, InvSize );
SetShaderValue(RHICmdList, ShaderRHI, InputUvFactorAndOffsetParameter, InputUvFactorAndOffset );
SetShaderValue(RHICmdList, ShaderRHI, InputViewportMaxBoundParameter, InputViewportMaxBound );
SceneTextureParameters.Set(RHICmdList, ShaderRHI, View );
}
void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, const FIntPoint& Size, FShaderResourceViewRHIParamRef ShaderResourceView )
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View );
const FVector2D InvSize( 1.0f / Size.X, 1.0f / Size.Y );
SetShaderValue(RHICmdList, ShaderRHI, InvSizeParameter, InvSize );
//SetTextureParameter( ShaderRHI, TextureParameter, TextureParameterSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), Texture );
SetSRVParameter(RHICmdList, ShaderRHI, TextureParameter, ShaderResourceView );
SetSamplerParameter(RHICmdList, ShaderRHI, TextureParameterSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI() );
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << InvSizeParameter;
Ar << InputUvFactorAndOffsetParameter;
Ar << InputViewportMaxBoundParameter;
Ar << SceneTextureParameters;
Ar << TextureParameter;
Ar << TextureParameterSampler;
return bShaderHasOutdatedParameters;
}
};
IMPLEMENT_SHADER_TYPE(template<>,THZBBuildPS<0>,TEXT("HZBOcclusion"),TEXT("HZBBuildPS"),SF_Pixel);
IMPLEMENT_SHADER_TYPE(template<>,THZBBuildPS<1>,TEXT("HZBOcclusion"),TEXT("HZBBuildPS"),SF_Pixel);
void BuildHZB( FRHICommandListImmediate& RHICmdList, FViewInfo& View )
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_BuildHZB);
SCOPED_DRAW_EVENT(RHICmdList, BuildHZB);
// View.ViewRect.{Width,Height}() are most likely to be < 2^24, so the float
// conversion won't loss any precision (assuming float have 23bits for mantissa)
const int32 NumMipsX = FMath::Max(FPlatformMath::CeilToInt(FMath::Log2(float(View.ViewRect.Width()))) - 1, 1);
const int32 NumMipsY = FMath::Max(FPlatformMath::CeilToInt(FMath::Log2(float(View.ViewRect.Height()))) - 1, 1);
const uint32 NumMips = FMath::Max(NumMipsX, NumMipsY);
// Must be power of 2
const FIntPoint HZBSize( 1 << NumMipsX, 1 << NumMipsY );
View.HZBMipmap0Size = HZBSize;
FPooledRenderTargetDesc Desc(FPooledRenderTargetDesc::Create2DDesc(HZBSize, PF_R16F, FClearValueBinding::None, TexCreate_None, TexCreate_RenderTargetable | TexCreate_ShaderResource | TexCreate_NoFastClear, false, NumMips));
Desc.Flags |= TexCreate_FastVRAM;
GRenderTargetPool.FindFreeElement( Desc, View.HZB, TEXT("HZB") );
FSceneRenderTargetItem& HZBRenderTarget = View.HZB->GetRenderTargetItem();
RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
RHICmdList.SetDepthStencilState(TStaticDepthStencilState< false, CF_Always >::GetRHI());
// Mip 0
{
SetRenderTarget(RHICmdList, HZBRenderTarget.TargetableTexture, 0, NULL);
TShaderMapRef< FPostProcessVS > VertexShader(View.ShaderMap);
TShaderMapRef< THZBBuildPS<0> > PixelShader(View.ShaderMap);
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
// Imperfect sampling, doesn't matter too much
PixelShader->SetParameters( RHICmdList, View );
RHICmdList.SetViewport(0, 0, 0.0f, HZBSize.X, HZBSize.Y, 1.0f);
DrawRectangle(
RHICmdList,
0, 0,
HZBSize.X, HZBSize.Y,
View.ViewRect.Min.X, View.ViewRect.Min.Y,
View.ViewRect.Width(), View.ViewRect.Height(),
HZBSize,
FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY(),
*VertexShader,
EDRF_UseTriangleOptimization);
RHICmdList.CopyToResolveTarget(HZBRenderTarget.TargetableTexture, HZBRenderTarget.ShaderResourceTexture, false, FResolveParams(FResolveRect(), CubeFace_PosX, 0));
}
FIntPoint SrcSize = HZBSize;
FIntPoint DstSize = SrcSize / 2;
// Downsampling...
for( uint8 MipIndex = 1; MipIndex < NumMips; MipIndex++ )
{
DstSize.X = FMath::Max(DstSize.X, 1);
DstSize.Y = FMath::Max(DstSize.Y, 1);
SetRenderTarget(RHICmdList, HZBRenderTarget.TargetableTexture, MipIndex, NULL);
TShaderMapRef< FPostProcessVS > VertexShader(View.ShaderMap);
TShaderMapRef< THZBBuildPS<1> > PixelShader(View.ShaderMap);
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
PixelShader->SetParameters(RHICmdList, View, SrcSize, HZBRenderTarget.MipSRVs[ MipIndex - 1 ] );
RHICmdList.SetViewport(0, 0, 0.0f, DstSize.X, DstSize.Y, 1.0f);
DrawRectangle(
RHICmdList,
0, 0,
DstSize.X, DstSize.Y,
0, 0,
SrcSize.X, SrcSize.Y,
DstSize,
SrcSize,
*VertexShader,
EDRF_UseTriangleOptimization);
RHICmdList.CopyToResolveTarget(HZBRenderTarget.TargetableTexture, HZBRenderTarget.ShaderResourceTexture, false, FResolveParams(FResolveRect(), CubeFace_PosX, MipIndex));
SrcSize /= 2;
DstSize /= 2;
}
GRenderTargetPool.VisualizeTexture.SetCheckPoint( RHICmdList, View.HZB );
}
void FDeferredShadingSceneRenderer::BeginOcclusionTests(FRHICommandListImmediate& RHICmdList, bool bRenderQueries, bool bRenderHZB)
{
SCOPE_CYCLE_COUNTER(STAT_BeginOcclusionTestsTime);
int32 NumBufferedFrames = FOcclusionQueryHelpers::GetNumBufferedFrames();
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
const bool bUseDownsampledDepth = SceneContext.UseDownsizedOcclusionQueries() && IsValidRef(SceneContext.SmallDepthZ) && IsValidRef(SceneContext.GetSmallDepthSurface());
if (bUseDownsampledDepth)
{
SetRenderTarget(RHICmdList, NULL, SceneContext.GetSmallDepthSurface(), ESimpleRenderTargetMode::EExistingColorAndDepth, FExclusiveDepthStencil::DepthRead_StencilWrite);
}
else
{
SetRenderTarget(RHICmdList, NULL, SceneContext.GetSceneDepthSurface(), ESimpleRenderTargetMode::EExistingColorAndDepth, FExclusiveDepthStencil::DepthRead_StencilWrite);
}
if (bRenderQueries)
{
RHICmdList.BeginOcclusionQueryBatch();
// Perform occlusion queries for each view
for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
{
SCOPED_DRAW_EVENT(RHICmdList, BeginOcclusionTests);
FViewInfo& View = Views[ViewIndex];
if (bUseDownsampledDepth)
{
const uint32 DownsampledX = FMath::TruncToInt(View.ViewRect.Min.X / SceneContext.GetSmallColorDepthDownsampleFactor());
const uint32 DownsampledY = FMath::TruncToInt(View.ViewRect.Min.Y / SceneContext.GetSmallColorDepthDownsampleFactor());
const uint32 DownsampledSizeX = FMath::TruncToInt(View.ViewRect.Width() / SceneContext.GetSmallColorDepthDownsampleFactor());
const uint32 DownsampledSizeY = FMath::TruncToInt(View.ViewRect.Height() / SceneContext.GetSmallColorDepthDownsampleFactor());
// Setup the viewport for rendering to the downsampled depth buffer
RHICmdList.SetViewport(DownsampledX, DownsampledY, 0.0f, DownsampledX + DownsampledSizeX, DownsampledY + DownsampledSizeY, 1.0f);
}
else
{
RHICmdList.SetViewport(View.ViewRect.Min.X, View.ViewRect.Min.Y, 0.0f, View.ViewRect.Max.X, View.ViewRect.Max.Y, 1.0f);
}
FSceneViewState* ViewState = (FSceneViewState*)View.State;
if (ViewState && !View.bDisableQuerySubmissions)
{
// Depth tests, no depth writes, no color writes, opaque, solid rasterization wo/ backface culling.
RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_DepthNearOrEqual>::GetRHI());
// We only need to render the front-faces of the culling geometry (this halves the amount of pixels we touch)
RHICmdList.SetRasterizerState(View.bReverseCulling ? TStaticRasterizerState<FM_Solid, CM_CCW>::GetRHI() : TStaticRasterizerState<FM_Solid, CM_CW>::GetRHI());
RHICmdList.SetBlendState(TStaticBlendState<CW_NONE>::GetRHI());
// Lookup the vertex shader.
TShaderMapRef<FOcclusionQueryVS> VertexShader(View.ShaderMap);
SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), OcclusionTestBoundShaderState, GetVertexDeclarationFVector3(), *VertexShader, NULL);
VertexShader->SetParameters(RHICmdList, View);
// Issue this frame's occlusion queries (occlusion queries from last frame may still be in flight)
const uint32 QueryIndex = FOcclusionQueryHelpers::GetQueryIssueIndex(ViewState->PendingPrevFrameNumber, NumBufferedFrames);
FSceneViewState::ShadowKeyOcclusionQueryMap& ShadowOcclusionQueryMap = ViewState->ShadowOcclusionQueryMaps[QueryIndex];
// Clear primitives which haven't been visible recently out of the occlusion history, and reset old pending occlusion queries.
ViewState->TrimOcclusionHistory(RHICmdList, ViewFamily.CurrentRealTime - GEngine->PrimitiveProbablyVisibleTime, ViewFamily.CurrentRealTime, ViewState->OcclusionFrameCounter);
// Give back all these occlusion queries to the pool.
for (TMap<FSceneViewState::FProjectedShadowKey, FRenderQueryRHIRef>::TIterator QueryIt(ShadowOcclusionQueryMap); QueryIt; ++QueryIt)
{
//FRenderQueryRHIParamRef Query = QueryIt.Value();
//check( Query.GetRefCount() == 1 );
ViewState->OcclusionQueryPool.ReleaseQuery(RHICmdList, QueryIt.Value());
}
ShadowOcclusionQueryMap.Reset();
{
SCOPED_DRAW_EVENT(RHICmdList, ShadowFrustumQueries);
for (TSparseArray<FLightSceneInfoCompact>::TConstIterator LightIt(Scene->Lights); LightIt; ++LightIt)
{
const FVisibleLightInfo& VisibleLightInfo = VisibleLightInfos[LightIt.GetIndex()];
for (int32 ShadowIndex = 0; ShadowIndex < VisibleLightInfo.AllProjectedShadows.Num(); ShadowIndex++)
{
const FProjectedShadowInfo& ProjectedShadowInfo = *VisibleLightInfo.AllProjectedShadows[ShadowIndex];
if (ProjectedShadowInfo.DependentView && ProjectedShadowInfo.DependentView != &View)
{
continue;
}
if (ProjectedShadowInfo.CascadeSettings.bOnePassPointLightShadow)
{
FLightSceneProxy& LightProxy = *(ProjectedShadowInfo.GetLightSceneInfo().Proxy);
// Query one pass point light shadows separately because they don't have a shadow frustum, they have a bounding sphere instead.
FSphere LightBounds = LightProxy.GetBoundingSphere();
const bool bCameraInsideLightGeometry = ((FVector)View.ViewMatrices.ViewOrigin - LightBounds.Center).SizeSquared() < FMath::Square(LightBounds.W * 1.05f + View.NearClippingDistance * 2.0f);
if (!bCameraInsideLightGeometry)
{
const FRenderQueryRHIRef ShadowOcclusionQuery = ViewState->OcclusionQueryPool.AllocateQuery();
RHICmdList.BeginRenderQuery(ShadowOcclusionQuery);
FSceneViewState::FProjectedShadowKey Key(ProjectedShadowInfo);
checkSlow(ShadowOcclusionQueryMap.Find(Key) == NULL);
ShadowOcclusionQueryMap.Add(Key, ShadowOcclusionQuery);
// Draw bounding sphere
VertexShader->SetParametersWithBoundingSphere(RHICmdList, View, LightBounds);
StencilingGeometry::DrawSphere(RHICmdList);
RHICmdList.EndRenderQuery(ShadowOcclusionQuery);
}
}
// Don't query preshadows, since they are culled if their subject is occluded.
// Don't query if any subjects are visible because the shadow frustum will be definitely unoccluded
else if (!ProjectedShadowInfo.IsWholeSceneDirectionalShadow() && !ProjectedShadowInfo.bPreShadow && !ProjectedShadowInfo.SubjectsVisible(View))
{
IssueProjectedShadowOcclusionQuery(RHICmdList, View, ProjectedShadowInfo, *VertexShader, NumBufferedFrames);
}
}
// Issue occlusion queries for all per-object projected shadows that we would have rendered but were occluded last frame.
for (int32 ShadowIndex = 0; ShadowIndex < VisibleLightInfo.OccludedPerObjectShadows.Num(); ShadowIndex++)
{
const FProjectedShadowInfo& ProjectedShadowInfo = *VisibleLightInfo.OccludedPerObjectShadows[ShadowIndex];
IssueProjectedShadowOcclusionQuery(RHICmdList, View, ProjectedShadowInfo, *VertexShader, NumBufferedFrames);
}
}
}
// Don't do primitive occlusion if we have a view parent or are frozen.
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
if (!ViewState->HasViewParent() && !ViewState->bIsFrozen)
#endif
{
VertexShader->SetParameters(RHICmdList, View);
{
SCOPED_DRAW_EVENT(RHICmdList, IndividualQueries);
View.IndividualOcclusionQueries.Flush(RHICmdList);
}
{
SCOPED_DRAW_EVENT(RHICmdList, GroupedQueries);
View.GroupedOcclusionQueries.Flush(RHICmdList);
}
}
}
}
RHICmdList.EndOcclusionQueryBatch();
}
if (bRenderHZB)
{
for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
{
FViewInfo& View = Views[ViewIndex];
FSceneViewState* ViewState = (FSceneViewState*)View.State;
if (ViewState && ViewState->HZBOcclusionTests.GetNum() != 0)
{
check(ViewState->HZBOcclusionTests.IsValidFrame(ViewState->OcclusionFrameCounter));
SCOPED_DRAW_EVENT(RHICmdList, HZB);
ViewState->HZBOcclusionTests.Submit(RHICmdList, View);
}
}
}
if (bUseDownsampledDepth)
{
// Restore default render target
SceneContext.BeginRenderingSceneColor(RHICmdList, ESimpleRenderTargetMode::EUninitializedColorExistingDepth, FExclusiveDepthStencil::DepthRead_StencilWrite);
}
}
| bsd-2-clause |
tidepool-org/platform | prescription/store/mongo/prescription_repository.go | 13931 | package mongo
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/tidepool-org/platform/page"
"github.com/tidepool-org/platform/log"
structureValidator "github.com/tidepool-org/platform/structure/validator"
"github.com/tidepool-org/platform/errors"
"github.com/tidepool-org/platform/prescription"
structuredMongo "github.com/tidepool-org/platform/store/structured/mongo"
)
type PrescriptionRepository struct {
*structuredMongo.Repository
}
func (p *PrescriptionRepository) CreateIndexes(ctx context.Context) error {
indexes := []mongo.IndexModel{
{
Keys: bson.D{{Key: "patientUserId", Value: 1}},
Options: options.Index().
SetName("GetByPatientId").
SetBackground(true),
},
{
Keys: bson.D{{Key: "prescriberUserId", Value: 1}},
Options: options.Index().
SetName("GetByPrescriberId").
SetBackground(true),
},
{
Keys: bson.D{{Key: "createdUserId", Value: 1}},
Options: options.Index().
SetName("GetByCreatedUserId").
SetBackground(true),
},
{
Keys: bson.D{{Key: "accessCode", Value: 1}},
Options: options.Index().
SetName("GetByUniqueAccessCode").
SetUnique(true).
SetSparse(true).
SetBackground(true),
},
{
Keys: bson.D{{Key: "latestRevision.attributes.email", Value: 1}},
Options: options.Index().
SetName("GetByPatientEmail").
SetBackground(true),
},
{
Keys: bson.D{{Key: "_id", Value: 1}, {Key: "revisionHistory.revisionId", Value: 1}},
Options: options.Index().
SetName("UniqueRevisionId").
SetUnique(true).
SetBackground(true),
},
}
return p.CreateAllIndexes(ctx, indexes)
}
func (p *PrescriptionRepository) CreatePrescription(ctx context.Context, create *prescription.RevisionCreate) (*prescription.Prescription, error) {
if ctx == nil {
return nil, errors.New("context is missing")
}
model := prescription.NewPrescription(create)
if err := structureValidator.New().Validate(model); err != nil {
return nil, errors.Wrap(err, "prescription is invalid")
}
now := time.Now()
logger := log.LoggerFromContext(ctx).WithFields(log.Fields{"userId": create.ClinicianID, "create": create})
_, err := p.InsertOne(ctx, model)
logger.WithFields(log.Fields{"id": model.ID, "duration": time.Since(now) / time.Microsecond}).WithError(err).Debug("CreatePrescription")
if err != nil {
return nil, errors.Wrap(err, "unable to create prescription")
}
return model, nil
}
func (p *PrescriptionRepository) ListPrescriptions(ctx context.Context, filter *prescription.Filter, pagination *page.Pagination) (prescription.Prescriptions, error) {
if ctx == nil {
return nil, errors.New("context is missing")
}
if filter == nil {
return nil, errors.New("filter is missing")
} else if err := structureValidator.New().Validate(filter); err != nil {
return nil, errors.Wrap(err, "filter is invalid")
}
if pagination == nil {
pagination = page.NewPagination()
} else if err := structureValidator.New().Validate(pagination); err != nil {
return nil, errors.Wrap(err, "pagination is invalid")
}
now := time.Now()
logger := log.LoggerFromContext(ctx).WithFields(log.Fields{"filter": filter})
selector := newMongoSelectorFromFilter(filter)
selector["deletedTime"] = nil
opts := structuredMongo.FindWithPagination(pagination)
cursor, err := p.Find(ctx, selector, opts)
logger.WithFields(log.Fields{"duration": time.Since(now) / time.Microsecond}).WithError(err).Debug("ListPrescriptions")
if err != nil {
return nil, errors.Wrap(err, "unable to list prescriptions")
}
prescriptions := prescription.Prescriptions{}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &prescriptions); err != nil {
return nil, errors.Wrap(err, "unable to decode prescriptions")
}
return prescriptions, nil
}
func (p *PrescriptionRepository) DeletePrescription(ctx context.Context, clinicID, prescriptionID, clinicianID string) (bool, error) {
if ctx == nil {
return false, errors.New("context is missing")
}
if clinicianID == "" {
return false, errors.New("clinician id is missing")
}
if clinicID == "" {
return false, errors.New("clinic id is missing")
}
now := time.Now()
logger := log.LoggerFromContext(ctx).WithFields(log.Fields{"clinicId": clinicID, "id": prescriptionID})
id, err := primitive.ObjectIDFromHex(prescriptionID)
if err == primitive.ErrInvalidHex {
return false, nil
} else if err != nil {
return false, err
}
selector := bson.M{
"_id": id,
"clinicId": clinicID,
"state": bson.M{
"$in": []string{prescription.StateDraft, prescription.StatePending},
},
"deletedTime": nil,
}
update := bson.M{
"$set": bson.M{
"deletedUserId": clinicianID,
"deletedTime": now,
},
}
res, err := p.UpdateOne(ctx, selector, update)
logger.WithFields(log.Fields{"duration": time.Since(now) / time.Microsecond}).WithError(err).Debug("DeletePrescription")
if err != nil {
return false, errors.Wrap(err, "unable to delete prescription")
}
success := res.ModifiedCount == 1
return success, nil
}
func (p *PrescriptionRepository) AddRevision(ctx context.Context, prescriptionID string, create *prescription.RevisionCreate) (*prescription.Prescription, error) {
if ctx == nil {
return nil, errors.New("context is missing")
}
logger := log.LoggerFromContext(ctx).WithFields(log.Fields{"userId": create.ClinicianID, "prescriptionId": prescriptionID, "create": create})
id, err := primitive.ObjectIDFromHex(prescriptionID)
if err == primitive.ErrInvalidHex {
return nil, nil
} else if err != nil {
return nil, err
}
selector := bson.M{
"_id": id,
"clinicId": create.ClinicID,
}
prescr := &prescription.Prescription{}
err = p.FindOne(ctx, selector).Decode(prescr)
if err == mongo.ErrNoDocuments {
return nil, nil
} else if err != nil {
return nil, errors.Wrap(err, "could not get prescription to add revision to")
}
prescriptionUpdate := prescription.NewPrescriptionAddRevisionUpdate(prescr, create)
if err := structureValidator.New().Validate(prescriptionUpdate); err != nil {
return nil, errors.Wrap(err, "the prescription update is invalid")
}
// Concurrent updates are safe, because updates are atomic at the document level and
// because revision ids are guaranteed to be unique in a document.
updateSelector := bson.M{
"_id": prescr.ID,
"latestRevision.revisionId": prescr.LatestRevision.RevisionID,
}
update := newMongoUpdateFromPrescriptionUpdate(prescriptionUpdate)
now := time.Now()
res, err := p.UpdateOne(ctx, updateSelector, update)
logger.WithFields(log.Fields{"id": prescriptionID, "duration": time.Since(now) / time.Microsecond}).WithError(err).Debug("UpdatePrescription")
if err != nil {
return nil, errors.Wrap(err, "unable to update prescription")
} else if res.ModifiedCount == 0 {
return nil, errors.New("unable to find prescription to update")
}
err = p.FindOneByID(ctx, prescr.ID, prescr)
if err != nil {
return nil, errors.Wrap(err, "unable to find updated prescription")
}
return prescr, nil
}
func (p *PrescriptionRepository) ClaimPrescription(ctx context.Context, claim *prescription.Claim) (*prescription.Prescription, error) {
if ctx == nil {
return nil, errors.New("context is missing")
}
logger := log.LoggerFromContext(ctx).WithFields(log.Fields{"userId": claim.PatientID, "claim": claim})
if claim.RevisionHash == "" {
return nil, fmt.Errorf("cannot claim prescription without integrity hash")
}
prescr, err := p.GetClaimablePrescription(ctx, claim)
if err != nil || prescr == nil {
return nil, err
}
id := prescr.ID
prescriptionUpdate := prescription.NewPrescriptionClaimUpdate(claim.PatientID, prescr)
if err := structureValidator.New().Validate(prescriptionUpdate); err != nil {
return nil, errors.Wrap(err, "the prescription update is invalid")
}
selector := newClaimSelector(claim)
update := newMongoUpdateFromPrescriptionUpdate(prescriptionUpdate)
now := time.Now()
res, err := p.UpdateOne(ctx, selector, update)
logger.WithFields(log.Fields{"id": id, "duration": time.Since(now) / time.Microsecond}).WithError(err).Debug("UpdatePrescription")
if err != nil {
return nil, errors.Wrap(err, "unable to update prescription")
} else if res.ModifiedCount == 0 {
return nil, errors.New("unable to find prescription to update")
}
prescr = &prescription.Prescription{}
err = p.FindOneByID(ctx, id, prescr)
if err != nil {
return nil, errors.Wrap(err, "unable to find updated prescription")
}
return prescr, nil
}
func (p *PrescriptionRepository) GetClaimablePrescription(ctx context.Context, claim *prescription.Claim) (*prescription.Prescription, error) {
if ctx == nil {
return nil, errors.New("context is missing")
}
selector := newClaimSelector(claim)
prescr := &prescription.Prescription{}
err := p.FindOne(ctx, selector).Decode(prescr)
if err == mongo.ErrNoDocuments {
return nil, nil
} else if err != nil {
return nil, errors.Wrap(err, "could not get claimable prescription")
}
return prescr, nil
}
func (p *PrescriptionRepository) UpdatePrescriptionState(ctx context.Context, prescriptionID string, update *prescription.StateUpdate) (*prescription.Prescription, error) {
if ctx == nil {
return nil, errors.New("context is missing")
}
logger := log.LoggerFromContext(ctx).WithFields(log.Fields{"userId": update.PatientID, "id": prescriptionID, "update": update})
id, err := primitive.ObjectIDFromHex(prescriptionID)
if err == primitive.ErrInvalidHex {
return nil, nil
} else if err != nil {
return nil, err
}
selector := bson.M{
"_id": id,
"patientUserId": update.PatientID,
}
prescr := &prescription.Prescription{}
err = p.FindOne(ctx, selector).Decode(prescr)
if err == mongo.ErrNoDocuments {
return nil, nil
}
prescriptionUpdate := prescription.NewPrescriptionStateUpdate(prescr, update)
if err := structureValidator.New().Validate(prescriptionUpdate); err != nil {
return nil, errors.Wrap(err, "the prescription update is invalid")
}
mongoUpdate := newMongoUpdateFromPrescriptionUpdate(prescriptionUpdate)
if err = p.deactiveActivePrescriptions(ctx, update.PatientID); err != nil {
return nil, err
}
now := time.Now()
res, err := p.UpdateOne(ctx, selector, mongoUpdate)
logger.WithFields(log.Fields{"id": prescr.ID, "duration": time.Since(now) / time.Microsecond}).WithError(err).Debug("UpdatePrescription")
if err != nil {
return nil, errors.Wrap(err, "unable to update prescription")
} else if res.ModifiedCount == 0 {
return nil, errors.New("unable to find prescription to update")
}
err = p.FindOneByID(ctx, prescr.ID, prescr)
if err != nil {
return nil, errors.Wrap(err, "unable to find updated prescription")
}
return prescr, nil
}
func (p *PrescriptionRepository) deactiveActivePrescriptions(ctx context.Context, patientUserID string) error {
logger := log.LoggerFromContext(ctx).WithFields(log.Fields{"userId": patientUserID})
selector := bson.M{
"patientUserId": patientUserID,
"state": prescription.StateActive,
}
update := bson.M{
"$set": bson.M{
"state": prescription.StateInactive,
},
}
now := time.Now()
_, err := p.UpdateMany(ctx, selector, update)
logger.WithFields(log.Fields{"duration": time.Since(now) / time.Microsecond}).WithError(err).Debug("DeactivatePrescriptions")
if err != nil {
return errors.Wrap(err, "unable to deactivate prescriptions for user")
}
return err
}
func newMongoSelectorFromFilter(filter *prescription.Filter) bson.M {
selector := bson.M{}
if filter.ClinicID != "" {
selector["clinicId"] = filter.ClinicID
}
if filter.PatientUserID != "" {
selector["patientUserId"] = filter.PatientUserID
}
if filter.PatientEmail != "" {
selector["latestRevision.attributes.email"] = filter.PatientEmail
}
if filter.ID != "" {
objID, err := primitive.ObjectIDFromHex(filter.ID)
if err != nil {
selector["_id"] = nil
} else {
selector["_id"] = objID
}
}
if filter.State != "" {
selector["state"] = filter.State
}
if filter.CreatedAfter != nil {
selector["createdTime"] = bson.M{"$gte": filter.CreatedAfter}
}
if filter.CreatedBefore != nil {
selector["createdTime"] = bson.M{"$lt": filter.CreatedBefore}
}
if filter.ModifiedAfter != nil {
selector["modifiedTime"] = bson.M{"$gte": filter.ModifiedAfter}
}
if filter.ModifiedBefore != nil {
selector["modifiedTime"] = bson.M{"$lt": filter.ModifiedBefore}
}
return selector
}
func newMongoUpdateFromPrescriptionUpdate(prescrUpdate *prescription.Update) bson.M {
set := bson.M{}
update := bson.M{
"$set": &set,
}
set["state"] = prescrUpdate.State
set["expirationTime"] = prescrUpdate.ExpirationTime
if prescrUpdate.Revision != nil {
set["latestRevision"] = prescrUpdate.Revision
update["$push"] = bson.M{
"revisionHistory": prescrUpdate.Revision,
}
}
if prescrUpdate.GetUpdatedAccessCode() != nil {
code := *prescrUpdate.GetUpdatedAccessCode()
if code != "" {
set["accessCode"] = code
} else {
update["$unset"] = bson.M{
"accessCode": "",
}
}
}
if prescrUpdate.PrescriberUserID != "" {
set["prescriberUserId"] = prescrUpdate.PrescriberUserID
}
if prescrUpdate.PatientUserID != "" {
set["patientUserId"] = prescrUpdate.PatientUserID
}
if prescrUpdate.SubmittedTime != nil {
set["submittedTime"] = prescrUpdate.SubmittedTime
}
return update
}
func newClaimSelector(claim *prescription.Claim) bson.M {
selector := bson.M{
"accessCode": claim.AccessCode,
"latestRevision.attributes.birthday": claim.Birthday,
"patientUserId": nil,
"state": prescription.StateSubmitted,
}
if claim.RevisionHash != "" {
selector["latestRevision.integrityHash.hash"] = claim.RevisionHash
}
return selector
}
| bsd-2-clause |
kodejava/kodejava.project | kodejava-spring-jdbc/src/main/java/org/kodejava/domain/Record.java | 130 | package org.kodejava.domain;
import lombok.Data;
@Data
public class Record {
private Long id;
private String title;
}
| bsd-2-clause |
mxk/gmdb | _gmdb/cmd/backup.py | 6942 |
#
# Written by Maxim Khitrov (July 2011)
#
from . import Command, SigHandler
from .. import IMAP4Control, DBControl, conf
from ..util import *
import logging
import socket
def store(op, queue):
count = len(queue)
while queue:
op.store(queue.popleft())
return count
def check_abort(op):
if sig.abort:
op.commit()
raise KeyboardInterrupt
class backup(Command):
"""Perform account backup.
A complete copy of each message on the server is saved to the local disk. By
default, messages in Spam and Trash are excluded from the backup, but may be
included by using --spam and --trash options. Messages may be filtered using
the Gmail search syntax to reduce the size of the backup. For help on
creating search criteria see:
http://mail.google.com/support/bin/answer.py?answer=7190
The argument to --filter (-f) must in the same format as shown in the Gmail
search box AFTER executing the search. For example, if Gmail changes the
search string 'label:a/b/c' to 'label:a-b-c' (which it does), you should
specify --filter 'label:a-b-c' on the command line.
"""
uses_imap = True
uses_db = True
def __call__(self):
global log, sig
log = logging.getLogger('gmdb.cmd.backup')
err = log.exception if conf.verbose else log.error
source = ['allmail']
if conf.trash:
source.append('trash')
if conf.spam:
source.append('spam')
if conf.db is None:
conf.db = conf.account
try:
with SigHandler() as sig, DBControl(conf.db) as db:
log.info('Account: {!a}', conf.account)
op = db.begin_op('backup')
with IMAP4Control() as self.imap:
if self.imap.srv_type != 'gmail':
raise RuntimeError('not a gmail server')
for mbox in source:
self._backup(sig, op, mbox)
check_abort(op)
op.finish()
return 0
except KeyboardInterrupt:
err('Backup interrupted by user')
except socket.timeout:
err('Connection timeout')
except Exception as exc:
msg = str(exc)
err(msg[:1].upper() + msg[1:])
return 1
@staticmethod
def build_args(subp):
subp.add_argument('-d', '--db', metavar='DIR',
help='database directory (defaults to account name)')
subp.add_argument('-f', '--filter', metavar='CRITERIA',
help='message filter criteria (gmail search syntax)')
subp.add_argument('-L', '--no-labels', action='store_true',
help='do not backup message labels (for better performance)')
subp.add_argument('--spam', action='store_true',
help='back up messages in spam')
subp.add_argument('--trash', action='store_true',
help='back up messages in trash')
subp.add_argument('account',
help='login account (e.g. someuser@example.com)')
def _backup(self, sig, op, mbox):
exists = self.imap.select(self.imap.find_mbox(mbox))
if not exists:
log.info('No messages found in {!a}', mbox)
return
check_abort(op)
log.info('Scanning {} message(s) in {!a}...', exists, mbox)
# Add an extra label to each message depending on the location
add_lbl = '^' + mbox.capitalize() if mbox in ('spam', 'trash') else None
queue = {}
status = Status(op, self.imap, queue)
sig.enable_status(status)
n = 0
for n, msg in self.imap.scan(conf.filter, not conf.no_labels, True):
if n is None:
self._checkpoint(op, queue, status)
else:
if add_lbl:
msg['labels'].append(add_lbl)
if msg['msg_id'] in op.db:
op.update(msg)
else:
queue[msg['uid']] = msg
status.update(n)
check_abort(op)
if n is not None:
self._checkpoint(op, queue, status)
status.done()
def _checkpoint(self, op, queue, status):
if queue:
if conf.verbose >= 2:
msize = lambda msg: msg['size']
count = len(queue)
bytes = bytes_fmt(sum(map(msize, queue.values())))
log.debug2('Downloading {} messages (~{})...', count, bytes)
buf_queue = deque() # Downloaded message queue
buf_bytes = 0 # Size of downloaded message queue
status.dl_begin()
for msg in self.imap.fetch_body(queue):
del queue[msg['uid']]
buf_queue.append(msg)
buf_bytes += len(msg['body'])
# Write messages to disk in groups of DL_BUFFER_LIMIT bytes
if buf_bytes >= conf.DL_BUFFER_LIMIT:
status.dl_done(store(op, buf_queue), buf_bytes)
buf_bytes = 0
check_abort(op)
status.dl_begin()
if buf_queue:
status.dl_done(store(op, buf_queue), buf_bytes)
if queue:
status.dl_failed(len(queue))
queue.clear()
else:
log.debug2('Checkpoint (nothing to download)...')
op.commit()
op.begin()
class Status:
def __init__(self, op, imap, queue):
total = imap.mbox['exists']
log.info('Progress: 0 / {} (0%)', total)
self.op = op # Current database operation
self.imap = imap # IMAP4 connection
self.total = total # Total number of messages in the mailbox
self.next_n = 1 # Next expected message number
self.scanned = 0 # Number of messages scanned
self.skipped = 0 # Number of messages skipped
self.dl_queue = queue # Queue of messages waiting to be downloaded
self.dl_count = 0 # Number of new messages downloaded
self.dl_bytes = 0 # Total number of bytes downloaded (bodies only)
self.dl_rate = None # Download rate (exponential moving average)
self.dl_start = 0.0 # Time when the current download started
self.prog = 0.0 # Backup progress (percent)
self.report = 0 # Last reported progress
def show(self):
runtime = self.op.duration
progress = (self.update(), self.total, self.prog, runtime)
dl_bytes = bytes_fmt(self.dl_bytes)
ema_rate = bytes_fmt(0.0 if self.dl_rate is None else self.dl_rate)
avg_rate = bytes_fmt(self.dl_bytes / runtime)
report = log.info
report('--- Backup Status ---')
report(' Mailbox: {!a}', self.imap.mbox['name'])
report(' Progress: {} / {} ({:.3f}%) in {} sec', *progress)
report(' Skipped: {}', self.skipped)
report(' Queued: {}', len(self.dl_queue))
report(' Downloaded: {} ({})', self.dl_count, dl_bytes)
report('Current rate: {}/s', ema_rate)
report('Overall rate: {}/s', avg_rate)
report('--- End of Status ---')
def update(self, n=None):
if n:
self.scanned += 1
self.skipped += n - self.next_n
self.next_n = n + 1
else:
n = self.scanned + self.skipped
done = (n - len(self.dl_queue))
self.prog = done / self.total * 100.0
prog = int(self.prog)
if self.report != prog:
log.info('Progress: {} / {} ({}%)', done, self.total, prog)
self.report = prog
return done
def dl_begin(self):
self.dl_start = walltime()
def dl_done(self, count, bytes):
now = walltime()
self.dl_count += count
self.dl_bytes += bytes
self.dl_rate = ema(self.dl_rate, bytes / (now - self.dl_start))
self.update()
def dl_failed(self, count):
self.scanned -= count
self.skipped += count
log.warn('Failed to download {} message(s)', count)
def done(self):
if self.next_n != self.total + 1:
self.update(self.total)
self.show()
| bsd-2-clause |
rohe/pysaml2-3 | src/saml2/config.py | 16171 | #!/usr/bin/env python
__author__ = 'rolandh'
import sys
import os
import re
import logging
import logging.handlers
from importlib import import_module
from saml2 import root_logger, BINDING_URI, SAMLError
from saml2 import BINDING_SOAP
from saml2 import BINDING_HTTP_REDIRECT
from saml2 import BINDING_HTTP_POST
from saml2 import BINDING_HTTP_ARTIFACT
from saml2.attribute_converter import ac_factory
from saml2.assertion import Policy
from saml2.mdstore import MetadataStore
from saml2.virtual_org import VirtualOrg
logger = logging.getLogger(__name__)
from saml2 import md
from saml2 import saml
from saml2.extension import mdui
from saml2.extension import idpdisc
from saml2.extension import dri
from saml2.extension import mdattr
from saml2.extension import ui
import xmldsig
import xmlenc
ONTS = {
saml.NAMESPACE: saml,
mdui.NAMESPACE: mdui,
mdattr.NAMESPACE: mdattr,
dri.NAMESPACE: dri,
ui.NAMESPACE: ui,
idpdisc.NAMESPACE: idpdisc,
md.NAMESPACE: md,
xmldsig.NAMESPACE: xmldsig,
xmlenc.NAMESPACE: xmlenc
}
COMMON_ARGS = [
"entityid", "xmlsec_binary", "debug", "key_file", "cert_file",
"secret", "accepted_time_diff", "name", "ca_certs",
"description", "valid_for", "verify_ssl_cert",
"organization",
"contact_person",
"name_form",
"virtual_organization",
"logger",
"only_use_keys_in_metadata",
"logout_requests_signed",
"disable_ssl_certificate_validation",
"referred_binding",
"session_storage",
"entity_category",
"xmlsec_path",
"extension_schemas",
"cert_handler_extra_class",
"generate_cert_func",
"generate_cert_info",
"verify_encrypt_cert",
"tmp_cert_file",
"tmp_key_file",
"validate_certificate",
"extensions"
]
SP_ARGS = [
"required_attributes",
"optional_attributes",
"idp",
"aa",
"subject_data",
"want_response_signed",
"want_assertions_signed",
"authn_requests_signed",
"name_form",
"endpoints",
"ui_info",
"discovery_response",
"allow_unsolicited",
"ecp",
"name_id_format",
"allow_unknown_attributes",
]
AA_IDP_ARGS = [
"sign_assertion",
"sign_response",
"encrypt_assertion",
"want_authn_requests_signed",
"want_authn_requests_only_with_valid_cert",
"provided_attributes",
"subject_data",
"sp",
"scope",
"endpoints",
"metadata",
"ui_info",
"name_id_format",
"domain",
"name_qualifier",
"edu_person_targeted_id",
]
PDP_ARGS = ["endpoints", "name_form", "name_id_format"]
AQ_ARGS = ["endpoints"]
COMPLEX_ARGS = ["attribute_converters", "metadata", "policy"]
ALL = set(COMMON_ARGS + SP_ARGS + AA_IDP_ARGS + PDP_ARGS + COMPLEX_ARGS)
SPEC = {
"": COMMON_ARGS + COMPLEX_ARGS,
"sp": COMMON_ARGS + COMPLEX_ARGS + SP_ARGS,
"idp": COMMON_ARGS + COMPLEX_ARGS + AA_IDP_ARGS,
"aa": COMMON_ARGS + COMPLEX_ARGS + AA_IDP_ARGS,
"pdp": COMMON_ARGS + COMPLEX_ARGS + PDP_ARGS,
"aq": COMMON_ARGS + COMPLEX_ARGS + AQ_ARGS,
}
# --------------- Logging stuff ---------------
LOG_LEVEL = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
LOG_HANDLER = {
"rotating": logging.handlers.RotatingFileHandler,
"syslog": logging.handlers.SysLogHandler,
"timerotate": logging.handlers.TimedRotatingFileHandler,
"memory": logging.handlers.MemoryHandler,
}
LOG_FORMAT = "%(asctime)s %(name)s:%(levelname)s %(message)s"
_RPA = [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST, BINDING_HTTP_ARTIFACT]
_PRA = [BINDING_HTTP_POST, BINDING_HTTP_REDIRECT, BINDING_HTTP_ARTIFACT]
_SRPA = [BINDING_SOAP, BINDING_HTTP_REDIRECT, BINDING_HTTP_POST,
BINDING_HTTP_ARTIFACT]
PREFERRED_BINDING = {
"single_logout_service": _SRPA,
"manage_name_id_service": _SRPA,
"assertion_consumer_service": _PRA,
"single_sign_on_service": _RPA,
"name_id_mapping_service": [BINDING_SOAP],
"authn_query_service": [BINDING_SOAP],
"attribute_service": [BINDING_SOAP],
"authz_service": [BINDING_SOAP],
"assertion_id_request_service": [BINDING_URI],
"artifact_resolution_service": [BINDING_SOAP],
"attribute_consuming_service": _RPA
}
class ConfigurationError(SAMLError):
pass
# -----------------------------------------------------------------
class Config(object):
def_context = ""
def __init__(self, homedir="."):
self._homedir = homedir
self.entityid = None
self.xmlsec_binary = None
self.xmlsec_path = []
self.debug = False
self.key_file = None
self.cert_file = None
self.encryption_type = 'both'
self.secret = None
self.accepted_time_diff = None
self.name = None
self.ca_certs = None
self.verify_ssl_cert = False
self.description = None
self.valid_for = None
self.organization = None
self.contact_person = None
self.name_form = None
self.name_id_format = None
self.virtual_organization = None
self.logger = None
self.only_use_keys_in_metadata = True
self.logout_requests_signed = None
self.disable_ssl_certificate_validation = None
self.context = ""
self.attribute_converters = None
self.metadata = None
self.policy = None
self.serves = []
self.vorg = {}
self.preferred_binding = PREFERRED_BINDING
self.domain = ""
self.name_qualifier = ""
self.entity_category = ""
self.crypto_backend = 'xmlsec1'
self.scope = ""
self.allow_unknown_attributes = False
self.extension_schema = {}
self.cert_handler_extra_class = None
self.verify_encrypt_cert = None
self.generate_cert_func = None
self.generate_cert_info = None
self.tmp_cert_file = None
self.tmp_key_file = None
self.validate_certificate = None
self.extensions = {}
def setattr(self, context, attr, val):
if context == "":
setattr(self, attr, val)
else:
setattr(self, "_%s_%s" % (context, attr), val)
def getattr(self, attr, context=None):
if context is None:
context = self.context
if context == "":
return getattr(self, attr, None)
else:
return getattr(self, "_%s_%s" % (context, attr), None)
def load_special(self, cnf, typ, metadata_construction=False):
for arg in SPEC[typ]:
try:
self.setattr(typ, arg, cnf[arg])
except KeyError:
pass
self.context = typ
self.load_complex(cnf, typ, metadata_construction=metadata_construction)
self.context = self.def_context
def load_complex(self, cnf, typ="", metadata_construction=False):
try:
self.setattr(typ, "policy", Policy(cnf["policy"]))
except KeyError:
pass
# for srv, spec in cnf["service"].items():
# try:
# self.setattr(srv, "policy",
# Policy(cnf["service"][srv]["policy"]))
# except KeyError:
# pass
try:
try:
acs = ac_factory(cnf["attribute_map_dir"])
except KeyError:
acs = ac_factory()
if not acs:
raise ConfigurationError("No attribute converters, something is wrong!!")
_acs = self.getattr("attribute_converters", typ)
if _acs:
_acs.extend(acs)
else:
self.setattr(typ, "attribute_converters", acs)
except KeyError:
pass
if not metadata_construction:
try:
self.setattr(typ, "metadata",
self.load_metadata(cnf["metadata"]))
except KeyError:
pass
def unicode_convert(self, item):
try:
return str(item, "utf-8")
except TypeError:
_uc = self.unicode_convert
if isinstance(item, dict):
return dict([(key, _uc(val)) for key, val in list(item.items())])
elif isinstance(item, list):
return [_uc(v) for v in item]
elif isinstance(item, tuple):
return tuple([_uc(v) for v in item])
else:
return item
def load(self, cnf, metadata_construction=False):
""" The base load method, loads the configuration
:param cnf: The configuration as a dictionary
:param metadata_construction: Is this only to be able to construct
metadata. If so some things can be left out.
:return: The Configuration instance
"""
_uc = self.unicode_convert
for arg in COMMON_ARGS:
if arg == "virtual_organization":
if "virtual_organization" in cnf:
for key, val in list(cnf["virtual_organization"].items()):
self.vorg[key] = VirtualOrg(None, key, val)
continue
elif arg == "extension_schemas":
# List of filename of modules representing the schemas
if "extension_schemas" in cnf:
for mod_file in cnf["extension_schemas"]:
_mod = self._load(mod_file)
self.extension_schema[_mod.NAMESPACE] = _mod
try:
setattr(self, arg, _uc(cnf[arg]))
except KeyError:
pass
except TypeError: # Something that can't be a string
setattr(self, arg, cnf[arg])
if "service" in cnf:
for typ in ["aa", "idp", "sp", "pdp", "aq"]:
try:
self.load_special(
cnf["service"][typ], typ,
metadata_construction=metadata_construction)
self.serves.append(typ)
except KeyError:
pass
if "extensions" in cnf:
self.do_extensions(cnf["extensions"])
self.load_complex(cnf, metadata_construction=metadata_construction)
self.context = self.def_context
return self
def _load(self, fil):
head, tail = os.path.split(fil)
if head == "":
if sys.path[0] != ".":
sys.path.insert(0, ".")
else:
sys.path.insert(0, head)
return import_module(tail)
def load_file(self, config_file, metadata_construction=False):
if config_file.endswith(".py"):
config_file = config_file[:-3]
mod = self._load(config_file)
#return self.load(eval(open(config_file).read()))
return self.load(mod.CONFIG, metadata_construction)
def load_metadata(self, metadata_conf):
""" Loads metadata into an internal structure """
acs = self.attribute_converters
if acs is None:
raise ConfigurationError(
"Missing attribute converter specification")
try:
ca_certs = self.ca_certs
except:
ca_certs = None
try:
disable_validation = self.disable_ssl_certificate_validation
except:
disable_validation = False
mds = MetadataStore(
list(ONTS.values()), acs, self, ca_certs,
disable_ssl_certificate_validation=disable_validation)
mds.imp(metadata_conf)
return mds
def endpoint(self, service, binding=None, context=None):
""" Goes through the list of endpoint specifications for the
given type of service and returnes the first endpoint that matches
the given binding. If no binding is given any endpoint for that
service will be returned.
:param service: The service the endpoint should support
:param binding: The expected binding
:return: All the endpoints that matches the given restrictions
"""
spec = []
unspec = []
endps = self.getattr("endpoints", context)
if endps and service in endps:
for endpspec in endps[service]:
try:
endp, bind = endpspec
if binding is None or bind == binding:
spec.append(endp)
except ValueError:
unspec.append(endpspec)
if spec:
return spec
else:
return unspec
def log_handler(self):
try:
_logconf = self.logger
except KeyError:
return None
handler = None
for htyp in LOG_HANDLER:
if htyp in _logconf:
if htyp == "syslog":
args = _logconf[htyp]
if "socktype" in args:
import socket
if args["socktype"] == "dgram":
args["socktype"] = socket.SOCK_DGRAM
elif args["socktype"] == "stream":
args["socktype"] = socket.SOCK_STREAM
else:
raise ConfigurationError("Unknown socktype!")
try:
handler = LOG_HANDLER[htyp](**args)
except TypeError: # difference between 2.6 and 2.7
del args["socktype"]
handler = LOG_HANDLER[htyp](**args)
else:
handler = LOG_HANDLER[htyp](**_logconf[htyp])
break
if handler is None:
# default if rotating logger
handler = LOG_HANDLER["rotating"]()
if "format" in _logconf:
formatter = logging.Formatter(_logconf["format"])
else:
formatter = logging.Formatter(LOG_FORMAT)
handler.setFormatter(formatter)
return handler
def setup_logger(self):
if root_logger.level != logging.NOTSET: # Someone got there before me
return root_logger
_logconf = self.logger
if _logconf is None:
return root_logger
try:
root_logger.setLevel(LOG_LEVEL[_logconf["loglevel"].lower()])
except KeyError: # reasonable default
root_logger.setLevel(logging.INFO)
root_logger.addHandler(self.log_handler())
root_logger.info("Logging started")
return root_logger
def endpoint2service(self, endpoint, context=None):
endps = self.getattr("endpoints", context)
for service, specs in list(endps.items()):
for endp, binding in specs:
if endp == endpoint:
return service, binding
return None, None
def do_extensions(self, extensions):
for key, val in extensions.items():
self.extensions[key] = val
class SPConfig(Config):
def_context = "sp"
def __init__(self):
Config.__init__(self)
def vo_conf(self, vo_name):
try:
return self.virtual_organization[vo_name]
except KeyError:
return None
def ecp_endpoint(self, ipaddress):
"""
Returns the entity ID of the IdP which the ECP client should talk to
:param ipaddress: The IP address of the user client
:return: IdP entity ID or None
"""
_ecp = self.getattr("ecp")
if _ecp:
for key, eid in list(_ecp.items()):
if re.match(key, ipaddress):
return eid
return None
class IdPConfig(Config):
def_context = "idp"
def __init__(self):
Config.__init__(self)
def config_factory(typ, filename):
if typ == "sp":
conf = SPConfig().load_file(filename)
conf.context = typ
elif typ in ["aa", "idp", "pdp", "aq"]:
conf = IdPConfig().load_file(filename)
conf.context = typ
else:
conf = Config().load_file(filename)
conf.context = typ
return conf
| bsd-2-clause |
kwgoodman/bottleneck | bottleneck/tests/move_test.py | 7685 | """Test moving window functions."""
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal, assert_equal, assert_raises
import bottleneck as bn
from .util import array_order, arrays
@pytest.mark.parametrize("func", bn.get_functions("move"), ids=lambda x: x.__name__)
def test_move(func):
"""Test that bn.xxx gives the same output as a reference function."""
fmt = (
"\nfunc %s | window %d | min_count %s | input %s (%s) | shape %s | "
"axis %s | order %s\n"
)
fmt += "\nInput array:\n%s\n"
aaae = assert_array_almost_equal
func_name = func.__name__
func0 = eval("bn.slow.%s" % func_name)
if func_name == "move_var":
decimal = 3
else:
decimal = 5
for i, a in enumerate(arrays(func_name)):
axes = range(-1, a.ndim)
for axis in axes:
windows = range(1, a.shape[axis])
for window in windows:
min_counts = list(range(1, window + 1)) + [None]
for min_count in min_counts:
actual = func(a, window, min_count, axis=axis)
desired = func0(a, window, min_count, axis=axis)
tup = (
func_name,
window,
str(min_count),
"a" + str(i),
str(a.dtype),
str(a.shape),
str(axis),
array_order(a),
a,
)
err_msg = fmt % tup
aaae(actual, desired, decimal, err_msg)
err_msg += "\n dtype mismatch %s %s"
da = actual.dtype
dd = desired.dtype
assert_equal(da, dd, err_msg % (da, dd))
# ---------------------------------------------------------------------------
# Test argument parsing
@pytest.mark.parametrize("func", bn.get_functions("move"), ids=lambda x: x.__name__)
def test_arg_parsing(func, decimal=5) -> None:
"""test argument parsing."""
name = func.__name__
func0 = eval("bn.slow.%s" % name)
a = np.array([1.0, 2, 3])
fmt = "\n%s" % func
fmt += "%s\n"
fmt += "\nInput array:\n%s\n" % a
actual = func(a, 2)
desired = func0(a, 2)
err_msg = fmt % "(a, 2)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
actual = func(a, 2, 1)
desired = func0(a, 2, 1)
err_msg = fmt % "(a, 2, 1)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
actual = func(a, window=2)
desired = func0(a, window=2)
err_msg = fmt % "(a, window=2)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
actual = func(a, window=2, min_count=1)
desired = func0(a, window=2, min_count=1)
err_msg = fmt % "(a, window=2, min_count=1)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
actual = func(a, window=2, min_count=1, axis=0)
desired = func0(a, window=2, min_count=1, axis=0)
err_msg = fmt % "(a, window=2, min_count=1, axis=0)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
actual = func(a, min_count=1, window=2, axis=0)
desired = func0(a, min_count=1, window=2, axis=0)
err_msg = fmt % "(a, min_count=1, window=2, axis=0)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
actual = func(a, axis=-1, min_count=None, window=2)
desired = func0(a, axis=-1, min_count=None, window=2)
err_msg = fmt % "(a, axis=-1, min_count=None, window=2)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
actual = func(a=a, axis=-1, min_count=None, window=2)
desired = func0(a=a, axis=-1, min_count=None, window=2)
err_msg = fmt % "(a=a, axis=-1, min_count=None, window=2)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
if name in ("move_std", "move_var"):
actual = func(a, 2, 1, -1, ddof=1)
desired = func0(a, 2, 1, -1, ddof=1)
err_msg = fmt % "(a, 2, 1, -1, ddof=1)"
assert_array_almost_equal(actual, desired, decimal, err_msg)
# regression test: make sure len(kwargs) == 0 doesn't raise
args = (a, 1, 1, -1)
kwargs = {}
func(*args, **kwargs)
@pytest.mark.parametrize("func", bn.get_functions("move"), ids=lambda x: x.__name__)
def test_arg_parse_raises(func) -> None:
"""test argument parsing raises in move"""
a = np.array([1.0, 2, 3])
assert_raises(TypeError, func)
assert_raises(TypeError, func, axis=a)
assert_raises(TypeError, func, a, 2, axis=0, extra=0)
assert_raises(TypeError, func, a, 2, axis=0, a=a)
assert_raises(TypeError, func, a, 2, 2, 0, 0, 0)
assert_raises(TypeError, func, a, 2, axis="0")
assert_raises(TypeError, func, a, 1, min_count="1")
if func.__name__ not in ("move_std", "move_var"):
assert_raises(TypeError, func, a, 2, ddof=0)
# ---------------------------------------------------------------------------
# move_median.c is complicated. Let's do some more testing.
#
# If you make changes to move_median.c then do lots of tests by increasing
# range(100) in the two functions below to range(10000). And for extra credit
# increase size to 30. With those two changes the unit tests will take a
# LONG time to run.
def test_move_median_with_nans() -> None:
"""test move_median.c with nans"""
fmt = "\nfunc %s | window %d | min_count %s\n\nInput array:\n%s\n"
aaae = assert_array_almost_equal
min_count = 1
size = 10
func = bn.move_median
func0 = bn.slow.move_median
rs = np.random.RandomState([1, 2, 3])
for i in range(100):
a = np.arange(size, dtype=np.float64)
idx = rs.rand(*a.shape) < 0.1
a[idx] = np.inf
idx = rs.rand(*a.shape) < 0.2
a[idx] = np.nan
rs.shuffle(a)
for window in range(2, size + 1):
actual = func(a, window=window, min_count=min_count)
desired = func0(a, window=window, min_count=min_count)
err_msg = fmt % (func.__name__, window, min_count, a)
aaae(actual, desired, decimal=5, err_msg=err_msg)
def test_move_median_without_nans() -> None:
"""test move_median.c without nans"""
fmt = "\nfunc %s | window %d | min_count %s\n\nInput array:\n%s\n"
aaae = assert_array_almost_equal
min_count = 1
size = 10
func = bn.move_median
func0 = bn.slow.move_median
rs = np.random.RandomState([1, 2, 3])
for i in range(100):
a = np.arange(size, dtype=np.int64)
rs.shuffle(a)
for window in range(2, size + 1):
actual = func(a, window=window, min_count=min_count)
desired = func0(a, window=window, min_count=min_count)
err_msg = fmt % (func.__name__, window, min_count, a)
aaae(actual, desired, decimal=5, err_msg=err_msg)
# ----------------------------------------------------------------------------
# Regression test for square roots of negative numbers
def test_move_std_sqrt() -> None:
"""Test move_std for neg sqrt."""
a = [
0.0011448196318903589,
0.00028718669878572767,
0.00028718669878572767,
0.00028718669878572767,
0.00028718669878572767,
]
err_msg = "Square root of negative number. ndim = %d"
b = bn.move_std(a, window=3)
assert np.isfinite(b[2:]).all(), err_msg % 1
a2 = np.array([a, a])
b = bn.move_std(a2, window=3, axis=1)
assert np.isfinite(b[:, 2:]).all(), err_msg % 2
a3 = np.array([[a, a], [a, a]])
b = bn.move_std(a3, window=3, axis=2)
assert np.isfinite(b[:, :, 2:]).all(), err_msg % 3
| bsd-2-clause |
resmio/django-sendgrid | setup.py | 1152 | import os
from setuptools import setup, find_packages
def read_file(filename):
"""Read a file into a string"""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepath).read()
except IOError:
return ''
setup(
name='django-sendgrid-webhook',
version=__import__('sendgrid').__version__,
author='Resmio',
author_email='support@gmail.com',
packages=find_packages(),
include_package_data=True,
url='https://github.com/resmio/django-sendgrid',
license='BSD 2-Clause',
description=' '.join(__import__('sendgrid').__doc__.splitlines()).strip(),
classifiers=[
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Framework :: Django',
'Framework :: Django :: 2.2',
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
],
long_description=read_file('README.md'),
test_suite='runtests.run_tests',
zip_safe=False,
)
| bsd-2-clause |
djaodjin/djaodjin-survey | survey/forms.py | 8596 | # Copyright (c) 2020, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pylint: disable=no-member
import uuid
from django import forms
from django.template.defaultfilters import slugify
from .compat import six
from .models import Answer, Campaign, EnumeratedQuestions, Sample
from .utils import get_question_model
def _create_field(question_type, text,
has_other=False, required=False, choices=None):
fields = (None, None)
question_model = get_question_model()
if question_type == question_model.TEXT:
fields = (forms.CharField(label=text, required=required,
widget=forms.Textarea), None)
elif question_type == question_model.RADIO:
radio = forms.ChoiceField(label=text, required=required,
widget=forms.RadioSelect(), choices=choices)
if has_other:
fields = (radio, forms.CharField(required=False,
label="Please could you specify?",
widget=forms.TextInput(attrs={'class':'other-input'})))
else:
fields = (radio, None)
elif question_type == question_model.DROPDOWN:
radio = forms.ChoiceField(label=text, required=required,
widget=forms.Select(), choices=choices)
if has_other:
fields = (radio, forms.CharField(required=False,
label="Please could you specify?",
widget=forms.TextInput(attrs={'class':'other-input'})))
else:
fields = (radio, None)
elif question_type == question_model.SELECT_MULTIPLE:
multiple = forms.MultipleChoiceField(label=text, required=required,
widget=forms.CheckboxSelectMultiple, choices=choices)
if has_other:
fields = (multiple, forms.CharField(required=False,
label="Please could you specify?",
widget=forms.TextInput(attrs={'class':'other-input'})))
else:
fields = (multiple, None)
elif question_type == question_model.INTEGER:
fields = (forms.IntegerField(label=text, required=required), None)
return fields
class AnswerForm(forms.ModelForm):
"""
Form used to submit an Answer to a Question as part of Sample to a Campaign.
"""
class Meta:
model = Answer
fields = []
def __init__(self, *args, **kwargs):
super(AnswerForm, self).__init__(*args, **kwargs)
if self.instance.question:
question = self.instance.question
elif 'question' in kwargs.get('initial', {}):
question = kwargs['initial']['question']
required = True
if self.instance.sample and self.instance.sample.campaign:
campaign_attrs = EnumeratedQuestions.objects.filter(
campaign=self.instance.sample.campaign,
question=question).first()
if campaign_attrs:
required = campaign_attrs.required
fields = _create_field(question.question_type, question.text,
required=required, choices=question.choices)
self.fields['text'] = fields[0]
def save(self, commit=True):
# We same in the view.
pass
class QuestionForm(forms.ModelForm):
class Meta:
model = get_question_model()
fields = ('path', 'title', 'text', 'default_metric', 'extra')
def clean_choices(self):
self.cleaned_data['choices'] = self.cleaned_data['choices'].strip()
return self.cleaned_data['choices']
class SampleCreateForm(forms.ModelForm):
class Meta:
model = Sample
fields = []
def __init__(self, *args, **kwargs):
super(SampleCreateForm, self).__init__(*args, **kwargs)
for idx, question in enumerate(self.initial.get('questions', [])):
key = 'question-%d' % (idx + 1)
required = True
campaign_attrs = EnumeratedQuestions.objects.filter(
campaign=self.instance.campaign,
question=question).first()
if campaign_attrs:
required = campaign_attrs.required
fields = _create_field(question.question_type, question.text,
required=required, choices=question.choices)
self.fields[key] = fields[0]
if fields[1]:
self.fields[key.replace('question-', 'other-')] = fields[1]
def clean(self):
super(SampleCreateForm, self).clean()
items = six.iteritems(self.cleaned_data)
for key, value in items:
if key.startswith('other-'):
if value:
self.cleaned_data[key.replace(
'other-', 'question-')] = value
del self.cleaned_data[key]
return self.cleaned_data
def save(self, commit=True):
if 'account' in self.initial:
self.instance.account = self.initial['account']
if 'campaign' in self.initial:
self.instance.campaign = self.initial['campaign']
self.instance.slug = slugify(uuid.uuid4().hex)
return super(SampleCreateForm, self).save(commit)
class SampleUpdateForm(forms.ModelForm):
"""
Auto-generated ``Form`` from a list of ``Question`` in a ``Campaign``.
"""
class Meta:
model = Sample
fields = []
def __init__(self, *args, **kwargs):
super(SampleUpdateForm, self).__init__(*args, **kwargs)
for idx, answer in enumerate(self.instance.get_answers_by_rank()):
question = answer.question
required = True
rank = idx
campaign_attrs = EnumeratedQuestions.objects.filter(
campaign=self.instance.campaign,
question=question).first()
if campaign_attrs:
required = campaign_attrs.required
rank = campaign_attrs.rank
fields = _create_field(question.question_type, question.text,
required=required, choices=question.choices)
# XXX set value.
self.fields['question-%d' % rank] = fields[0]
if fields[1]:
self.fields['other-%d' % rank] = fields[1]
class CampaignForm(forms.ModelForm):
class Meta:
model = Campaign
fields = ['title', 'description', 'quizz_mode']
def clean_title(self):
"""
Creates a slug from the campaign title and
checks it does not yet exists.
"""
slug = slugify(self.cleaned_data.get('title'))
if Campaign.objects.filter(slug__exact=slug).exists():
raise forms.ValidationError(
"Title conflicts with an existing campaign.")
return self.cleaned_data['title']
def save(self, commit=True):
if 'account' in self.initial:
self.instance.account = self.initial['account']
self.instance.slug = slugify(self.cleaned_data.get('title'))
return super(CampaignForm, self).save(commit)
class SendCampaignForm(forms.Form):
from_address = forms.EmailField(
help_text="add your email addresse to be contacted")
to_addresses = forms.CharField(
widget=forms.Textarea,
help_text="add email addresses separated by new line")
message = forms.CharField(widget=forms.Textarea,
help_text="You can explain the aim of this campaign")
| bsd-2-clause |
allpassos/AutoNet | assets/tci/js/tci-employees-add.js | 19517 | var addEmployee = function () {
var handleSelect2 = function () {
// Set the "bootstrap" theme as the default theme for all Select2 widgets.
// @see https://github.com/select2/select2/issues/2927
$.fn.select2.defaults.set("theme", "bootstrap");
var placeholder = "Seleccione";
$(".select2, .select2-multiple").select2({
placeholder: placeholder,
width: null
});
$(".select2-allow-clear").select2({
allowClear: true,
placeholder: placeholder,
width: null
});
// @see https://select2.github.io/examples.html#data-ajax
function formatRepo(repo) {
if (repo.loading)
return repo.text;
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + repo.full_name + "</div>";
if (repo.description) {
markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
}
markup += "<div class='select2-result-repository__statistics'>" +
"<div class='select2-result-repository__forks'><span class='glyphicon glyphicon-flash'></span> " + repo.forks_count + " Forks</div>" +
"<div class='select2-result-repository__stargazers'><span class='glyphicon glyphicon-star'></span> " + repo.stargazers_count + " Stars</div>" +
"<div class='select2-result-repository__watchers'><span class='glyphicon glyphicon-eye-open'></span> " + repo.watchers_count + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatRepoSelection(repo) {
return repo.full_name || repo.text;
}
$(".js-data-example-ajax").select2({
width: "off",
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
$("button[data-select2-open]").click(function () {
$("#" + $(this).data("select2-open")).select2("open");
});
$(":checkbox").on("click", function () {
$(this).parent().nextAll("select").prop("disabled", !this.checked);
});
// copy Bootstrap validation states to Select2 dropdown
//
// add .has-waring, .has-error, .has-succes to the Select2 dropdown
// (was #select2-drop in Select2 v3.x, in Select2 v4 can be selected via
// body > .select2-container) if _any_ of the opened Select2's parents
// has one of these forementioned classes (YUCK! ;-))
$(".select2, .select2-multiple, .select2-allow-clear, .js-data-example-ajax").on("select2:open", function () {
if ($(this).parents("[class*='has-']").length) {
var classNames = $(this).parents("[class*='has-']")[0].className.split(/\s+/);
for (var i = 0; i < classNames.length; ++i) {
if (classNames[i].match("has-")) {
$("body > .select2-container").addClass(classNames[i]);
}
}
}
});
$(".js-btn-set-scaling-classes").on("click", function () {
$("#select2-multiple-input-sm, #select2-single-input-sm").next(".select2-container--bootstrap").addClass("input-sm");
$("#select2-multiple-input-lg, #select2-single-input-lg").next(".select2-container--bootstrap").addClass("input-lg");
$(this).removeClass("btn-primary btn-outline").prop("disabled", true);
});
}
var handleRut = function () {
$('#rut').Rut({
format_on: 'keyup'
});
};
var handleDatePickers = function () {
if (jQuery().datepicker) {
$('#dob').datepicker({
rtl: App.isRTL(),
clearBtn: true,
language: 'es',
startDate: '-70y',
endDate: '-18y',
format: "dd-mm-yyyy",
orientation: "left",
autoclose: true,
});
$('#hired').datepicker({
rtl: App.isRTL(),
clearBtn: true,
language: 'es',
startDate: '-30d',
endDate: '+0d',
format: "dd-mm-yyyy",
orientation: "left",
autoclose: true
});
$('#fired').datepicker({
rtl: App.isRTL(),
clearBtn: true,
language: 'es',
startDate: '-60d',
endDate: '+0d',
format: "dd-mm-yyyy",
orientation: "left",
autoclose: true
});
//$('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
}
/* Workaround to restrict daterange past date select: http://stackoverflow.com/questions/11933173/how-to-restrict-the-selectable-date-ranges-in-bootstrap-datepicker */
}
var handleValidation = function () {
var form = $('#add-form');
//custom validation rule
jQuery.validator.addMethod("emailregex", function (value, element) {
var rgx = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
return this.optional(element) || rgx.test(value);
}, "Por favor, introduce una dirección de correo electrónico válida");
jQuery.validator.addMethod("rutPlugin", function(value, element) {
return this.optional(element) || $.Rut.validar(value);
}, "RUT incorrecto");
form.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
//ignore: "", // validate all fields including form hidden input
rules: {
names: {
required: true,
minlength: 3
},
surnames: {
required: true,
minlength: 3
},
rut: {
rutPlugin:true,
required: true
},
dob: {
required: true
},
gender: {
required: true
},
addr: {
required: true,
minlength: 6
},
idcomuna_fk: {
required: true
},
provincia: {
required: true
},
region: {
required: true
},
email: {
minlength: 3,
emailregex:true
},
idcbranch_fk: {
required: true
},
position: {
required: true,
minlength: 2
},
salary: {
required: true
},
hired: {
required: true
},
idafp_fk: {
required: true
},
idisapre_fk: {
required: true
},
dependents: {
required: true
}
},
messages: {
names: {
required: "Se requiere nombres",
minlength: jQuery.validator.format("Por favor, introduzca al menos {0} caracteres")
},
surnames: {
required: "Se requiere apellido materno",
minlength: jQuery.validator.format("Por favor, introduzca al menos {0} caracteres")
},
rut: {
required: "Se requiere RUT"
},
dob: {
required: "Se requiere fecha de nacimiento"
},
gender: {
required: "Se requiere sexo"
},
addr: {
required: "Se requiere dirección",
minlength: jQuery.validator.format("Por favor, introduzca al menos {0} caracteres")
},
idcomuna_fk: {
required: "Se requiere comuna"
},
provincia: {
required: "Se requiere provincia"
},
region: {
required: "Se requiere región"
},
email: {
required: "Se requiere Email",
minlength: jQuery.validator.format("Por favor, introduzca al menos {0} caracteres")
},
idcbranch_fk: {
required: "Se requiere sede"
},
position: {
required: "Se requiere cargo",
minlength: jQuery.validator.format("Por favor, introduzca al menos {0} caracteres")
},
salary: {
required: "Se requiere sueldo base"
},
hired: {
required: "Se requiere fecha de contratación"
},
idafp_fk: {
required: "Se requiere afp"
},
idisapre_fk: {
required: "Se requiere isapre"
},
dependents: {
required: "Se requiere numero de cargas familiares"
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
App.scrollTo(form, -200);
},
errorPlacement: function (error, element) {
if (element.is(':checkbox')) {
error.insertAfter(element.closest(".md-checkbox-list, .md-checkbox-inline, .checkbox-list, .checkbox-inline"));
} else if (element.is(':radio')) {
error.insertAfter(element.closest(".md-radio-list, .md-radio-inline, .radio-list,.radio-inline"));
} else if (element.is('.select2')) {
error.insertAfter(element.closest(".tci-select2-error"));
} else {
error.insertAfter(element); // for other inputs, just perform default behavior
}
},
highlight: function (element) { // hightlight error inputs
$(element).closest('.form-group').addClass('has-error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change done by hightlight
$(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
$("#gender, #idcomuna_fk, #idcbranch_fk, #idafp_fk, #idisapre_fk, #dependents").on("select2:close", function (e) {
$(this).closest('.form-group').removeClass('has-error');
$(this).closest('.form-group').find('.help-block').remove();
});
$("#dob, #hired").on("change", function (e) {
$(this).closest('.form-group').removeClass('has-error');
$(this).closest('.form-group').find('.help-block').remove();
});
},
success: function (label) {
label.closest('.form-group').removeClass('has-error'); // set success class to the control group
},
submitHandler: function (form) {
var dataString = $(form).find(":input").filter(function () {
return $.trim(this.value).length > 0}).serialize();
//console.log(dataString);
$.ajax({
type: "POST",
url: "/employees/ajxAddEmployee",
data: dataString,
dataType: "json",
cache: false,
beforeSend: function () {},
success: function (data) {
var obj = data;
if (obj.success) {
var response = $('#alert-builder').html(obj.success);
App.scrollTo(response, -200);
var allInputs = $(":input").removeAttr('checked').removeAttr('selected').not(':button, :submit, :reset, :hidden, :radio, :checkbox').val('');
$("#gender").select2('val', '');
$("#idcbranch_fk").select2('val', '');
$("#idcomuna_fk").select2('val', '');
$("#idafp_fk").select2('val', '');
$("#idisapre_fk").select2('val', '');
$("#marital_status").select2('val', '');
$("#dependents").select2('val', '');
} else {
if (obj.error) {
var error = $('#alert-builder').html(obj.error);
App.scrollTo(error, -200);
}
}
},
error: function (xhr, err) {
alert("readyState PARENT: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText PARENT: " + xhr.responseText);
},
complete: function () {}
});
}
});
}
var phoneMask = function () {
$("#tel1, #tel2").inputmask("mask", {
mask: "+56 [9]9 9999 9999",
removeMaskOnSubmit: false,
numericInput: true,
greedy: false
});
};
var moneyMask = function () {
$('#salary').inputmask("currency", {
placeholder: '0',
prefix: '$',
digitsOptional: false,
digits: 2,
radixPoint: ",",
autoGroup: true,
groupSeparator: ".",
allowMinus: false,
rightAlign: false,
greedy: false
});
};
var selComunas = function () {
$('#idcomuna_fk').change(function (e) {
$(this).closest('.form-group').removeClass('has-error');
$(this).closest('.form-group').find('.help-block').remove();
var csrf_tci_token = $('input[name="csrf_tci_token"]').val();
var idcomuna_fk = $(this).val();
if (idcomuna_fk !== '') {
var dataString = 'idcomuna_fk=' + idcomuna_fk + '&csrf_tci_token=' + csrf_tci_token;
$.ajax({
type: "POST",
url: "/employees/ajxHandleComunas",
data: dataString,
dataType: "json",
cache: false,
beforeSend: function () {},
success: function (data) {
var obj = data;
if (obj.response) {
//console.log(obj);
$('#idprovincia_fk').val(obj.response['idprovincia']);
$('#idregion_fk').val(obj.response['idregion']);
var provincia = $('#provincia').val(obj.response['provincia']);
var region = $('#region').val(obj.response['region']);
provincia.closest('.form-group').removeClass('has-error');
region.closest('.form-group').removeClass('has-error');
provincia.closest('.form-group').find('.help-block').remove();
region.closest('.form-group').find('.help-block').remove();
}
if (obj.error) {
$('.alert-danger').find('span').html(obj.error);
$('.alert-danger', $('.login-form')).show();
}
},
error: function (xhr, err) {
alert("readyState PARENT: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText PARENT: " + xhr.responseText);
},
complete: function () {}
});
}
});
};
var selAfp = function () {
$('#idafp_fk').change(function (e) {
var afp = $('option:selected', this).text();
$('#afp').val(afp);
});
};
var selIsapre = function () {
$('#idisapre_fk').change(function (e) {
var isapre = $('option:selected', this).text();
$('#isapre').val(isapre);
});
};
return {
init: function () {
handleSelect2();
handleRut();
handleDatePickers();
handleValidation();
phoneMask();
moneyMask();
selComunas();
selAfp();
selIsapre();
}
};
}();
if (App.isAngularJsApp() === false) {
jQuery(document).ready(function () {
addEmployee.init();
});
} | bsd-2-clause |
ritschwumm/scutil | modules/core/src/test/scala/scutil/lang/ShowInterpolatorTest.scala | 2201 | package scutil.lang
import minitest._
import scutil.lang.implicits._
object ShowInterpolatorTest extends SimpleTestSuite {
test("show interpolator should do an empty string") {
assertEquals(
show"""""",
""
)
}
test("show interpolator should do a single string") {
assertEquals(
show"""a""",
"a"
)
}
test("show interpolator should do a single value") {
val a = "1"
assertEquals(
show"""$a""",
"1"
)
}
test("show interpolator should do a string and a value") {
val a = "1"
assertEquals(
show"""${a}test""",
"1test"
)
}
test("show interpolator should do a value and a string") {
val a = "1"
assertEquals(
show"""test${a}""",
"test1"
)
}
test("show interpolator should work with multiple values and types") {
val a = "1"
val b = 2
val c = true
assertEquals(
show"""aaa${a}bbb${b}ccc${c}""",
"aaa1bbb2ccctrue"
)
}
//------------------------------------------------------------------------------
import scutil.lang.tc._
implicit def OptionShow[T:Show]:Show[Option[T]] =
Show instance {
case Some(x) => "some: " + (Show doit x)
case None => "none"
}
test("show interpolator should work with custom instances") {
val o:Option[Int] = Some(1)
assertEquals(
show"""$o""",
"some: 1"
)
}
//------------------------------------------------------------------------------
/*
test("show interpolator should work with inheritance") {
val o:Some[Int] = Some(1)
assertEquals(
show"""$o""",
"some: 1"
)
}
*/
//------------------------------------------------------------------------------
test("show interpolator should allow escapes") {
assertEquals(
show"\t",
"\t"
)
}
test("show interpolator should allow escapes") {
assertEquals(
show"\u0000",
s"\u0000"
)
}
/*
// fails at compile time, as it should
test("show interpolator should disallow unknown escapes") {
assertEquals(
show"""\x""",
s"\t"
)
}
*/
test("show interpolator should allow double quote escapes") {
assertEquals(
show"""\"""",
s"""\""""
)
}
test("show interpolator should allow double quote escapes") {
assertEquals(
show"""\"""",
"\""
)
}
}
| bsd-2-clause |
khchine5/book | lino_book/projects/min9/modlib/contacts/models.py | 4984 | # -*- coding: UTF-8 -*-
# Copyright 2013-2017 Luc Saffre
# License: BSD (see file COPYING for details)
"""
The `models` module for `lino.projects.min2.modlib.contacts`.
"""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import string_concat
from lino.api import dd, rt
from lino_xl.lib.contacts.models import *
from lino.modlib.comments.mixins import Commentable
from lino_xl.lib.cal.workflows import feedback
# from lino_xl.lib.addresses.mixins import AddressOwner
from lino_xl.lib.dupable_partners.mixins import DupablePartner, DupablePerson
class Partner(Partner, mixins.CreatedModified, DupablePartner, Commentable):
"""A Partner as seen in `lino.projects.min2`. It does not define any
specific field but inherits from a specific set of mixins.
"""
hidden_columns = 'created modified'
# def get_overview_elems(self, ar):
# # In the base classes, Partner must come first because
# # otherwise Django won't inherit `meta.verbose_name`. OTOH we
# # want to get the `get_overview_elems` from AddressOwner, not
# # from Partner (i.e. AddressLocation).
# elems = super(Partner, self).get_overview_elems(ar)
# elems += AddressOwner.get_overview_elems(self, ar)
# return elems
class PartnerDetail(PartnerDetail):
main = "general contact misc"
general = dd.Panel("""
overview:20 general2:20 general3:40
reception.AppointmentsByPartner comments.CommentsByRFC
""", label=_("General"))
general2 = """
id language
url
"""
general3 = """
email:40
phone
gsm
fax
"""
contact = dd.Panel("""
address_box
remarks:30
""", label=_("Contact"))
address_box = """
country region city zip_code:10
addr1
street_prefix street:25 street_no street_box
addr2
"""
misc = dd.Panel("""
created modified
changes.ChangesByMaster
""", label=_("Miscellaneous"))
class Person(Person, Partner, DupablePerson):
"""
Represents a physical person.
"""
class Meta(Person.Meta):
verbose_name = _("Person")
verbose_name_plural = _("Persons")
#~ ordering = ['last_name','first_name']
def get_queryset(self, ar):
return self.model.objects.select_related('country', 'city')
def get_print_language(self):
"Used by DirectPrintAction"
return self.language
dd.update_field(Person, 'first_name', blank=False)
dd.update_field(Person, 'last_name', blank=False)
class PersonDetail(PersonDetail):
main = "general contact misc"
general = dd.Panel("""
overview:20 general2:40 general3:40
contacts.RolesByPerson:20 households.MembersByPerson:40 \
humanlinks.LinksByHuman
""", label=_("General"))
general2 = """
title first_name:15 middle_name:15
last_name
gender:10 birth_date age:10
id language
"""
general3 = """
email:40
phone
gsm
fax
"""
contact = dd.Panel("""
#address_box addresses.AddressesByPartner
remarks:30
""", label=_("Contact"))
address_box = """
country region city zip_code:10
addr1
street_prefix street:25 street_no street_box
addr2
"""
misc = dd.Panel("""
url
created modified
reception.AppointmentsByPartner
""", label=_("Miscellaneous"))
class Persons(Persons):
detail_layout = PersonDetail()
class Company(Company, Partner):
"""A company as seen in `lino.projects.min2`.
.. attribute:: vat_id
The VAT identification number.
"""
class Meta:
verbose_name = _("Organisation")
verbose_name_plural = _("Organisations")
vat_id = models.CharField(_("VAT id"), max_length=200, blank=True)
class CompanyDetail(CompanyDetail):
main = "general contact notes misc"
general = dd.Panel("""
overview:20 general2:40 general3:40
contacts.RolesByCompany
""", label=_("General"))
general2 = """
prefix:20 name:40
type vat_id
url
"""
general3 = """
email:40
phone
gsm
fax
"""
contact = dd.Panel("""
#address_box addresses.AddressesByPartner
remarks:30
""", label=_("Contact"))
address_box = """
country region city zip_code:10
addr1
street_prefix street:25 street_no street_box
addr2
"""
notes = "notes.NotesByCompany"
misc = dd.Panel("""
id language
created modified
reception.AppointmentsByPartner
""", label=_("Miscellaneous"))
class Companies(Companies):
detail_layout = CompanyDetail()
# @dd.receiver(dd.post_analyze)
# def my_details(sender, **kw):
# contacts = sender.modules.contacts
# contacts.Partners.set_detail_layout(contacts.PartnerDetail())
# contacts.Companies.set_detail_layout(contacts.CompanyDetail())
Partners.set_detail_layout(PartnerDetail())
Companies.set_detail_layout(CompanyDetail())
| bsd-2-clause |
mmetak/streamlink | src/streamlink/plugins/earthcam.py | 3356 | from __future__ import print_function
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream, RTMPStream
from streamlink.utils import parse_json
class EarthCam(Plugin):
url_re = re.compile(r"https?://(?:www.)?earthcam.com/.*")
playpath_re = re.compile(r"(?P<folder>/.*/)(?P<file>.*?\.flv)")
swf_url = "http://static.earthcam.com/swf/streaming/stream_viewer_v3.swf"
json_base_re = re.compile(r"""var[ ]+json_base[^=]+=.*?(\{.*?});""", re.DOTALL)
cam_name_re = re.compile(r"""var[ ]+currentName[^=]+=[ \t]+(?P<quote>["'])(?P<name>\w+)(?P=quote);""", re.DOTALL)
cam_data_schema = validate.Schema(
validate.transform(json_base_re.search),
validate.any(
None,
validate.all(
validate.get(1),
validate.transform(lambda d: d.replace("\\/", "/")),
validate.transform(parse_json),
)
)
)
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
def _get_streams(self):
res = http.get(self.url)
m = self.cam_name_re.search(res.text)
cam_name = m and m.group("name")
json_base = self.cam_data_schema.validate(res.text)
cam_data = json_base["cam"][cam_name]
self.logger.debug("Found cam for {0} - {1}", cam_data["group"], cam_data["title"])
is_live = (cam_data["liveon"] == "true" and cam_data["defaulttab"] == "live")
# HLS data
hls_domain = cam_data["html5_streamingdomain"]
hls_playpath = cam_data["html5_streampath"]
# RTMP data
rtmp_playpath = ""
if is_live:
n = "live"
rtmp_domain = cam_data["streamingdomain"]
rtmp_path = cam_data["livestreamingpath"]
rtmp_live = cam_data["liveon"]
if rtmp_path:
match = self.playpath_re.search(rtmp_path)
rtmp_playpath = match.group("file")
rtmp_url = rtmp_domain + match.group("folder")
else:
n = "vod"
rtmp_domain = cam_data["archivedomain"]
rtmp_path = cam_data["archivepath"]
rtmp_live = cam_data["archiveon"]
if rtmp_path:
rtmp_playpath = rtmp_path
rtmp_url = rtmp_domain
# RTMP stream
if rtmp_playpath:
self.logger.debug("RTMP URL: {0}{1}", rtmp_url, rtmp_playpath)
params = {
"rtmp": rtmp_url,
"playpath": rtmp_playpath,
"pageUrl": self.url,
"swfUrl": self.swf_url,
"live": rtmp_live
}
yield n, RTMPStream(self.session, params)
# HLS stream
if hls_playpath and is_live:
hls_url = hls_domain + hls_playpath
self.logger.debug("HLS URL: {0}", hls_url)
for s in HLSStream.parse_variant_playlist(self.session, hls_url).items():
yield s
if not (rtmp_playpath or hls_playpath):
self.logger.error("This cam stream appears to be in offline or "
"snapshot mode and not live stream can be played.")
return
__plugin__ = EarthCam
| bsd-2-clause |
mbcoguno/homebrew-core | Formula/patchelf.rb | 2240 | class Patchelf < Formula
desc "Modify dynamic ELF executables"
homepage "https://github.com/NixOS/patchelf"
url "https://github.com/NixOS/patchelf/releases/download/0.13/patchelf-0.13.tar.bz2"
sha256 "4c7ed4bcfc1a114d6286e4a0d3c1a90db147a4c3adda1814ee0eee0f9ee917ed"
license "GPL-3.0-or-later"
head "https://github.com/NixOS/patchelf.git", branch: "master"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "d2c5ae0910087e5d745179a034d334b994d48a54398deab50c7efa389d0ad5de"
sha256 cellar: :any_skip_relocation, big_sur: "6ce62acab3314332cc248a08ba8285882a8d33d976196f1cfb8b1d6553035635"
sha256 cellar: :any_skip_relocation, catalina: "5a42eb843bb076dd938eb114e8e751ee871ca04f1db023051e0ae546b5e9fc79"
sha256 cellar: :any_skip_relocation, mojave: "d2f37f5a48c8054def582fd9cfda48b114a6f4f3287d45719d0d9a58adf6d5de"
sha256 cellar: :any_skip_relocation, x86_64_linux: "e2d839514014027d8222d5de10868a4ba754c3b4cf5f502bfc791fc4d2eaa705"
end
resource "helloworld" do
url "http://timelessname.com/elfbin/helloworld.tar.gz"
sha256 "d8c1e93f13e0b7d8fc13ce75d5b089f4d4cec15dad91d08d94a166822d749459"
end
def install
on_linux do
# Fix ld.so path and rpath
# see https://github.com/Homebrew/linuxbrew-core/pull/20548#issuecomment-672061606
ENV["HOMEBREW_DYNAMIC_LINKER"] = File.readlink("#{HOMEBREW_PREFIX}/lib/ld.so")
ENV["HOMEBREW_RPATH_PATHS"] = nil
end
system "./configure", "--prefix=#{prefix}",
"--disable-dependency-tracking",
"--disable-silent-rules"
system "make", "install"
end
test do
resource("helloworld").stage do
assert_equal "/lib/ld-linux.so.2\n", shell_output("#{bin}/patchelf --print-interpreter chello")
assert_equal "libc.so.6\n", shell_output("#{bin}/patchelf --print-needed chello")
assert_equal "\n", shell_output("#{bin}/patchelf --print-rpath chello")
assert_equal "", shell_output("#{bin}/patchelf --set-rpath /usr/local/lib chello")
assert_equal "/usr/local/lib\n", shell_output("#{bin}/patchelf --print-rpath chello")
end
end
end
| bsd-2-clause |
maxk-org/hogl | include/hogl/detail/refcount.hpp | 2746 | /*
Copyright (c) 2015-2020 Max Krasnyansky <max.krasnyansky@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file hogl/detail/refcount.h
* Simple atomic refcount.
*/
#ifndef HOGL_DETAIL_REFCOUNT_HPP
#define HOGL_DETAIL_REFCOUNT_HPP
#include <hogl/detail/compiler.hpp>
__HOGL_PRIV_NS_OPEN__
namespace hogl {
/**
* Simple atomic refcount.
*/
class refcount {
private:
mutable volatile int _count;
public:
// FIXME: Uses GCC builtins without checking for GCC
/**
* Increment reference count.
* @param v value to increment by
* @return new value of the counter
*/
int inc(int v = 1)
{
return __sync_add_and_fetch(&_count, v);
}
/**
* Decrement reference count.
* @param v value to decrement by
* @return new value of the counter
*/
int dec(int v = 1)
{
return __sync_sub_and_fetch(&_count, v);
}
/**
* Set reference count value.
* @param v value to decrement by
* @return previous value of the counter
*/
int set(int v)
{
return _count = v;
}
/**
* Get reference count value.
* @return counter value
*/
int get() const
{
return __sync_add_and_fetch(&_count, 0);
}
/**
* Initialize refcount
* @param v initial value
*/
refcount(int c = 0) : _count(c) { }
/**
* Initialize refcount
* @param r initial value
*/
refcount(const refcount &r) { set(r.get()); }
};
} // namespace hogl
__HOGL_PRIV_NS_CLOSE__
#endif // HOGL_DETAIL_REFCOUNT_HPP
| bsd-2-clause |
lifematrix/mcv | test/test_gas.cpp | 383 | //
// Created by Steven on 17/4/4.
//
#include <mcv/core.h>
#include <mcv/conv.h>
int main(int argc, char *argv[])
{
mcv::Matrix<float> img(10, 10, 3), dest;
for(int i=0; i < img.n_rows; i++)
for(int j=0; j < img.n_cols; j++)
for(int c=0; c < img.n_channels; c++)
img.at(i, j, c) = 1.0;
dest.copy_from(img);
mcv::gas_blur(img, 1, dest);
}
| bsd-2-clause |
huanhuashengling/our-information-class | app/Models/SendMailList.php | 1503 | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SendMailList extends Model
{
protected $fillable = ['server_provider', 'num_limit_one_day', 'username', 'mail_address', 'password', 'auth_code', 'is_useable', 'schools_id'];
}
/*
sudo docker run -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=admin' --name 'sql1' -p 1401:1433 -v sql1data:/var/mssql -d mcr.microsoft.com/mssql/server:2017-latest
docker exec -it sql1 mkdir /var/mssql/backup
docker exec -it sql1 /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'admin' -Q 'RESTORE FILELISTONLY FROM DISK = "/var/mssql/backup/ShareStacks.bak"' | tr -s ' ' | cut -d ' ' -f 1-2
sudo docker cp Downloads/ShareStacks.bak MSSQL_1433:/var/opt/mssql/backup
docker exec -it MSSQL_1433 /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'yourStrong(!)Password' -Q 'RESTORE FILELISTONLY FROM DISK = "/var/opt/mssql/backup/ShareStacks.bak"' | tr -s ' ' | cut -d ' ' -f 1-2
docker exec -it MSSQL_1433 /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'yourStrong(!)Password' -Q 'RESTORE DATABASE ShareStacks FROM DISK = "/var/opt/mssql/backup/ShareStacks.bak" WITH MOVE "ShareStacks" TO "/var/opt/mssql/data/ShareStacks.mdf", MOVE "ShareStacks_log" TO "/var/opt/mssql/data/ShareStacks.ldf"'
codesign -f -s "Navicat Register" /Applications/Navicat\ Premium.app/Contents/MacOS/Navicat\ Premium
./navicat-keygen 2048key.pem
NAV9-NHRJ-VMR4-3EP9
codesign -f -s "foobar" /Applications/Navicat\ Premium.app/Contents/MacOS/Navicat\ Premium*/ | bsd-2-clause |
maplesond/homebrew-science | molden.rb | 1094 | class Molden < Formula
desc "Pre- and post-processing of molecular and electronic structure"
homepage "http://www.cmbi.ru.nl/molden/"
url "ftp://ftp.cmbi.ru.nl/pub/molgraph/molden/molden5.7.tar.gz"
sha256 "8c52229f1762e987995c53936f0dc2cfd086277ec777bf9083d76c0bf0483887"
# tag "chemistry"
# doi "10.1023/A:1008193805436"
bottle do
cellar :any
sha256 "52ef22a806997d35e9d981c1b779ed9c0834eba9e3b9d9c32741b990cab59959" => :sierra
sha256 "c4a03bcfac4651420a5a626b95b962333045904c91379fe41f3acd88a8660299" => :el_capitan
sha256 "792ce5702cf158143210a46cde9d15e8301cc8005f27daf4010efc774497b85f" => :yosemite
end
depends_on :x11
depends_on :fortran
def install
system "make"
bin.install "molden", "gmolden"
end
def caveats; <<-EOS.undent
Two versions of Molden were installed:
- gmolden is the full OpenGL version
- molden is the Xwindows version
EOS
end
test do
# molden is an interactive program, there is not much we can test here
assert_match "Molden#{version}", shell_output("#{bin}/gmolden -h")
end
end
| bsd-2-clause |
sebastienros/jint | Jint.Tests.Test262/test/language/statements/variable/dstr-obj-ptrn-id-init-fn-name-class.js | 1390 | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-fn-name-class.case
// - src/dstr-binding/default/var-stmt.template
/*---
description: SingleNameBinding assigns `name` to "anonymous" classes (`var` statement)
esid: sec-variable-statement-runtime-semantics-evaluation
es6id: 13.3.2.4
features: [destructuring-binding]
flags: [generated]
info: |
VariableDeclaration : BindingPattern Initializer
1. Let rhs be the result of evaluating Initializer.
2. Let rval be GetValue(rhs).
3. ReturnIfAbrupt(rval).
4. Return the result of performing BindingInitialization for
BindingPattern passing rval and undefined as arguments.
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
6. If Initializer is present and v is undefined, then
[...]
d. If IsAnonymousFunctionDefinition(Initializer) is true, then
i. Let hasNameProperty be HasOwnProperty(v, "name").
ii. ReturnIfAbrupt(hasNameProperty).
iii. If hasNameProperty is false, perform SetFunctionName(v,
bindingId).
---*/
var { cls = class {}, xCls = class X {}, xCls2 = class { static name() {} } } = {};
assert.sameValue(cls.name, 'cls');
assert.notSameValue(xCls.name, 'xCls');
assert.notSameValue(xCls2.name, 'xCls2');
| bsd-2-clause |
ehughes/trashCAN | trashCAN/TRASH_CAN_CORE_SRC/CANMessageSniffer/Properties/Resources.Designer.cs | 3160 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CANMessageSniffer.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CANMessageSniffer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap nose {
get {
object obj = ResourceManager.GetObject("nose", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| bsd-2-clause |
Iprotechs2017/BTT_Lawyer2017 | sample-videochat-webrtc/src/main/java/com/VideoCalling/sample/groupchatwebrtc/fragments/OnCallEventsController.java | 145 | package com.VideoCalling.sample.groupchatwebrtc.fragments;
public interface OnCallEventsController {
void onUseHeadSet(boolean use);
}
| bsd-2-clause |
geops/ole2 | src/control/rotate.js | 4285 | import { Style, Icon } from 'ol/style';
import Point from 'ol/geom/Point';
import Vector from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Pointer from 'ol/interaction/Pointer';
import Control from './control';
import rotateSVG from '../../img/rotate.svg';
import rotateMapSVG from '../../img/rotate_map.svg';
/**
* Tool with for rotating geometries.
* @extends {ole.Control}
* @alias ole.RotateControl
*/
class RotateControl extends Control {
/**
* @inheritdoc
* @param {Object} [options] Control options.
* @param {string} [options.rotateAttribute] Name of a feature attribute
* that is used for storing the rotation in rad.
* @param {ol.style.Style.StyleLike} [options.style] Style used for the rotation layer.
*/
constructor(options) {
super({
title: 'Rotate',
className: 'icon-rotate',
image: rotateSVG,
...options,
});
/**
* @type {ol.interaction.Pointer}
* @private
*/
this.pointerInteraction = new Pointer({
handleDownEvent: this.onDown.bind(this),
handleDragEvent: this.onDrag.bind(this),
handleUpEvent: this.onUp.bind(this),
});
/**
* @type {string}
* @private
*/
this.rotateAttribute = options.rotateAttribute || 'ole_rotation';
/**
* Layer for rotation feature.
* @type {ol.layer.Vector}
* @private
*/
this.rotateLayer = new Vector({
source: new VectorSource(),
style:
options.style ||
((f) => {
const rotation = f.get(this.rotateAttribute);
return [
new Style({
geometry: new Point(this.center),
image: new Icon({
rotation,
src: rotateMapSVG,
}),
}),
];
}),
});
}
/**
* Handle a pointer down event.
* @param {ol.MapBrowserEvent} event Down event
* @private
*/
onDown(evt) {
this.dragging = false;
this.feature = this.map.forEachFeatureAtPixel(evt.pixel, (f) => {
if (this.source.getFeatures().indexOf(f) > -1) {
return f;
}
return null;
});
if (this.center && this.feature) {
this.feature.set(
this.rotateAttribute,
this.feature.get(this.rotateAttribute) || 0,
);
// rotation between clicked coordinate and feature center
this.initialRotation =
Math.atan2(
evt.coordinate[1] - this.center[1],
evt.coordinate[0] - this.center[0],
) + this.feature.get(this.rotateAttribute);
}
if (this.feature) {
return true;
}
return false;
}
/**
* Handle a pointer drag event.
* @param {ol.MapBrowserEvent} event Down event
* @private
*/
onDrag(evt) {
this.dragging = true;
if (this.feature && this.center) {
const rotation = Math.atan2(
evt.coordinate[1] - this.center[1],
evt.coordinate[0] - this.center[0],
);
const rotationDiff = this.initialRotation - rotation;
const geomRotation =
rotationDiff - this.feature.get(this.rotateAttribute);
this.feature.getGeometry().rotate(-geomRotation, this.center);
this.rotateFeature.getGeometry().rotate(-geomRotation, this.center);
this.feature.set(this.rotateAttribute, rotationDiff);
this.rotateFeature.set(this.rotateAttribute, rotationDiff);
}
}
/**
* Handle a pointer up event.
* @param {ol.MapBrowserEvent} event Down event
* @private
*/
onUp(evt) {
if (!this.dragging) {
if (this.feature) {
this.rotateFeature = this.feature;
this.center = evt.coordinate;
this.rotateLayer.getSource().clear();
this.rotateLayer.getSource().addFeature(this.rotateFeature);
} else {
this.rotateLayer.getSource().clear();
}
}
}
/**
* @inheritdoc
*/
activate() {
this.map.addInteraction(this.pointerInteraction);
this.rotateLayer.setMap(this.map);
super.activate();
}
/**
* @inheritdoc
*/
deactivate(silent) {
this.rotateLayer.getSource().clear();
this.rotateLayer.setMap(null);
this.map.removeInteraction(this.pointerInteraction);
super.deactivate(silent);
}
}
export default RotateControl;
| bsd-2-clause |
harryjoy/Light-box-jar | harsh/p/raval/lightbox/LightBoxException.java | 2164 | // Copyright (c) 2011, Harsh P. Raval
// All rights reserved.
//
// Redistribution and use in source and binary forms,
// with or without modification, are permitted provided that the
// following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package harsh.p.raval.lightbox;
/**
* Exception class for Light box effect jar.
* @author harsh
*/
public class LightBoxException extends Exception {
private static final long serialVersionUID = 3523762473012640617L;
/**
*
*/
public LightBoxException() {
}
/**
* @param message
*/
public LightBoxException(String message) {
super(message);
}
/**
* @param throwable
*/
public LightBoxException(Throwable throwable) {
super(throwable);
}
/**
* @param message
* @param throwable
*/
public LightBoxException(String message, Throwable throwable) {
super(message, throwable);
}
}
//If you find my program useful, you can support my site providing link to
//my site of this program or to the home page of my site:
//Web site: http://harryjoy.wordpress.com/ | bsd-2-clause |
askl56/homebrew-cask | Casks/kyoku.rb | 357 | cask v1: 'kyoku' do
version '0.0.4'
sha256 '5bac75ce062206a12c14d67411a8e802999fa31fb177e730b1ea913c293d6bd9'
url "https://github.com/cheeaun/kyoku/releases/download/#{version}/Kyoku.app.zip"
appcast 'https://github.com/cheeaun/kyoku/releases.atom'
name 'Kyoku'
homepage 'https://github.com/cheeaun/kyoku'
license :mit
app 'Kyoku.app'
end
| bsd-2-clause |
askl56/homebrew-cask | Casks/filezilla.rb | 797 | cask v1: 'filezilla' do
if MacOS.release <= :snow_leopard
version '3.8.1'
sha256 '86c725246e2190b04193ce8e7e5ea89d5b9318e9f20f5b6f9cdd45b6f5c2d283'
else
version '3.12.0.2'
sha256 '628feaaf36a93bbd0fe2e21d9d9c201320d99ca43d9a2230325830ff1f95db78'
end
# sourceforge.net is the official download host per the vendor homepage
url "http://downloads.sourceforge.net/project/filezilla/FileZilla_Client/#{version}/FileZilla_#{version}_macosx-x86.app.tar.bz2"
name 'FileZilla'
homepage 'https://filezilla-project.org/'
license :gpl
app 'FileZilla.app'
zap delete: [
'~/Library/Saved Application State/de.filezilla.savedState',
'~/Library/Preferences/de.filezilla.plist',
],
rmdir: '~/.config/filezilla'
end
| bsd-2-clause |
ymakino/echowand | src/echowand/info/PropertyConstraintAirSpeed.java | 1582 | package echowand.info;
import echowand.util.Constraint;
import echowand.util.ConstraintShort;
import echowand.util.ConstraintUnion;
/**
* 風速センサのデータ制約を表現する。
* データの範囲は0x0000 - 0xfffd (0 m/sec - 655.33 m/sec)となる。
* オーバーフローコードとして0xFFFF、アンダーフローコードとして0xFFFEが利用される。
* @author Yoshiki Makino
*/
public class PropertyConstraintAirSpeed implements Constraint {
private static final short MIN_VALUE = (short)0x0000;
private static final short MAX_VALUE = (short)0xfffd;
private static final short OVERFLOW = (short)0xffff;
private static final short UNDERFLOW = (short)0xfffe;
private ConstraintUnion constraint;
/**
* PropertyConstraintAirSpeedを生成する。
*/
public PropertyConstraintAirSpeed() {
ConstraintShort normal = new ConstraintShort(MIN_VALUE, MAX_VALUE);
ConstraintShort overflow = new ConstraintShort(OVERFLOW);
ConstraintShort underflow = new ConstraintShort(UNDERFLOW);
ConstraintUnion invalid = new ConstraintUnion(overflow, underflow);
constraint = new ConstraintUnion(normal, invalid);
}
@Override
public boolean isValid(byte[] data) {
return constraint.isValid(data);
}
/**
* PropertyConstraintAirSpeedの文字列表現を返す。
* @return PropertyConstraintAirSpeedの文字列表現
*/
@Override
public String toString() {
return constraint.toString();
}
}
| bsd-2-clause |
scikit-multilearn/scikit-multilearn | skmultilearn/cluster/random.py | 4376 | from __future__ import absolute_import
import random
import numpy as np
from .base import LabelSpaceClustererBase
class RandomLabelSpaceClusterer(LabelSpaceClustererBase):
"""Randomly divides the label space into equally-sized clusters
This method divides the label space by drawing without replacement a desired number of
equally sized subsets of label space, in a partitioning or overlapping scheme.
Parameters
----------
cluster_size : int
desired size of a single cluster, will be automatically
put under :code:`self.cluster_size`.
cluster_count: int
number of clusters to divide into, will be automatically
put under :code:`self.cluster_count`.
allow_overlap : bool
whether to allow overlapping clusters or not, will be automatically
put under :code:`self.allow_overlap`.
Examples
--------
The following code performs random label space partitioning.
.. code :: python
from skmultilearn.cluster import RandomLabelSpaceClusterer
# assume X,y contain the data, example y contains 5 labels
cluster_count = 2
cluster_size = y.shape[1]//cluster_count # == 2
clr = RandomLabelSpaceClusterer(cluster_size, cluster_count, allow_overlap=False)
clr.fit_predict(X,y)
# Result:
# array([list([0, 4]), list([2, 3]), list([1])], dtype=object)
Note that the leftover labels that did not fit in `cluster_size` x `cluster_count` classifiers will be appended
to an additional last cluster of size at most `cluster_size` - 1.
You can also use this class to get a random division of the label space, even with multiple overlaps:
.. code :: python
from skmultilearn.cluster import RandomLabelSpaceClusterer
cluster_size = 3
cluster_count = 5
clr = RandomLabelSpaceClusterer(cluster_size, cluster_count, allow_overlap=True)
clr.fit_predict(X,y)
# Result
# array([[2, 1, 3],
# [3, 0, 4],
# [2, 3, 1],
# [2, 3, 4],
# [3, 4, 0],
# [3, 0, 2]])
Note that you will never get the same label subset twice.
"""
def __init__(self, cluster_size, cluster_count, allow_overlap):
super(RandomLabelSpaceClusterer, self).__init__()
self.cluster_size = cluster_size
self.cluster_count = cluster_count
self.allow_overlap = allow_overlap
def fit_predict(self, X, y):
"""Cluster the output space
Parameters
----------
X : currently unused, left for scikit compatibility
y : scipy.sparse
label space of shape :code:`(n_samples, n_labels)`
Returns
-------
arrray of arrays of label indexes (numpy.ndarray)
label space division, each sublist represents labels that are in that community
"""
if (self.cluster_count+1) * self.cluster_size < y.shape[1]:
raise ValueError("Cannot include all of {} labels in {} clusters of {} labels".format(
y.shape[1],
self.cluster_count,
self.cluster_size
))
all_labels_assigned_to_division = False
# make sure the final label set division includes all labels
while not all_labels_assigned_to_division:
label_sets = []
free_labels = range(y.shape[1])
while len(label_sets) <= self.cluster_count:
if not self.allow_overlap:
if len(free_labels) == 0:
break
# in this case, we are unable to draw new labels, add all that remain
if len(free_labels) < self.cluster_size:
label_sets.append(free_labels)
break
label_set = random.sample(free_labels, self.cluster_size)
if not self.allow_overlap:
free_labels = list(set(free_labels).difference(set(label_set)))
if label_set not in label_sets:
label_sets.append(label_set)
all_labels_assigned_to_division = all(
any(label in subset for subset in label_sets)
for label in range(y.shape[1])
)
return np.array(label_sets)
| bsd-2-clause |
eregon/mozart-graal | vm/src/org/mozartoz/truffle/nodes/builtins/VirtualStringBuiltins.java | 7886 | package org.mozartoz.truffle.nodes.builtins;
import static org.mozartoz.truffle.nodes.builtins.Builtin.ALL;
import org.mozartoz.truffle.nodes.DerefNode;
import org.mozartoz.truffle.nodes.OzGuards;
import org.mozartoz.truffle.nodes.OzNode;
import org.mozartoz.truffle.nodes.builtins.VirtualStringBuiltinsFactory.ToAtomNodeFactory;
import org.mozartoz.truffle.runtime.Arity;
import org.mozartoz.truffle.runtime.Errors;
import org.mozartoz.truffle.runtime.OzCons;
import org.mozartoz.truffle.runtime.OzObject;
import org.mozartoz.truffle.runtime.OzRecord;
import org.mozartoz.truffle.runtime.OzString;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.CreateCast;
import com.oracle.truffle.api.dsl.GenerateNodeFactory;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.NodeChildren;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.object.Property;
public abstract class VirtualStringBuiltins {
@Builtin(name = "is", deref = ALL)
@GenerateNodeFactory
@NodeChild("value")
public static abstract class IsVirtualStringNode extends OzNode {
@Child DerefNode derefNode = DerefNode.create();
public abstract boolean executeIsVirtualString(Object value);
@Specialization
boolean isVirtualString(long value) {
return true;
}
@Specialization
boolean isVirtualString(double value) {
return true;
}
@Specialization
boolean isVirtualString(String atom) {
return true;
}
@Specialization
boolean isVirtualString(OzCons cons) {
Object list = cons;
while (list instanceof OzCons) {
OzCons xs = (OzCons) list;
Object head = deref(xs.getHead());
assert head instanceof Long;
list = deref(xs.getTail());
}
assert list == "nil";
return true;
}
@TruffleBoundary
@Specialization
boolean isVirtualString(DynamicObject tuple) {
Arity arity = OzRecord.getArity(tuple);
if (arity.isTupleArity() && arity.getLabel() == "#") {
for (long i = 1L; i <= arity.getWidth(); i++) {
Object value = deref(tuple.get(i));
if (!executeIsVirtualString(value)) {
return false;
}
}
return true;
}
return false;
}
@Specialization
boolean isVirtualString(OzObject object) {
return false;
}
private Object deref(Object value) {
return derefNode.executeDeref(value);
}
}
@Builtin(deref = ALL)
@GenerateNodeFactory
@NodeChild("value")
public static abstract class ToCompactStringNode extends OzNode {
@Child ToAtomNode toAtomNode = ToAtomNode.create();
@Specialization
OzString toCompactString(Object value) {
String chars = toAtomNode.executeToAtom(value);
return new OzString(chars);
}
}
@Builtin(deref = ALL)
@GenerateNodeFactory
@NodeChildren({ @NodeChild("value"), @NodeChild("tail") })
public static abstract class ToCharListNode extends OzNode {
@Child DerefNode derefNode = DerefNode.create();
public abstract Object executeToCharList(Object value, Object tail);
@TruffleBoundary
@Specialization
Object toCharList(long number, Object tail) {
String str = Long.toString(number).intern();
return executeToCharList(str, tail);
}
@TruffleBoundary
@Specialization
Object toCharList(double number, Object tail) {
String str = Double.toString(number).intern();
return executeToCharList(str, tail);
}
@Specialization
Object toCharList(String atom, Object tail) {
Object list = tail;
for (int i = atom.length() - 1; i >= 0; i--) {
list = new OzCons((long) atom.charAt(i), list);
}
return list;
}
@TruffleBoundary
@Specialization
Object toCharList(OzCons cons, Object tail) {
Object head = deref(cons.getHead());
assert head instanceof Long;
Object consTail = deref(cons.getTail());
if (consTail == "nil") {
return new OzCons(head, tail);
} else {
return new OzCons(head, executeToCharList(consTail, tail));
}
}
@TruffleBoundary
@Specialization
Object toCharList(DynamicObject record, Object tail) {
assert OzRecord.getLabel(record) == "#";
Object list = tail;
// We want to traverse in reverse order here
for (Property property : record.getShape().getPropertyListInternal(false)) {
if (!property.isHidden()) {
Object value = deref(property.get(record, record.getShape()));
if (value != "nil") {
list = executeToCharList(value, list);
}
}
}
return list;
}
private Object deref(Object value) {
return derefNode.executeDeref(value);
}
}
@Builtin(deref = ALL)
@GenerateNodeFactory
@NodeChild("value")
public static abstract class ToAtomNode extends OzNode {
public static ToAtomNode create() {
return ToAtomNodeFactory.create(null);
}
@Child DerefNode derefNode = DerefNode.create();
public abstract String executeToAtom(Object value);
@TruffleBoundary
@Specialization
String toAtom(long number) {
return Long.toString(number).intern();
}
@Specialization
String toAtom(String atom) {
assert OzGuards.isAtom(atom);
return atom;
}
@Specialization
String toAtom(OzString string) {
return string.getChars().intern();
}
@TruffleBoundary
@Specialization
String toAtom(OzCons cons) {
StringBuilder builder = new StringBuilder();
Object list = cons;
while (list instanceof OzCons) {
OzCons xs = (OzCons) list;
Object head = deref(xs.getHead());
assert head instanceof Long;
long longHead = (long) head;
char c = (char) longHead;
builder.append(c);
list = deref(xs.getTail());
}
assert list == "nil";
return builder.toString().intern();
}
@TruffleBoundary
@Specialization
String toAtom(DynamicObject record) {
assert OzRecord.getLabel(record) == "#";
StringBuilder builder = new StringBuilder();
for (Property property : record.getShape().getProperties()) {
Object value = deref(property.get(record, record.getShape()));
if (value != "nil") {
builder.append(executeToAtom(value));
}
}
return builder.toString().intern();
}
private Object deref(Object value) {
return derefNode.executeDeref(value);
}
}
@Builtin(deref = ALL)
@GenerateNodeFactory
@NodeChild("value")
public static abstract class LengthNode extends OzNode {
@Child DerefNode derefNode = DerefNode.create();
public abstract long executeLength(Object value);
@Specialization
long length(long number) {
return Long.toString(number).length();
}
@Specialization
long length(String atom) {
return atom.length();
}
@TruffleBoundary
@Specialization
long length(OzCons cons) {
long length = 0;
Object list = cons;
while (list instanceof OzCons) {
OzCons xs = (OzCons) list;
Object head = deref(xs.getHead());
assert head instanceof Long;
length += 1;
list = deref(xs.getTail());
}
assert list == "nil";
return length;
}
@TruffleBoundary
@Specialization
long length(DynamicObject record) {
assert OzRecord.getLabel(record) == "#";
long length = 0;
for (Property property : record.getShape().getProperties()) {
Object value = deref(property.get(record, record.getShape()));
if (value != "nil") {
length += executeLength(value);
}
}
return length;
}
private Object deref(Object value) {
return derefNode.executeDeref(value);
}
}
@Builtin(deref = ALL)
@GenerateNodeFactory
@NodeChild("value")
public static abstract class ToFloatNode extends OzNode {
@CreateCast("value")
protected OzNode castValue(OzNode value) {
return ToAtomNodeFactory.create(value);
}
@TruffleBoundary
@Specialization
double toFloat(String atom) {
try {
return Double.valueOf(atom.replace('~', '-'));
} catch (Exception e) {
throw Errors.kernelError(this, "stringNoFloat", atom);
}
}
}
}
| bsd-2-clause |
vladimirvivien/learning-go | ch07/map_make.go | 349 | package main
import "fmt"
func main() {
hist := make(map[string]int, 6)
hist["Jan"] = 100
hist["Feb"] = 445
hist["Mar"] = 514
hist["Apr"] = 233
hist["May"] = 321
hist["Jun"] = 644
hist["Jul"] = 113
hist["Aug"] = 734
hist["Sep"] = 553
hist["Oct"] = 344
hist["Nov"] = 831
hist["Dec"] = 312
fmt.Println(hist)
fmt.Println(len(hist))
}
| bsd-2-clause |
WojciechMula/toys | avx512-sort/avx512-sort-any.cpp | 21542 | #include <immintrin.h>
#define FORCE_INLINE inline __attribute__((always_inline))
namespace avx512sort {
// sort 16 elements
void FORCE_INLINE sort1xreg_update(const __m512i b, const __m512i v1, __m512i& r1) {
const uint64_t lt1 = _mm512_cmplt_epi32_mask(v1, b);
const uint64_t lt_cnt = _mm_popcnt_u64(lt1);
const uint64_t eq1 = _mm512_cmpeq_epi32_mask(v1, b);
const uint64_t eq_cnt = _mm_popcnt_u64(eq1);
const uint64_t mask = (uint64_t(1) << (lt_cnt + eq_cnt)) - (uint64_t(1) << lt_cnt);
r1 = _mm512_mask_mov_epi32(r1, mask, b);
}
// sort less than 16 elements
void FORCE_INLINE sort1xreg_tail_update(const __m512i b, const __m512i v1, __mmask16 v1tail, __m512i& r1) {
const uint64_t lt1 = _mm512_mask_cmplt_epi32_mask(v1tail, v1, b);
const uint64_t eq1 = _mm512_mask_cmpeq_epi32_mask(v1tail, v1, b);
const uint64_t lt_cnt = _mm_popcnt_u64(lt1);
const uint64_t eq_cnt = _mm_popcnt_u64(eq1);
const uint64_t mask = (uint64_t(1) << (lt_cnt + eq_cnt)) - (uint64_t(1) << lt_cnt);
r1 = _mm512_mask_mov_epi32(r1, mask, b);
}
// sort 32 elements
void FORCE_INLINE sort2xreg_update(
const __m512i b,
const __m512i v1, const __m512i v2,
__m512i& r1, __m512i& r2) {
const uint64_t lt1 = _mm512_cmplt_epi32_mask(v1, b);
const uint64_t lt2 = _mm512_cmplt_epi32_mask(v2, b);
const uint64_t lt_cnt = _mm_popcnt_u64(lt1 | (lt2 << 16));
const uint64_t eq1 = _mm512_cmpeq_epi32_mask(v1, b);
const uint64_t eq2 = _mm512_cmpeq_epi32_mask(v2, b);
const uint64_t eq_cnt = _mm_popcnt_u64(eq1 | (eq2 << 16));
const uint64_t mask = (uint64_t(1) << (lt_cnt + eq_cnt)) - (uint64_t(1) << lt_cnt);
r1 = _mm512_mask_mov_epi32(r1, mask & 0xffff, b);
r2 = _mm512_mask_mov_epi32(r2, (mask >> 16) & 0xffff, b);
}
// sort 17 .. 31 elements
void FORCE_INLINE sort2xreg_tail_update(
const __m512i b,
const __m512i v1, const __m512i v2, __mmask16 v2tail,
__m512i& r1, __m512i& r2) {
const uint64_t lt1 = _mm512_cmplt_epi32_mask(v1, b);
const uint64_t lt2 = _mm512_mask_cmplt_epi32_mask(v2tail, v2, b);
const uint64_t lt_cnt = _mm_popcnt_u64(lt1 | (lt2 << 16));
const uint64_t eq1 = _mm512_cmpeq_epi32_mask(v1, b);
const uint64_t eq2 = _mm512_mask_cmpeq_epi32_mask(v2tail, v2, b);
const uint64_t eq_cnt = _mm_popcnt_u64(eq1 | (eq2 << 16));
const uint64_t mask = (uint64_t(1) << (lt_cnt + eq_cnt)) - (uint64_t(1) << lt_cnt);
r1 = _mm512_mask_mov_epi32(r1, mask & 0xffff, b);
r2 = _mm512_mask_mov_epi32(r2, (mask >> 16) & 0xffff, b);
}
// sort 48 elements
void FORCE_INLINE sort3xreg_update(
const __m512i b,
const __m512i v1, const __m512i v2, const __m512i v3,
__m512i& r1, __m512i& r2, __m512i& r3) {
const uint64_t lt1 = _mm512_cmplt_epi32_mask(v1, b);
const uint64_t lt2 = _mm512_cmplt_epi32_mask(v2, b);
const uint64_t lt3 = _mm512_cmplt_epi32_mask(v3, b);
const uint64_t lt_cnt = _mm_popcnt_u64(lt1 | (lt2 << 16) | (lt3 << 32));
const uint64_t eq1 = _mm512_cmpeq_epi32_mask(v1, b);
const uint64_t eq2 = _mm512_cmpeq_epi32_mask(v2, b);
const uint64_t eq3 = _mm512_cmpeq_epi32_mask(v3, b);
const uint64_t eq_cnt = _mm_popcnt_u64(eq1 | (eq2 << 16) | (eq3 << 32));
const uint64_t mask = (uint64_t(1) << (lt_cnt + eq_cnt)) - (uint64_t(1) << lt_cnt);
r1 = _mm512_mask_mov_epi32(r1, mask & 0xffff, b);
r2 = _mm512_mask_mov_epi32(r2, (mask >> 16) & 0xffff, b);
r3 = _mm512_mask_mov_epi32(r3, (mask >> 32) & 0xffff, b);
}
// sort 33 .. 47 elements
void FORCE_INLINE sort3xreg_tail_update(
const __m512i b,
const __m512i v1, const __m512i v2, const __m512i v3, __mmask16 v3tail,
__m512i& r1, __m512i& r2, __m512i& r3) {
const uint64_t lt1 = _mm512_cmplt_epi32_mask(v1, b);
const uint64_t lt2 = _mm512_cmplt_epi32_mask(v2, b);
const uint64_t lt3 = _mm512_mask_cmplt_epi32_mask(v3tail, v3, b);
const uint64_t lt_cnt = _mm_popcnt_u64(lt1 | (lt2 << 16) | (lt3 << 32));
const uint64_t eq1 = _mm512_cmpeq_epi32_mask(v1, b);
const uint64_t eq2 = _mm512_cmpeq_epi32_mask(v2, b);
const uint64_t eq3 = _mm512_mask_cmpeq_epi32_mask(v3tail, v3, b);
const uint64_t eq_cnt = _mm_popcnt_u64(eq1 | (eq2 << 16) | (eq3 << 32));
const uint64_t mask = (uint64_t(1) << (lt_cnt + eq_cnt)) - (uint64_t(1) << lt_cnt);
r1 = _mm512_mask_mov_epi32(r1, mask & 0xffff, b);
r2 = _mm512_mask_mov_epi32(r2, (mask >> 16) & 0xffff, b);
r3 = _mm512_mask_mov_epi32(r3, (mask >> 32) & 0xffff, b);
}
// sort 64 elements
void FORCE_INLINE sort4xreg_update(
const __m512i b,
const __m512i v1, const __m512i v2, const __m512i v3, const __m512i v4,
__m512i& r1, __m512i& r2, __m512i& r3, __m512i& r4) {
const uint64_t lt1 = _mm512_cmplt_epi32_mask(v1, b);
const uint64_t lt2 = _mm512_cmplt_epi32_mask(v2, b);
const uint64_t lt3 = _mm512_cmplt_epi32_mask(v3, b);
const uint64_t lt4 = _mm512_cmplt_epi32_mask(v4, b);
const uint64_t lt_cnt = _mm_popcnt_u64(lt1 | (lt2 << 16) | (lt3 << 32) | (lt4 << 48));
const uint64_t eq1 = _mm512_cmpeq_epi32_mask(v1, b);
const uint64_t eq2 = _mm512_cmpeq_epi32_mask(v2, b);
const uint64_t eq3 = _mm512_cmpeq_epi32_mask(v3, b);
const uint64_t eq4 = _mm512_cmpeq_epi32_mask(v4, b);
const uint64_t eq_cnt = _mm_popcnt_u64(eq1 | (eq2 << 16) | (eq3 << 32) | (eq4 << 48));
if (eq_cnt == 64) {
r1 = r2 = r3 = r4 = b;
return;
}
const uint64_t mask = (uint64_t(1) << (lt_cnt + eq_cnt)) - (uint64_t(1) << lt_cnt);
r1 = _mm512_mask_mov_epi32(r1, mask & 0xffff, b);
r2 = _mm512_mask_mov_epi32(r2, (mask >> 16) & 0xffff, b);
r3 = _mm512_mask_mov_epi32(r3, (mask >> 32) & 0xffff, b);
r4 = _mm512_mask_mov_epi32(r4, (mask >> 48) & 0xffff, b);
}
// sort 49 to 63 elements
void FORCE_INLINE sort4xreg_tail_update(
const __m512i b,
const __m512i v1, const __m512i v2, const __m512i v3, const __m512i v4, __mmask16 v4tail,
__m512i& r1, __m512i& r2, __m512i& r3, __m512i& r4) {
const uint64_t lt1 = _mm512_cmplt_epi32_mask(v1, b);
const uint64_t lt2 = _mm512_cmplt_epi32_mask(v2, b);
const uint64_t lt3 = _mm512_cmplt_epi32_mask(v3, b);
const uint64_t lt4 = _mm512_mask_cmplt_epi32_mask(v4tail, v4, b);
const uint64_t lt_cnt = _mm_popcnt_u64(lt1 | (lt2 << 16) | (lt3 << 32) | (lt4 << 48));
const uint64_t eq1 = _mm512_cmpeq_epi32_mask(v1, b);
const uint64_t eq2 = _mm512_cmpeq_epi32_mask(v2, b);
const uint64_t eq3 = _mm512_cmpeq_epi32_mask(v3, b);
const uint64_t eq4 = _mm512_mask_cmpeq_epi32_mask(v4tail, v4, b);
const uint64_t eq_cnt = _mm_popcnt_u64(eq1 | (eq2 << 16) | (eq3 << 32) | (eq4 << 48));
if (eq_cnt == 64) {
r1 = r2 = r3 = r4 = b;
return;
}
const uint64_t mask = (uint64_t(1) << (lt_cnt + eq_cnt)) - (uint64_t(1) << lt_cnt);
r1 = _mm512_mask_mov_epi32(r1, mask & 0xffff, b);
r2 = _mm512_mask_mov_epi32(r2, (mask >> 16) & 0xffff, b);
r3 = _mm512_mask_mov_epi32(r3, (mask >> 32) & 0xffff, b);
r4 = _mm512_mask_mov_epi32(r4, (mask >> 48) & 0xffff, b);
}
// ------------------------------------------------------------
__m512i sort1xreg(const __m512i v) {
__m512i result = v;
__m512i index = _mm512_setzero_si512();
__m512i incr = _mm512_set1_epi32(1);
#define STEP(unused) { \
const __m512i b = _mm512_permutexvar_epi32(index, v); \
index = _mm512_add_epi32(index, incr); \
sort1xreg_update(b, v, result); \
}
STEP(0x0); STEP(0x1); STEP(0x2); STEP(0x3);
STEP(0x4); STEP(0x5); STEP(0x6); STEP(0x7);
STEP(0x8); STEP(0x9); STEP(0xa); STEP(0xb);
STEP(0xc); STEP(0xd); STEP(0xe); STEP(0xf);
#undef STEP
return result;
}
template <unsigned size>
__m512i sort1xreg_tail(const __m512i v) {
static_assert(size > 1, "invalid size");
static_assert(size < 16, "invalid size");
const __mmask16 tail = (1 << size) - 1;
__m512i result = v;
__m512i index = _mm512_setzero_si512();
__m512i incr = _mm512_set1_epi32(1);
#define STEP(step) if (step < size) { \
const __m512i b = _mm512_permutexvar_epi32(index, v); \
index = _mm512_add_epi32(index, incr); \
sort1xreg_tail_update(b, v, tail, result); \
}
STEP(0x0); STEP(0x1); STEP(0x2); STEP(0x3);
STEP(0x4); STEP(0x5); STEP(0x6); STEP(0x7);
STEP(0x8); STEP(0x9); STEP(0xa); STEP(0xb);
STEP(0xc); STEP(0xd); STEP(0xe); STEP(0xf);
#undef STEP
return result;
}
void sort2xreg(__m512i& v1, __m512i& v2) {
__m512i r1 = v1;
__m512i r2 = v2;
__m512i index;
__m512i incr = _mm512_set1_epi32(1);
#define STEP(input) { \
const __m512i b = _mm512_permutexvar_epi32(index, input); \
index = _mm512_add_epi32(index, incr); \
sort2xreg_update(b, v1, v2, r1, r2); \
}
#define STEP_16x(input) \
index = _mm512_setzero_si512(); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input);
STEP_16x(v1);
STEP_16x(v2);
#undef STEP_16x
#undef STEP
v1 = r1;
v2 = r2;
}
template <unsigned size>
void sort2xreg_tail(__m512i& v1, __m512i& v2) {
static_assert(size > 16, "invalid size");
static_assert(size < 32, "invalid size");
const __mmask16 tail = (1 << (size - 16)) - 1;
__m512i r1 = v1;
__m512i r2 = v2;
__m512i index;
__m512i incr = _mm512_set1_epi32(1);
#define STEP(step, input) if (step < size) { \
const __m512i b = _mm512_permutexvar_epi32(index, input); \
index = _mm512_add_epi32(index, incr); \
sort2xreg_tail_update(b, v1, v2, tail, r1, r2); \
}
#define STEP_16x(shift, input) \
index = _mm512_setzero_si512(); \
STEP(0x0 + shift, input); STEP(0x1 + shift, input); STEP(0x2 + shift, input); STEP(0x3 + shift, input); \
STEP(0x4 + shift, input); STEP(0x5 + shift, input); STEP(0x6 + shift, input); STEP(0x7 + shift, input); \
STEP(0x8 + shift, input); STEP(0x9 + shift, input); STEP(0xa + shift, input); STEP(0xb + shift, input); \
STEP(0xc + shift, input); STEP(0xd + shift, input); STEP(0xe + shift, input); STEP(0xf + shift, input);
STEP_16x( 0, v1);
STEP_16x(16, v2);
#undef STEP_16x
#undef STEP
v1 = r1;
v2 = r2;
}
void sort3xreg(__m512i& v1, __m512i& v2, __m512i& v3) {
__m512i r1 = v1;
__m512i r2 = v2;
__m512i r3 = v3;
__m512i index;
__m512i incr = _mm512_set1_epi32(1);
#define STEP(input) { \
const __m512i b = _mm512_permutexvar_epi32(index, input); \
index = _mm512_add_epi32(index, incr); \
sort3xreg_update(b, v1, v2, v3, r1, r2, r3); \
}
#define STEP_16x(input) \
index = _mm512_setzero_si512(); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input);
STEP_16x(v1);
STEP_16x(v2);
STEP_16x(v3);
#undef STEP_16x
#undef STEP
v1 = r1;
v2 = r2;
v3 = r3;
}
template <unsigned size>
void sort3xreg_tail(__m512i& v1, __m512i& v2, __m512i& v3) {
static_assert(size > 32, "invalid size");
static_assert(size < 48, "invalid size");
const __mmask16 tail = (1 << (size - 32)) - 1;
__m512i r1 = v1;
__m512i r2 = v2;
__m512i r3 = v3;
__m512i index;
__m512i incr = _mm512_set1_epi32(1);
#define STEP(step, input) if (step < size) { \
const __m512i b = _mm512_permutexvar_epi32(index, input); \
index = _mm512_add_epi32(index, incr); \
sort3xreg_tail_update(b, v1, v2, v3, tail, r1, r2, r3); \
}
#define STEP_16x(shift, input) \
index = _mm512_setzero_si512(); \
STEP(0x0 + shift, input); STEP(0x1 + shift, input); STEP(0x2 + shift, input); STEP(0x3 + shift, input); \
STEP(0x4 + shift, input); STEP(0x5 + shift, input); STEP(0x6 + shift, input); STEP(0x7 + shift, input); \
STEP(0x8 + shift, input); STEP(0x9 + shift, input); STEP(0xa + shift, input); STEP(0xb + shift, input); \
STEP(0xc + shift, input); STEP(0xd + shift, input); STEP(0xe + shift, input); STEP(0xf + shift, input);
STEP_16x( 0, v1);
STEP_16x(16, v2);
STEP_16x(32, v3);
#undef STEP_16x
#undef STEP
v1 = r1;
v2 = r2;
v3 = r3;
}
void sort4xreg(__m512i& v1, __m512i& v2, __m512i& v3, __m512i& v4) {
__m512i r1 = v1;
__m512i r2 = v2;
__m512i r3 = v3;
__m512i r4 = v4;
__m512i index;
__m512i incr = _mm512_set1_epi32(1);
#define STEP(input) { \
const __m512i b = _mm512_permutexvar_epi32(index, input); \
index = _mm512_add_epi32(index, incr); \
sort4xreg_update(b, v1, v2, v3, v4, r1, r2, r3, r4); \
}
#define STEP_16x(input) \
index = _mm512_setzero_si512(); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input); \
STEP(input); STEP(input); STEP(input); STEP(input);
STEP_16x(v1);
STEP_16x(v2);
STEP_16x(v3);
STEP_16x(v4);
#undef STEP_16x
#undef STEP
v1 = r1;
v2 = r2;
v3 = r3;
v4 = r4;
}
template <unsigned size>
void sort4xreg_tail(__m512i& v1, __m512i& v2, __m512i& v3, __m512i& v4) {
static_assert(size > 48, "invalid size");
static_assert(size < 64, "invalid size");
const __mmask16 tail = (1 << (size - 48)) - 1;
__m512i r1 = v1;
__m512i r2 = v2;
__m512i r3 = v3;
__m512i r4 = v4;
__m512i index;
__m512i incr = _mm512_set1_epi32(1);
#define STEP(step, input) if (step < size) { \
const __m512i b = _mm512_permutexvar_epi32(index, input); \
index = _mm512_add_epi32(index, incr); \
sort4xreg_tail_update(b, v1, v2, v3, v4, tail, r1, r2, r3, r4); \
}
#define STEP_16x(shift, input) \
index = _mm512_setzero_si512(); \
STEP(0x0 + shift, input); STEP(0x1 + shift, input); STEP(0x2 + shift, input); STEP(0x3 + shift, input); \
STEP(0x4 + shift, input); STEP(0x5 + shift, input); STEP(0x6 + shift, input); STEP(0x7 + shift, input); \
STEP(0x8 + shift, input); STEP(0x9 + shift, input); STEP(0xa + shift, input); STEP(0xb + shift, input); \
STEP(0xc + shift, input); STEP(0xd + shift, input); STEP(0xe + shift, input); STEP(0xf + shift, input);
STEP_16x( 0, v1);
STEP_16x(16, v2);
STEP_16x(32, v3);
STEP_16x(48, v4);
#undef STEP_16x
#undef STEP
v1 = r1;
v2 = r2;
v3 = r3;
v4 = r4;
}
void sort_inplace(uint32_t* array, size_t size) {
if (size == 0 && size == 1) {
return;
}
if (size <= 16) {
__m512i v1 = _mm512_loadu_si512(array);
switch (size) {
case 2: v1 = sort1xreg_tail<2>(v1); break;
case 3: v1 = sort1xreg_tail<3>(v1); break;
case 4: v1 = sort1xreg_tail<4>(v1); break;
case 5: v1 = sort1xreg_tail<5>(v1); break;
case 6: v1 = sort1xreg_tail<6>(v1); break;
case 7: v1 = sort1xreg_tail<7>(v1); break;
case 8: v1 = sort1xreg_tail<8>(v1); break;
case 9: v1 = sort1xreg_tail<9>(v1); break;
case 10: v1 = sort1xreg_tail<10>(v1); break;
case 11: v1 = sort1xreg_tail<11>(v1); break;
case 12: v1 = sort1xreg_tail<12>(v1); break;
case 13: v1 = sort1xreg_tail<13>(v1); break;
case 14: v1 = sort1xreg_tail<14>(v1); break;
case 15: v1 = sort1xreg_tail<15>(v1); break;
case 16: v1 = sort1xreg(v1); break;
}
_mm512_storeu_si512(array, v1);
return;
}
if (size <= 32) {
__m512i v1 = _mm512_loadu_si512(array);
__m512i v2 = _mm512_loadu_si512(array + 16);
switch (size) {
case 17: sort2xreg_tail<17>(v1, v2); break;
case 18: sort2xreg_tail<18>(v1, v2); break;
case 19: sort2xreg_tail<19>(v1, v2); break;
case 20: sort2xreg_tail<20>(v1, v2); break;
case 21: sort2xreg_tail<21>(v1, v2); break;
case 22: sort2xreg_tail<22>(v1, v2); break;
case 23: sort2xreg_tail<23>(v1, v2); break;
case 24: sort2xreg_tail<24>(v1, v2); break;
case 25: sort2xreg_tail<25>(v1, v2); break;
case 26: sort2xreg_tail<26>(v1, v2); break;
case 27: sort2xreg_tail<27>(v1, v2); break;
case 28: sort2xreg_tail<28>(v1, v2); break;
case 29: sort2xreg_tail<29>(v1, v2); break;
case 30: sort2xreg_tail<30>(v1, v2); break;
case 31: sort2xreg_tail<31>(v1, v2); break;
case 32: sort2xreg(v1, v2); break;
}
_mm512_storeu_si512(array, v1);
_mm512_storeu_si512(array + 16, v2);
return;
}
if (size <= 48) {
__m512i v1 = _mm512_loadu_si512(array);
__m512i v2 = _mm512_loadu_si512(array + 16);
__m512i v3 = _mm512_loadu_si512(array + 32);
switch (size) {
case 33: sort3xreg_tail<33>(v1, v2, v3); break;
case 34: sort3xreg_tail<34>(v1, v2, v3); break;
case 35: sort3xreg_tail<35>(v1, v2, v3); break;
case 36: sort3xreg_tail<36>(v1, v2, v3); break;
case 37: sort3xreg_tail<37>(v1, v2, v3); break;
case 38: sort3xreg_tail<38>(v1, v2, v3); break;
case 39: sort3xreg_tail<39>(v1, v2, v3); break;
case 40: sort3xreg_tail<40>(v1, v2, v3); break;
case 41: sort3xreg_tail<41>(v1, v2, v3); break;
case 42: sort3xreg_tail<42>(v1, v2, v3); break;
case 43: sort3xreg_tail<43>(v1, v2, v3); break;
case 44: sort3xreg_tail<44>(v1, v2, v3); break;
case 45: sort3xreg_tail<45>(v1, v2, v3); break;
case 46: sort3xreg_tail<46>(v1, v2, v3); break;
case 47: sort3xreg_tail<47>(v1, v2, v3); break;
case 48: sort3xreg(v1, v2, v3); break;
}
_mm512_storeu_si512(array, v1);
_mm512_storeu_si512(array + 16, v2);
_mm512_storeu_si512(array + 32, v3);
return;
}
if (size <= 64) {
__m512i v1 = _mm512_loadu_si512(array);
__m512i v2 = _mm512_loadu_si512(array + 16);
__m512i v3 = _mm512_loadu_si512(array + 32);
__m512i v4 = _mm512_loadu_si512(array + 48);
switch (size) {
case 49: sort4xreg_tail<49>(v1, v2, v3, v4); break;
case 50: sort4xreg_tail<50>(v1, v2, v3, v4); break;
case 51: sort4xreg_tail<51>(v1, v2, v3, v4); break;
case 52: sort4xreg_tail<52>(v1, v2, v3, v4); break;
case 53: sort4xreg_tail<53>(v1, v2, v3, v4); break;
case 54: sort4xreg_tail<54>(v1, v2, v3, v4); break;
case 55: sort4xreg_tail<55>(v1, v2, v3, v4); break;
case 56: sort4xreg_tail<56>(v1, v2, v3, v4); break;
case 57: sort4xreg_tail<57>(v1, v2, v3, v4); break;
case 58: sort4xreg_tail<58>(v1, v2, v3, v4); break;
case 59: sort4xreg_tail<59>(v1, v2, v3, v4); break;
case 60: sort4xreg_tail<60>(v1, v2, v3, v4); break;
case 61: sort4xreg_tail<61>(v1, v2, v3, v4); break;
case 62: sort4xreg_tail<62>(v1, v2, v3, v4); break;
case 63: sort4xreg_tail<63>(v1, v2, v3, v4); break;
case 64: sort4xreg(v1, v2, v3, v4); break;
}
_mm512_storeu_si512(array, v1);
_mm512_storeu_si512(array + 16, v2);
_mm512_storeu_si512(array + 32, v3);
_mm512_storeu_si512(array + 48, v4);
return;
}
}
} // namespace avx512sort
| bsd-2-clause |
astrofrog/sedfitter | sedfitter/timer.py | 1041 | from __future__ import print_function, division
import time
import numpy as np
class Timer(object):
def __init__(self):
self.time1 = time.time()
self.n = 0
self.step = 1
print(" # Sources CPU time (sec) Sources/sec ")
print(" ----------------------------------------------")
def display(self, force=False):
self.n += 1
if np.mod(self.n, self.step) == 0:
self.time2 = time.time()
if self.time2 - self.time1 < 1.:
self.step *= 10
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
elif force:
self.time2 = time.time()
if self.time2 == self.time1:
print(" %7i %10.1f -------" % (self.n, self.time2 - self.time1))
else:
print(" %7i %10.1f %7.2f" % (self.n, self.time2 - self.time1, self.n / (self.time2 - self.time1)))
| bsd-2-clause |
depp/sglib | script/sglib/version.py | 2789 | # Copyright 2013-2014 Dietrich Epp.
# This file is part of SGLib. SGLib is licensed under the terms of the
# 2-clause BSD license. For more information, see LICENSE.txt.
from d3build.shell import get_output
from d3build.error import format_block
from d3build.generatedsource import GeneratedSource, NOTICE
import collections
import sys
import re
def warn(*msg):
print(*msg, file=sys.stderr)
# 'number' is a triplet (x, y, z)
# 'desc' is the Git description 'vX.Y.Z-1-gSHA1'
# 'sha1' is the Git SHA-1
Version = collections.namedtuple('Version', 'number desc sha1')
VERSION_STRING = re.compile(
r'v(\d+)(?:\.(\d+)(?:\.(\d+))?)?(?:-\d+(?:-.*)?)?')
def get_info(git, path):
"""Get the of the given Git repository."""
stdout, stderr, retcode = get_output(
[git, 'rev-parse', 'HEAD'], cwd=path)
if retcode:
warn(
'could not get SHA-1 for repository: {}'.format(path),
format_block(stderr))
return Version((0, 0, 0), 'v0.0.0', '<none>')
sha1 = stdout.strip()
stdout, stderr, retcode = get_output(
['git', 'describe'], cwd=path)
if retcode:
warn(
'could not get version number for repository: {}'.format(path),
format_block(stderr))
stdout, stderr, retcode = get_output(
['git', 'rev-list', 'HEAD'], cwd=path)
if retcode:
warn(
'could not get list of git revisions for repository: {}'
.format(path), format_block(stderr))
version = 'v0.0.0'
else:
nrev = len(stdout.splitlines())
version = 'v0.0.0-{}-g{}'.format(nrev, sha1[:7])
else:
version = stdout.strip()
m = VERSION_STRING.match(version)
if not m:
warn('could not parse version number: {}'.format(version))
number = 0, 0, 0
else:
number = tuple(int(x) if x is not None else 0 for x in m.groups())
return Version(number, version, sha1)
class VersionInfo(GeneratedSource):
__slots__ = ['_target', 'app_path', 'sglib_path', 'git']
def __init__(self, target, app_path, sglib_path, git):
self._target = target
self.app_path = app_path
self.sglib_path = sglib_path
self.git = git
@property
def is_regenerated_always(self):
return True
@property
def target(self):
return self._target
def write(self, fp):
fp.write('/* {} */\n'.format(NOTICE))
for name, path in (('APP', self.app_path), ('SG', self.sglib_path)):
version = get_info(self.git, path)
fp.write(
'const char SG_{}_VERSION[] = "{}";\n'
'const char SG_{}_COMMIT[] = "{}";\n'
.format(name, version.desc, name, version.sha1))
| bsd-2-clause |
ZickZakk/HTWK_SmartDriving_2015 | HTWK_SD_FILTER/SD_SimpleDrive/SimpleDrive.cpp | 52854 | /**
* Copyright (c) 2014-2015, HTWK SmartDriving
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* AUTHORS: Silvio Feig, Denny Hecht, Andreas Kluge, Lars Kollmann, Eike Florian Petersen, Artem Pokas
*
*/
/**
* @filename
* @copyright (c) Copyright 2014 SD-Team HTWK
* @author dhecht
* @details
*/
#include "stdafx.h"
#include "SimpleDrive.h"
ADTF_FILTER_PLUGIN(FILTER_NAME, OID_NEW_LANE_DETECTION, SimpleDrive);
SimpleDrive::SimpleDrive(const char *__info) : cFilter(__info)
{
this->isFirstFrame = true;
this->xPositionBefore = 560;
this->yPositionBefore = 310;
this->previousSteerAngle = 0;
this->steerAngle = 0;
this->isDriveActive = false;
this->isTurnStraightActive = false;
this->isTurnStraightWaitActive = false;
this->isDriveStraightActive = false;
this->initDriveStraight = true;
// stop line
this->standsOnStopLine = false;
this->isDriveToStopLineActivated = false;
this->neededDistance = 50000;
this->isStopLineDetected = false;
this->photoShot = false;
this->isEmergencyBrakeActive = false;
this->lastWheelRotation = 0;
this->wheelRotationCounter = 0;
// depthImage
this->searchLeftAccess = false;
this->isLeftAccesFound = false;
// brake
this->isHardBrake = true;
// turn right
this->isTurnRightActive = false;
this->isStep1Active = false;
this->isStep2Active = false;
this->ticksToFinishStep1 = 0;
this->ticksToFinishStep2 = 0;
// turn left
this->isTurnLeftActive = false;
this->ticksToStopAtCrossroad = 0;
this->isTurnLeftStep1Active = false;
this->isTurnLeftStep2Active = false;
this->isTurnLeftStep3Active = false;
this->isTurnLeftStep4Active = false;
this->isTurnLeftTimeSet = false;
// RPM
this->initRpm = true;
this->currentTime = -1;
this->previousTime = -1;
// interfaces
this->crossroadDetector.reset(new CrossRoadDetector());
this->driveAlgorithm.reset(new DriveAlgorithm());
this->obstacleDetection.reset(new Vdar());
this->decisionEvaluator.reset(new DecisionEvaluator());
this->emergencySystem.reset(new EmergencySystem());
this->parkGap.reset(new ParkGap());
loadReferenceBackground();
// park gap
this->searchParkGap = false;
this->isParkGapFound = false;
// properties
initProperties();
time1 = -1;
}
tVoid SimpleDrive::loadReferenceBackground(void)
{
this->obstacleDetection->setReferenceBackground(imread("/home/odroid/Desktop/REPOS/AADC/main/HTWK_SD_FILTER/SD_SimpleDrive/depth.png"));
}
tResult SimpleDrive::initProperties()
{
// smooth curve properties
this->smoothCurveValue = 1;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_SMOOTH_CURVE_VALUE, this->smoothCurveValue));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_SMOOTH_CURVE_VALUE NSSUBPROP_MINIMUM, 1));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_SMOOTH_CURVE_VALUE NSSUBPROP_MAXIMUM, 255));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_SMOOTH_CURVE_VALUE NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_SMOOTH_CURVE_VALUE NSSUBPROP_ISCHANGEABLE, tTrue));
this->driveAlgorithm->setSmoothCurveValue(this->smoothCurveValue);
// lane assist properties
MIN_RIGHT_LANE_POSITION = 540;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MIN_RIGHT_LANE_POSITION, MIN_RIGHT_LANE_POSITION));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MIN_RIGHT_LANE_POSITION NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MIN_RIGHT_LANE_POSITION NSSUBPROP_MAXIMUM, 639));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_MIN_RIGHT_LANE_POSITION NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_MIN_RIGHT_LANE_POSITION NSSUBPROP_ISCHANGEABLE, tTrue));
this->driveAlgorithm->setMinRightLanePosition(MIN_RIGHT_LANE_POSITION);
MAX_RIGHT_LANE_POSITION = 545;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MAX_RIGHT_LANE_POSITION, MAX_RIGHT_LANE_POSITION));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MAX_RIGHT_LANE_POSITION NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MAX_RIGHT_LANE_POSITION NSSUBPROP_MAXIMUM, 639));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_MAX_RIGHT_LANE_POSITION NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_MAX_RIGHT_LANE_POSITION NSSUBPROP_ISCHANGEABLE, tTrue));
this->driveAlgorithm->setMaxRightLanePosition(MAX_RIGHT_LANE_POSITION);
MIN_LEFT_LANE_POSITION = 305;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MIN_LEFT_LANE_POSITION, MIN_LEFT_LANE_POSITION));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MIN_LEFT_LANE_POSITION NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MIN_LEFT_LANE_POSITION NSSUBPROP_MAXIMUM, 479));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_MIN_LEFT_LANE_POSITION NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_MIN_LEFT_LANE_POSITION NSSUBPROP_ISCHANGEABLE, tTrue));
this->driveAlgorithm->setMinLeftLanePosition(MIN_LEFT_LANE_POSITION);
MAX_LEFT_LANE_POSITION = 310;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MAX_LEFT_LANE_POSITION, MAX_LEFT_LANE_POSITION));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MAX_LEFT_LANE_POSITION NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_MAX_LEFT_LANE_POSITION NSSUBPROP_MAXIMUM, 479));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_MAX_LEFT_LANE_POSITION NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_MAX_LEFT_LANE_POSITION NSSUBPROP_ISCHANGEABLE, tTrue));
this->driveAlgorithm->setMaxLeftLanePosition(MAX_LEFT_LANE_POSITION);
// debug property
this->isDebugActive = false;
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_DRIVE_ALGORITHM, this->isDebugActive));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_DRIVE_ALGORITHM NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_DRIVE_ALGORITHM NSSUBPROP_ISCHANGEABLE, tTrue));
this->driveAlgorithm->setIsDebugActive(this->isDebugActive);
// drive, break speed properties
this->driveSpeed = 30.0;
RETURN_IF_FAILED(SetPropertyFloat(PROP_NAME_DRIVE_SPEED, static_cast<tFloat64>(this->driveSpeed)));
RETURN_IF_FAILED(SetPropertyFloat(PROP_NAME_DRIVE_SPEED NSSUBPROP_MINIMUM, 0.0));
RETURN_IF_FAILED(SetPropertyFloat(PROP_NAME_DRIVE_SPEED NSSUBPROP_MAXIMUM, 100.0));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DRIVE_SPEED NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DRIVE_SPEED NSSUBPROP_ISCHANGEABLE, tTrue));
this->breakSpeed = -15.0;
RETURN_IF_FAILED(SetPropertyFloat(PROP_NAME_BREAK_SPEED, static_cast<tFloat64>(this->breakSpeed)));
RETURN_IF_FAILED(SetPropertyFloat(PROP_NAME_BREAK_SPEED NSSUBPROP_MINIMUM, -20.0));
RETURN_IF_FAILED(SetPropertyFloat(PROP_NAME_BREAK_SPEED NSSUBPROP_MAXIMUM, 0.0));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_BREAK_SPEED NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_BREAK_SPEED NSSUBPROP_ISCHANGEABLE, tTrue));
this->ticksToStopLine = 5;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TICKS_TO_STOP_LINE, this->ticksToStopLine));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TICKS_TO_STOP_LINE NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TICKS_TO_STOP_LINE NSSUBPROP_MAXIMUM, 20));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TICKS_TO_STOP_LINE NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TICKS_TO_STOP_LINE NSSUBPROP_ISCHANGEABLE, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_EMERGENCY_SYSTEM, false));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_EMERGENCY_SYSTEM NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_EMERGENCY_SYSTEM NSSUBPROP_ISCHANGEABLE, tTrue));
this->emergencySystem->setIsDebugActive(false);
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_IR_FRONT_CENTER, 8));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_IR_FRONT_CENTER NSSUBPROP_MINIMUM, 8));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_IR_FRONT_CENTER NSSUBPROP_MAXIMUM, 30));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_IR_FRONT_CENTER NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_IR_FRONT_CENTER NSSUBPROP_ISCHANGEABLE, tTrue));
this->emergencySystem->setIrDistanceFront(8);
// turn right
this->turnRightTicksStraight = 5;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_TICKS_STRAIGHT, this->turnRightTicksStraight));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_TICKS_STRAIGHT NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_TICKS_STRAIGHT NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_RIGHT_TICKS_STRAIGHT NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_RIGHT_TICKS_STRAIGHT NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnRightSteeringAngle = 2;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_STEERING_ANGLE, this->turnRightSteeringAngle));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_STEERING_ANGLE NSSUBPROP_MINIMUM, -30));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_STEERING_ANGLE NSSUBPROP_MAXIMUM, 30));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_RIGHT_STEERING_ANGLE NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_RIGHT_STEERING_ANGLE NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnRightTicksRight = 20;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_TICKS_RIGHT, this->turnRightTicksRight));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_TICKS_RIGHT NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_RIGHT_TICKS_RIGHT NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_RIGHT_TICKS_RIGHT NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_RIGHT_TICKS_RIGHT NSSUBPROP_ISCHANGEABLE, tTrue));
// turn left
this->turnLeftMeasuringError = 20;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_ERROR, this->turnLeftMeasuringError));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_ERROR NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_ERROR NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_ERROR NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_ERROR NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnLeftWait = 5000000;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_ERROR, this->turnLeftMeasuringError));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_ERROR NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_ERROR NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_ERROR NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_ERROR NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnLeftWait = 5000000;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_WAIT, this->turnLeftWait));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_WAIT NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_WAIT NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_WAIT NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_WAIT NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnLeftTicksStraight = 2;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_TICKS_STRAIGHT, this->turnLeftTicksStraight));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_TICKS_STRAIGHT NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_TICKS_STRAIGHT NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_TICKS_STRAIGHT NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_TICKS_STRAIGHT NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnLeftSteeringAngle = -25;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_STEERING_ANGLE, this->turnLeftSteeringAngle));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_STEERING_ANGLE NSSUBPROP_MINIMUM, -30));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_STEERING_ANGLE NSSUBPROP_MAXIMUM, 30));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_STEERING_ANGLE NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_STEERING_ANGLE NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnLeftTicksLeft = 20;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_TICKS_LEFT, this->turnLeftTicksLeft));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_TICKS_LEFT NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_TICKS_LEFT NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_TICKS_LEFT NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_TICKS_LEFT NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnLeftStopTicksStraight = 5;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_STOP_TICKS_STRAIGHT, this->turnLeftStopTicksStraight));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_STOP_TICKS_STRAIGHT NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_TURN_LEFT_STOP_TICKS_STRAIGHT NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_STOP_TICKS_STRAIGHT NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_TURN_LEFT_STOP_TICKS_STRAIGHT NSSUBPROP_ISCHANGEABLE, tTrue));
this->turnStraightTicks = 280;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_CROSSROAD_STRAIGHT_LANE_POSITION, this->turnStraightTicks));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_CROSSROAD_STRAIGHT_LANE_POSITION NSSUBPROP_MINIMUM, 200));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_CROSSROAD_STRAIGHT_LANE_POSITION NSSUBPROP_MAXIMUM, 639));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_CROSSROAD_STRAIGHT_LANE_POSITION NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_CROSSROAD_STRAIGHT_LANE_POSITION NSSUBPROP_ISCHANGEABLE, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_PARK_GAP, false));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_PARK_GAP NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_DEBUG_PARK_GAP NSSUBPROP_ISCHANGEABLE, tTrue));
this->parkGap->setIsDebugActive(false);
this->crossDriveStraightDistance = 30;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_CPDRIVESTRAIGHTDISTANCE, this->crossDriveStraightDistance));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_CPDRIVESTRAIGHTDISTANCE NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_CPDRIVESTRAIGHTDISTANCE NSSUBPROP_MAXIMUM, 100));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_CPDRIVESTRAIGHTDISTANCE NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_CPDRIVESTRAIGHTDISTANCE NSSUBPROP_ISCHANGEABLE, tTrue));
this->parallelDriveStraightDistance = 9500000;
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_PPDRIVESTRAIGHTBEFORGOINGAP, this->parallelDriveStraightDistance));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_PPDRIVESTRAIGHTBEFORGOINGAP NSSUBPROP_MINIMUM, 0));
RETURN_IF_FAILED(SetPropertyInt(PROP_NAME_PPDRIVESTRAIGHTBEFORGOINGAP NSSUBPROP_MAXIMUM, 1000000000));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_PPDRIVESTRAIGHTBEFORGOINGAP NSSUBPROP_REQUIRED, tTrue));
RETURN_IF_FAILED(SetPropertyBool(PROP_NAME_PPDRIVESTRAIGHTBEFORGOINGAP NSSUBPROP_ISCHANGEABLE, tTrue));
RETURN_NOERROR;
}
SimpleDrive::~SimpleDrive(void)
{
}
tResult SimpleDrive::Init(tInitStage eStage, __exception)
{
RETURN_IF_FAILED(cFilter::Init(eStage, __exception_ptr));
if (eStage == StageFirst)
{
RETURN_IF_FAILED(_runtime->GetObject(OID_ADTF_MEDIA_DESCRIPTION_MANAGER, IID_ADTF_MEDIA_DESCRIPTION_MANAGER, (tVoid**) &this->descriptionManager, __exception_ptr));
cObjectPtr<IMediaType> wheelTickMediaType;
cObjectPtr<IMediaType> rpmMediaType;
cObjectPtr<IMediaType> irMediaType;
cObjectPtr<IMediaType> irRightMediaType;
cObjectPtr<IMediaType> steeringAngleMediaType;
cObjectPtr<IMediaType> accelerationMediaType;
cObjectPtr<IMediaType> maneuverFinishedMediaType;
cObjectPtr<IMediaType> decisionMediaType;
cObjectPtr<IMediaType> lightMediaType;
RETURN_IF_FAILED(initMediaType("tSignalValue", wheelTickMediaType, this->coderDescriptionWheelTicks));
RETURN_IF_FAILED(initMediaType("tSignalValue", rpmMediaType, this->coderDescriptionRpm));
RETURN_IF_FAILED(initMediaType("tSignalValue", irMediaType, this->coderDescriptionIr));
RETURN_IF_FAILED(initMediaType("tSignalValue", irRightMediaType, this->coderDescriptionIrRight));
RETURN_IF_FAILED(initMediaType("tSignalValue", steeringAngleMediaType, this->coderDescriptionSteeringAngle));
RETURN_IF_FAILED(initMediaType("tSignalValue", accelerationMediaType, this->coderDescriptionAcceleration));
RETURN_IF_FAILED(initMediaType("tSteeringAngleData", maneuverFinishedMediaType, this->coderDescriptionManeuverFinished));
RETURN_IF_FAILED(initMediaType("tSteeringAngleData", decisionMediaType, this->coderDescriptionDecision));
RETURN_IF_FAILED(initMediaType("tSteeringAngleData", lightMediaType, this->coderDescriptionLight));
// input pins
RETURN_IF_FAILED(createVideoInputPin("rgbVideo", this->ipmVideoInput));
RETURN_IF_FAILED(createVideoInputPin("depthVideo", this->depthImage));
RETURN_IF_FAILED(createInputPin("mergedWheelRotation", this->mergedWheelRotationPin, wheelTickMediaType));
RETURN_IF_FAILED(createInputPin("RPM", this->rpmPin, rpmMediaType));
RETURN_IF_FAILED(createInputPin("decision_in", this->decisionPin, decisionMediaType));
RETURN_IF_FAILED(createInputPin("irFrontCenter", this->irFrontCenterPin, irMediaType));
RETURN_IF_FAILED(createInputPin("irRight", this->irRightPin, irRightMediaType));
// output pins
RETURN_IF_FAILED(createOutputPin("steerAngleOut", this->steerAngleOutput, steeringAngleMediaType));
RETURN_IF_FAILED(createOutputPin("acceleration", this->accelerationPin, accelerationMediaType));
RETURN_IF_FAILED(createOutputPin("Maneuver_Finished", this->maneuverFinishedPin, maneuverFinishedMediaType));
RETURN_IF_FAILED(createOutputPin("decision_out", this->decisionOutputPin, decisionMediaType));
RETURN_IF_FAILED(createOutputPin("light", this->lightPin, lightMediaType));
}
else if (eStage == StageGraphReady)
{
cObjectPtr<IMediaSerializer> serializer;
RETURN_IF_FAILED(this->coderDescriptionManeuverFinished->GetMediaSampleSerializer(&serializer));
this->ddlSizeUI16 = serializer->GetDeserializedSize();
RETURN_IF_FAILED(this->coderDescriptionAcceleration->GetMediaSampleSerializer(&serializer));
this->ddlSizeF32 = serializer->GetDeserializedSize();
}
RETURN_NOERROR;
}
tResult SimpleDrive::initMediaType(const char *mediaTypeDescriptionName, cObjectPtr<IMediaType> &mediaType, cObjectPtr<IMediaTypeDescription> &coderDescription)
{
tChar const *descriptionSignalValue = this->descriptionManager->GetMediaDescription(mediaTypeDescriptionName);
RETURN_IF_POINTER_NULL(descriptionSignalValue);
mediaType = new cMediaType(0, 0, 0, mediaTypeDescriptionName, descriptionSignalValue, IMediaDescription::MDF_DDL_DEFAULT_VERSION);
RETURN_IF_FAILED(mediaType->GetInterface(IID_ADTF_MEDIA_TYPE_DESCRIPTION, (tVoid**) &coderDescription));
RETURN_NOERROR;
}
tResult SimpleDrive::createVideoInputPin(const tChar *pinName, cVideoPin &pin)
{
pin.Create(pinName, IPin::PD_Input, static_cast<IPinEventSink*>(this));
RETURN_IF_FAILED(RegisterPin(&pin));
RETURN_NOERROR;
}
tResult SimpleDrive::createInputPin(const char *pinName, cInputPin &pin, cObjectPtr<IMediaType> &typeSignal)
{
RETURN_IF_FAILED(pin.Create(pinName, typeSignal, static_cast<IPinEventSink*> (this)));
RETURN_IF_FAILED(RegisterPin(&pin));
RETURN_NOERROR;
}
tResult SimpleDrive::createOutputPin(const char *pinName, cOutputPin &pin, cObjectPtr<IMediaType> &typeSignal)
{
RETURN_IF_FAILED(pin.Create(pinName, typeSignal));
RETURN_IF_FAILED(RegisterPin(&pin));
RETURN_NOERROR;
}
tResult SimpleDrive::Start(__exception)
{
RETURN_IF_FAILED(cFilter::Start(__exception_ptr));
RETURN_NOERROR;
}
tResult SimpleDrive::Stop(__exception)
{
RETURN_IF_FAILED(cFilter::Stop(__exception_ptr));
RETURN_NOERROR;
}
tResult SimpleDrive::Shutdown(tInitStage eStage, __exception)
{
RETURN_IF_FAILED(cFilter::Shutdown(eStage, __exception_ptr));
RETURN_NOERROR;
}
tResult SimpleDrive::OnPinEvent(IPin *source, tInt eventCore, tInt param1, tInt param2, IMediaSample *mediaSample)
{
RETURN_IF_POINTER_NULL(source);
RETURN_IF_POINTER_NULL(mediaSample);
if (eventCore == IPinEventSink::PE_MediaSampleReceived)
{
if (source == &this->depthImage)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(processDepthImage(mediaSample), "cant read out depth image");
}
else if (source == &this->irRightPin)
{
if (this->searchParkGap)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(processSearchParkGap(), "cant process search park gap");
}
}
else if (source == &this->ipmVideoInput)
{
if (this->isFirstFrame)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(initVideoStream(), "Cant init video stream");
this->isFirstFrame = false;
}
else
{
if (this->emergencySystem->isObstacleFrontCenter(this->irFrontValue) && this->isDriveActive)
{
// LOG_WARNING("Obstacle detected");
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitStop(this->breakSpeed), "Cant stop the car");
this->isEmergencyBrakeActive = true;
}
else
{
if (this->isDriveActive && this->isEmergencyBrakeActive)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitDrive(this->driveSpeed), "Cant drive");
this->isEmergencyBrakeActive = false;
}
RETURN_IF_FAILED_AND_LOG_ERROR_STR(processImage(mediaSample), "Error in image processing");
}
}
}
else if (source == &this->mergedWheelRotationPin)
{
processWheelTicks(mediaSample);
}
else if (source == &this->decisionPin)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(getDecision(mediaSample, this->currentDecision, this->prevDecision, this->ticksToCrossroad), "Cant get Decision from RoadSignDetection");
if (this->prevDecision == DECISION_PULL_OUT_LEFT || this->prevDecision == DECISION_PULL_OUT_RIGHT)
{
this->steerAngle = 0;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitSteeringAngle(this->steerAngle), "Cant init steer angle");
}
if (this->decisionEvaluator->isDecisionParking(this->currentDecision))
{
// leite den Befehl weiter an den MakroPlayer
// bzw. suche nach einer Parklücke und leite dann den Befehl weiter
/*this->isDriveActive = false;
LOG_WARNING("Stop because macro player");
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitStop(this->breakSpeed), "cant stop the car");
LOG_INFO("Sending parking decision to macro_player");
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitDecision(this->currentDecision), "cant send decision to macro player");*/
this->searchParkGap = true;
this->parkGap->setDecision(this->currentDecision);
}
else if (this->decisionEvaluator->isDecisionPullOut(this->currentDecision))
{
this->isDriveActive = false;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitStop(this->breakSpeed), "cant stop the car");
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitDecision(this->currentDecision), "cant send decision to macro player");
}
else if (this->currentDecision == DECISION_STOP)
{
this->isDriveActive = false;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitStop(this->breakSpeed), "cant stop the car");
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitDecision(DECISION_STOP), "cant send stop to macro_player");
}
else if (this->currentDecision == DECISION_DRIVE)
{
this->isDriveActive = true;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitDrive(this->driveSpeed), "cant start the car");
// init steering angle
this->steerAngle = 0;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitSteeringAngle(this->steerAngle), "Cant init steer angle");
}
}
else if (source == &this->irFrontCenterPin)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(getIrValue(mediaSample, this->irFrontValue), "Cant read out ir front center value");
}
else if (source == &this->rpmPin)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(getRpm(mediaSample, this->currentRPM), "Cant get RPM");
}
}
RETURN_NOERROR;
}
tResult SimpleDrive::initVideoStream(void)
{
//Read media type
cObjectPtr<IMediaType> type;
RETURN_IF_FAILED(this->ipmVideoInput.GetMediaType(&type));
cObjectPtr<IMediaTypeVideo> typeVideo;
RETURN_IF_FAILED(type->GetInterface(IID_ADTF_MEDIA_TYPE_VIDEO, (tVoid**)(&typeVideo)));
const tBitmapFormat *format = typeVideo->GetFormat();
RETURN_IF_POINTER_NULL(format);
//Set media type
setBitmapFormat(format);
RETURN_NOERROR;
}
tResult SimpleDrive::processSearchParkGap()
{
if (!this->isParkGapFound)
{
if (this->parkGap->searchParkingGap(this->irFrontValue, this->wheelRotation))
{
this->isParkGapFound = true;
this->distanceToFinishCrossParking = this->crossDriveStraightDistance + (this->wheelRotation * 4);
this->timeToFinishParallelParking = cHighResTimer::GetTime() + this->parallelDriveStraightDistance;
}
}
else
{
if (this->currentDecision == DECISION_CROSS_PARKING)
{
static tInt tmpDistance;
tmpDistance = this->distanceToFinishCrossParking - (this->wheelRotation * 4);
if (tmpDistance <= 0)
{
this->searchParkGap = false;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitStop(this->breakSpeed), "cant stop the car");
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitDecision(this->currentDecision), "cant send decision to macro player");
this->isDriveActive = false;
this->isParkGapFound = false;
}
}
else if (this->currentDecision == DECISION_PARALLEL_PARKING)
{
if (cHighResTimer::GetTime() >= this->timeToFinishParallelParking)
{
this->searchParkGap = false;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitStop(this->breakSpeed), "cant stop the car");
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitDecision(this->currentDecision), "cant send decision to macro player");
this->isDriveActive = false;
this->isParkGapFound = false;
}
}
}
RETURN_NOERROR;
}
tVoid SimpleDrive::setBitmapFormat(const tBitmapFormat *format)
{
this->videoInputInfo.nBitsPerPixel = format->nBitsPerPixel;
this->videoInputInfo.nBytesPerLine = format->nBytesPerLine;
this->videoInputInfo.nPaletteSize = format->nPaletteSize;
this->videoInputInfo.nPixelFormat = format->nPixelFormat;
this->videoInputInfo.nHeight = format->nHeight;
this->videoInputInfo.nWidth = format->nWidth;
this->videoInputInfo.nSize = format->nSize;
}
tResult SimpleDrive::processImage(IMediaSample *mediaSample)
{
const tVoid *buffer;
if (isDriveActive && IS_OK(mediaSample->Lock(&buffer)))
{
//Receive the image
Mat image(Size(this->videoInputInfo.nWidth, this->videoInputInfo.nHeight), CV_8UC3, (char*) buffer);
Mat result = image.clone();
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaSample->Unlock(buffer), "Cant unlock image");
this->driveAlgorithm->prepareImage(result);
// Schritt 1
// x-Pixel der rechten Fahrspur bestimmen
static tInt xPosition;
static tInt yPosition;
static tBool isRightLaneDetected;
static tBool isLeftLaneDetected;
isRightLaneDetected = this->driveAlgorithm->getRightLanePosition(result, xPosition);
isLeftLaneDetected = this->driveAlgorithm->getLeftLanePosition(result, yPosition);
if (!this->isTurnLeftActive && this->decisionEvaluator->isDecisionDetectCrossroadAndTurnLeft(this->currentDecision))
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitLight(LIGHT_TURN_LEFT), "cant send turn left");
this->currentTurn = TURN_LEFT;
this->isTurnLeftActive = true;
this->isTurnLeftStep1Active = true;
this->initRpm = true;
this->ticksToStopAtCrossroad = this->wheelRotation + static_cast<tInt>(this->ticksToCrossroad) - this->turnLeftMeasuringError;
}
else if (this->decisionEvaluator->isDecisionDetectCrossroadAndTurnRight(this->currentDecision))
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitLight(LIGHT_TURN_RIGHT), "cant send turn right");
if (!isRightLaneDetected)
{
this->isDriveActive = false;
this->isTurnRightActive = true;
this->isStep1Active = true;
this->ticksToFinishStep1 = this->wheelRotation + this->turnRightTicksStraight;
this->initRpm = true;
}
}
// Geradeaus fahren
else if (!this->isTurnStraightActive && this->decisionEvaluator->isDecisionDetectCrossroadAndDriveStraight(this->currentDecision))
{
// 2 Varianten
if (isRightLaneDetected)
{
if (this->initDriveStraight)
{
this->ticksToStopAtCrossroad = this->wheelRotation + static_cast<tInt>(this->ticksToCrossroad) - this->turnLeftMeasuringError;
this->initDriveStraight = false;
}
else
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(driveStraight(), "failed to drive straight");
}
}
else
{
if (!this->isTurnStraightActive)
{
this->isTurnStraightActive = true;
this->turnStraightTicksToFinish = 10 + this->wheelRotation;
}
}
// 1 fahren bis rechts gasse kommt und dann 20 ticks oder
// 2 fahre so weit bis das Schild passiert is
}
/****** Steering ******/
if (!this->isTurnStraightActive)
{
if (!isRightLaneDetected)
{
if (isLeftLaneDetected)
{
this->driveAlgorithm->calculateSteeringAngle(LANE_LEFT, yPosition, this->steerAngle);
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitSteeringAngle(this->steerAngle), "Cant steer :( OMG!!!");
}
else
{
this->driveAlgorithm->getLeftLanePositionFromX(image, this->steerAngle);
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitSteeringAngle(this->steerAngle), "cant transmit steering angle");
}
}
else
{
// LOG_INFO(cString::Format("x-Position: %d", xPosition));
// Lenkwinkel berechnen
this->driveAlgorithm->calculateSteeringAngle(LANE_RIGHT, xPosition, this->steerAngle);
// Schritt 3
// Lenkwinkel senden
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitSteeringAngle(this->steerAngle), "Cant steer :( OMG!!!");
}
}
// Schritt 2
if (this->isTurnStraightActive || this->isTurnStraightWaitActive)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(driveStraightOverCrossroad(result), "Failed to drive over the crossroad");
}
else if (this->decisionEvaluator->isDecisionDetectCrossroadAndStop(this->currentDecision))
{
if (this->decisionEvaluator->isDecisionDetectCrossroadAndStopTurnLeft(this->currentDecision))
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitLight(LIGHT_TURN_LEFT), "cant send turn left");
}
else if (this->decisionEvaluator->isDecisionDetectCrossroadAndStopTurnRight(this->currentDecision))
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitLight(LIGHT_TURN_RIGHT), "cant send turn left");
}
if (!this->standsOnStopLine)
{
if (!this->isStopLineDetected)
{
if (this->crossroadDetector->searchStopLine(result))
{
this->neededDistance = this->wheelRotation + this->ticksToStopLine;
this->isDriveToStopLineActivated = true;
this->isStopLineDetected = true;
}
}
}
else
{
// turn left
if (this->decisionEvaluator->isDecisionDetectCrossroadAndStopTurnLeft(this->currentDecision))
{
this->isTurnLeftActive = true;
this->isTurnLeftStep2Active = true;
this->currentTurn = TURN_LEFT_STOP;
this->initRpm = true;
}
// turn right
else if (this->decisionEvaluator->isDecisionDetectCrossroadAndStopTurnRight(this->currentDecision))
{
this->isDriveActive = false;
this->isTurnRightActive = true;
this->initRpm = true;
this->isTurnRightWaitActive = true;
}
else
{
// drive straight!
// wir stehen an der Haltelinie
this->isTurnStraightWaitActive = true;
}
}
}
}
RETURN_NOERROR;
}
tResult SimpleDrive::processDepthImage(IMediaSample *mediaSample)
{
const tVoid *buffer;
if (this->searchLeftAccess && IS_OK(mediaSample->Lock(&buffer)))
{
//Receive the image
Mat image(Size(this->videoInputInfo.nWidth, this->videoInputInfo.nHeight), CV_16U, (char*) buffer);
Mat depthImage = image.clone();
RETURN_IF_FAILED(mediaSample->Unlock(buffer));
if (this->obstacleDetection->isObstacleInAreaInDepthImg(Rect(-100, 150, 30, -20), depthImage))
{
RETURN_IF_FAILED(transmitStop(this->breakSpeed));
this->searchLeftAccess = false;
}
}
RETURN_NOERROR;
}
tResult SimpleDrive::processWheelTicks(IMediaSample *mediaSample)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(getWheelTicks(mediaSample, this->wheelRotation), "Cant get distance");
if (isDriveToStopLineActivated)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(driveToStopLine(), "drive to stop line failed");
}
else if (this->isTurnRightActive)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(turnRight(), "turn right failed");
}
else if (this->isTurnLeftActive)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(turnLeft(), "cant turn left!");
}
else if (this->searchParkGap)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(processSearchParkGap(), "cant process search park gap");
}
RETURN_NOERROR;
}
tResult SimpleDrive::processDecisions(IMediaSample *mediaSample)
{
RETURN_NOERROR;
}
tResult SimpleDrive::processRPM(void)
{
static tInt counter;
static tFloat32 driveInc;
if (this->initRpm)
{
counter = 0;
driveInc = 0.0f;
this->initRpm = false;
}
else
{
counter++;
if (counter >= 50)
{
this->driveSpeed += driveInc;
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
counter = 0;
driveInc += 1.5f;
}
}
RETURN_NOERROR;
}
tVoid SimpleDrive::validateSteeringAngle(tInt &steeringAngle)
{
const static tInt MIN_STEER_ANGLE = -30;
const static tInt MAX_STEER_ANGLE = 30;
steeringAngle = (steeringAngle < MIN_STEER_ANGLE) ? MIN_STEER_ANGLE : steeringAngle;
steeringAngle = (steeringAngle > MAX_STEER_ANGLE) ? MAX_STEER_ANGLE : steeringAngle;
}
tResult SimpleDrive::driveToStopLine()
{
static tInt tmpDistance;
tmpDistance = this->neededDistance - this->wheelRotation;
if (tmpDistance <= 0)
{
RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitStop(this->breakSpeed), "Cant stop the car");
this->isDriveToStopLineActivated = false;
this->standsOnStopLine = true;
this->isStopLineDetected = false;
}
RETURN_NOERROR;
}
tResult SimpleDrive::turnRight()
{
if (this->isTurnRightWaitActive)
{
// wait
if (!this->isTurnLeftTimeSet)
{
this->turnLeftTime = cHighResTimer::GetTime() + this->turnLeftWait;
RETURN_IF_FAILED(transmitStop(this->breakSpeed));
this->isTurnLeftTimeSet = true;
}
else
{
if ((this->turnLeftTime - cHighResTimer::GetTime()) <= 0)
{
// time is over
this->isTurnLeftTimeSet = false;
this->isTurnRightWaitActive = false;
this->isStep1Active = true;
this->turnStraightTicksToFinish = this->turnStraightTicks + this->wheelRotation;
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
}
}
else if (this->isStep1Active)
{
static tInt tmpDistance1;
tmpDistance1 = this->ticksToFinishStep1 - this->wheelRotation;
if (this->currentRPM >= 0 && this->currentRPM <= 35)
{
RETURN_IF_FAILED(processRPM());
}
else if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
if (tmpDistance1 <= 0)
{
if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
this->isStep1Active = false;
this->isStep2Active = true;
this->ticksToFinishStep2 = this->wheelRotation + this->turnRightTicksRight;
this->steerAngle = this->turnRightSteeringAngle;
RETURN_IF_FAILED(transmitSteeringAngle(this->steerAngle));
}
}
else if (this->isStep2Active)
{
static tInt tmpDistance3;
tmpDistance3 = this->ticksToFinishStep2 - this->wheelRotation;
if (this->currentRPM >= 0 && this->currentRPM <= 35)
{
RETURN_IF_FAILED(processRPM());
}
else if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
if (tmpDistance3 <= 0)
{
if (this->driveSpeed > GetPropertyFloat(PROP_NAME_DRIVE_SPEED))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
this->isStep2Active = false;
this->isTurnRightActive = false;
this->steerAngle = 0;
RETURN_IF_FAILED(transmitSteeringAngle(this->steerAngle));
RETURN_IF_FAILED(transmitLight(LIGHT_TURN_DISABLED));
RETURN_IF_FAILED(transmitManeuverIsFinished());
this->isDriveActive = true;
}
}
RETURN_NOERROR;
}
tResult SimpleDrive::turnLeft()
{
static tInt tmpTicks;
tmpTicks = this->ticksToStopAtCrossroad - this->wheelRotation;
if (this->isTurnLeftStep1Active)
{
if (tmpTicks <= 0)
{
this->isDriveActive = false;
this->searchLeftAccess = false;
RETURN_IF_FAILED(transmitStop(this->breakSpeed));
this->isTurnLeftStep1Active = false;
this->isTurnLeftStep2Active = true;
}
}
else if (this->isTurnLeftStep2Active)
{
this->isDriveActive = false;
// wait
if (!this->isTurnLeftTimeSet)
{
this->turnLeftTime = cHighResTimer::GetTime() + this->turnLeftWait;
RETURN_IF_FAILED(transmitStop(this->breakSpeed));
this->isTurnLeftTimeSet = true;
}
else
{
if ((this->turnLeftTime - cHighResTimer::GetTime()) <= 0)
{
// time is over
this->isTurnLeftTimeSet = false;
this->isTurnLeftStep2Active = false;
this->isTurnLeftStep3Active = true;
if (this->currentTurn == TURN_LEFT)
{
this->turnLeftTicksToFinishDriveStraight = this->turnLeftTicksStraight + this->wheelRotation;
}
else if (this->currentTurn == TURN_LEFT_STOP)
{
this->turnLeftTicksToFinishDriveStraight = this->turnLeftStopTicksStraight + this->wheelRotation;
}
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
}
}
else if (this->isTurnLeftStep3Active)
{
if (this->currentRPM >= 0 && this->currentRPM <= 35)
{
RETURN_IF_FAILED(processRPM());
}
else if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
static tInt tmpDistance;
tmpDistance = this->turnLeftTicksToFinishDriveStraight - this->wheelRotation;
if (tmpDistance <= 0)
{
if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
this->isTurnLeftStep3Active = false;
this->isTurnLeftStep4Active = true;
this->turnLeftTicksToFinishDriveLeft = this->wheelRotation + this->turnLeftTicksLeft;
this->steerAngle = this->turnLeftSteeringAngle;
RETURN_IF_FAILED(transmitSteeringAngle(this->steerAngle));
}
}
else if (this->isTurnLeftStep4Active)
{
static tInt tmpDistance;
tmpDistance = this->turnLeftTicksToFinishDriveLeft - this->wheelRotation;
if (this->currentRPM >= 0 && this->currentRPM <= 35)
{
RETURN_IF_FAILED(processRPM());
}
else if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
if (tmpDistance <= 0)
{
this->isTurnLeftStep4Active = false;
this->isTurnLeftActive = false;
if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
this->steerAngle = 0;
RETURN_IF_FAILED(transmitSteeringAngle(this->steerAngle));
RETURN_IF_FAILED(transmitLight(LIGHT_TURN_DISABLED));
RETURN_IF_FAILED(transmitLight(LIGHT_TURN_DISABLED));
RETURN_IF_FAILED(transmitManeuverIsFinished());
this->isDriveActive = true;
}
}
RETURN_NOERROR;
}
tResult SimpleDrive::driveStraightOverCrossroad(const Mat &image)
{
if (this->isTurnStraightWaitActive)
{
// wait
if (!this->isTurnLeftTimeSet)
{
this->turnLeftTime = cHighResTimer::GetTime() + this->turnLeftWait;
RETURN_IF_FAILED(transmitStop(this->breakSpeed));
this->isTurnLeftTimeSet = true;
}
else
{
if ((this->turnLeftTime - cHighResTimer::GetTime()) <= 0)
{
this->turnStraightTicksToFinish = this->turnStraightTicks + this->wheelRotation;
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
this->isTurnStraightActive = true;
this->isTurnStraightWaitActive = false;
this->isTurnLeftTimeSet = false;
}
}
}
else if (this->isTurnStraightActive)
{
static tInt tmpDistance;
tmpDistance = this->turnStraightTicksToFinish - this->wheelRotation;
static tInt position;
this->driveAlgorithm->getCrossroadStraightLanePosition(image, position);
this->driveAlgorithm->calculateSteeringAngle(LANE_CROSSROAD, position, this->steerAngle);
RETURN_IF_FAILED(transmitSteeringAngle(this->steerAngle));
if (this->currentRPM >= 0 && this->currentRPM <= 35)
{
RETURN_IF_FAILED(processRPM());
}
else if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
if (tmpDistance <= 0)
{
if (this->driveSpeed > static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED)))
{
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
RETURN_IF_FAILED(transmitDrive(this->driveSpeed));
}
this->isTurnStraightActive = false;
RETURN_IF_FAILED(transmitManeuverIsFinished());
}
}
RETURN_NOERROR;
}
tResult SimpleDrive::driveStraight(void)
{
static tInt tmpDistance;
tmpDistance = this->ticksToStopAtCrossroad - this->wheelRotation;
if (tmpDistance <= 0)
{
RETURN_IF_FAILED(transmitManeuverIsFinished());
this->initDriveStraight = true;
}
RETURN_NOERROR;
}
tResult SimpleDrive::PropertyChanged(const char *name)
{
// drive, break speed properties
this->driveSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_DRIVE_SPEED));
this->breakSpeed = static_cast<tFloat32>(GetPropertyFloat(PROP_NAME_BREAK_SPEED));
this->ticksToStopLine = GetPropertyInt(PROP_NAME_TICKS_TO_STOP_LINE);
// smooth curve properties
this->smoothCurveValue = GetPropertyInt(PROP_NAME_SMOOTH_CURVE_VALUE);
this->driveAlgorithm->setSmoothCurveValue(this->smoothCurveValue);
// lane assist properties
MIN_RIGHT_LANE_POSITION = GetPropertyInt(PROP_NAME_MIN_RIGHT_LANE_POSITION);
this->driveAlgorithm->setMinRightLanePosition(GetPropertyInt(PROP_NAME_MIN_RIGHT_LANE_POSITION));
MAX_RIGHT_LANE_POSITION = GetPropertyInt(PROP_NAME_MAX_RIGHT_LANE_POSITION);
this->driveAlgorithm->setMaxRightLanePosition(GetPropertyInt(PROP_NAME_MAX_RIGHT_LANE_POSITION));
MIN_LEFT_LANE_POSITION = GetPropertyInt(PROP_NAME_MIN_LEFT_LANE_POSITION);
this->driveAlgorithm->setMinLeftLanePosition(GetPropertyInt(PROP_NAME_MIN_LEFT_LANE_POSITION));
MAX_LEFT_LANE_POSITION = GetPropertyInt(PROP_NAME_MAX_LEFT_LANE_POSITION);
this->driveAlgorithm->setMaxLeftLanePosition(GetPropertyInt(PROP_NAME_MAX_LEFT_LANE_POSITION));
// debug propertiy
this->isDebugActive = GetPropertyBool(PROP_NAME_DEBUG_DRIVE_ALGORITHM);
this->driveAlgorithm->setIsDebugActive(GetPropertyBool(PROP_NAME_DEBUG_DRIVE_ALGORITHM));
this->emergencySystem->setIsDebugActive(GetPropertyBool(PROP_NAME_DEBUG_EMERGENCY_SYSTEM));
this->emergencySystem->setIrDistanceFront(GetPropertyInt(PROP_NAME_IR_FRONT_CENTER));
// turn right
this->turnRightTicksStraight = GetPropertyInt(PROP_NAME_TURN_RIGHT_TICKS_STRAIGHT);
this->turnRightTicksRight = GetPropertyInt(PROP_NAME_TURN_RIGHT_TICKS_RIGHT);
this->turnRightSteeringAngle = GetPropertyInt(PROP_NAME_TURN_RIGHT_STEERING_ANGLE);
// turn left
this->turnLeftMeasuringError = GetPropertyInt(PROP_NAME_TURN_LEFT_ERROR);
this->turnLeftWait = GetPropertyInt(PROP_NAME_TURN_LEFT_WAIT);
this->turnLeftTicksStraight = GetPropertyInt(PROP_NAME_TURN_LEFT_TICKS_STRAIGHT);
this->turnLeftSteeringAngle = GetPropertyInt(PROP_NAME_TURN_LEFT_STEERING_ANGLE);
this->turnLeftTicksLeft = GetPropertyInt(PROP_NAME_TURN_LEFT_TICKS_LEFT);
this->turnLeftStopTicksStraight = GetPropertyInt(PROP_NAME_TURN_LEFT_STOP_TICKS_STRAIGHT);
this->turnStraightTicks = GetPropertyInt(PROP_NAME_CROSSROAD_STRAIGHT_LANE_POSITION);
this->driveAlgorithm->setCrossroadStraightLanePosition(GetPropertyInt(PROP_NAME_CROSSROAD_STRAIGHT_LANE_POSITION));
this->parkGap->setIsDebugActive(GetPropertyBool(PROP_NAME_DEBUG_PARK_GAP));
this->parallelDriveStraightDistance = GetPropertyInt(PROP_NAME_PPDRIVESTRAIGHTBEFORGOINGAP);
this->crossDriveStraightDistance = GetPropertyInt(PROP_NAME_CPDRIVESTRAIGHTDISTANCE);
RETURN_NOERROR;
}
// get values
tResult SimpleDrive::getSteeringAngle(IMediaSample *mediaSample, tInt &steeringAngle)
{
static tFloat32 tmpSteeringAngle;
RETURN_IF_FAILED(getF32Value(mediaSample, this->coderDescriptionSteeringAngle, tmpSteeringAngle));
steeringAngle = static_cast<tInt>(tmpSteeringAngle );
RETURN_NOERROR;
}
tResult SimpleDrive::getIrValue(IMediaSample *mediaSample, tInt &irValue)
{
static tFloat32 tmpIrValue;
RETURN_IF_FAILED(getF32Value(mediaSample, this->coderDescriptionIr, tmpIrValue));
irValue = static_cast<tInt>(tmpIrValue);
RETURN_NOERROR;
}
tResult SimpleDrive::getWheelTicks(IMediaSample *mediaSample, tInt &wheelTicks)
{
static tFloat32 tmpWheelTicks;
RETURN_IF_FAILED(getF32Value(mediaSample, this->coderDescriptionWheelTicks, tmpWheelTicks));
wheelTicks = static_cast<tInt>(tmpWheelTicks);
RETURN_NOERROR;
}
tResult SimpleDrive::getRpm(IMediaSample *mediaSample, tInt &rpm)
{
static tFloat32 tmpRpm;
RETURN_IF_FAILED(getF32Value(mediaSample, this->coderDescriptionRpm, tmpRpm));
rpm = static_cast<tInt>(tmpRpm);
RETURN_NOERROR;
}
tResult SimpleDrive::getF32Value(IMediaSample *mediaSample, cObjectPtr<IMediaTypeDescription> &mediaType, tFloat32 &value)
{
static tFloat32 tmpValue;
static tTimeStamp timeStamp;
cObjectPtr<IMediaCoder> coder;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Lock(mediaSample, &coder), "Get32 Failed to lock f32");
coder->Get("f32Value", (tVoid*) &tmpValue);
coder->Get("ui32ArduinoTimestamp", (tVoid*) &timeStamp);
value = tmpValue;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Unlock(coder), "Get32 Failed to unlock f32");
RETURN_NOERROR;
}
tResult SimpleDrive::getDecision(IMediaSample *mediaSample, Decision ¤tDecision, Decision &previousDecision, tUInt32 &ticksToCrossroad)
{
static tUInt16 tmpDecisionValue;
RETURN_IF_FAILED(getUI16Value(mediaSample, this->coderDescriptionDecision, tmpDecisionValue, ticksToCrossroad));
this->decisionEvaluator->getDecisionFromValue(tmpDecisionValue, currentDecision, previousDecision);
RETURN_NOERROR;
}
tResult SimpleDrive::getUI16Value(IMediaSample *mediaSample, cObjectPtr<IMediaTypeDescription> &mediaType, tUInt16 &value, tUInt32 &ticksToCrossroad)
{
static tUInt16 tmpValue;
cObjectPtr<IMediaCoder> coder;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Lock(mediaSample, &coder), "Get UI16 failed to unlock");
coder->Get("ui16Angle", (tVoid*) &tmpValue);
coder->Get("ui32ArduinoTimestamp", (tVoid*) &ticksToCrossroad);
value = tmpValue;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Unlock(coder), "Get UI16 failed to unlock");
RETURN_NOERROR;
}
// transmit values
tResult SimpleDrive::transmitSteeringAngle(tInt &steeringAngle)
{
validateSteeringAngle(steeringAngle);
if (this->previousSteerAngle != this->steerAngle)
{
RETURN_IF_FAILED(transmitF32Value(this->steerAngleOutput, this->coderDescriptionSteeringAngle, static_cast<tFloat32>(steeringAngle)));
}
this->previousSteerAngle = this->steerAngle;
RETURN_NOERROR;
}
tResult SimpleDrive::transmitDrive(const tFloat32 &driveSpeed)
{
RETURN_IF_FAILED(transmitLight(LIGHT_HEAD));
RETURN_IF_FAILED(transmitLight(LIGHT_BREAK_DISABLED));
if (this->prevDecision == DECISION_STOP)
{
RETURN_IF_FAILED(transmitLight(LIGHT_TURN_DISABLED));
}
RETURN_IF_FAILED(transmitF32Value(this->accelerationPin, this->coderDescriptionAcceleration, driveSpeed));
this->isHardBrake = true;
RETURN_NOERROR;
}
tResult SimpleDrive::transmitStop(const tFloat32 &stopSpeed)
{
RETURN_IF_FAILED(transmitLight(LIGHT_BREAK));
if (this->isHardBrake)
{
RETURN_IF_FAILED(transmitF32Value(this->accelerationPin, this->coderDescriptionAcceleration, stopSpeed));
this->isHardBrake = false;
}
else
{
RETURN_IF_FAILED(transmitF32Value(this->accelerationPin, this->coderDescriptionAcceleration, 0.0f));
}
RETURN_NOERROR;
}
tResult SimpleDrive::transmitF32Value(cOutputPin &pin, cObjectPtr<IMediaTypeDescription> &mediaType, const tFloat32 value)
{
cObjectPtr<IMediaSample> mediaSample;
RETURN_IF_FAILED(AllocMediaSample((tVoid**) &mediaSample));
RETURN_IF_FAILED(mediaSample->AllocBuffer(this->ddlSizeF32));
// write date to the media sample with the coder of the descriptor
cObjectPtr<IMediaCoder> coder;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->WriteLock(mediaSample, &coder), "Set F32 Failed to lock f32");
static tTimeStamp now;
now = _clock ? _clock->GetStreamTime() : cHighResTimer::GetTime();
coder->Set("f32Value", (tVoid*) &value);
coder->Set("ui32ArduinoTimestamp", (tVoid*) &now);
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Unlock(coder), "Set F32 Failed to lock f32");
// transmit media sample over output pin
RETURN_IF_FAILED(mediaSample->SetTime(now));
RETURN_IF_FAILED(pin.Transmit(mediaSample));
RETURN_NOERROR;
}
tResult SimpleDrive::transmitManeuverIsFinished(void)
{
static tUInt16 maneuverFinished;
maneuverFinished = MANEUVER_FINISHED;
this->standsOnStopLine = false;
RETURN_IF_FAILED(transmitUI16Value(this->maneuverFinishedPin, this->coderDescriptionManeuverFinished, maneuverFinished));
RETURN_NOERROR;
}
tResult SimpleDrive::transmitDecision(const Decision &decision)
{
static tUInt16 decisionValue;
decisionValue = decision;
RETURN_IF_FAILED(transmitUI16Value(this->decisionOutputPin, this->coderDescriptionDecision, decisionValue));
RETURN_NOERROR;
}
tResult SimpleDrive::transmitLight(const Light &light)
{
static tUInt16 lightValue;
lightValue = light;
RETURN_IF_FAILED(transmitUI16Value(this->lightPin, this->coderDescriptionLight, lightValue));
RETURN_NOERROR;
}
tResult SimpleDrive::transmitUI16Value(cOutputPin &pin, cObjectPtr<IMediaTypeDescription> &mediaType, const tUInt16 value)
{
cObjectPtr<IMediaSample> mediaSample;
RETURN_IF_FAILED(AllocMediaSample((tVoid**) &mediaSample));
RETURN_IF_FAILED(mediaSample->AllocBuffer(this->ddlSizeUI16));
cObjectPtr<IMediaCoder> coder;
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->WriteLock(mediaSample, &coder), "Set UI16 failed to unlock");
static tTimeStamp now;
now = _clock ? _clock->GetStreamTime() : cHighResTimer::GetTime();
coder->Set("ui16Angle", (tVoid*) &value);
coder->Set("ui32ArduinoTimestamp", (tVoid*) &now);
RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Unlock(coder), "Set UI16 failed to unlock");
RETURN_IF_FAILED(mediaSample->SetTime(now));
RETURN_IF_FAILED(pin.Transmit(mediaSample));
RETURN_NOERROR;
} | bsd-2-clause |
cgloger/inviwo | src/core/links/linkevaluator.cpp | 6849 | /*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2016 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/links/linkevaluator.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/links/linkconditions.h>
#include <inviwo/core/properties/propertyconvertermanager.h>
#include <inviwo/core/properties/propertyconverter.h>
#include <inviwo/core/util/raiiutils.h>
#include <inviwo/core/properties/property.h>
#include <inviwo/core/processors/processor.h>
#include <inviwo/core/network/processornetwork.h>
#include <inviwo/core/network/networklock.h>
#include <inviwo/core/properties/compositeproperty.h>
namespace inviwo {
LinkEvaluator::LinkEvaluator(ProcessorNetwork* network) : network_(network) {}
void LinkEvaluator::addLink(const PropertyLink& propertyLink) {
Property* src = propertyLink.getSource();
Property* dst = propertyLink.getDestination();
// Update ProcessorLink cache
Processor* p1 = src->getOwner()->getProcessor();
Processor* p2 = dst->getOwner()->getProcessor();
processorLinksCache_[ProcessorPair(p1, p2)].push_back(propertyLink);
// Update primary cache
auto& cachelist = propertyLinkPrimaryCache_[src];
util::push_back_unique(cachelist, dst);
if (cachelist.empty()) {
propertyLinkPrimaryCache_.erase(src);
}
propertyLinkSecondaryCache_.clear();
}
void LinkEvaluator::removeLink(const PropertyLink& propertyLink) {
Property* src = propertyLink.getSource();
Property* dst = propertyLink.getDestination();
// Update ProcessorLink cache
Processor* p1 = src->getOwner()->getProcessor();
Processor* p2 = dst->getOwner()->getProcessor();
auto it = processorLinksCache_.find(ProcessorPair(p1, p2));
if (it != processorLinksCache_.end()) {
util::erase_remove(it->second, propertyLink);
if (it->second.empty()) processorLinksCache_.erase(it);
}
// Update primary cache
auto& cachelist = propertyLinkPrimaryCache_[src];
util::erase_remove(cachelist, dst);
if (cachelist.empty()) {
propertyLinkPrimaryCache_.erase(src);
}
propertyLinkSecondaryCache_.clear();
}
std::vector<PropertyLink> LinkEvaluator::getLinksBetweenProcessors(Processor* p1, Processor* p2) {
auto it = processorLinksCache_.find(ProcessorPair(p1, p2));
if (it != processorLinksCache_.end()) {
return it->second;
} else {
return std::vector<PropertyLink>();
}
}
std::vector<LinkEvaluator::Link>& LinkEvaluator::getTriggerdLinksForProperty(Property* property) {
if (propertyLinkSecondaryCache_.find(property) != propertyLinkSecondaryCache_.end()) {
return propertyLinkSecondaryCache_[property];
} else {
return addToSecondaryCache(property);
}
}
std::vector<Property*> LinkEvaluator::getPropertiesLinkedTo(Property* property) {
// check if link connectivity has been computed and cached already
auto& list = (propertyLinkSecondaryCache_.find(property) != propertyLinkSecondaryCache_.end())
? propertyLinkSecondaryCache_[property]
: addToSecondaryCache(property);
return util::transform(list, [](const Link& link) { return link.dst_; });
}
std::vector<LinkEvaluator::Link>& LinkEvaluator::addToSecondaryCache(Property* src) {
for (auto& dst : propertyLinkPrimaryCache_[src]) {
if (src != dst) secondaryCacheHelper(propertyLinkSecondaryCache_[src], src, dst);
}
return propertyLinkSecondaryCache_[src];
}
void LinkEvaluator::secondaryCacheHelper(std::vector<Link>& links, Property* src, Property* dst) {
// Check that we don't use a previous source or destination as the new destination.
if (!util::contains_if(
links, [dst](const Link& link) { return link.src_ == dst || link.dst_ == dst; })) {
auto manager = network_->getApplication()->getPropertyConverterManager();
if (auto converter = manager->getConverter(src, dst)) {
links.emplace_back(src, dst, converter);
}
// Follow the links of destination all links of all owners (CompositeProperties).
for (Property* newSrc = dst; newSrc != nullptr;
newSrc = dynamic_cast<Property*>(newSrc->getOwner())) {
// Recurse over outgoing links.
for (auto& elem : propertyLinkPrimaryCache_[newSrc]) {
if (newSrc != elem) secondaryCacheHelper(links, newSrc, elem);
}
}
// If we link to a CompositeProperty, make sure to evaluate sub-links.
if (auto cp = dynamic_cast<CompositeProperty*>(dst)) {
for (auto& srcProp : cp->getProperties()) {
// Recurse over outgoing links.
for (auto& elem : propertyLinkPrimaryCache_[srcProp]) {
if (srcProp != elem) secondaryCacheHelper(links, srcProp, elem);
}
}
}
}
}
bool LinkEvaluator::isLinking() const { return !visited_.empty(); }
void LinkEvaluator::evaluateLinksFromProperty(Property* modifiedProperty) {
if (util::contains(visited_, modifiedProperty)) return;
NetworkLock lock(network_);
auto& links = getTriggerdLinksForProperty(modifiedProperty);
VisitedHelper helper(visited_, links);
for (auto& link : links) {
link.converter_->convert(link.src_, link.dst_);
}
}
} // namespace | bsd-2-clause |
askl56/homebrew-cask | Casks/todos.rb | 404 | cask v1: 'todos' do
version :latest
sha256 :no_check
url 'http://dbachrach.com/opensoft/downloads/apps/Todos.dmg'
appcast 'http://www.dbachrach.com/opensoft/appcasts/Todos.xml'
name 'Todos'
homepage 'http://dbachrach.com/opensoft/index.php?page=Todos'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Todos.app'
end
| bsd-2-clause |
inviwo/inviwo | modules/meshrenderinggl/src/processors/meshrasterizer.cpp | 24141 | /*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019-2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/meshrenderinggl/processors/meshrasterizer.h>
#include <modules/meshrenderinggl/datastructures/transformedrasterization.h>
#include <modules/opengl/geometry/meshgl.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/rendering/meshdrawerfactory.h>
#include <inviwo/core/util/stdextensions.h>
#include <modules/opengl/openglutils.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/base/algorithm/dataminmax.h>
#include <modules/opengl/image/layergl.h>
#include <modules/opengl/openglcapabilities.h>
#include <modules/opengl/rendering/meshdrawergl.h>
#include <sstream>
#include <chrono>
#include <variant>
#include <fmt/format.h>
namespace inviwo {
namespace {
void configComposite(BoolCompositeProperty& comp) {
auto callback = [&comp]() mutable {
comp.setCollapsed(!comp.isChecked());
for (auto p : comp) {
if (p == comp.getBoolProperty()) continue;
p->setReadOnly(!comp.isChecked());
}
};
comp.getBoolProperty()->onChange(callback);
callback();
}
} // namespace
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo MeshRasterizer::processorInfo_{
"org.inviwo.MeshRasterizer", // Class identifier
"Mesh Rasterizer", // Display name
"Mesh Rendering", // Category
CodeState::Experimental, // Code state
Tags::GL, // Tags
};
const ProcessorInfo MeshRasterizer::getProcessorInfo() const { return processorInfo_; }
MeshRasterizer::MeshRasterizer()
: Processor()
, inport_("geometry")
, outport_("image")
, lightingProperty_("lighting", "Lighting")
, transformSetting_("transformSettings", "Additional Transform")
, forceOpaque_("forceOpaque", "Shade Opaque", false, InvalidationLevel::InvalidResources)
, drawSilhouette_("drawSilhouette", "Draw Silhouette", false,
InvalidationLevel::InvalidResources)
, silhouetteColor_("silhouetteColor", "Silhouette Color", {0.f, 0.f, 0.f, 1.f})
, normalSource_(
"normalSource", "Normals Source",
{
{"inputVertex", "Input: Vertex Normal", NormalSource::InputVertex},
{"generateVertex", "Generate: Vertex Normal", NormalSource::GenerateVertex},
{"generateTriangle", "Generate: Triangle Normal", NormalSource::GenerateTriangle},
},
0, InvalidationLevel::InvalidResources)
, normalComputationMode_(
"normalComputationMode", "Normals Computation",
{{"noWeighting", "No Weighting", meshutil::CalculateMeshNormalsMode::NoWeighting},
{"area", "Area-weighting", meshutil::CalculateMeshNormalsMode::WeightArea},
{"angle", "Angle-weighting", meshutil::CalculateMeshNormalsMode::WeightAngle},
{"nmax", "Based on N.Max", meshutil::CalculateMeshNormalsMode::WeightNMax}},
3, InvalidationLevel::InvalidResources)
, faceSettings_{true, false}
, shader_(std::make_shared<Shader>("fancymeshrenderer.vert", "fancymeshrenderer.geom",
"fancymeshrenderer.frag", Shader::Build::No)) {
// input and output ports
addPort(inport_).onChange([this]() { updateMeshes(); });
addPort(outport_);
drawSilhouette_.onChange([this]() { updateMeshes(); });
addProperties(lightingProperty_, transformSetting_, forceOpaque_, drawSilhouette_,
silhouetteColor_, normalSource_, normalComputationMode_, alphaSettings_,
edgeSettings_, faceSettings_[0].show_, faceSettings_[1].show_);
silhouetteColor_.visibilityDependsOn(drawSilhouette_, [](const auto& p) { return p.get(); });
normalComputationMode_.visibilityDependsOn(
normalSource_, [](const auto& p) { return p.get() == NormalSource::GenerateVertex; });
alphaSettings_.visibilityDependsOn(forceOpaque_, [](const auto& p) { return !p.get(); });
auto edgevis = [this](auto) {
return drawSilhouette_.get() || faceSettings_[0].showEdges_.get() ||
faceSettings_[1].showEdges_.get();
};
edgeSettings_.visibilityDependsOn(drawSilhouette_, edgevis);
edgeSettings_.visibilityDependsOn(faceSettings_[0].showEdges_, edgevis);
edgeSettings_.visibilityDependsOn(faceSettings_[1].showEdges_, edgevis);
lightingProperty_.setCollapsed(true);
transformSetting_.setCollapsed(true);
transformSetting_.setCurrentStateAsDefault();
silhouetteColor_.setSemantics(PropertySemantics::Color);
faceSettings_[1].frontPart_ = &faceSettings_[0];
}
MeshRasterizer::AlphaSettings::AlphaSettings()
: CompositeProperty("alphaContainer", "Alpha")
, enableUniform_("alphaUniform", "Uniform", true, InvalidationLevel::InvalidResources)
, uniformScaling_("alphaUniformScaling", "Scaling", 0.5f, 0.f, 1.f, 0.01f)
, minimumAlpha_("minimumAlpha", "Minimum Alpha", 0.1f, 0.f, 1.f, 0.01f)
, enableAngleBased_("alphaAngleBased", "Angle-based", false,
InvalidationLevel::InvalidResources)
, angleBasedExponent_("alphaAngleBasedExponent", "Exponent", 1.f, 0.f, 5.f, 0.01f)
, enableNormalVariation_("alphaNormalVariation", "Normal variation", false,
InvalidationLevel::InvalidResources)
, normalVariationExponent_("alphaNormalVariationExponent", "Exponent", 1.f, 0.f, 5.f, 0.01f)
, enableDensity_("alphaDensity", "Density-based", false, InvalidationLevel::InvalidResources)
, baseDensity_("alphaBaseDensity", "Base density", 1.f, 0.f, 2.f, 0.01f)
, densityExponent_("alphaDensityExponent", "Exponent", 1.f, 0.f, 5.f, 0.01f)
, enableShape_("alphaShape", "Shape-based", false, InvalidationLevel::InvalidResources)
, shapeExponent_("alphaShapeExponent", "Exponent", 1.f, 0.f, 5.f, 0.01f) {
addProperties(minimumAlpha_, enableUniform_, uniformScaling_, enableAngleBased_,
angleBasedExponent_, enableNormalVariation_, normalVariationExponent_,
enableDensity_, baseDensity_, densityExponent_, enableShape_, shapeExponent_);
const auto get = [](const auto& p) { return p.get(); };
uniformScaling_.visibilityDependsOn(enableUniform_, get);
angleBasedExponent_.visibilityDependsOn(enableAngleBased_, get);
normalVariationExponent_.visibilityDependsOn(enableNormalVariation_, get);
baseDensity_.visibilityDependsOn(enableDensity_, get);
densityExponent_.visibilityDependsOn(enableDensity_, get);
shapeExponent_.visibilityDependsOn(enableShape_, get);
}
void MeshRasterizer::AlphaSettings::setUniforms(Shader& shader, std::string_view prefix) const {
std::array<std::pair<std::string_view, std::variant<float>>, 7> uniforms{
{{"minAlpha", minimumAlpha_},
{"uniformScale", uniformScaling_},
{"angleExp", angleBasedExponent_},
{"normalExp", normalVariationExponent_},
{"baseDensity", baseDensity_},
{"densityExp", densityExponent_},
{"shapeExp", shapeExponent_}}};
for (const auto& [key, val] : uniforms) {
std::visit([&, akey = key](
auto& aval) { shader.setUniform(fmt::format("{}{}", prefix, akey), aval); },
val);
}
} // namespace inviwo
MeshRasterizer::EdgeSettings::EdgeSettings()
: CompositeProperty("edges", "Edges")
, edgeThickness_("thickness", "Thickness", 2.f, 0.1f, 10.f, 0.1f)
, depthDependent_("depth", "Depth dependent", false, InvalidationLevel::InvalidResources)
, smoothEdges_("smooth", "Smooth edges", true, InvalidationLevel::InvalidResources) {
addProperties(edgeThickness_, depthDependent_, smoothEdges_);
}
MeshRasterizer::HatchingSettings::HatchingSettings()
: hatching_("hatching", "Hatching Settings", false)
, mode_("hatchingMode", "Hatching",
{{"u", "U", HatchingMode::U},
{"v", "V", HatchingMode::V},
{"uv", "UV", HatchingMode::UV}},
0, InvalidationLevel::InvalidResources)
, steepness_("steepness", "Steepness", 5, 1, 10)
, baseFrequencyU_("frequencyU", "U-Frequency", 3, 1, 10)
, baseFrequencyV_("frequencyV", "V-Frequency", 3, 1, 10)
, modulation_("modulation", "Modulation", false)
, modulationMode_("modulationMode", "Modulation",
{{"u", "U", HatchingMode::U},
{"v", "V", HatchingMode::V},
{"uv", "UV", HatchingMode::UV}})
, modulationAnisotropy_("modulationAnisotropy", "Anisotropy", 0.5f, -1.f, 1.f, 0.01f)
, modulationOffset_("modulationOffset", "Offset", 0.f, 0.f, 1.f, 0.01f)
, color_("color", "Color", {0.f, 0.f, 0.f})
, strength_("strength", "Strength", 0.5f, 0.f, 1.f, 0.01f)
, blendingMode_("blending", "Blending",
{{"mult", "Multiplicative", HatchingBlendingMode::Multiplicative},
{"add", "Additive", HatchingBlendingMode::Additive}}) {
hatching_.getBoolProperty()->setInvalidationLevel(InvalidationLevel::InvalidResources);
configComposite(hatching_);
// init properties
color_.setSemantics(PropertySemantics::Color);
// add to container
modulation_.addProperties(modulationMode_, modulationAnisotropy_, modulationOffset_);
configComposite(modulation_);
hatching_.addProperties(mode_, steepness_, baseFrequencyU_, baseFrequencyV_, modulation_,
color_, strength_, blendingMode_);
baseFrequencyU_.visibilityDependsOn(
mode_, [](const auto& prop) { return prop.get() != HatchingMode::V; });
baseFrequencyV_.visibilityDependsOn(
mode_, [](const auto& prop) { return prop.get() != HatchingMode::U; });
modulation_.visibilityDependsOn(
mode_, [](const auto& prop) { return prop.get() == HatchingMode::UV; });
}
MeshRasterizer::FaceSettings::FaceSettings(bool frontFace)
: frontFace_(frontFace)
, show_(frontFace ? "frontcontainer" : "backcontainer", frontFace ? "Front Face" : "Back Face",
true)
, sameAsFrontFace_("same", "Same as Front Face")
, copyFrontToBack_("copy", "Copy Front to Back")
, transferFunction_("tf", "Transfer Function")
, externalColor_("extraColor", "Color", {1.f, 0.3f, 0.01f})
, colorSource_("colorSource", "Color Source",
{{"vertexColor", "VertexColor", ColorSource::VertexColor},
{"tf", "Transfer Function", ColorSource::TransferFunction},
{"external", "Constant Color", ColorSource::ExternalColor}},
2, InvalidationLevel::InvalidResources)
, separateUniformAlpha_("separateUniformAlpha", "Separate Uniform Alpha")
, uniformAlpha_("uniformAlpha", "Uniform Alpha", 0.5f, 0.f, 1.f, 0.01f)
, shadingMode_("shadingMode", "Shading Mode",
{{"off", "Off", ShadingMode::Off}, {"phong", "Phong", ShadingMode::Phong}})
, showEdges_("showEdges", "Show Edges", false, InvalidationLevel::InvalidResources)
, edgeColor_("edgeColor", "Edge color", {0.f, 0.f, 0.f})
, edgeOpacity_("edgeOpacity", "Edge Opacity", 0.5f, 0.f, 2.f, 0.01f)
, hatching_() {
externalColor_.setSemantics(PropertySemantics::Color);
edgeColor_.setSemantics(PropertySemantics::Color);
if (!frontFace) {
show_.addProperties(sameAsFrontFace_, copyFrontToBack_);
copyFrontToBack_.onChange([this]() { copyFrontToBack(); });
}
show_.addProperties(colorSource_, transferFunction_, externalColor_, separateUniformAlpha_,
uniformAlpha_, shadingMode_, showEdges_, edgeColor_, edgeOpacity_,
hatching_.hatching_);
configComposite(show_);
const auto get = [](const auto& p) { return p.get(); };
edgeColor_.visibilityDependsOn(showEdges_, get);
edgeOpacity_.visibilityDependsOn(showEdges_, get);
uniformAlpha_.visibilityDependsOn(separateUniformAlpha_,
[](const auto& prop) { return prop.get(); });
transferFunction_.visibilityDependsOn(
colorSource_, [](const auto& prop) { return prop.get() == ColorSource::TransferFunction; });
externalColor_.visibilityDependsOn(
colorSource_, [](const auto& prop) { return prop.get() == ColorSource::ExternalColor; });
}
void MeshRasterizer::FaceSettings::copyFrontToBack() {
for (auto src : frontPart_->show_) {
if (auto dst = show_.getPropertyByIdentifier(src->getIdentifier())) {
dst->set(src);
}
}
}
void MeshRasterizer::FaceSettings::setUniforms(Shader& shader, std::string_view prefix) const {
std::array<std::pair<std::string_view, std::variant<bool, int, float, vec4>>, 15> uniforms{
{{"externalColor", vec4{*externalColor_, 1.0f}},
{"colorSource", static_cast<int>(*colorSource_)},
{"separateUniformAlpha", separateUniformAlpha_},
{"uniformAlpha", uniformAlpha_},
{"shadingMode", static_cast<int>(*shadingMode_)},
{"showEdges", showEdges_},
{"edgeColor", vec4{*edgeColor_, *edgeOpacity_}},
{"hatchingMode", (hatching_.mode_.get() == HatchingMode::UV)
? 3 + static_cast<int>(hatching_.modulationMode_.get())
: static_cast<int>(hatching_.mode_.get())},
{"hatchingSteepness", hatching_.steepness_.get()},
{"hatchingFreqU", hatching_.baseFrequencyU_.getMaxValue() - hatching_.baseFrequencyU_},
{"hatchingFreqV", hatching_.baseFrequencyV_.getMaxValue() - hatching_.baseFrequencyV_},
{"hatchingModulationAnisotropy", hatching_.modulationAnisotropy_},
{"hatchingModulationOffset", hatching_.modulationOffset_},
{"hatchingColor", vec4(hatching_.color_.get(), hatching_.strength_.get())},
{"hatchingBlending", static_cast<int>(hatching_.blendingMode_.get())}}};
for (const auto& [key, val] : uniforms) {
std::visit([&, akey = key](
auto aval) { shader.setUniform(fmt::format("{}{}", prefix, akey), aval); },
val);
}
}
void MeshRasterizer::process() {
if (!faceSettings_[0].show_ && !faceSettings_[1].show_) {
outport_.setData(nullptr);
LogWarn("Both sides are disabled, not rendering anything.");
return; // everything is culled
}
shader_->activate();
// general settings for camera, lighting, picking, mesh data
utilgl::setUniforms(*shader_, lightingProperty_);
// update face render settings
std::array<TextureUnit, 2> transFuncUnit;
for (size_t j = 0; j < faceSettings_.size(); ++j) {
const std::string prefix = fmt::format("renderSettings[{}].", j);
auto& face = faceSettings_[faceSettings_[1].sameAsFrontFace_.get() ? 0 : j];
face.setUniforms(*shader_, prefix);
}
// update alpha settings
alphaSettings_.setUniforms(*shader_, "alphaSettings.");
// update other global fragment shader settings
shader_->setUniform("silhouetteColor", silhouetteColor_);
// update geometry shader settings
shader_->setUniform("geomSettings.edgeWidth", edgeSettings_.edgeThickness_);
shader_->setUniform("geomSettings.triangleNormal",
normalSource_ == NormalSource::GenerateTriangle);
shader_->deactivate();
std::shared_ptr<const Rasterization> rasterization =
std::make_shared<const MeshRasterization>(*this);
// If transform is applied, wrap rasterization.
if (transformSetting_.transforms_.size() > 0) {
outport_.setData(std::make_shared<TransformedRasterization>(rasterization,
transformSetting_.getMatrix()));
} else {
outport_.setData(rasterization);
}
}
void MeshRasterizer::updateMeshes() {
enhancedMeshes_.clear();
for (auto mesh : inport_) {
std::shared_ptr<Mesh> copy = nullptr;
if (drawSilhouette_) {
copy = std::make_shared<Mesh>(*mesh, noData);
for (auto&& [info, buffer] : mesh->getBuffers()) {
copy->addBuffer(info, std::shared_ptr<BufferBase>(buffer->clone()));
}
// create adjacency information
const auto halfEdges = HalfEdges{*mesh};
// add new index buffer with adjacency information
copy->addIndices(
{DrawType::Triangles, ConnectivityType::Adjacency},
std::make_shared<IndexBuffer>(halfEdges.createIndexBufferWithAdjacency()));
if (!meshHasAdjacency_) {
meshHasAdjacency_ = true;
initializeResources();
}
} else {
if (meshHasAdjacency_) {
meshHasAdjacency_ = false;
initializeResources();
}
}
if (normalSource_.get() == NormalSource::GenerateVertex) {
if (!copy) copy = std::shared_ptr<Mesh>(mesh->clone());
meshutil::calculateMeshNormals(*copy, normalComputationMode_);
}
enhancedMeshes_.push_back(copy ? copy : mesh);
}
}
MeshRasterization::MeshRasterization(const MeshRasterizer& processor)
: enhancedMeshes_(processor.enhancedMeshes_)
, forceOpaque_(processor.forceOpaque_)
, showFace_{processor.faceSettings_[0].show_, processor.faceSettings_[1].show_}
, tfTextures_{processor.faceSettings_[0].transferFunction_->getData(),
processor.faceSettings_[processor.faceSettings_[1].sameAsFrontFace_.get() ? 0 : 1]
.transferFunction_->getData()}
, shader_(processor.shader_) {}
void MeshRasterizer::initializeResources() {
auto fso = shader_->getFragmentShaderObject();
fso->addShaderExtension("GL_NV_gpu_shader5", true);
fso->addShaderExtension("GL_EXT_shader_image_load_store", true);
fso->addShaderExtension("GL_NV_shader_buffer_load", true);
fso->addShaderExtension("GL_EXT_bindable_uniform", true);
// shading defines
utilgl::addShaderDefines(*shader_, lightingProperty_);
const std::array<std::pair<std::string, bool>, 15> defines = {
{{"USE_FRAGMENT_LIST", !forceOpaque_.get()},
{"ALPHA_UNIFORM", alphaSettings_.enableUniform_},
{"ALPHA_ANGLE_BASED", alphaSettings_.enableAngleBased_},
{"ALPHA_NORMAL_VARIATION", alphaSettings_.enableNormalVariation_},
{"ALPHA_DENSITY", alphaSettings_.enableDensity_},
{"ALPHA_SHAPE", alphaSettings_.enableShape_},
{"DRAW_EDGES", faceSettings_[0].showEdges_ || faceSettings_[1].showEdges_},
{"DRAW_EDGES_DEPTH_DEPENDENT", edgeSettings_.depthDependent_},
{"DRAW_EDGES_SMOOTHING", edgeSettings_.smoothEdges_},
{"MESH_HAS_ADJACENCY", meshHasAdjacency_},
{"DRAW_SILHOUETTE", drawSilhouette_},
{"SEND_TEX_COORD", faceSettings_[0].hatching_.hatching_.isChecked() ||
faceSettings_[1].hatching_.hatching_.isChecked()},
{"SEND_SCALAR", faceSettings_[0].colorSource_ == ColorSource::TransferFunction ||
faceSettings_[1].colorSource_ == ColorSource::TransferFunction},
{"SEND_COLOR", faceSettings_[0].colorSource_ == ColorSource::VertexColor ||
faceSettings_[1].colorSource_ == ColorSource::VertexColor}}};
for (auto&& [key, val] : defines) {
for (auto&& so : shader_->getShaderObjects()) {
so.setShaderDefine(key, val);
}
}
shader_->build();
}
void MeshRasterization::rasterize(const ivec2& imageSize, const mat4& worldMatrixTransform,
std::function<void(Shader&)> setUniformsRenderer) const {
shader_->activate();
// set transfer function textures
std::array<TextureUnit, 2> transFuncUnit;
for (size_t j = 0; j < 2; ++j) {
const LayerGL* transferFunctionGL = tfTextures_[j]->getRepresentation<LayerGL>();
transferFunctionGL->bindTexture(transFuncUnit[j].getEnum());
shader_->setUniform(fmt::format("transferFunction{}", j), transFuncUnit[j].getUnitNumber());
}
shader_->setUniform("halfScreenSize", imageSize / ivec2(2));
// call the callback provided by the renderer calling this function
setUniformsRenderer(*shader_);
{
// various OpenGL states: depth, blending, culling
utilgl::GlBoolState depthTest(GL_DEPTH_TEST, forceOpaque_);
utilgl::DepthMaskState depthMask(forceOpaque_ ? GL_TRUE : GL_FALSE);
utilgl::CullFaceState culling(!showFace_[0] && showFace_[1] ? GL_FRONT
: showFace_[0] && !showFace_[1] ? GL_BACK
: GL_NONE);
utilgl::BlendModeState blendModeState(forceOpaque_ ? GL_ONE : GL_SRC_ALPHA,
forceOpaque_ ? GL_ZERO : GL_ONE_MINUS_SRC_ALPHA);
// Finally, draw it
for (auto mesh : enhancedMeshes_) {
MeshDrawerGL::DrawObject drawer{mesh->getRepresentation<MeshGL>(),
mesh->getDefaultMeshInfo()};
auto transform = CompositeTransform(mesh->getModelMatrix(),
mesh->getWorldMatrix() * worldMatrixTransform);
utilgl::setShaderUniforms(*shader_, transform, "geometry");
shader_->setUniform("pickingEnabled", meshutil::hasPickIDBuffer(mesh.get()));
drawer.draw();
}
}
shader_->deactivate();
}
Document MeshRasterization::getInfo() const {
Document doc;
doc.append("p", fmt::format("Mesh rasterization functor with {} {}. {}", enhancedMeshes_.size(),
(enhancedMeshes_.size() == 1) ? " mesh" : " meshes",
usesFragmentLists() ? "Using A-buffer" : "Rendering opaque"));
return doc;
}
Rasterization* MeshRasterization::clone() const { return new MeshRasterization(*this); }
} // namespace inviwo
| bsd-2-clause |
kunjanrshah/Stickty_SectionList | gen/pl/polidea/sectionedlist/BuildConfig.java | 166 | /** Automatically generated file. DO NOT MODIFY */
package pl.polidea.sectionedlist;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | bsd-2-clause |
wukan1986/kquant_data | kquant_data/config.py | 2172 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
配置信息
股票数据要能正常运行,需要准备工作如下
1. 安装通达信(日线数据来源),然后配置实际的__CONFIG_TDX_STK_DIR__
2. 安装大智慧(除权除息来源),确保路径__CONFIG_DZH_PWR_FILE__的目录已经创建。也可不安装大智慧直接建立对应的目录
3. 根据以下的配置文件,在D盘创建相应的目录
"""
import os
"""
股票
"""
# 通达信目录
__CONFIG_TDX_STK_DIR__ = r'D:\new_hbzq'
# 大智慧权息文件(已经废弃)
__CONFIG_DZH_PWR_FILE__ = r"D:\dzh2\Download\PWR\full.PWR"
# 通达信股票变迁文件
__CONFIG_TDX_GBBQ_FILE__ = os.path.join(__CONFIG_TDX_STK_DIR__, 'T0002', 'hq_cache', 'gbbq')
# __CONFIG_TDX_GBBQ_FILE__ = r"D:\sh\gbbq"
# 输出的股票行情目录
__CONFIG_H5_STK_DIR__ = r'D:\DATA_STK'
# 股票的除权除息数据
__CONFIG_H5_STK_DIVIDEND_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'dividend')
# 股票行业信息
__CONFIG_H5_STK_SECTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'sectorconstituent')
# 指数权重信息
__CONFIG_H5_STK_WEIGHT_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'indexconstituent')
# 股票因子信息
__CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor')
# 交易日数据,请每年末更新一下第二年的交易日信息
__CONFIG_TDAYS_SSE_FILE__ = os.path.join(__CONFIG_H5_STK_DIR__, 'tdays', 'SSE.csv')
"""
期货
"""
# 期货行情数据
__CONFIG_H5_FUT_DIR__ = r'D:\DATA_FUT'
__CONFIG_H5_FUT_FACTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'factor')
__CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent')
__CONFIG_H5_FUT_DATA_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'data')
__CONFIG_TDAYS_SHFE_FILE__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'tdays', 'SHFE.csv')
__CONFIG_H5_FUT_MARKET_DATA_DIR__ = r'D:\DATA_FUT_HDF5\Data_P2'
"""
期权
"""
# 期货行情数据
__CONFIG_H5_OPT_DIR__ = r'D:\DATA_OPT'
# 为了将自定义库引入进来,注意这里要改
# sys.path.append(r'D:\Python\Kan')
# sys.path
# 使用这种方法更方便
# D:\Users\Kan\Anaconda3\Lib\site-packages\kquant.pth
| bsd-2-clause |
jijiang/xenadmin | XenModel/XenAPI-Extensions/Session.cs | 9836 | /* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Text;
using CookComputing.XmlRpc;
using log4net.Core;
using XenAdmin;
using XenAdmin.Core;
using XenAdmin.Network;
namespace XenAPI
{
public partial class Session
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public bool IsElevatedSession = false;
private Session(int timeout, IXenConnection connection, string url)
{
Connection = connection;
_proxy = XmlRpcProxyGen.Create<Proxy>();
_proxy.Url = url;
_proxy.NonStandard = XmlRpcNonStandard.All;
_proxy.Timeout = timeout;
_proxy.UseIndentation = false;
_proxy.UserAgent = UserAgent;
_proxy.KeepAlive = true;
_proxy.RequestEvent += LogRequest;
_proxy.ResponseEvent += LogResponse;
_proxy.Proxy = Proxy;
// reverted because of CA-137829/CA-137959: _proxy.ConnectionGroupName = Guid.NewGuid().ToString(); // this will force the Session onto a different set of TCP streams (see CA-108676)
}
public Session(Proxy proxy, IXenConnection connection)
{
Connection = connection;
_proxy = proxy;
}
public Session(Session session, Proxy proxy, IXenConnection connection)
: this(proxy, connection)
{
InitAD(session);
}
public Session(int timeout, IXenConnection connection, string host, int port)
: this(timeout, connection, GetUrl(host, port))
{
}
/// <summary>
/// Create a new Session instance, using the given instance and timeout. The connection details and Xen-API session handle will be
/// copied from the given instance, but a new connection will be created. Use this if you want a duplicate connection to a host,
/// for example when you need to cancel an operation that is blocking the primary connection.
/// </summary>
/// <param name="session"></param>
/// <param name="timeout"></param>
public Session(Session session, IXenConnection connection, int timeout)
: this(timeout, connection, session.Url)
{
InitAD(session);
}
private void InitAD(Session session)
{
_uuid = session.uuid;
APIVersion = session.APIVersion;
_userSid = session.UserSid;
_subject = session.Subject;
_isLocalSuperuser = session.IsLocalSuperuser;
roles = session.Roles;
permissions = session.Permissions;
}
/// <summary>
/// When the CacheWarming flag is set, we output logging at Debug rather than Info level.
/// This means that we don't spam the logs when the application starts.
/// </summary>
private bool _cacheWarming = false;
public bool CacheWarming
{
get { return _cacheWarming; }
set { _cacheWarming = value; }
}
private void LogRequest(object o, XmlRpcRequestEventArgs args)
{
Level logLevel;
string xml = DumpStream(args.RequestStream, String.Empty);
// Find the method name within the XML
string methodName = "";
int methodNameStart = xml.IndexOf("<methodName>");
if (methodNameStart >= 0)
{
methodNameStart += 12; // skip past "<methodName>"
int methodNameEnd = xml.IndexOf('<', methodNameStart);
if (methodNameEnd > methodNameStart)
methodName = xml.Substring(methodNameStart, methodNameEnd - methodNameStart);
}
if (CacheWarming)
logLevel = Level.Debug;
else if (methodName == "event.next" || methodName == "event.from" || methodName == "host.get_servertime" || methodName.StartsWith("task.get_")) // these occur frequently and we don't need to know about them
logLevel = Level.Debug;
else
logLevel = Level.Info;
// Only log the full XML at Debug level because it may have sensitive data in: CA-80174
if (logLevel == Level.Debug)
LogMsg(logLevel, "Invoking XML-RPC method " + methodName + ": " + xml);
else
LogMsg(logLevel, "Invoking XML-RPC method " + methodName);
}
private void LogResponse(object o, XmlRpcResponseEventArgs args)
{
if(log.IsDebugEnabled)
LogMsg(Level.Debug, DumpStream(args.ResponseStream, "XML-RPC response: "));
}
private string DumpStream(Stream s, string header)
{
try
{
StringBuilder stringBuilder = new StringBuilder(header);
using (TextReader r = new StreamReader(s))
{
string l;
while ((l = r.ReadLine()) != null)
stringBuilder.Append(l);
}
return stringBuilder.ToString();
}
catch(OutOfMemoryException ex)
{
LogMsg(Level.Debug, "Session ran out of memory while trying to log the XML response stream: " + ex.Message);
return String.Empty;
}
}
private void LogMsg(Level logLevel, String msg)
{
if (logLevel == Level.Debug)
log.Debug(msg);
else if (logLevel == Level.Info)
log.Info(msg);
else
System.Diagnostics.Trace.Assert(false, "Missing log level");
}
/// <summary>
/// The i18n'd string for the 'Logged in as:' username (AD or local root).
/// </summary>
public string UserFriendlyName()
{
if (IsLocalSuperuser)
return Messages.AD_LOCAL_ROOT_ACCOUNT;
if (!string.IsNullOrEmpty(CurrentUserDetails.UserDisplayName))
return CurrentUserDetails.UserDisplayName.Ellipsise(50);
if (!string.IsNullOrEmpty(CurrentUserDetails.UserName))
return CurrentUserDetails.UserName.Ellipsise(50);
return Messages.UNKNOWN_AD_USER;
}
/// <summary>
/// Useful as a unique name for logging purposes
/// </summary>
public string UserLogName()
{
if (IsLocalSuperuser)
return Messages.AD_LOCAL_ROOT_ACCOUNT;
if (!string.IsNullOrEmpty(CurrentUserDetails.UserName))
return CurrentUserDetails.UserName;
return UserSid;
}
/// <summary>
/// This gives either a friendly csv list of the sessions roles or a friendly string for Local root account.
/// If Pre MR gives Pool Admin for AD users.
/// </summary>
public string FriendlyRoleDescription()
{
if (IsLocalSuperuser || XenAdmin.Core.Helpers.GetMaster(Connection).external_auth_type != Auth.AUTH_TYPE_AD)
return Messages.AD_LOCAL_ROOT_ACCOUNT;
return Role.FriendlyCSVRoleList(Roles);
}
/// <summary>
/// This gives either a friendly string for the dominant role on the session or a friendly string for Local root account.
/// If Pre MR gives Pool Admin for AD users.
/// </summary>
public string FriendlySingleRoleDescription()
{
if (IsLocalSuperuser || XenAdmin.Core.Helpers.GetMaster(Connection).external_auth_type != Auth.AUTH_TYPE_AD)
return Messages.AD_LOCAL_ROOT_ACCOUNT;
//Sort roles from highest to lowest
roles.Sort((r1, r2) => { return r2.CompareTo(r1); });
//Take the highest role
return roles[0].FriendlyName();
}
public string ConnectionGroupName
{
get { return _proxy.ConnectionGroupName; }
set { _proxy.ConnectionGroupName = value; }
}
}
}
| bsd-2-clause |
kkuhrman/AblePolecat | usr/share/documentation/html/interface_able_polecat___access_control___role___user___authenticated_interface.js | 241 | var interface_able_polecat___access_control___role___user___authenticated_interface =
[
[ "getAuthority", "interface_able_polecat___access_control___role___user___authenticated_interface.html#a1f73860dd14340c5bad9094f0b5b97c2", null ]
]; | bsd-2-clause |
c0stra/focus-on-quality | test-builders/src/main/java/test/builders/models/Group.java | 417 | package test.builders.models;
import java.util.List;
public class Group<T> {
private String name;
private List<T> members;
public List<T> getMembers() {
return members;
}
public void setMembers(List<T> members) {
this.members = members;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| bsd-2-clause |
byt3bl33d3r/CrackMapExec | cme/protocols/winrm.py | 10478 |
import requests
import logging
import configparser
from impacket.smbconnection import SMBConnection, SessionError
from cme.connection import *
from cme.helpers.logger import highlight
from cme.helpers.bloodhound import add_user_bh
from cme.logger import CMEAdapter
from io import StringIO
from pypsrp.client import Client
# The following disables the InsecureRequests warning and the 'Starting new HTTPS connection' log message
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class SuppressFilter(logging.Filter):
# remove warning https://github.com/diyan/pywinrm/issues/269
def filter(self, record):
return 'wsman' not in record.getMessage()
class winrm(connection):
def __init__(self, args, db, host):
self.domain = None
self.server_os = None
connection.__init__(self, args, db, host)
@staticmethod
def proto_args(parser, std_parser, module_parser):
winrm_parser = parser.add_parser('winrm', help="own stuff using WINRM", parents=[std_parser, module_parser])
winrm_parser.add_argument("-H", '--hash', metavar="HASH", dest='hash', nargs='+', default=[], help='NTLM hash(es) or file(s) containing NTLM hashes')
winrm_parser.add_argument("--no-bruteforce", action='store_true', help='No spray when using file for username and password (user1 => password1, user2 => password2')
winrm_parser.add_argument("--continue-on-success", action='store_true', help="continues authentication attempts even after successes")
winrm_parser.add_argument("--port", type=int, default=0, help="Custom WinRM port")
dgroup = winrm_parser.add_mutually_exclusive_group()
dgroup.add_argument("-d", metavar="DOMAIN", dest='domain', type=str, default=None, help="domain to authenticate to")
dgroup.add_argument("--local-auth", action='store_true', help='authenticate locally to each target')
cgroup = winrm_parser.add_argument_group("Command Execution", "Options for executing commands")
cgroup.add_argument('--no-output', action='store_true', help='do not retrieve command output')
cgroup.add_argument("-x", metavar="COMMAND", dest='execute', help="execute the specified command")
cgroup.add_argument("-X", metavar="PS_COMMAND", dest='ps_execute', help='execute the specified PowerShell command')
return parser
def proto_flow(self):
self.proto_logger()
if self.create_conn_obj():
self.enum_host_info()
self.print_host_info()
if self.login():
if hasattr(self.args, 'module') and self.args.module:
self.call_modules()
else:
self.call_cmd_args()
def proto_logger(self):
self.logger = CMEAdapter(extra={'protocol': 'SMB',
'host': self.host,
'port': 'NONE',
'hostname': 'NONE'})
def enum_host_info(self):
# smb no open, specify the domain
if self.args.domain:
self.domain = self.args.domain
self.logger.extra['hostname'] = self.hostname
else:
try:
smb_conn = SMBConnection(self.host, self.host, None)
try:
smb_conn.login('', '')
except SessionError as e:
if "STATUS_ACCESS_DENIED" in e.message:
pass
self.domain = smb_conn.getServerDNSDomainName()
self.hostname = smb_conn.getServerName()
self.server_os = smb_conn.getServerOS()
self.logger.extra['hostname'] = self.hostname
try:
smb_conn.logoff()
except:
pass
except Exception as e:
logging.debug("Error retrieving host domain: {} specify one manually with the '-d' flag".format(e))
if self.args.domain:
self.domain = self.args.domain
if self.args.local_auth:
self.domain = self.hostname
def print_host_info(self):
if self.args.domain:
self.logger.extra['protocol'] = "HTTP"
self.logger.info(self.endpoint)
else:
self.logger.extra['protocol'] = "SMB"
self.logger.info(u"{} (name:{}) (domain:{})".format(self.server_os,
self.hostname,
self.domain))
self.logger.extra['protocol'] = "HTTP"
self.logger.info(self.endpoint)
self.logger.extra['protocol'] = "WINRM"
def create_conn_obj(self):
endpoints = [
'https://{}:{}/wsman'.format(self.host, self.args.port if self.args.port else 5986),
'http://{}:{}/wsman'.format(self.host, self.args.port if self.args.port else 5985)
]
for url in endpoints:
try:
requests.get(url, verify=False, timeout=3)
self.endpoint = url
if self.endpoint.startswith('https://'):
self.port = self.args.port if self.args.port else 5986
else:
self.port = self.args.port if self.args.port else 5985
self.logger.extra['port'] = self.port
return True
except Exception as e:
if 'Max retries exceeded with url' not in str(e):
logging.debug('Error in WinRM create_conn_obj:' + str(e))
return False
def plaintext_login(self, domain, username, password):
try:
from urllib3.connectionpool import log
log.addFilter(SuppressFilter())
self.conn = Client(self.host,
auth='ntlm',
username=u'{}\\{}'.format(domain, username),
password=password,
ssl=False)
# TO DO: right now we're just running the hostname command to make the winrm library auth to the server
# we could just authenticate without running a command :) (probably)
self.conn.execute_ps("hostname")
self.admin_privs = True
self.logger.success(u'{}\\{}:{} {}'.format(self.domain,
username,
password,
highlight('({})'.format(self.config.get('CME', 'pwn3d_label')) if self.admin_privs else '')))
add_user_bh(self.username, self.domain, self.logger, self.config)
if not self.args.continue_on_success:
return True
except Exception as e:
if "with ntlm" in str(e):
self.logger.error(u'{}\\{}:{}'.format(self.domain,
username,
password))
else:
self.logger.error(u'{}\\{}:{} "{}"'.format(self.domain,
username,
password,
e))
return False
def hash_login(self, domain, username, ntlm_hash):
try:
from urllib3.connectionpool import log
log.addFilter(SuppressFilter())
lmhash = '00000000000000000000000000000000:'
nthash = ''
#This checks to see if we didn't provide the LM Hash
if ntlm_hash.find(':') != -1:
lmhash, nthash = ntlm_hash.split(':')
else:
nthash = ntlm_hash
ntlm_hash = lmhash + nthash
self.hash = nthash
if lmhash: self.lmhash = lmhash
if nthash: self.nthash = nthash
self.conn = Client(self.host,
auth='ntlm',
username=u'{}\\{}'.format(domain, username),
password=ntlm_hash,
ssl=False)
# TO DO: right now we're just running the hostname command to make the winrm library auth to the server
# we could just authenticate without running a command :) (probably)
self.conn.execute_ps("hostname")
self.admin_privs = True
self.logger.success(u'{}\\{}:{} {}'.format(self.domain,
username,
self.hash,
highlight('({})'.format(self.config.get('CME', 'pwn3d_label')) if self.admin_privs else '')))
add_user_bh(self.username, self.domain, self.logger, self.config)
if not self.args.continue_on_success:
return True
except Exception as e:
if "with ntlm" in str(e):
self.logger.error(u'{}\\{}:{}'.format(self.domain,
username,
self.hash))
else:
self.logger.error(u'{}\\{}:{} "{}"'.format(self.domain,
username,
self.hash,
e))
return False
def execute(self, payload=None, get_output=False):
try:
r = self.conn.execute_cmd(self.args.execute)
except:
self.logger.debug('Cannot execute cmd command, probably because user is not local admin, but powershell command should be ok !')
r = self.conn.execute_ps(self.args.execute)
self.logger.success('Executed command')
self.logger.highlight(r[0])
def ps_execute(self, payload=None, get_output=False):
r = self.conn.execute_ps(self.args.ps_execute)
self.logger.success('Executed command')
self.logger.highlight(r[0]) | bsd-2-clause |
junejosheeraz/p4antExt | src/com/perforce/p4java/ant/tasks/RevertTask.java | 4060 | /**
* Copyright (c) 2010 Perforce Software. All rights reserved.
*/
package com.perforce.p4java.ant.tasks;
import org.apache.tools.ant.BuildException;
import com.perforce.p4java.core.IChangelist;
import com.perforce.p4java.core.file.FileSpecBuilder;
import com.perforce.p4java.exception.P4JavaError;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.option.client.RevertFilesOptions;
/**
* Discard changes from opened files. Revert an open file back to the revision
* previously synced from the depot, discarding any pending changelists or
* integrations that have been made. This command requires naming files
* explicitly. After running revert the named files will no longer be locked or
* open. </p>
*
* @see PerforceTask
* @see ClientTask
*/
public class RevertTask extends ClientTask {
/**
* If true, don't actually do the revert, just return the files that would
* have been opened for reversion.
*/
protected boolean noUpdate = false;
/**
* If positive, the reverted files are put into the pending changelist
* identified by changelistId (this changelist must have been previously
* created for this to succeed). If zero or negative, the file is opened in
* the 'default' (unnumbered) changelist.
*/
protected String changelist = String.valueOf(IChangelist.UNKNOWN);
/**
* If true, revert only unchanged files.
*/
protected boolean revertOnlyUnchanged = false;
/**
* If true bypass the client file refresh.
*/
protected boolean noClientRefresh = false;
/**
* Default constructor.
*/
public RevertTask() {
super();
commandOptions = new RevertFilesOptions(noUpdate,
parseChangelist(changelist), revertOnlyUnchanged,
noClientRefresh);
}
/**
* Sets the changelist.
*
* @param changelist
* the new changelist
*/
public void setChangelist(String changelist) {
((RevertFilesOptions) commandOptions)
.setChangelistId(parseChangelist(changelist));
}
/**
* Sets the no update.
*
* @param noUpdate
* the new no update
*/
public void setNoUpdate(boolean noUpdate) {
((RevertFilesOptions) commandOptions).setNoUpdate(noUpdate);
}
/**
* Sets the revert only unchanged.
*
* @param revertOnlyUnchanged
* the new revert only unchanged
*/
public void setRevertOnlyUnchanged(boolean revertOnlyUnchanged) {
((RevertFilesOptions) commandOptions)
.setRevertOnlyUnchanged(revertOnlyUnchanged);
}
/**
* Sets the no client refresh.
*
* @param noClientRefresh
* the new no client refresh
*/
public void setNoClientRefresh(boolean noClientRefresh) {
((RevertFilesOptions) commandOptions)
.setNoClientRefresh(noClientRefresh);
}
/**
* Execute the Perforce revert command with file specs and options. Log the
* returned file specs.
* <p>
* Revert open Perforce client workspace files back to the revision
* previously synced from the Perforce depot, discarding any pending
* changelists or integrations that have been made so far.
*
* @see PerforceTask#execP4Command()
*/
protected void execP4Command() throws BuildException {
try {
fileSpecs = FileSpecBuilder.makeFileSpecList(getFiles());
retFileSpecs = getP4Client().revertFiles(fileSpecs,
((RevertFilesOptions) commandOptions));
logFileSpecs(retFileSpecs);
} catch (P4JavaException e) {
throw new BuildException(e.getLocalizedMessage(), e, getLocation());
} catch (P4JavaError e) {
throw new BuildException(e.getLocalizedMessage(), e, getLocation());
} catch (Throwable t) {
throw new BuildException(t.getLocalizedMessage(), t, getLocation());
}
}
}
| bsd-2-clause |
coblo/isccbench | iscc_bench/readers/harvard.py | 2886 | # -*- coding: utf-8 -*-
"""Read data from 'Harvard Library Open Metadata'.
Records: ~12 Million
Size: 12.8 GigaByte (Unpacked)
Info: http://library.harvard.edu/open-metadata
Data: https://s3.amazonaws.com/hlom/harvard.tar.gz
Instructions:
Download datafile and run `tar xvf harvard.tar.gz` to extract marc21 files.
After moving the .mrc files to the /data/harvard folder you should be able
to run this script and see log output of parsed data.
"""
import os
import logging
import isbnlib
from pymarc import MARCReader
from iscc_bench import DATA_DIR, MetaData
log = logging.getLogger(__name__)
HARVARD_DATA = os.path.join(DATA_DIR, "harvard")
def harvard(path=HARVARD_DATA):
"""Return a generator that iterates over all harvard records with complete metadata.
:param str path: path to directory with harvard .mrc files
:return: Generator[:class:`MetaData`] (filtered for records that have ISBNs)
"""
for meta in marc21_dir_reader(path):
if all((meta.isbn, meta.title, meta.author)) and not isbnlib.notisbn(meta.isbn):
# Basic cleanup
try:
isbn = isbnlib.to_isbn13(meta.isbn)
title = meta.title.strip("/").strip().split(" : ")[0]
cleaned = MetaData(isbn, title, meta.author)
except Exception:
log.exception("Error parsing data")
continue
log.debug(cleaned)
yield cleaned
def marc21_dir_reader(path=HARVARD_DATA):
"""Return a generator that iterates over all harvard marc21 files in a
directory and yields parsed MetaData objects from those files.
:param str path: path to directory with harvard .mrc files
:return: Generator[:class:`MetaData`]
"""
for marc21_file_name in os.listdir(path):
marc21_file_path = os.path.join(path, marc21_file_name)
log.info("Reading harvard marc21 file: {}".format(marc21_file_name))
for meta_record in marc21_file_reader(marc21_file_path):
yield meta_record
def marc21_file_reader(file_path):
"""Return a generator that yields parsed MetaData records from a harvard marc21 file.
:param str file_path: path to harvard marc21 file
:return: Generator[:class:`MetaData`]
"""
with open(file_path, "rb") as mf:
reader = MARCReader(mf, utf8_handling="ignore")
while True:
try:
record = next(reader)
yield MetaData(record.isbn(), record.title(), record.author())
except UnicodeDecodeError as e:
log.error(e)
continue
except StopIteration:
break
if __name__ == "__main__":
"""Demo usage."""
# logging.basicConfig(level=logging.DEBUG)
for entry in harvard():
# Do something with entry (MetaData object)
print(entry)
| bsd-2-clause |
fetus-hina/tarte | tarte/components/Twitter/TwitterUserStream.php | 17297 | <?php
class TwitterUserStream extends CComponent {
const WATCHDOG_TIMEOUT = 1200;
private $screen_name, $id, $socket, $watchdog;
private $is_chunked = false, $chunk_buffer = '';
public function __construct($screen_name) {
$this->screen_name = $screen_name;
$this->id = $this->getUserId();
}
public function __destruct() {
$this->close();
}
public function getScreenName() {
return $this->screen_name;
}
public function init() {
Yii::trace(__METHOD__ . '()...', 'twitter');
$this->open();
Yii::trace(__METHOD__ . '() ok', 'twitter');
}
public function run() {
Yii::trace(__METHOD__ . '()...', 'twitter');
if(!$this->socket) {
$this->open();
}
$is_idle = false;
$this->watchdog = microtime(true);
while(true) {
if($this->dispatch()) {
$is_idle = false;
$this->watchdog = microtime(true);
continue;
}
if(microtime(true) - $this->watchdog >= self::WATCHDOG_TIMEOUT) {
$this->onWatchdogTimeout();
break;
}
if($is_idle) {
$this->onIdling();
continue;
}
$is_idle = true;
$this->onIdleStart();
}
}
public function getUserId() {
if(!is_null($this->id)) {
return $this->id;
}
Yii::trace(__METHOD__ . '() begin');
$twitter = new Twitter($this->screen_name);
$user = $twitter->accountVerifyCredentials(array('skip_status' => 'true'));
if(!$user || !$user instanceof TwUser || $user->id == '') {
throw new CException(__METHOD__ . '(): アカウント情報が確認できません');
}
if(strtolower($user->screen_name) !== strtolower($this->screen_name)) {
Yii::log(
sprintf(
'%s(): アカウント情報が違います config=%s, real=%s',
__METHOD__, $this->screen_name, $user->screen_name
),
'error', 'twitter'
);
throw new CException(
__METHOD__ . '(): アカウント情報が違います ' .
strtolower($user->screen_name) . ' vs ' . strtolower($this->screen_name)
);
}
Yii::trace(__METHOD__ . '() end. id=' . $user->id);
return $this->id = $user->id;
}
private function close() {
$this->disconnect();
}
private function open() {
$this->close();
$uri = Zend_Uri::factory('https://userstream.twitter.com/1.1/user.json');
$this->connect($uri);
$this->handshake($uri);
}
private function disconnect() {
if($this->socket) {
$this->onBeginDisconnect();
@fclose($this->socket);
$this->socket = null;
$this->onAfterDisconnect();
}
}
private function connect($uri) {
$socket_host = (strtolower($uri->getScheme()) === 'https' ? 'ssl://' : '') . $uri->getHost();
$socket_port =
($uri->getPort() > 0)
? $uri->getPort()
: (strtolower($uri->getScheme()) === 'https' ? 443 : 80);
$this->onBeginConnect();
if(!$this->socket = @fsockopen($socket_host, $socket_port)) {
throw new CException($uri->getHost() . 'に接続できません');
}
$this->onAfterConnect();
}
private function writeLn($text) {
if(!fwrite($this->socket, $text . "\x0d\x0a")) {
throw new CException('ソケットに書き込めません。接続が閉じられた?');
}
}
private function readline() {
if(feof($this->socket)) {
throw new CException('ソケットから読み込めません。接続が閉じられた?');
}
return fgets($this->socket);
}
private function readBodyLine() {
if(!$this->is_chunked) {
return $this->readline();
}
while(strpos($this->chunk_buffer, "\x0d\x0a") === false) {
$chunk_size_hex = trim($this->readline());
if(substr($chunk_size_hex, 0, 1) === '0') { // last-chunk = 1*("0") [ chunk-extension ] CRLF
throw new CException('ストリームの終端に達しました');
}
if(!preg_match('/^([[:xdigit:]]+)(?:$|;)/', $chunk_size_hex, $match)) { // chunk-size [ chunk-extension ] CRLF
throw new CException('チャンクサイズが不正な形式です');
}
$tmp = fread($this->socket, hexdec($match[1]));
if($tmp === false) {
throw new CException('ソケットから読み込めません。接続が閉じられた?');
}
if(strlen($tmp) !== hexdec($match[1])) {
throw new CException('ソケットから読み込めません。接続が閉じられた?');
}
$this->chunk_buffer .= $tmp;
if(fread($this->socket, 2) !== "\x0d\x0a") {
throw new CException('チャンク終端が一致しません');
}
}
if(!preg_match('/^.*?(?:\x0d\x0a|\x0d|\x0a)/', $this->chunk_buffer, $match)) {
throw new CException('BUG: 改行が見つからない');
}
$this->chunk_buffer = substr($this->chunk_buffer, strlen($match[0]));
return $match[0];
}
private function isSocketReadable($timeout_usec = null) {
if(is_null($timeout_usec)) {
$timeout_usec = mt_rand(1 * 1000 * 1000, 2 * 1000 * 1000);
}
$read = array($this->socket);
$write = null;
$expect = null;
$status = stream_select($read, $write, $expect, 0, $timeout_usec);
if($status === false) {
throw new CException('ソケットに異常発生。接続が閉じられた?');
}
return $status > 0;
}
private function handshake($uri) {
$this->onBeginHandshake();
$this->sendRequest($uri);
$resp = $this->recvResponseHeader();
if(!$resp->isSuccessful()) {
throw new CException('ストリームに接続できません');
}
$this->is_chunked = stripos($resp->getHeader('Transfer-Encoding'), 'chunked') !== false;
$this->onAfterHandshake();
}
private function sendRequest($uri) {
$this->onBeginRequest();
foreach($this->buildRequestHeaders($uri) as $line) {
$this->writeLn($line);
}
$this->writeLn('');
$this->onAfterRequest();
}
private function buildRequestHeaders($uri) {
$ret = array();
$path = $uri->getPath() . ($uri->getQuery() != '' ? '?' . $uri->getQuery() : '');
$ret[] = sprintf('GET %s HTTP/1.1', $path);
$host = strtolower($uri->getHost());
$port = (int)$uri->getPort();
if($port > 0) {
if((strtolower($uri->getScheme()) !== 'https' && $port !== 443) ||
(strtolower($uri->getScheme()) !== 'http' && $port !== 80))
{
$host .= ':' . (string)$port;
}
}
$ret[] = sprintf('Host: %s', $host);
$ret[] = sprintf('User-Agent: %s', HttpClient::getUserAgent());
$ret[] = sprintf('Authorization: %s', $this->getOAuthConfig()->getAuthorizationHeader('GET', $uri));
return $ret;
}
private function recvResponseHeader() {
$data = '';
while(true) {
$line = $this->readline();
$data .= $line;
if(trim($line) === '') {
return Zend_Http_Response::fromString($data);
}
}
}
private function getOAuthConfig() {
$config = BotConfig::factory($this->screen_name);
$oauth = Yii::app()->oauth;
$oauth->user = $config->oauth;
return $oauth;
}
private function dispatch() {
if(!$this->isSocketReadable()) {
return false;
}
$line = trim($this->readBodyLine());
if($line === '') {
return false;
}
if($json = Zend_Json::decode($line)) {
if(isset($json['text'])) {
$this->onStatus($json);
} elseif(isset($json['event'])) {
switch($json['event']) {
case 'block': $this->onBlock($json); break;
case 'unblock': $this->onUnblock($json); break;
case 'favorite': $this->onFavorite($json); break;
case 'unfavorite': $this->onUnfavorite($json); break;
case 'follow': $this->onFollow($json); break;
case 'unfollow': $this->onUnfollow($json); break;
case 'list_created': $this->onListCreated($json); break;
case 'list_destroyed': $this->onListDestroyed($json); break;
case 'list_updated': $this->onListUpdated($json); break;
case 'list_member_added': $this->onListMemberAdded($json); break;
case 'list_member_removed': $this->onListMemberRemoved($json); break;
case 'list_user_subscribed': $this->onListUserSubscribed($json); break;
case 'list_user_unsubscribed': $this->onListUserUnsubscribed($json); break;
case 'user_update': $this->onUserUpdate($json); break;
}
}
}
return true;
}
private function onBeginDisconnect() {
$this->raiseEvent('onBeginDisconnect', new TwitterEvent($this));
}
private function onAfterDisconnect() {
$this->raiseEvent('onAfterDisconnect', new TwitterEvent($this));
}
private function onBeginConnect() {
$this->raiseEvent('onBeginConnect', new TwitterEvent($this));
}
private function onAfterConnect() {
$this->raiseEvent('onAfterConnect', new TwitterEvent($this));
}
private function onBeginHandshake() {
$this->raiseEvent('onBeginHandshake', new TwitterEvent($this));
}
private function onAfterHandshake() {
$this->raiseEvent('onAfterHandshake', new TwitterEvent($this));
}
private function onBeginRequest() {
$this->raiseEvent('onBeginRequest', new TwitterEvent($this));
}
private function onAfterRequest() {
$this->raiseEvent('onAfterRequest', new TwitterEvent($this));
}
private function onIdling() {
Yii::trace(__METHOD__, 'twitter');
$this->raiseEvent('onIdling', new TwitterEvent($this));
}
private function onIdleStart() {
Yii::trace(__METHOD__, 'twitter');
$this->raiseEvent('onIdleStart', new TwitterEvent($this));
}
private function onWatchdogTimeout() {
Yii::trace(__METHOD__, 'twitter');
$this->raiseEvent('onWatchdogTimeout', new TwitterEvent($this));
}
private function onStatus(array $json) {
Yii::trace(__METHOD__, 'twitter');
$this->raiseEvent(
'onStatus',
new TwitterEvent(
$this,
TwStatus::factory($json, 'TwStatus')
));
}
private function onBlock(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onUnblock(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onFavorite(array $json) {
Yii::trace(__METHOD__, 'twitter');
$source = TwUser::factory($json['source'], 'TwUser');
$target = TwUser::factory($json['target'], 'TwUser');
$tweet = TwStatus::factory($json['target_object'], 'TwStatus');
$this->raiseEvent(
'onFavorite',
new TwitterEvent(
$this,
array(
'source' => $source,
'target' => $target,
'status' => $tweet,
)
)
);
if($source->id == $this->id) {
$this->onUserFavoritesATweet($target, $tweet);
} elseif($target->id == $this->id) {
$this->onUsersTweetIsFavorited($source, $tweet);
}
}
private function onUserFavoritesATweet(TwUser $user, TwStatus $tweet) {
$this->raiseEvent(
'onUserFavoritesATweet',
new TwitterEvent(
$this,
array(
'user' => $user,
'status' => $tweet,
)
)
);
}
private function onUsersTweetIsFavorited(TwUser $user, TwStatus $tweet) {
$this->raiseEvent(
'onUsersTweetIsFavorited',
new TwitterEvent(
$this,
array(
'user' => $user,
'status' => $tweet,
)
)
);
}
private function onUnfavorite(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onFollow(array $json) {
Yii::trace(__METHOD__, 'twitter');
$source = TwStatus::factory($json['source'], 'TwUser');
$target = TwStatus::factory($json['target'], 'TwUser');
$this->raiseEvent(
'onFollow',
new TwitterEvent(
$this,
array(
'source' => $source,
'target' => $target,
)
)
);
if($source->id == $this->id) {
$this->onUserFollowsSomeone($target);
} elseif($target->id == $this->id) {
$this->onUserIsFollowed($source);
}
}
private function onUserFollowsSomeone(TwUser $user) {
$this->raiseEvent('onUserFollowsSomeone', new TwitterEvent($this, $user));
}
private function onUserIsFollowed(TwUser $user) {
$this->raiseEvent('onUserIsFollowed', new TwitterEvent($this, $user));
}
private function onUnfollow(array $json) {
Yii::trace(__METHOD__, 'twitter');
$source = TwStatus::factory($json['source'], 'TwUser');
$target = TwStatus::factory($json['target'], 'TwUser');
$this->raiseEvent(
'onUnfollow',
new TwitterEvent(
$this,
array(
'source' => $source,
'target' => $target,
)
)
);
if($source->id == $this->id) {
$this->onUserUnfollowsSomeone($target);
} elseif($target->id == $this->id) {
$this->onUserIsUnfollowed($source);
}
}
private function onUserUnfollowsSomeone(TwUser $user) {
$this->raiseEvent('onUserUnfollowsSomeone', new TwitterEvent($this, $user));
}
private function onUserIsUnfollowed(TwUser $user) {
$this->raiseEvent('onUserIsUnfollowed', new TwitterEvent($this, $user));
}
private function onListCreated(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onListDestroyed(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onListUpdated(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onListMemberAdded(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onListMemberRemoved(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onListUserSubscribed(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onListUserUnsubscribed(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
private function onUserUpdate(array $json) {
Yii::trace(__METHOD__, 'twitter');
Yii::log(__METHOD__ . '(): Not impl.', 'info', 'twitter');
}
}
| bsd-2-clause |
linkedin-inc/redis | redis_test.go | 5164 | package redis_test
import (
"bytes"
"net"
"github.com/linkedin-inc/redis"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Client", func() {
var client *redis.Client
BeforeEach(func() {
client = redis.NewClient(redisOptions())
Expect(client.FlushDb().Err()).To(BeNil())
})
AfterEach(func() {
client.Close()
})
It("should Stringer", func() {
Expect(client.String()).To(Equal("Redis<:6380 db:15>"))
})
It("should ping", func() {
val, err := client.Ping().Result()
Expect(err).NotTo(HaveOccurred())
Expect(val).To(Equal("PONG"))
})
It("should return pool stats", func() {
Expect(client.PoolStats()).To(BeAssignableToTypeOf(&redis.PoolStats{}))
})
It("should support custom dialers", func() {
custom := redis.NewClient(&redis.Options{
Addr: ":1234",
Dialer: func() (net.Conn, error) {
return net.Dial("tcp", redisAddr)
},
})
val, err := custom.Ping().Result()
Expect(err).NotTo(HaveOccurred())
Expect(val).To(Equal("PONG"))
Expect(custom.Close()).NotTo(HaveOccurred())
})
It("should close", func() {
Expect(client.Close()).NotTo(HaveOccurred())
err := client.Ping().Err()
Expect(err).To(MatchError("redis: client is closed"))
})
It("should close pubsub without closing the client", func() {
pubsub := client.PubSub()
Expect(pubsub.Close()).NotTo(HaveOccurred())
_, err := pubsub.Receive()
Expect(err).To(MatchError("redis: client is closed"))
Expect(client.Ping().Err()).NotTo(HaveOccurred())
})
It("should close multi without closing the client", func() {
multi := client.Multi()
Expect(multi.Close()).NotTo(HaveOccurred())
_, err := multi.Exec(func() error {
multi.Ping()
return nil
})
Expect(err).To(MatchError("redis: client is closed"))
Expect(client.Ping().Err()).NotTo(HaveOccurred())
})
It("should close pipeline without closing the client", func() {
pipeline := client.Pipeline()
Expect(pipeline.Close()).NotTo(HaveOccurred())
pipeline.Ping()
_, err := pipeline.Exec()
Expect(err).To(MatchError("redis: client is closed"))
Expect(client.Ping().Err()).NotTo(HaveOccurred())
})
It("should close pubsub when client is closed", func() {
pubsub := client.PubSub()
Expect(client.Close()).NotTo(HaveOccurred())
Expect(pubsub.Close()).NotTo(HaveOccurred())
})
It("should close multi when client is closed", func() {
multi := client.Multi()
Expect(client.Close()).NotTo(HaveOccurred())
Expect(multi.Close()).NotTo(HaveOccurred())
})
It("should close pipeline when client is closed", func() {
pipeline := client.Pipeline()
Expect(client.Close()).NotTo(HaveOccurred())
Expect(pipeline.Close()).NotTo(HaveOccurred())
})
It("should select DB", func() {
db2 := redis.NewClient(&redis.Options{
Addr: redisAddr,
DB: 2,
})
Expect(db2.FlushDb().Err()).NotTo(HaveOccurred())
Expect(db2.Get("db").Err()).To(Equal(redis.Nil))
Expect(db2.Set("db", 2, 0).Err()).NotTo(HaveOccurred())
n, err := db2.Get("db").Int64()
Expect(err).NotTo(HaveOccurred())
Expect(n).To(Equal(int64(2)))
Expect(client.Get("db").Err()).To(Equal(redis.Nil))
Expect(db2.FlushDb().Err()).NotTo(HaveOccurred())
Expect(db2.Close()).NotTo(HaveOccurred())
})
It("should process custom commands", func() {
cmd := redis.NewCmd("PING")
client.Process(cmd)
Expect(cmd.Err()).NotTo(HaveOccurred())
Expect(cmd.Val()).To(Equal("PONG"))
})
It("should retry command on network error", func() {
Expect(client.Close()).NotTo(HaveOccurred())
client = redis.NewClient(&redis.Options{
Addr: redisAddr,
MaxRetries: 1,
})
// Put bad connection in the pool.
cn, err := client.Pool().Get()
Expect(err).NotTo(HaveOccurred())
cn.NetConn = &badConn{}
err = client.Pool().Put(cn)
Expect(err).NotTo(HaveOccurred())
err = client.Ping().Err()
Expect(err).NotTo(HaveOccurred())
})
It("should update conn.UsedAt on read/write", func() {
cn, err := client.Pool().Get()
Expect(err).NotTo(HaveOccurred())
Expect(cn.UsedAt).NotTo(BeZero())
createdAt := cn.UsedAt
err = client.Pool().Put(cn)
Expect(err).NotTo(HaveOccurred())
Expect(cn.UsedAt.Equal(createdAt)).To(BeTrue())
err = client.Ping().Err()
Expect(err).NotTo(HaveOccurred())
cn, err = client.Pool().Get()
Expect(err).NotTo(HaveOccurred())
Expect(cn).NotTo(BeNil())
Expect(cn.UsedAt.After(createdAt)).To(BeTrue())
})
It("should escape special chars", func() {
set := client.Set("key", "hello1\r\nhello2\r\n", 0)
Expect(set.Err()).NotTo(HaveOccurred())
Expect(set.Val()).To(Equal("OK"))
get := client.Get("key")
Expect(get.Err()).NotTo(HaveOccurred())
Expect(get.Val()).To(Equal("hello1\r\nhello2\r\n"))
})
It("should handle big vals", func() {
bigVal := string(bytes.Repeat([]byte{'*'}, 1<<17)) // 128kb
err := client.Set("key", bigVal, 0).Err()
Expect(err).NotTo(HaveOccurred())
// Reconnect to get new connection.
Expect(client.Close()).To(BeNil())
client = redis.NewClient(redisOptions())
got, err := client.Get("key").Result()
Expect(err).NotTo(HaveOccurred())
Expect(len(got)).To(Equal(len(bigVal)))
Expect(got).To(Equal(bigVal))
})
})
| bsd-2-clause |
PetterS/easy-IP | third-party/gecode/test/int/rel.cpp | 19851 | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2005
*
* Last modified:
* $Date: 2011-11-29 17:20:37 +0100 (ti, 29 nov 2011) $ by $Author: schulte $
* $Revision: 12486 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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.
*
*/
#include "test/int.hh"
#include <gecode/minimodel.hh>
namespace Test { namespace Int {
/// %Tests for relation constraints
namespace Rel {
/**
* \defgroup TaskTestIntRel Relation constraints
* \ingroup TaskTestInt
*/
//@{
/// %Test for simple relation involving integer variables
class IntVarXY : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
IntVarXY(Gecode::IntRelType irt0, int n, Gecode::IntConLevel icl)
: Test("Rel::Int::Var::XY::"+str(irt0)+"::"+str(icl)+"::"+str(n),
n+1,-3,3,n==1,icl),
irt(irt0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
if (x.size() == 2) {
return cmp(x[0],irt,x[1]);
} else {
return cmp(x[0],irt,x[2]) && cmp(x[1],irt,x[2]);
}
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
if (x.size() == 2) {
rel(home, x[0], irt, x[1], icl);
} else {
IntVarArgs y(2);
y[0]=x[0]; y[1]=x[1];
rel(home, y, irt, x[2], icl);
}
}
/// Post reified constraint on \a x for \a r
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x,
Gecode::Reify r) {
assert(x.size() == 2);
Gecode::rel(home, x[0], irt, x[1], r, icl);
}
};
/// %Test for simple relation involving shared integer variables
class IntVarXX : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
IntVarXX(Gecode::IntRelType irt0, Gecode::IntConLevel icl)
: Test("Rel::Int::Var::XX::"+str(irt0)+"::"+str(icl),
1,-3,3,true,icl),
irt(irt0) {
contest = ((irt != Gecode::IRT_LE) &&
(irt != Gecode::IRT_GR) &&
(irt != Gecode::IRT_NQ))
? CTL_DOMAIN : CTL_NONE;
}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
return cmp(x[0],irt,x[0]);
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
Gecode::rel(home, x[0], irt, x[0], icl);
}
/// Post reified constraint on \a x for \a r
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x,
Gecode::Reify r) {
Gecode::rel(home, x[0], irt, x[0], r, icl);
}
};
/// %Test for simple relation involving Boolean variables
class BoolVarXY : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
BoolVarXY(Gecode::IntRelType irt0, int n)
: Test("Rel::Bool::Var::XY::"+str(irt0)+"::"+str(n),n+1,0,1,
n==1),
irt(irt0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
if (x.size() == 2) {
return cmp(x[0],irt,x[1]);
} else {
return cmp(x[0],irt,x[2]) && cmp(x[1],irt,x[2]);
}
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
if (x.size() == 2) {
rel(home, channel(home,x[0]), irt, channel(home,x[1]));
} else {
BoolVarArgs y(2);
y[0]=channel(home,x[0]); y[1]=channel(home,x[1]);
rel(home, y, irt, channel(home,x[2]));
}
}
/// Post reified constraint on \a x for \a r
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x,
Gecode::Reify r) {
assert(x.size() == 2);
using namespace Gecode;
rel(home,
channel(home,x[0]), irt, channel(home,x[1]),
r);
}
};
/// %Test for simple relation involving shared Boolean variables
class BoolVarXX : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
BoolVarXX(Gecode::IntRelType irt0)
: Test("Rel::Bool::Var::XX::"+str(irt0),1,0,1),
irt(irt0) {
contest = ((irt != Gecode::IRT_LE) &&
(irt != Gecode::IRT_GR) &&
(irt != Gecode::IRT_NQ))
? CTL_DOMAIN : CTL_NONE;
}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
return cmp(x[0],irt,x[0]);
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
Gecode::BoolVar b = Gecode::channel(home,x[0]);
Gecode::rel(home, b, irt, b);
}
};
/// %Test for simple relation involving integer variable and integer constant
class IntInt : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
/// Integer constant
int c;
public:
/// Create and register test
IntInt(Gecode::IntRelType irt0, int n, int c0)
: Test("Rel::Int::Int::"+str(irt0)+"::"+str(n)+"::"+str(c0),
n,-3,3,n==1),
irt(irt0), c(c0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
if (x.size() == 1)
return cmp(x[0],irt,c);
else
return cmp(x[0],irt,c) && cmp(x[1],irt,c);
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
if (x.size() == 1)
rel(home, x[0], irt, c);
else
rel(home, x, irt, c);
}
/// Post reified constraint on \a x for \a r
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x,
Gecode::Reify r) {
assert(x.size() == 1);
Gecode::rel(home, x[0], irt, c, r);
}
};
/// %Test for simple relation involving Boolean variable and integer constant
class BoolInt : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
/// Integer constant
int c;
public:
/// Create and register test
BoolInt(Gecode::IntRelType irt0, int n, int c0)
: Test("Rel::Bool::Int::"+str(irt0)+"::"+str(n)+"::"+str(c0),n,0,1,
n==1),
irt(irt0), c(c0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
if (x.size() == 1)
return cmp(x[0],irt,c);
else
return cmp(x[0],irt,c) && cmp(x[1],irt,c);
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
if (x.size() == 1) {
rel(home, channel(home,x[0]), irt, c);
} else {
BoolVarArgs y(2);
y[0]=channel(home,x[0]); y[1]=channel(home,x[1]);
rel(home, y, irt, c);
}
}
/// Post reified constraint on \a x for \a r
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x,
Gecode::Reify r) {
assert(x.size() == 1);
using namespace Gecode;
rel(home, channel(home,x[0]), irt, c, r);
}
};
/// %Test for sequence of relations between integer variables
class IntSeq : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
IntSeq(int n, Gecode::IntRelType irt0, Gecode::IntConLevel icl)
: Test("Rel::Int::Seq::"+str(n)+"::"+str(irt0)+"::"+str(icl),
n,-3,3,false,icl),
irt(irt0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
if (irt == Gecode::IRT_NQ) {
if (x.size() < 2)
return false;
for (int i=0; i<x.size()-1; i++)
if (x[i] != x[i+1])
return true;
return false;
} else {
for (int i=0; i<x.size()-1; i++)
if (!cmp(x[i],irt,x[i+1]))
return false;
return true;
}
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
Gecode::rel(home, x, irt, icl);
}
};
/// %Test for sequence of relations between shared integer variables
class IntSharedSeq : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
IntSharedSeq(int n, Gecode::IntRelType irt0, Gecode::IntConLevel icl)
: Test("Rel::Int::Seq::Shared::"+str(n)+"::"+str(irt0)+"::"+str(icl),
n,-3,3,false,icl),
irt(irt0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
if (irt == Gecode::IRT_NQ) {
if (x.size() < 2)
return false;
for (int i=0; i<x.size()-1; i++)
if (x[i] != x[i+1])
return true;
return false;
} else {
int n = x.size();
for (int i=0; i<2*n-1; i++)
if (!cmp(x[i % n],irt,x[(i+1) % n]))
return false;
return true;
}
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
int n = x.size();
IntVarArgs y(2*n);
for (int i=n; i--; )
y[i] = y[n+i] = x[i];
rel(home, y, irt, icl);
}
};
/// %Test for sequence of relations between Boolean variables
class BoolSeq : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
BoolSeq(int n, Gecode::IntRelType irt0)
: Test("Rel::Bool::Seq::"+str(n)+"::"+str(irt0),n,0,1),
irt(irt0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
if (irt == Gecode::IRT_NQ) {
if (x.size() < 2)
return false;
for (int i=0; i<x.size()-1; i++)
if (x[i] != x[i+1])
return true;
return false;
} else {
for (int i=0; i<x.size()-1; i++)
if (!cmp(x[i],irt,x[i+1]))
return false;
return true;
}
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
BoolVarArgs b(x.size());
for (int i=x.size(); i--; )
b[i]=channel(home,x[i]);
rel(home, b, irt);
}
};
/// %Test for sequence of relations between shared Boolean variables
class BoolSharedSeq : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
BoolSharedSeq(int n, Gecode::IntRelType irt0)
: Test("Rel::Bool::Seq::Shared::"+str(n)+"::"+str(irt0),n,0,1),
irt(irt0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
if (irt == Gecode::IRT_NQ) {
if (x.size() < 2)
return false;
for (int i=0; i<x.size()-1; i++)
if (x[i] != x[i+1])
return true;
return false;
} else {
int n = x.size();
for (int i=0; i<2*n-1; i++)
if (!cmp(x[i % n],irt,x[(i+1) % n]))
return false;
return true;
}
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
int n = x.size();
BoolVarArgs b(2*n);
for (int i=n; i--; )
b[i]=b[n+i]=channel(home,x[i]);
rel(home, b, irt);
}
};
/// %Test for relation between same sized arrays of integer variables
class IntArray : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
IntArray(Gecode::IntRelType irt0)
: Test("Rel::Int::Array::"+str(irt0),6,-2,2), irt(irt0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
int n=x.size() >> 1;
for (int i=0; i<n; i++)
if (x[i] != x[n+i])
return cmp(x[i],irt,x[n+i]);
return ((irt == Gecode::IRT_LQ) || (irt == Gecode::IRT_GQ) ||
(irt == Gecode::IRT_EQ));
GECODE_NEVER;
return false;
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
int n=x.size() >> 1;
IntVarArgs y(n); IntVarArgs z(n);
for (int i=0; i<n; i++) {
y[i]=x[i]; z[i]=x[n+i];
}
rel(home, y, irt, z);
}
};
/// %Test for relation between differently sized arrays of integer variables
class IntArrayDiff : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
/// How many variables in total
static const int n = 4;
/// How big is the first array
int n_fst;
public:
/// Create and register test
IntArrayDiff(Gecode::IntRelType irt0, int m)
: Test("Rel::Int::Array::"+str(irt0)+"::"+str(m)+"::"+str(n-m),
n,-2,2),
irt(irt0), n_fst(m) {
assert(n_fst <= n);
}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
int n_snd = n - n_fst;
for (int i=0; i<std::min(n_fst,n_snd); i++)
if (x[i] != x[n_fst+i])
return cmp(x[i],irt,x[n_fst+i]);
return cmp(n_fst,irt,n_snd);
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
int n_snd = n - n_fst;
IntVarArgs y(n_fst); IntVarArgs z(n_snd);
for (int i=0; i<n_fst; i++) {
y[i]=x[i];
}
for (int i=0; i<n_snd; i++) {
z[i]=x[n_fst + i];
}
rel(home, y, irt, z);
}
};
/// %Test for relation between arrays of Boolean variables
class BoolArray : public Test {
protected:
/// Integer relation type to propagate
Gecode::IntRelType irt;
public:
/// Create and register test
BoolArray(Gecode::IntRelType irt0)
: Test("Rel::Bool::Array::"+str(irt0),10,0,1), irt(irt0) {}
/// %Test whether \a x is solution
virtual bool solution(const Assignment& x) const {
int n=x.size() >> 1;
for (int i=0; i<n; i++)
if (x[i] != x[n+i])
return cmp(x[i],irt,x[n+i]);
return ((irt == Gecode::IRT_LQ) || (irt == Gecode::IRT_GQ) ||
(irt == Gecode::IRT_EQ));
GECODE_NEVER;
return false;
}
/// Post constraint on \a x
virtual void post(Gecode::Space& home, Gecode::IntVarArray& x) {
using namespace Gecode;
int n=x.size() >> 1;
BoolVarArgs y(n); BoolVarArgs z(n);
for (int i=0; i<n; i++) {
y[i]=channel(home,x[i]); z[i]=channel(home,x[n+i]);
}
rel(home, y, irt, z);
}
};
/// Help class to create and register tests
class Create {
public:
/// Perform creation and registration
Create(void) {
using namespace Gecode;
for (IntRelTypes irts; irts(); ++irts) {
for (IntConLevels icls; icls(); ++icls) {
(void) new IntVarXY(irts.irt(),1,icls.icl());
(void) new IntVarXY(irts.irt(),2,icls.icl());
(void) new IntVarXX(irts.irt(),icls.icl());
(void) new IntSeq(1,irts.irt(),icls.icl());
(void) new IntSeq(2,irts.irt(),icls.icl());
(void) new IntSeq(3,irts.irt(),icls.icl());
(void) new IntSeq(5,irts.irt(),icls.icl());
(void) new IntSharedSeq(1,irts.irt(),icls.icl());
(void) new IntSharedSeq(2,irts.irt(),icls.icl());
(void) new IntSharedSeq(3,irts.irt(),icls.icl());
(void) new IntSharedSeq(4,irts.irt(),icls.icl());
}
(void) new BoolVarXY(irts.irt(),1);
(void) new BoolVarXY(irts.irt(),2);
(void) new BoolVarXX(irts.irt());
(void) new BoolSeq(1,irts.irt());
(void) new BoolSeq(2,irts.irt());
(void) new BoolSeq(3,irts.irt());
(void) new BoolSeq(10,irts.irt());
(void) new BoolSharedSeq(1,irts.irt());
(void) new BoolSharedSeq(2,irts.irt());
(void) new BoolSharedSeq(3,irts.irt());
(void) new BoolSharedSeq(4,irts.irt());
(void) new BoolSharedSeq(8,irts.irt());
for (int c=-4; c<=4; c++) {
(void) new IntInt(irts.irt(),1,c);
(void) new IntInt(irts.irt(),2,c);
}
for (int c=0; c<=1; c++) {
(void) new BoolInt(irts.irt(),1,c);
(void) new BoolInt(irts.irt(),2,c);
}
(void) new IntArray(irts.irt());
for (int n_fst=0; n_fst<=4; n_fst++)
(void) new IntArrayDiff(irts.irt(),n_fst);
(void) new BoolArray(irts.irt());
}
}
};
Create c;
//@}
}
}}
// STATISTICS: test-int
| bsd-2-clause |
kerwinxu/barcodeManager | zxing/cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/dvi.py | 2450 | """SCons.Tool.dvi
Common DVI Builder definition for various other Tool modules that use it.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# 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.
#
__revision__ = "src/engine/SCons/Tool/dvi.py 5023 2010/06/14 22:05:46 scons"
import SCons.Builder
import SCons.Tool
DVIBuilder = None
def generate(env):
try:
env['BUILDERS']['DVI']
except KeyError:
global DVIBuilder
if DVIBuilder is None:
# The suffix is hard-coded to '.dvi', not configurable via a
# construction variable like $DVISUFFIX, because the output
# file name is hard-coded within TeX.
DVIBuilder = SCons.Builder.Builder(action = {},
source_scanner = SCons.Tool.LaTeXScanner,
suffix = '.dvi',
emitter = {},
source_ext_match = None)
env['BUILDERS']['DVI'] = DVIBuilder
def exists(env):
# This only puts a skeleton Builder in place, so if someone
# references this Tool directly, it's always "available."
return 1
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| bsd-2-clause |
jalabort/ijcv-2014-aam | aam/image/test/image_test.py | 18144 | import warnings
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from nose.tools import raises
from menpo.testing import is_same_array
from menpo.image import BooleanImage, MaskedImage, Image
@raises(ValueError)
def test_create_1d_error():
Image(np.ones(1))
def test_image_n_elements():
image = Image(np.ones((10, 10, 3)))
assert(image.n_elements == 10 * 10 * 3)
def test_image_width():
image = Image(np.ones((6, 4, 3)))
assert(image.width == 4)
def test_image_height():
image = Image(np.ones((6, 4, 3)))
assert(image.height == 6)
def test_image_blank():
image = Image(np.zeros((6, 4, 1)))
image_blank = Image.blank((6, 4))
assert(np.all(image_blank.pixels == image.pixels))
def test_image_blank_fill():
image = Image(np.ones((6, 4, 1)) * 7)
image_blank = Image.blank((6, 4), fill=7)
assert(np.all(image_blank.pixels == image.pixels))
def test_image_blank_n_channels():
image = Image(np.zeros((6, 4, 7)))
image_blank = Image.blank((6, 4), n_channels=7)
assert(np.all(image_blank.pixels == image.pixels))
def test_image_centre():
pixels = np.ones((10, 20, 1))
image = Image(pixels)
assert(np.all(image.centre == np.array([5, 10])))
def test_image_str_shape_4d():
pixels = np.ones((10, 20, 11, 12, 1))
image = Image(pixels)
assert(image._str_shape == '10 x 20 x 11 x 12')
def test_image_str_shape_2d():
pixels = np.ones((10, 20, 1))
image = Image(pixels)
assert(image._str_shape == '20W x 10H')
def test_image_as_vector():
pixels = np.random.rand(10, 20, 1)
image = Image(pixels)
assert(np.all(image.as_vector() == pixels.ravel()))
def test_image_as_vector_keep_channels():
pixels = np.random.rand(10, 20, 2)
image = Image(pixels)
assert(np.all(image.as_vector(keep_channels=True) ==
pixels.reshape([-1, 2])))
def test_image_from_vector():
pixels = np.random.rand(10, 20, 2)
pixels2 = np.random.rand(10, 20, 2)
image = Image(pixels)
image2 = image.from_vector(pixels2.ravel())
assert(np.all(image2.pixels == pixels2))
def test_image_from_vector_custom_channels():
pixels = np.random.rand(10, 20, 2)
pixels2 = np.random.rand(10, 20, 3)
image = Image(pixels)
image2 = image.from_vector(pixels2.ravel(), n_channels=3)
assert(np.all(image2.pixels == pixels2))
def test_image_from_vector_no_copy():
pixels = np.random.rand(10, 20, 2)
pixels2 = np.random.rand(10, 20, 2)
image = Image(pixels)
image2 = image.from_vector(pixels2.ravel(), copy=False)
assert(is_same_array(image2.pixels, pixels2))
def test_image_from_vector_inplace_no_copy():
pixels = np.random.rand(10, 20, 2)
pixels2 = np.random.rand(10, 20, 2)
image = Image(pixels)
image.from_vector_inplace(pixels2.ravel(), copy=False)
assert(is_same_array(image.pixels, pixels2))
def test_image_from_vector_inplace_no_copy_warning():
pixels = np.random.rand(10, 20, 2)
pixels2 = np.random.rand(10, 20, 2)
image = Image(pixels)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
image.from_vector_inplace(pixels2.ravel()[::-1], copy=False)
assert len(w) == 1
def test_image_from_vector_inplace_copy_default():
pixels = np.random.rand(10, 20, 2)
pixels2 = np.random.rand(10, 20, 2)
image = Image(pixels)
image.from_vector_inplace(pixels2.ravel())
assert(not is_same_array(image.pixels, pixels2))
def test_image_from_vector_inplace_copy_explicit():
pixels = np.random.rand(10, 20, 2)
pixels2 = np.random.rand(10, 20, 2)
image = Image(pixels)
image.from_vector_inplace(pixels2.ravel(), copy=True)
assert(not is_same_array(image.pixels, pixels2))
def test_image_from_vector_custom_channels_no_copy():
pixels = np.random.rand(10, 20, 2)
pixels2 = np.random.rand(10, 20, 3)
image = Image(pixels)
image2 = image.from_vector(pixels2.ravel(), n_channels=3, copy=False)
assert(is_same_array(image2.pixels, pixels2))
@raises(ValueError)
def test_boolean_image_wrong_round():
BooleanImage.blank((12, 12), round='ads')
def test_boolean_image_proportion_true():
image = BooleanImage.blank((10, 10))
image.pixels[:7] = False
assert(image.proportion_true == 0.3)
def test_boolean_image_proportion_false():
image = BooleanImage.blank((10, 10))
image.pixels[:7] = False
assert(image.proportion_false == 0.7)
def test_boolean_image_proportion_sums():
image = BooleanImage.blank((10, 10))
image.pixels[:7] = False
assert(image.proportion_true + image.proportion_false == 1)
def test_boolean_image_false_indices():
image = BooleanImage.blank((2, 3))
image.pixels[0, 1] = False
image.pixels[1, 2] = False
assert(np.all(image.false_indices == np.array([[0, 1],
[1, 2]])))
def test_boolean_image_false_indices():
image = BooleanImage.blank((2, 3))
assert(image.__str__() == '3W x 2H 2D mask, 100.0% of which is True')
def test_boolean_image_from_vector():
vector = np.zeros(16, dtype=np.bool)
image = BooleanImage.blank((4, 4))
image2 = image.from_vector(vector)
assert(np.all(image2.as_vector() == vector))
def test_boolean_image_from_vector_no_copy():
vector = np.zeros(16, dtype=np.bool)
image = BooleanImage.blank((4, 4))
image2 = image.from_vector(vector, copy=False)
assert(is_same_array(image2.pixels.ravel(), vector))
def test_boolean_image_from_vector_no_copy_raises():
vector = np.zeros(16, dtype=np.bool)
image = BooleanImage.blank((4, 4))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
image.from_vector(vector[::-1], copy=False)
assert len(w) == 1
def test_boolean_image_invert_inplace():
image = BooleanImage.blank((4, 4))
image.invert_inplace()
assert(np.all(image.pixels == False))
def test_boolean_image_invert_inplace_double_noop():
image = BooleanImage.blank((4, 4))
image.invert_inplace()
image.invert_inplace()
assert(np.all(image.pixels == True))
def test_boolean_image_invert():
image = BooleanImage.blank((4, 4))
image2 = image.invert()
assert(np.all(image.pixels == True))
assert(np.all(image2.pixels == False))
def test_boolean_bounds_false():
mask = BooleanImage.blank((8, 8), fill=True)
mask.pixels[1, 2] = False
mask.pixels[5, 4] = False
mask.pixels[3:2, 3] = False
min_b, max_b = mask.bounds_false()
assert(np.all(min_b == np.array([1, 2])))
assert(np.all(max_b == np.array([5, 4])))
@raises(ValueError)
def test_boolean_prevent_order_kwarg():
mask = BooleanImage.blank((8, 8), fill=True)
mask.warp_to(mask, None, order=4)
def test_create_image_copy_false():
pixels = np.ones((100, 100, 1))
image = Image(pixels, copy=False)
assert (is_same_array(image.pixels, pixels))
def test_create_image_copy_true():
pixels = np.ones((100, 100, 1))
image = Image(pixels)
assert (not is_same_array(image.pixels, pixels))
def test_create_image_copy_false_not_c_contiguous():
pixels = np.ones((100, 100, 1), order='F')
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
Image(pixels, copy=False)
assert(len(w) == 1)
def mask_image_3d_test():
mask_shape = (120, 121, 13)
mask_region = np.ones(mask_shape)
return BooleanImage(mask_region)
def test_mask_creation_basics():
mask_shape = (120, 121, 3)
mask_region = np.ones(mask_shape)
mask = BooleanImage(mask_region)
assert_equal(mask.n_channels, 1)
assert_equal(mask.n_dims, 3)
assert_equal(mask.shape, mask_shape)
def test_mask_blank():
mask = BooleanImage.blank((56, 12, 3))
assert (np.all(mask.pixels))
def test_boolean_copy_false_boolean():
mask = np.zeros((10, 10), dtype=np.bool)
boolean_image = BooleanImage(mask, copy=False)
assert (is_same_array(boolean_image.pixels, mask))
def test_boolean_copy_true():
mask = np.zeros((10, 10), dtype=np.bool)
boolean_image = BooleanImage(mask)
assert (not is_same_array(boolean_image.pixels, mask))
def test_boolean_copy_false_non_boolean():
mask = np.zeros((10, 10))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
BooleanImage(mask, copy=False)
assert(len(w) == 1)
def test_mask_blank_rounding_floor():
mask = BooleanImage.blank((56.1, 12.1), round='floor')
assert_allclose(mask.shape, (56, 12))
def test_mask_blank_rounding_ceil():
mask = BooleanImage.blank((56.1, 12.1), round='ceil')
assert_allclose(mask.shape, (57, 13))
def test_mask_blank_rounding_round():
mask = BooleanImage.blank((56.1, 12.6), round='round')
assert_allclose(mask.shape, (56, 13))
def test_mask_blank_false_fill():
mask = BooleanImage.blank((56, 12, 3), fill=False)
assert (np.all(~mask.pixels))
def test_mask_n_true_n_false():
mask = BooleanImage.blank((64, 14), fill=False)
assert_equal(mask.n_true, 0)
assert_equal(mask.n_false, 64 * 14)
mask.mask[0, 0] = True
mask.mask[9, 13] = True
assert_equal(mask.n_true, 2)
assert_equal(mask.n_false, 64 * 14 - 2)
def test_mask_true_indices():
mask = BooleanImage.blank((64, 14, 51), fill=False)
mask.mask[0, 2, 5] = True
mask.mask[5, 13, 4] = True
true_indices = mask.true_indices
true_indices_test = np.array([[0, 2, 5], [5, 13, 4]])
assert_equal(true_indices, true_indices_test)
def test_mask_false_indices():
mask = BooleanImage.blank((64, 14, 51), fill=True)
mask.mask[0, 2, 5] = False
mask.mask[5, 13, 4] = False
false_indices = mask.false_indices
false_indices_test = np.array([[0, 2, 5], [5, 13, 4]])
assert_equal(false_indices, false_indices_test)
def test_mask_true_bounding_extent():
mask = BooleanImage.blank((64, 14, 51), fill=False)
mask.mask[0, 13, 5] = True
mask.mask[5, 2, 4] = True
tbe = mask.bounds_true()
true_extends_mins = np.array([0, 2, 4])
true_extends_maxs = np.array([5, 13, 5])
assert_equal(tbe[0], true_extends_mins)
assert_equal(tbe[1], true_extends_maxs)
def test_3channel_image_creation():
pixels = np.ones((120, 120, 3))
MaskedImage(pixels)
def test_no_channels_image_creation():
pixels = np.ones((120, 120))
MaskedImage(pixels)
def test_create_MaskedImage_copy_false_mask_array():
pixels = np.ones((100, 100, 1))
mask = np.ones((100, 100), dtype=np.bool)
image = MaskedImage(pixels, mask=mask, copy=False)
assert (is_same_array(image.pixels, pixels))
assert (is_same_array(image.mask.pixels, mask))
def test_create_MaskedImage_copy_false_mask_BooleanImage():
pixels = np.ones((100, 100, 1))
mask = np.ones((100, 100), dtype=np.bool)
mask_image = BooleanImage(mask, copy=False)
image = MaskedImage(pixels, mask=mask_image, copy=False)
assert (is_same_array(image.pixels, pixels))
assert (is_same_array(image.mask.pixels, mask))
def test_create_MaskedImage_copy_true_mask_array():
pixels = np.ones((100, 100))
mask = np.ones((100, 100), dtype=np.bool)
image = MaskedImage(pixels, mask=mask)
assert (not is_same_array(image.pixels, pixels))
assert (not is_same_array(image.mask.pixels, mask))
def test_create_MaskedImage_copy_true_mask_BooleanImage():
pixels = np.ones((100, 100, 1))
mask = np.ones((100, 100), dtype=np.bool)
mask_image = BooleanImage(mask, copy=False)
image = MaskedImage(pixels, mask=mask_image, copy=True)
assert (not is_same_array(image.pixels, pixels))
assert (not is_same_array(image.mask.pixels, mask))
def test_2d_crop_without_mask():
pixels = np.ones((120, 120, 3))
im = MaskedImage(pixels)
cropped_im = im.crop([10, 50], [20, 60])
assert (cropped_im.shape == (10, 10))
assert (cropped_im.n_channels == 3)
assert (np.alltrue(cropped_im.shape))
def test_2d_crop_with_mask():
pixels = np.ones((120, 120, 3))
mask = np.zeros_like(pixels[..., 0])
mask[10:100, 20:30] = 1
im = MaskedImage(pixels, mask=mask)
cropped_im = im.crop([0, 0], [20, 60])
assert (cropped_im.shape == (20, 60))
assert (np.alltrue(cropped_im.shape))
def test_normalize_std_default():
pixels = np.ones((120, 120, 3))
pixels[..., 0] = 0.5
pixels[..., 1] = 0.2345
image = MaskedImage(pixels)
image.normalize_std_inplace()
assert_allclose(np.mean(image.pixels), 0, atol=1e-10)
assert_allclose(np.std(image.pixels), 1)
def test_normalize_norm_default():
pixels = np.ones((120, 120, 3))
pixels[..., 0] = 0.5
pixels[..., 1] = 0.2345
image = MaskedImage(pixels)
image.normalize_norm_inplace()
assert_allclose(np.mean(image.pixels), 0, atol=1e-10)
assert_allclose(np.linalg.norm(image.pixels), 1)
@raises(ValueError)
def test_normalize_std_no_variance_exception():
pixels = np.ones((120, 120, 3))
pixels[..., 0] = 0.5
pixels[..., 1] = 0.2345
image = MaskedImage(pixels)
image.normalize_std_inplace(mode='per_channel')
@raises(ValueError)
def test_normalize_norm_zero_norm_exception():
pixels = np.zeros((120, 120, 3))
image = MaskedImage(pixels)
image.normalize_norm_inplace(mode='per_channel')
def test_normalize_std_per_channel():
pixels = np.random.randn(120, 120, 3)
pixels[..., 1] *= 7
pixels[..., 0] += -14
pixels[..., 2] /= 130
image = MaskedImage(pixels)
image.normalize_std_inplace(mode='per_channel')
assert_allclose(
np.mean(image.as_vector(keep_channels=True), axis=0), 0, atol=1e-10)
assert_allclose(
np.std(image.as_vector(keep_channels=True), axis=0), 1)
def test_normalize_norm_per_channel():
pixels = np.random.randn(120, 120, 3)
pixels[..., 1] *= 7
pixels[..., 0] += -14
pixels[..., 2] /= 130
image = MaskedImage(pixels)
image.normalize_norm_inplace(mode='per_channel')
assert_allclose(
np.mean(image.as_vector(keep_channels=True), axis=0), 0, atol=1e-10)
assert_allclose(
np.linalg.norm(image.as_vector(keep_channels=True), axis=0), 1)
def test_normalize_std_masked():
pixels = np.random.randn(120, 120, 3)
pixels[..., 1] *= 7
pixels[..., 0] += -14
pixels[..., 2] /= 130
mask = np.zeros((120, 120))
mask[30:50, 20:30] = 1
image = MaskedImage(pixels, mask=mask)
image.normalize_std_inplace(mode='per_channel', limit_to_mask=True)
assert_allclose(
np.mean(image.as_vector(keep_channels=True), axis=0), 0, atol=1e-10)
assert_allclose(
np.std(image.as_vector(keep_channels=True), axis=0), 1)
def test_normalize_norm_masked():
pixels = np.random.randn(120, 120, 3)
pixels[..., 1] *= 7
pixels[..., 0] += -14
pixels[..., 2] /= 130
mask = np.zeros((120, 120))
mask[30:50, 20:30] = 1
image = MaskedImage(pixels, mask=mask)
image.normalize_norm_inplace(mode='per_channel', limit_to_mask=True)
assert_allclose(
np.mean(image.as_vector(keep_channels=True), axis=0), 0, atol=1e-10)
assert_allclose(
np.linalg.norm(image.as_vector(keep_channels=True), axis=0), 1)
def test_rescale_single_num():
image = MaskedImage(np.random.randn(120, 120, 3))
new_image = image.rescale(0.5)
assert_allclose(new_image.shape, (60, 60))
def test_rescale_tuple():
image = MaskedImage(np.random.randn(120, 120, 3))
new_image = image.rescale([0.5, 2.0])
assert_allclose(new_image.shape, (60, 240))
@raises(ValueError)
def test_rescale_negative():
image = MaskedImage(np.random.randn(120, 120, 3))
image.rescale([0.5, -0.5])
@raises(ValueError)
def test_rescale_negative_single_num():
image = MaskedImage(np.random.randn(120, 120, 3))
image.rescale(-0.5)
def test_rescale_boundaries_interpolation():
image = MaskedImage(np.random.randn(60, 60, 3))
for i in [x * 0.1 for x in range(1, 31)]:
image_rescaled = image.rescale(i)
assert_allclose(image_rescaled.mask.proportion_true, 1.0)
def test_resize():
image = MaskedImage(np.random.randn(120, 120, 3))
new_size = (250, 250)
new_image = image.resize(new_size)
assert_allclose(new_image.shape, new_size)
def test_as_greyscale_luminosity():
image = MaskedImage(np.ones([120, 120, 3]))
new_image = image.as_greyscale(mode='luminosity')
assert (new_image.shape == image.shape)
assert (new_image.n_channels == 1)
def test_as_greyscale_average():
image = MaskedImage(np.ones([120, 120, 3]))
new_image = image.as_greyscale(mode='average')
assert (new_image.shape == image.shape)
assert (new_image.n_channels == 1)
@raises(ValueError)
def test_as_greyscale_channels_no_index():
image = MaskedImage(np.ones([120, 120, 3]))
new_image = image.as_greyscale(mode='channel')
assert (new_image.shape == image.shape)
assert (new_image.n_channels == 1)
def test_as_greyscale_channels():
image = MaskedImage(np.random.randn(120, 120, 3))
new_image = image.as_greyscale(mode='channel', channel=0)
assert (new_image.shape == image.shape)
assert (new_image.n_channels == 1)
assert_allclose(new_image.pixels[..., 0], image.pixels[..., 0])
def test_as_pil_image_1channel():
im = MaskedImage(np.random.randn(120, 120, 1))
new_im = im.as_PILImage()
assert_allclose(np.asarray(new_im.getdata()).reshape(im.pixels.shape),
(im.pixels * 255).astype(np.uint8))
def test_as_pil_image_3channels():
im = MaskedImage(np.random.randn(120, 120, 3))
new_im = im.as_PILImage()
assert_allclose(np.asarray(new_im.getdata()).reshape(im.pixels.shape),
(im.pixels * 255).astype(np.uint8))
def test_image_gradient_sanity():
# Only a sanity check - does it run and generate sensible output?
image = Image(np.zeros([120, 120, 3]))
new_image = image.gradient()
assert(type(new_image) == Image)
assert(new_image.shape == image.shape)
assert(new_image.n_channels == image.n_channels * 2)
| bsd-2-clause |
david-novak/orange3-text | orangecontrib/text/tests/test_corpus.py | 5157 | import os
import unittest
from itertools import chain
import numpy as np
from Orange.data import Table
from Orange.data.domain import Domain, StringVariable
from orangecontrib.text.corpus import Corpus
class CorpusTests(unittest.TestCase):
def test_corpus_from_file(self):
c = Corpus.from_file('bookexcerpts')
self.assertEqual(len(c), 140)
self.assertEqual(len(c.domain), 1)
self.assertEqual(len(c.domain.metas), 1)
self.assertEqual(c.metas.shape, (140, 1))
c = Corpus.from_file('deerwester')
self.assertEqual(len(c), 9)
self.assertEqual(len(c.domain), 1)
self.assertEqual(len(c.domain.metas), 1)
self.assertEqual(c.metas.shape, (9, 1))
def test_corpus_from_file_abs_path(self):
c = Corpus.from_file('bookexcerpts')
path = os.path.dirname(__file__)
file = os.path.abspath(os.path.join(path, '..', 'datasets', 'bookexcerpts.tab'))
c2 = Corpus.from_file(file)
self.assertEqual(c, c2)
def test_corpus_from_file_with_tab(self):
c = Corpus.from_file('bookexcerpts')
c2 = Corpus.from_file('bookexcerpts.tab')
self.assertEqual(c, c2)
def test_corpus_from_file_missing(self):
with self.assertRaises(FileNotFoundError):
Corpus.from_file('missing_file')
def test_corpus_from_init(self):
c = Corpus.from_file('bookexcerpts')
c2 = Corpus(c.X, c.Y, c.metas, c.domain, c.text_features)
self.assertEqual(c, c2)
def test_extend_corpus(self):
c = Corpus.from_file('bookexcerpts')
n_classes = len(c.domain.class_var.values)
c_copy = c.copy()
new_y = [c.domain.class_var.values[int(i)] for i in c.Y]
new_y[0] = 'teenager'
c.extend_corpus(c.metas, new_y)
self.assertEqual(len(c), len(c_copy)*2)
self.assertEqual(c.Y.shape[0], c_copy.Y.shape[0]*2)
self.assertEqual(c.metas.shape[0], c_copy.metas.shape[0]*2)
self.assertEqual(c.metas.shape[1], c_copy.metas.shape[1])
self.assertEqual(len(c_copy.domain.class_var.values), n_classes+1)
def test_corpus_not_eq(self):
c = Corpus.from_file('bookexcerpts')
n_doc = c.X.shape[0]
c2 = Corpus(c.X, c.Y, c.metas, c.domain, [])
self.assertNotEqual(c, c2)
c2 = Corpus(np.ones((n_doc, 1)), c.Y, c.metas, c.domain, c.text_features)
self.assertNotEqual(c, c2)
c2 = Corpus(c.X, np.ones((n_doc, 1)), c.metas, c.domain, c.text_features)
self.assertNotEqual(c, c2)
broken_metas = np.copy(c.metas)
broken_metas[0, 0] = ''
c2 = Corpus(c.X, c.Y, broken_metas, c.domain, c.text_features)
self.assertNotEqual(c, c2)
new_meta = [StringVariable('text2')]
broken_domain = Domain(c.domain.attributes, c.domain.class_var, new_meta)
c2 = Corpus(c.X, c.Y, c.metas, broken_domain, new_meta)
self.assertNotEqual(c, c2)
def test_from_table(self):
t = Table.from_file('brown-selected')
self.assertIsInstance(t, Table)
c = Corpus.from_table(t.domain, t)
self.assertIsInstance(c, Corpus)
self.assertEqual(len(t), len(c))
np.testing.assert_equal(t.metas, c.metas)
self.assertEqual(c.text_features, [t.domain.metas[0]])
def test_from_corpus(self):
c = Corpus.from_file('bookexcerpts')
c2 = Corpus.from_corpus(c.domain, c, row_indices=list(range(5)))
self.assertEqual(len(c2), 5)
def test_infer_text_features(self):
c = Corpus.from_file('friends-transcripts')
tf = c.text_features
self.assertEqual(len(tf), 1)
self.assertEqual(tf[0].name, 'Quote')
c = Corpus.from_file('deerwester')
tf = c.text_features
self.assertEqual(len(tf), 1)
self.assertEqual(tf[0].name, 'text')
def test_documents(self):
c = Corpus.from_file('bookexcerpts')
docs = c.documents
types = set(type(i) for i in docs)
self.assertEqual(len(docs), len(c))
self.assertEqual(len(types), 1)
self.assertIn(str, types)
def test_documents_from_features(self):
c = Corpus.from_file('bookexcerpts')
docs = c.documents_from_features([c.domain.class_var])
types = set(type(i) for i in docs)
self.assertTrue(all(
[sum(cls in doc for cls in c.domain.class_var.values) == 1
for doc in docs]))
self.assertEqual(len(docs), len(c))
self.assertEqual(len(types), 1)
self.assertIn(str, types)
def test_asserting_errors(self):
c = Corpus.from_file('bookexcerpts')
with self.assertRaises(TypeError):
Corpus(1.0, c.Y, c.metas, c.domain, c.text_features)
too_large_x = np.vstack((c.X, c.X))
with self.assertRaises(ValueError):
Corpus(too_large_x, c.Y, c.metas, c.domain, c.text_features)
with self.assertRaises(ValueError):
c.set_text_features([StringVariable('foobar')])
with self.assertRaises(ValueError):
c.set_text_features([c.domain.metas[0], c.domain.metas[0]])
| bsd-2-clause |
cunhalima/cgcam | src/server/sv_connect.cpp | 2288 | #include <cassert>
#include <cstring>
#include "../defs.h"
int SV_FindClientByNNode(nnode_t *nn) {
assert(nn != NULL);
for (int i = 0; i < MAX_CLIENTS; i++) {
nnode_t *cnn = ss.clients[i].nn;
if (cnn == NULL) {
continue;
}
if (nnode_cmp(nn, cnn) == 0) {
return i;
}
}
return INVALID_CLIENT_ID;
}
int SV_AddClientWithNNode(nnode_t *nn) {
assert(nn != NULL);
for (int i = 0; i < MAX_CLIENTS; i++) {
svClient_t *c = &ss.clients[i];
nnode_t *cnn = c->nn;
if (cnn != NULL) {
continue;
}
memset(c, 0, sizeof(*c));
c->nn = nnode_dup(nn);
c->constate = CS_SPAWNED;
c->id = i;
svEntity_t *e = SV_SpawnEntity(c->id);
//e->model = 1;
return i;
}
return INVALID_CLIENT_ID;
}
svClient_t *SV_GetClientById(int id) {
if (!IS_VALID_CLIENT_ID(id)) {
return NULL;
}
return &ss.clients[id];
}
void SV_ConnAttempt(nnode_t *nn, szb_t *msg) {
assert(nn != NULL);
assert(msg != NULL);
int i = SV_FindClientByNNode(nn);
if (IS_VALID_CLIENT_ID(i)) {
CON_ERR("already connected"); // FIXME: should be ignored because will happen
return;
}
i = SV_AddClientWithNNode(nn);
svClient_t *c = SV_GetClientById(i);
c->lastPacketTime = g_Time;
if (var_dbconn->integer != 0) {
con_printf("sv conn ok\n");
}
}
void SV_Connless(nnode_t *nn, szb_t *msg) {
assert(nn != NULL);
assert(msg != NULL);
while (!szb_eof(msg)) {
int cmd = szb_read8(msg);
switch (cmd) {
case C2S_CONNECT:
//con_printf("conn req\n");
SV_ConnAttempt(nn, msg);
break;
case C2S_DISCONNECT:
{
int i = SV_FindClientByNNode(nn);
if (IS_VALID_CLIENT_ID(i)) {
SV_SilentDrop(SV_GetClientById(i));
}
}
break;
default:
CON_ERR("invalid cmd");
break;
}
}
}
void SV_SilentDrop(svClient_t *c) {
assert(c != NULL);
SV_RemoveEntity(c->id);
nnode_free(c->nn);
c->nn = NULL;
memset(c, 0, sizeof(*c));
con_printf("drop\n");
} | bsd-2-clause |
EricssonResearch/scream | gstscream/src/screamrx/imp.rs | 18517 | use glib::subclass::prelude::*;
use gst::prelude::*;
use gst::subclass::prelude::*;
use crate::gst::prelude::PadExtManual;
use std::convert::TryInto;
use std::sync::Arc;
use std::sync::Mutex;
pub use gstreamer_rtp::rtp_buffer::compare_seqnum;
pub use gstreamer_rtp::rtp_buffer::RTPBuffer;
pub use gstreamer_rtp::rtp_buffer::RTPBufferExt;
use once_cell::sync::Lazy;
use super::ScreamRx;
struct ClockWait {
clock_id: Option<gst::ClockId>,
_flushing: bool,
}
pub struct Screamrx {
srcpad: gst::Pad,
rtcp_srcpad: Option<Arc<Mutex<gst::Pad>>>,
sinkpad: gst::Pad,
lib_data: Mutex<ScreamRx::ScreamRx>,
clock_wait: Mutex<ClockWait>,
}
pub static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| {
gst::DebugCategory::new(
"screamrx",
gst::DebugColorFlags::empty(),
Some("Screamrx Element"),
)
});
impl Screamrx {
// Called whenever a new buffer is passed to our sink pad. Here buffers should be processed and
// whenever some output buffer is available have to push it out of the source pad.
// Here we just pass through all buffers directly
//
// See the documentation of gst::Buffer and gst::BufferRef to see what can be done with
// buffers.
fn sink_chain(
&self,
pad: &gst::Pad,
_element: &super::Screamrx,
buffer: gst::Buffer,
) -> Result<gst::FlowSuccess, gst::FlowError> {
gst_trace!(CAT, obj: pad, "gstscream Handling buffer {:?}", buffer);
let rtp_buffer = RTPBuffer::from_buffer_readable(&buffer).unwrap();
let seq = rtp_buffer.seq();
let payload_type = rtp_buffer.payload_type();
let timestamp = rtp_buffer.timestamp();
let ssrc = rtp_buffer.ssrc();
let marker = rtp_buffer.is_marker();
gst_trace!(
CAT,
obj: pad,
"gstscream Handling rtp buffer seq {} payload_type {} timestamp {} ",
seq,
payload_type,
timestamp
);
drop(rtp_buffer);
let size: u32 = buffer.size().try_into().unwrap();
// TBD get ECN
let ecn_ce: u8 = 0;
{
let mut screamrx = self.lib_data.lock().unwrap();
screamrx.ScreamReceiver(size, seq, payload_type, timestamp, ssrc, marker, ecn_ce);
}
self.srcpad.push(buffer)
}
// Called whenever an event arrives on the sink pad. It has to be handled accordingly and in
// most cases has to be either passed to Pad::event_default() on this pad for default handling,
// or Pad::push_event() on all pads with the opposite direction for direct forwarding.
// Here we just pass through all events directly to the source pad.
//
// See the documentation of gst::Event and gst::EventRef to see what can be done with
// events, and especially the gst::EventView type for inspecting events.
fn sink_event(&self, pad: &gst::Pad, _element: &super::Screamrx, event: gst::Event) -> bool {
gst_log!(
CAT,
obj: pad,
"gstscream Handling event {:?} {:?}",
event,
event.type_()
);
if let gst::EventView::StreamStart(ev) = event.view() {
let stream_id = ev.stream_id();
println!(
"gstscream Handling sink StreamStarT event {:?} ; {:?}; {}",
event, ev, stream_id
);
self.srcpad
.push_event(gst::event::StreamStart::new(stream_id));
let rtcp_srcpad = self.rtcp_srcpad.as_ref().unwrap().lock().unwrap();
let name = "rtcp_src";
let full_stream_id = rtcp_srcpad.create_stream_id(_element, Some(name));
// FIXME group id
rtcp_srcpad.push_event(gst::event::StreamStart::new(&full_stream_id));
// rtcp_srcpad.push_event(gst::event::Caps::new(caps));
// FIXME proper segment handling
let segment = gst::FormattedSegment::<gst::ClockTime>::default();
rtcp_srcpad.push_event(gst::event::Segment::new(&segment));
}
self.srcpad.push_event(event)
}
// Called whenever a query is sent to the sink pad. It has to be answered if the element can
// handle it, potentially by forwarding the query first to the peer pads of the pads with the
// opposite direction, or false has to be returned. Default handling can be achieved with
// Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the
// opposite direction.
// Here we just forward all queries directly to the source pad's peers.
//
// See the documentation of gst::Query and gst::QueryRef to see what can be done with
// queries, and especially the gst::QueryView type for inspecting and modifying queries.
fn sink_query(
&self,
pad: &gst::Pad,
_element: &super::Screamrx,
query: &mut gst::QueryRef,
) -> bool {
gst_log!(CAT, obj: pad, "gstscream Handling query {:?}", query);
self.srcpad.peer_query(query)
}
// Called whenever an event arrives on the source pad. It has to be handled accordingly and in
// most cases has to be either passed to Pad::event_default() on the same pad for default
// handling, or Pad::push_event() on all pads with the opposite direction for direct
// forwarding.
// Here we just pass through all events directly to the sink pad.
//
// See the documentation of gst::Event and gst::EventRef to see what can be done with
// events, and especially the gst::EventView type for inspecting events.
fn src_event(&self, pad: &gst::Pad, _element: &super::Screamrx, event: gst::Event) -> bool {
gst_log!(
CAT,
obj: pad,
"gstscream src Handling event {:?} {:?}",
event,
event.type_()
);
self.sinkpad.push_event(event)
}
fn rtcp_src_event(
&self,
pad: &gst::Pad,
_element: &super::Screamrx,
event: gst::Event,
) -> bool {
gst_log!(
CAT,
obj: pad,
"gstscream rtcp_src Handling event {:?} {:?}",
event,
event.type_()
);
false
// self.sinkpad.push_event(event)
}
fn rtcp_src_query(
&self,
pad: &gst::Pad,
_element: &super::Screamrx,
query: &mut gst::QueryRef,
) -> bool {
gst_log!(
CAT,
obj: pad,
"gstscream Handling rtcp src_query {:?}",
query
);
false
}
// Called whenever a query is sent to the source pad. It has to be answered if the element can
// handle it, potentially by forwarding the query first to the peer pads of the pads with the
// opposite direction, or false has to be returned. Default handling can be achieved with
// Pad::query_default() on this pad and forwarding with Pad::peer_query() on the pads with the
// opposite direction.
// Here we just forward all queries directly to the sink pad's peers.
//
// See the documentation of gst::Query and gst::QueryRef to see what can be done with
// queries, and especially the gst::QueryView type for inspecting and modifying queries.
fn src_query(
&self,
pad: &gst::Pad,
_element: &super::Screamrx,
query: &mut gst::QueryRef,
) -> bool {
gst_log!(CAT, obj: pad, "gstscream Handling query {:?}", query);
self.sinkpad.peer_query(query)
}
}
// This trait registers our type with the GObject object system and
// provides the entry points for creating a new instance and setting
// up the class data
#[glib::object_subclass]
impl ObjectSubclass for Screamrx {
const NAME: &'static str = "RsScreamrx";
type Type = super::Screamrx;
type ParentType = gst::Element;
// Called when a new instance is to be created. We need to return an instance
// of our struct here and also get the class struct passed in case it's needed
fn with_class(klass: &Self::Class) -> Self {
// Create our two pads from the templates that were registered with
// the class and set all the functions on them.
//
// Each function is wrapped in catch_panic_pad_function(), which will
// - Catch panics from the pad functions and instead of aborting the process
// it will simply convert them into an error message and poison the element
// instance
// - Extract our Screamrx struct from the object instance and pass it to us
//
// Details about what each function is good for is next to each function definition
let templ = klass.pad_template("sink").unwrap();
let sinkpad = gst::Pad::builder_with_template(&templ, Some("sink"))
.chain_function(|pad, parent, buffer| {
Screamrx::catch_panic_pad_function(
parent,
|| Err(gst::FlowError::Error),
|screamrx, element| screamrx.sink_chain(pad, element, buffer),
)
})
.event_function(|pad, parent, event| {
Screamrx::catch_panic_pad_function(
parent,
|| false,
|screamrx, element| screamrx.sink_event(pad, element, event),
)
})
.query_function(|pad, parent, query| {
Screamrx::catch_panic_pad_function(
parent,
|| false,
|screamrx, element| screamrx.sink_query(pad, element, query),
)
})
.build();
let templ = klass.pad_template("src").unwrap();
let srcpad = gst::Pad::builder_with_template(&templ, Some("src"))
.event_function(|pad, parent, event| {
Screamrx::catch_panic_pad_function(
parent,
|| false,
|screamrx, element| screamrx.src_event(pad, element, event),
)
})
.query_function(|pad, parent, query| {
Screamrx::catch_panic_pad_function(
parent,
|| false,
|screamrx, element| screamrx.src_query(pad, element, query),
)
})
.build();
let name = "rtcp_src";
let templ = klass.pad_template(name).unwrap();
let rtcp_srcpad = gst::Pad::builder_with_template(&templ, Some(name))
.event_function(|pad, parent, event| {
Screamrx::catch_panic_pad_function(
parent,
|| false,
|screamrx, element| screamrx.rtcp_src_event(pad, element, event),
)
})
.query_function(|pad, parent, query| {
Screamrx::catch_panic_pad_function(
parent,
|| false,
|screamrx, element| screamrx.rtcp_src_query(pad, element, query),
)
})
.build();
rtcp_srcpad.set_active(true).unwrap();
/*
if let Some(event) = pad.sticky_event(gst::EventType::StreamStart, 0) {
if let gst::EventView::StreamStart(ev) = event.view() {
stream_type = ev.stream().map(|s| s.stream_type());
}
}
assert!(sinkpad.send_event(gst::event::StreamStart::new("test")));
let mut events = Vec::new();
events.push(gst::event::StreamStart::new(&pull.stream_id));
let full_stream_id = rtcp_srcpad.create_stream_id(element, Some(name));
// FIXME group id
rtcp_srcpad.push_event(gst::event::StreamStart::new(&full_stream_id));
// rtcp_srcpad.push_event(gst::event::Caps::new(caps));
// FIXME proper segment handling
let segment = gst::FormattedSegment::<gst::ClockTime>::default();
rtcp_srcpad.push_event(gst::event::Segment::new(&segment));
*/
let rtcp_srcpad = Some(Arc::new(Mutex::new(rtcp_srcpad)));
let lib_data = Mutex::new(Default::default());
let clock_wait = Mutex::new(ClockWait {
clock_id: None,
_flushing: true,
});
// Return an instance of our struct and also include our debug category here.
// The debug category will be used later whenever we need to put something
// into the debug logs
Self {
srcpad,
rtcp_srcpad,
sinkpad,
lib_data,
clock_wait,
}
}
}
// Implementation of glib::Object virtual methods
impl ObjectImpl for Screamrx {
// Called right after construction of a new instance
fn constructed(&self, obj: &Self::Type) {
// Call the parent class' ::constructed() implementation first
self.parent_constructed(obj);
// Here we actually add the pads we created in Screamrx::new() to the
// element so that GStreamer is aware of their existence.
obj.add_pad(&self.sinkpad).unwrap();
let rtcp_srcpad = self.rtcp_srcpad.as_ref().unwrap().lock().unwrap();
obj.add_pad(&*rtcp_srcpad).unwrap();
obj.add_pad(&self.srcpad).unwrap();
}
}
// Implementation of gst::Element virtual methods
impl GstObjectImpl for Screamrx {}
impl ElementImpl for Screamrx {
// Set the element specific metadata. This information is what
// is visible from gst-inspect-1.0 and can also be programatically
// retrieved from the gst::Registry after initial registration
// without having to load the plugin in memory.
fn metadata() -> Option<&'static gst::subclass::ElementMetadata> {
// Set the element specific metadata. This information is what
// is visible from gst-inspect-1.0 and can also be programatically
// retrieved from the gst::Registry after initial registration
// without having to load the plugin in memory.
static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| {
gst::subclass::ElementMetadata::new(
"Screamrx",
"Generc",
"pass RTP packets to screamrx",
"Jacob Teplitsky <jacob.teplitsky@ericsson.com>",
)
});
Some(&*ELEMENT_METADATA)
}
// Create and add pad templates for our sink and source pad. These
// are later used for actually creating the pads and beforehand
// already provide information to GStreamer about all possible
// pads that could exist for this type.
//
// Actual instances can create pads based on those pad templates
fn pad_templates() -> &'static [gst::PadTemplate] {
static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| {
// Our element can accept any possible caps on both pads
// Create and add pad templates for our sink and source pad. These
// are later used for actually creating the pads and beforehand
// already provide information to GStreamer about all possible
// pads that could exist for this type.
// Our element can accept any possible caps on both pads
let caps = gst::Caps::new_simple("application/x-rtp", &[]);
let src_pad_template = gst::PadTemplate::new(
"src",
gst::PadDirection::Src,
gst::PadPresence::Always,
&caps,
)
.unwrap();
let sink_pad_template = gst::PadTemplate::new(
"sink",
gst::PadDirection::Sink,
gst::PadPresence::Always,
&caps,
)
.unwrap();
let caps = gst::Caps::new_any();
let rtcp_src_pad_template = gst::PadTemplate::new(
"rtcp_src",
gst::PadDirection::Src,
gst::PadPresence::Always,
&caps,
)
.unwrap();
vec![src_pad_template, rtcp_src_pad_template, sink_pad_template]
});
PAD_TEMPLATES.as_ref()
}
// Called whenever the state of the element should be changed. This allows for
// starting up the element, allocating/deallocating resources or shutting down
// the element again.
fn change_state(
&self,
element: &Self::Type,
transition: gst::StateChange,
) -> Result<gst::StateChangeSuccess, gst::StateChangeError> {
match transition {
gst::StateChange::NullToReady => {
{
let mut screamrx = self.lib_data.lock().unwrap();
gst_log!(CAT, "screamrx.ScreamReceiverPluginInit()");
screamrx.ScreamReceiverPluginInit(self.rtcp_srcpad.clone());
}
gst_debug!(CAT, obj: element, "Waiting for 1s before retrying");
let clock = gst::SystemClock::obtain();
let wait_time = clock.time().unwrap() + gst::ClockTime::SECOND;
let mut clock_wait = self.clock_wait.lock().unwrap();
let timeout = clock.new_periodic_id(wait_time, gst::ClockTime::from_useconds(500));
clock_wait.clock_id = Some(timeout.clone());
let element_weak = element.downgrade();
timeout
.wait_async(move |_clock, _time, _id| {
let element = match element_weak.upgrade() {
None => return,
Some(element) => element,
};
let lib_data = Screamrx::from_instance(&element);
let mut screamrx = lib_data.lib_data.lock().unwrap();
screamrx.periodic_flush();
})
.expect("Failed to wait async");
}
gst::StateChange::ReadyToNull => {
let mut clock_wait = self.clock_wait.lock().unwrap();
if let Some(clock_id) = clock_wait.clock_id.take() {
clock_id.unschedule();
}
}
_ => (),
}
gst_trace!(CAT, obj: element, "Changing state {:?}", transition);
// Call the parent class' implementation of ::change_state()
self.parent_change_state(element, transition)
}
}
| bsd-2-clause |
Rohde-Schwarz-Cybersecurity/botan | src/tests/test_psk_db.cpp | 8588 | /*
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_PSK_DB)
#include <botan/psk_db.h>
#if defined(BOTAN_HAS_SQLITE3)
#include <botan/psk_db_sql.h>
#include <botan/sqlite3.h>
#endif
namespace Botan_Tests {
namespace {
class Test_Map_PSK_Db : public Botan::Encrypted_PSK_Database
{
public:
Test_Map_PSK_Db(const Botan::secure_vector<uint8_t>& master_key) :
Botan::Encrypted_PSK_Database(master_key)
{}
void test_entry(Test::Result& result,
const std::string& index, const std::string& value)
{
auto i = m_vals.find(index);
if(i == m_vals.end())
{
result.test_failure("Expected to find encrypted name " + index);
}
else
{
result.test_eq("Encrypted value", i->second, value);
}
}
void kv_set(const std::string& index, const std::string& value) override
{
m_vals[index] = value;
}
std::string kv_get(const std::string& index) const override
{
auto i = m_vals.find(index);
if(i == m_vals.end())
return "";
return i->second;
}
void kv_del(const std::string& index) override
{
auto i = m_vals.find(index);
if(i != m_vals.end())
{
m_vals.erase(i);
}
}
std::set<std::string> kv_get_all() const override
{
std::set<std::string> names;
for(auto kv : m_vals)
{
names.insert(kv.first);
}
return names;
}
private:
std::map<std::string, std::string> m_vals;
};
}
class PSK_DB_Tests final : public Test
{
public:
std::vector<Test::Result> run() override
{
std::vector<Test::Result> results;
results.push_back(test_psk_db());
#if defined(BOTAN_HAS_SQLITE3)
results.push_back(test_psk_sql_db());
#endif
return results;
}
private:
Test::Result test_psk_db()
{
Test::Result result("PSK_DB");
const Botan::secure_vector<uint8_t> zeros(32);
Test_Map_PSK_Db db(zeros);
db.set_str("name", "value");
db.test_entry(result, "CUCJjJgWSa079ubutJQwlw==", "clYJSAf9CThuL96CP+rAfA==");
result.test_eq("DB read", db.get_str("name"), "value");
db.set_str("name", "value1");
db.test_entry(result, "CUCJjJgWSa079ubutJQwlw==", "7R8am3x/gLawOzMp5WwIJg==");
result.test_eq("DB read", db.get_str("name"), "value1");
db.set_str("name", "value");
db.test_entry(result, "CUCJjJgWSa079ubutJQwlw==", "clYJSAf9CThuL96CP+rAfA==");
result.test_eq("DB read", db.get_str("name"), "value");
db.set_str("name2", "value");
db.test_entry(result, "7CvsM7HDCZsV6VsFwWylNg==", "BqVQo4rdwOmf+ItCzEmjAg==");
result.test_eq("DB read", db.get_str("name2"), "value");
db.set_vec("name2", zeros);
db.test_entry(result, "7CvsM7HDCZsV6VsFwWylNg==", "x+I1bUF/fJYPOTvKwOihEPWGR1XGzVuyRdsw4n5gpBRzNR7LjH7vjw==");
result.test_eq("DB read", db.get("name2"), zeros);
// Test longer names
db.set_str("leroy jeeeeeeeenkins", "chicken");
db.test_entry(result, "KyYo272vlSjClM2F0OZBMlRYjr33ZXv2jN1oY8OfCEs=", "tCl1qShSTsXi9tA5Kpo9vg==");
result.test_eq("DB read", db.get_str("leroy jeeeeeeeenkins"), "chicken");
std::set<std::string> all_names = db.list_names();
result.test_eq("Expected number of names", all_names.size(), 3);
result.test_eq("Have expected name", all_names.count("name"), 1);
result.test_eq("Have expected name", all_names.count("name2"), 1);
result.test_eq("Have expected name", all_names.count("leroy jeeeeeeeenkins"), 1);
db.remove("name2");
all_names = db.list_names();
result.test_eq("Expected number of names", all_names.size(), 2);
result.test_eq("Have expected name", all_names.count("name"), 1);
result.test_eq("Have expected name", all_names.count("leroy jeeeeeeeenkins"), 1);
result.test_throws("exception if get called on non-existent PSK",
"Invalid argument Named PSK not located",
[&]() { db.get("name2"); });
// test that redundant remove calls accepted
db.remove("name2");
return result;
}
#if defined(BOTAN_HAS_SQLITE3)
void test_entry(Test::Result& result,
std::shared_ptr<Botan::SQL_Database> db,
const std::string& table,
const std::string& expected_name,
const std::string& expected_value)
{
auto stmt = db->new_statement("select psk_value from " + table + " where psk_name='" + expected_name + "'");
bool got_it = stmt->step();
result.confirm("Had expected name", got_it);
if(got_it)
{
result.test_eq("Had expected value", stmt->get_str(0), expected_value);
}
}
Test::Result test_psk_sql_db()
{
Test::Result result("PSK_DB SQL");
const Botan::secure_vector<uint8_t> zeros(32);
const Botan::secure_vector<uint8_t> not_zeros = Test::rng().random_vec(32);
const std::string table_name = "bobby";
std::shared_ptr<Botan::SQL_Database> sqldb = std::make_shared<Botan::Sqlite3_Database>(":memory:");
Botan::Encrypted_PSK_Database_SQL db(zeros, sqldb, table_name);
db.set_str("name", "value");
test_entry(result, sqldb, table_name, "CUCJjJgWSa079ubutJQwlw==", "clYJSAf9CThuL96CP+rAfA==");
result.test_eq("DB read", db.get_str("name"), "value");
db.set_str("name", "value1");
test_entry(result, sqldb, table_name, "CUCJjJgWSa079ubutJQwlw==", "7R8am3x/gLawOzMp5WwIJg==");
result.test_eq("DB read", db.get_str("name"), "value1");
db.set_str("name", "value");
test_entry(result, sqldb, table_name, "CUCJjJgWSa079ubutJQwlw==", "clYJSAf9CThuL96CP+rAfA==");
result.test_eq("DB read", db.get_str("name"), "value");
db.set_str("name2", "value");
test_entry(result, sqldb, table_name, "7CvsM7HDCZsV6VsFwWylNg==", "BqVQo4rdwOmf+ItCzEmjAg==");
result.test_eq("DB read", db.get_str("name2"), "value");
db.set_vec("name2", zeros);
test_entry(result, sqldb, table_name, "7CvsM7HDCZsV6VsFwWylNg==", "x+I1bUF/fJYPOTvKwOihEPWGR1XGzVuyRdsw4n5gpBRzNR7LjH7vjw==");
result.test_eq("DB read", db.get("name2"), zeros);
// Test longer names
db.set_str("leroy jeeeeeeeenkins", "chicken");
test_entry(result, sqldb, table_name, "KyYo272vlSjClM2F0OZBMlRYjr33ZXv2jN1oY8OfCEs=", "tCl1qShSTsXi9tA5Kpo9vg==");
result.test_eq("DB read", db.get_str("leroy jeeeeeeeenkins"), "chicken");
/*
* Test that we can have another database in the same table with distinct key
* without any problems.
*/
Botan::Encrypted_PSK_Database_SQL db2(not_zeros, sqldb, table_name);
db2.set_str("name", "price&value");
result.test_eq("DB read", db2.get_str("name"), "price&value");
result.test_eq("DB2 size", db2.list_names().size(), 1);
std::set<std::string> all_names = db.list_names();
result.test_eq("Expected number of names", all_names.size(), 3);
result.test_eq("Have expected name", all_names.count("name"), 1);
result.test_eq("Have expected name", all_names.count("name2"), 1);
result.test_eq("Have expected name", all_names.count("leroy jeeeeeeeenkins"), 1);
db.remove("name2");
all_names = db.list_names();
result.test_eq("Expected number of names", all_names.size(), 2);
result.test_eq("Have expected name", all_names.count("name"), 1);
result.test_eq("Have expected name", all_names.count("leroy jeeeeeeeenkins"), 1);
result.test_throws("exception if get called on non-existent PSK",
"Invalid argument Named PSK not located",
[&]() { db.get("name2"); });
// test that redundant remove calls accepted
db.remove("name2");
return result;
}
#endif
};
BOTAN_REGISTER_TEST("psk_db", PSK_DB_Tests);
}
#endif
| bsd-2-clause |
legend0702/jsgen | bin/jsgen1.js | 1191 | //引用lib文件下的utils.js
var utils = require('../lib/utils');
var fs = require('fs');
var path = require('path');
var fsUtils = require('../lib/fsUtils');
//var rs = fs.createReadStream('G:/Nodejs/sql.txt');
console.log(module.filename);
console.log(path.dirname(module.filename));
//error
console.log(path.resolve(path.dirname(module.filename),fs.readdirSync('G:/Nodejs/study/jsgen')[5]));
//console.log(path.resolve(path.dirname(fs.readdirSync.log(module.filename))));
// fs.readFile(path.resolve(path.dirname(fs.readdirSync(module.filename),fs.readdirSync('G:/Nodejs/study/jsgen')[5])),function(err,data){
// console.log(data);
// });
var bufs = [];
var json = {};
// rs.on('data',function(chunk){
// bufs.push(chunk);
// });
//rs.on('end',function(){
//json = JSON.parse(Buffer.concat(bufs).toString('utf-8'));
//console.log(json);
//console.log(json['name']);
//});
//console.log(buff.toString());
//调用node.js内置输出对象输出utils的helloWorld方法的执行结果
//console.log(utils.helloWorld());
//fsUtils.copy('G:/Nodejs/study/jsgen/package.json','G:/Nodejs/study/jsgen/package1.json');
//fsUtils.readTextSync('G:/Nodejs/study/jsgen/package.json');
| bsd-2-clause |
mbcraft/phal | src/ParentTagPlaceholder.php | 1724 | <?php
namespace Phal {
/**
* This class rapresents a parent placeholder tag. It does not render
* any tag itself, but can contain other tags or texts. It is used to
* keep an order inside the html and to reserve place for tags to be
* inserted in special conditions.
*/
class ParentTagPlaceholder implements IWritable {
private $childs = array();
/**
* Adds a writable child to this container.
*
* @param type $tag A IWritable object to add.
*/
public final function addChild($writable) {
if ($writable instanceof IWritable) {
array_push($this->childs, $writable);
} else {
throw new PhalException("The child added is not IWritable.");
}
}
/**
* Gets all the childs of this parent tag.
*
* @return type An array of all childs.
*/
public final function getChilds() {
return $this->childs;
}
/**
* Returns the presence of childs inside this tag.
*
* @return type true if this tag has childs, false otherwise
*/
public final function hasChilds() {
return !empty($this->childs);
}
/**
* Renders all the childs of this parent placeholder tag.
*
* @return type The concatenated rendered childs.
*/
public final function __toString() {
$result = "";
foreach ($this->childs as $ch) {
$result.= $ch;
}
return $result;
}
}
} | bsd-2-clause |
almarklein/bokeh | tests/glyphs/Oval.py | 932 | import numpy as np
from bokeh.document import Document
from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid
from bokeh.models.glyphs import Oval
from bokeh.plotting import show
N = 9
x = np.linspace(-2, 2, N)
y = x**2
source = ColumnDataSource(dict(x=x, y=y))
xdr = DataRange1d(sources=[source.columns("x")])
ydr = DataRange1d(sources=[source.columns("y")])
plot = Plot(
title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300,
h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None)
glyph = Oval(x="x", y="y", width=0.4, height=0.6, angle=-0.7, fill_color="#1d91d0")
plot.add_glyph(source, glyph)
xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')
yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
doc = Document()
doc.add(plot)
show(plot) | bsd-3-clause |
rwth-acis/LAS2peer | core/src/main/java/i5/las2peer/classLoaders/libraries/LibraryIdentifier.java | 4012 | package i5.las2peer.classLoaders.libraries;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* a basic class managing a library identifier of the format name-number where number fits the format of
* {@link LibraryVersion}
*
*/
public class LibraryIdentifier {
public static final String MANIFEST_LIBRARY_NAME_ATTRIBUTE = "Library-SymbolicName";
public static final String MANIFEST_LIBRARY_VERSION_ATTRIBUTE = "Library-Version";
private String name;
private LibraryVersion version;
public static LibraryIdentifier fromFilename(String filename) {
String fileNameWithOutExt = new File(filename).getName().replaceFirst("[.][^.]+$", "");
Pattern versionPattern = Pattern.compile("-[0-9]+(?:.[0-9]+(?:.[0-9]+)?)?(?:-[0-9]+)?$");
Matcher m = versionPattern.matcher(fileNameWithOutExt);
String sName = null;
String sVersion = null;
if (m.find()) { // look for version information in filename
sName = fileNameWithOutExt.substring(0, m.start());
sVersion = m.group().substring(1);
return new LibraryIdentifier(sName, sVersion);
} else {
sName = fileNameWithOutExt;
return new LibraryIdentifier(sName, (LibraryVersion) null);
}
}
/**
* generate a new LibraryIdentifier from its string representation
*
* @param name A canonical library name
* @throws IllegalArgumentException If the version information is not correctly formatted
*/
public LibraryIdentifier(String name) throws IllegalArgumentException {
int index = name.indexOf(";version=\"");
if (index == -1) {
throw new IllegalArgumentException("String does not include version info");
}
if (name.charAt(name.length() - 1) != '"') {
throw new IllegalArgumentException("Version info not in qoutes!");
}
this.name = name.substring(0, index);
String versionInfo = name.substring(index + 10, name.length() - 1);
this.version = new LibraryVersion(versionInfo);
}
/**
* generate a new identifier
*
* @param name A canonical library name
* @param version A library version
* @throws IllegalArgumentException If the version information is not correctly formatted
*/
public LibraryIdentifier(String name, String version) throws IllegalArgumentException {
if (version != null) {
this.name = name;
this.version = new LibraryVersion(version);
} else {
throw new IllegalArgumentException("null given as version information");
}
}
/**
* generate a new library identifier
*
* @param name A canonical library name
* @param version A library version
*/
public LibraryIdentifier(String name, LibraryVersion version) {
this.name = name;
this.version = version;
}
/**
*
* @return version of this library
*/
public LibraryVersion getVersion() {
return version;
}
/**
*
* @return name of the library
*/
public String getName() {
return name;
}
/**
* @return a string representation of this identifier
*/
@Override
public String toString() {
return name + ";version=\"" + version.toString() + "\"";
}
/**
* compares this identifier to another one
*
* @param i A library identifier
* @return true, if the given identifier is the same as this
*/
public boolean equals(LibraryIdentifier i) {
return this.toString().equals(i.toString());
}
/**
* compares this identifier against other objects if a string is given, the string representation of this identifier
* is compared to the given string
*
* @param o Another object to compare to
* @return true, if the given object is an identifier and is the same as this
*/
@Override
public boolean equals(Object o) {
if (o instanceof LibraryIdentifier) {
return this.equals((LibraryIdentifier) o);
} else if (o instanceof String) {
return this.toString().equals(o);
} else {
return false;
}
}
/**
* since equals is overridden, we should implement an own hashCode.
*
* @return a hash code
*/
@Override
public int hashCode() {
return (this.toString()).hashCode();
}
}
| bsd-3-clause |
skirpichev/omg | diofant/tests/solvers/test_inequalities.py | 15287 | """Tests for tools for solving inequalities and systems of inequalities."""
import pytest
from diofant import (And, E, Eq, FiniteSet, Float, Ge, Gt, Integer, Integral,
Interval, Le, Lt, Ne, Or, Piecewise, Poly, PurePoly,
Rational, RootOf, S, Symbol, Union, false, log, oo, pi,
reduce_inequalities, root, sin, solve, sqrt)
from diofant.abc import x, y
from diofant.solvers.inequalities import (reduce_piecewise_inequality,
reduce_rational_inequalities,
solve_poly_inequalities)
from diofant.solvers.inequalities import solve_poly_inequality as psolve
from diofant.solvers.inequalities import solve_univariate_inequality as isolve
__all__ = ()
inf = oo.evalf()
def test_solve_poly_inequality():
assert psolve(Poly(0, x), '==') == [S.Reals]
assert psolve(Poly(1, x), '==') == [S.EmptySet]
assert psolve(PurePoly(x + 1, x), '>') == [Interval(-1, oo, True, True)]
pytest.raises(ValueError, lambda: psolve(x, '=='))
pytest.raises(ValueError, lambda: psolve(Poly(x, x), '??'))
assert (solve_poly_inequalities(((Poly(x**2 - 3), '>'),
(Poly(-x**2 + 1), '>'))) ==
Union(Interval(-oo, -sqrt(3), True, True),
Interval(-1, 1, True, True),
Interval(sqrt(3), oo, True, True)))
def test_reduce_poly_inequalities_real_interval():
assert reduce_rational_inequalities(
[[Eq(x**2, 0)]], x, relational=False) == FiniteSet(0)
assert reduce_rational_inequalities(
[[Le(x**2, 0)]], x, relational=False) == FiniteSet(0)
assert reduce_rational_inequalities(
[[Lt(x**2, 0)]], x, relational=False) == S.EmptySet
assert reduce_rational_inequalities(
[[Ge(x**2, 0)]], x, relational=False) == \
S.Reals if x.is_extended_real else Interval(-oo, oo)
assert reduce_rational_inequalities(
[[Gt(x**2, 0)]], x, relational=False) == \
FiniteSet(0).complement(S.Reals)
assert reduce_rational_inequalities(
[[Ne(x**2, 0)]], x, relational=False) == \
FiniteSet(0).complement(S.Reals)
assert reduce_rational_inequalities(
[[Eq(x**2, 1)]], x, relational=False) == FiniteSet(-1, 1)
assert reduce_rational_inequalities(
[[Le(x**2, 1)]], x, relational=False) == Interval(-1, 1)
assert reduce_rational_inequalities(
[[Lt(x**2, 1)]], x, relational=False) == Interval(-1, 1, True, True)
assert reduce_rational_inequalities(
[[Ge(x**2, 1)]], x, relational=False) == \
Union(Interval(-oo, -1, True), Interval(1, oo, False, True))
assert reduce_rational_inequalities(
[[Gt(x**2, 1)]], x, relational=False) == \
Interval(-1, 1).complement(S.Reals)
assert reduce_rational_inequalities(
[[Ne(x**2, 1)]], x, relational=False) == \
FiniteSet(-1, 1).complement(S.Reals)
assert reduce_rational_inequalities([[Eq(
x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0, 1.0).evalf()
assert reduce_rational_inequalities(
[[Le(x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0)
assert reduce_rational_inequalities([[Lt(
x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0, True, True)
assert reduce_rational_inequalities(
[[Ge(x**2, 1.0)]], x, relational=False) == \
Union(Interval(-inf, -1.0, True), Interval(1.0, inf, False, True))
assert reduce_rational_inequalities(
[[Gt(x**2, 1.0)]], x, relational=False) == \
Union(Interval(-inf, -1.0, True, True),
Interval(1.0, inf, True, True))
assert reduce_rational_inequalities([[Ne(
x**2, 1.0)]], x, relational=False) == \
FiniteSet(-1.0, 1.0).complement(S.Reals)
s = sqrt(2)
assert reduce_rational_inequalities([[Lt(
x**2 - 1, 0), Gt(x**2 - 1, 0)]], x, relational=False) == S.EmptySet
assert reduce_rational_inequalities([[Le(x**2 - 1, 0), Ge(
x**2 - 1, 0)]], x, relational=False) == FiniteSet(-1, 1)
assert reduce_rational_inequalities(
[[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, False, False), Interval(1, s, False, False))
assert reduce_rational_inequalities(
[[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, False, True), Interval(1, s, True, False))
assert reduce_rational_inequalities(
[[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, True, False), Interval(1, s, False, True))
assert reduce_rational_inequalities(
[[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, True, True), Interval(1, s, True, True))
assert reduce_rational_inequalities(
[[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x, relational=False
) == Union(Interval(-s, -1, True, True), Interval(-1, 1, True, True),
Interval(1, s, True, True))
# issue sympy/sympy#10237
assert reduce_rational_inequalities(
[[x < oo, x >= 0, -oo < x]], x, relational=False) == Interval(0, oo, False, True)
assert reduce_rational_inequalities([[Eq((x + 1)/(x**2 - 1),
0)]], x) is false
def test_reduce_poly_inequalities_complex_relational():
assert reduce_rational_inequalities(
[[Eq(x**2, 0)]], x, relational=True) == Eq(x, 0)
assert reduce_rational_inequalities(
[[Le(x**2, 0)]], x, relational=True) == Eq(x, 0)
assert reduce_rational_inequalities(
[[Lt(x**2, 0)]], x, relational=True) is false
assert reduce_rational_inequalities(
[[Ge(x**2, 0)]], x, relational=True) == And(Lt(-oo, x), Lt(x, oo))
assert reduce_rational_inequalities(
[[Gt(x**2, 0)]], x, relational=True) == \
And(Or(And(Lt(-oo, x), Lt(x, 0)), And(Lt(0, x), Lt(x, oo))))
assert reduce_rational_inequalities(
[[Ne(x**2, 0)]], x, relational=True) == \
And(Or(And(Lt(-oo, x), Lt(x, 0)), And(Lt(0, x), Lt(x, oo))))
for one in (Integer(1), Float(1.0)):
inf = one*oo
assert reduce_rational_inequalities(
[[Eq(x**2, one)]], x, relational=True) == \
Or(Eq(x, -one), Eq(x, one))
assert reduce_rational_inequalities(
[[Le(x**2, one)]], x, relational=True) == \
And(And(Le(-one, x), Le(x, one)))
assert reduce_rational_inequalities(
[[Lt(x**2, one)]], x, relational=True) == \
And(And(Lt(-one, x), Lt(x, one)))
assert reduce_rational_inequalities(
[[Ge(x**2, one)]], x, relational=True) == \
And(Or(And(Le(one, x), Lt(x, inf)), And(Le(x, -one), Lt(-inf, x))))
assert reduce_rational_inequalities(
[[Gt(x**2, one)]], x, relational=True) == \
And(Or(And(Lt(-inf, x), Lt(x, -one)), And(Lt(one, x), Lt(x, inf))))
assert reduce_rational_inequalities(
[[Ne(x**2, one)]], x, relational=True) == \
Or(And(Lt(-inf, x), Lt(x, -one)),
And(Lt(-one, x), Lt(x, one)),
And(Lt(one, x), Lt(x, inf)))
def test_reduce_rational_inequalities_real_relational():
assert reduce_rational_inequalities([], x) is false
assert reduce_rational_inequalities(
[[(x**2 + 3*x + 2)/(x**2 - 16) >= 0]], x, relational=False) == \
Union(Interval.open(-oo, -4), Interval(-2, -1), Interval.open(4, oo))
assert reduce_rational_inequalities(
[[((-2*x - 10)*(3 - x))/((x**2 + 5)*(x - 2)**2) < 0]], x,
relational=False) == \
Union(Interval.open(-5, 2), Interval.open(2, 3))
assert reduce_rational_inequalities([[(x + 1)/(x - 5) <= 0]], x,
relational=False) == \
Interval.Ropen(-1, 5)
assert reduce_rational_inequalities([[(x**2 + 4*x + 3)/(x - 1) > 0]], x,
relational=False) == \
Union(Interval.open(-3, -1), Interval.open(1, oo))
assert reduce_rational_inequalities([[(x**2 - 16)/(x - 1)**2 < 0]], x,
relational=False) == \
Union(Interval.open(-4, 1), Interval.open(1, 4))
assert reduce_rational_inequalities([[(3*x + 1)/(x + 4) >= 1]], x,
relational=False) == \
Union(Interval.open(-oo, -4), Interval.Ropen(Rational(3, 2), oo))
assert reduce_rational_inequalities([[(x - 8)/x <= 3 - x]], x,
relational=False) == \
Union(Interval.Lopen(-oo, -2), Interval.Lopen(0, 4))
def test_reduce_piecewise_inequalities():
e = abs(x - 5) < 3
ans = And(Lt(2, x), Lt(x, 8))
assert reduce_inequalities(e) == ans
assert reduce_inequalities(e, x) == ans
assert reduce_inequalities(abs(x - 5)) == Eq(x, 5)
assert reduce_inequalities(
abs(2*x + 3) >= 8) == Or(And(Le(Rational(5, 2), x), Lt(x, oo)),
And(Le(x, -Rational(11, 2)), Lt(-oo, x)))
assert reduce_inequalities(abs(x - 4) + abs(
3*x - 5) < 7) == And(Lt(Rational(1, 2), x), Lt(x, 4))
assert reduce_inequalities(abs(x - 4) + abs(3*abs(x) - 5) < 7) == \
Or(And(Integer(-2) < x, x < -1), And(Rational(1, 2) < x, x < 4))
nr = Symbol('nr', extended_real=False)
pytest.raises(TypeError, lambda: reduce_inequalities(abs(nr - 5) < 3))
# sympy/sympy#10198
assert reduce_inequalities(-1 + 1/abs(1/x - 1) < 0) == \
Or(And(Lt(0, x), x < Rational(1, 2)), And(-oo < x, x < 0))
# sympy/sympy#10255
assert reduce_inequalities(Piecewise((1, x < 1), (3, True)) > 1) == \
And(Le(1, x), x < oo)
assert reduce_inequalities(Piecewise((x**2, x < 0), (2*x, x >= 0)) < 1) == \
And(Lt(-1, x), x < Rational(1, 2))
def test_reduce_inequalities_general():
assert reduce_inequalities(Ge(sqrt(2)*x, 1)) == And(sqrt(2)/2 <= x, x < oo)
assert reduce_inequalities(PurePoly(x + 1, x) > 0) == And(Integer(-1) < x, x < oo)
def test_reduce_inequalities_boolean():
assert reduce_inequalities(
[Eq(x**2, 0), True]) == Eq(x, 0)
assert reduce_inequalities([Eq(x**2, 0), False]) is false
def test_reduce_inequalities_multivariate():
assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == And(
Or(And(Le(1, x), Lt(x, oo)), And(Le(x, -1), Lt(-oo, x))),
Or(And(Le(1, y), Lt(y, oo)), And(Le(y, -1), Lt(-oo, y))))
def test_reduce_inequalities_errors():
pytest.raises(NotImplementedError, lambda: reduce_inequalities(Ge(sin(x) + x, 1)))
pytest.raises(NotImplementedError, lambda: reduce_inequalities(Ge(x**2*y + y, 1)))
def test_hacky_inequalities():
y = Symbol('y', real=True)
assert reduce_inequalities(x + y < 1, symbols=[x]) == And(-oo < x, x < -y + 1)
assert reduce_inequalities(x + y >= 1, symbols=[x]) == And(-y + 1 <= x, x < oo)
def test_sympyissue_10203():
y = Symbol('y', extended_real=True)
assert reduce_inequalities(Eq(0, x - y), symbols=[x]) == Eq(x, y)
assert reduce_inequalities(Ne(0, x - y), symbols=[x]) == \
Or(And(-oo < x, x < y), And(x < oo, y < x))
def test_sympyissue_6343():
eq = -3*x**2/2 - 45*x/4 + Rational(33, 2) > 0
assert reduce_inequalities(eq) == \
And(x < -Rational(15, 4) + sqrt(401)/4, -sqrt(401)/4 - Rational(15, 4) < x)
def test_sympyissue_8235():
assert reduce_inequalities(x**2 - 1 < 0) == \
And(Integer(-1) < x, x < Integer(1))
assert reduce_inequalities(x**2 - 1 <= 0) == \
And(Integer(-1) <= x, x <= 1)
assert reduce_inequalities(x**2 - 1 > 0) == \
Or(And(-oo < x, x < -1), And(x < oo, Integer(1) < x))
assert reduce_inequalities(x**2 - 1 >= 0) == \
Or(And(-oo < x, x <= Integer(-1)), And(Integer(1) <= x, x < oo))
eq = x**8 + x - 9 # we want RootOf solns here
sol = reduce_inequalities(eq >= 0)
tru = Or(And(RootOf(eq, 1) <= x, x < oo), And(-oo < x, x <= RootOf(eq, 0)))
assert sol == tru
# recast vanilla as real
assert reduce_inequalities(sqrt((-x + 1)**2) < 1) == And(Integer(0) < x, x < 2)
def test_sympyissue_5526():
assert reduce_inequalities(Integer(0) <=
x + Integral(y**2, (y, 1, 3)) - 1, [x]) == \
And(-Integral(y**2, (y, 1, 3)) + 1 <= x, x < oo)
def test_solve_univariate_inequality():
assert isolve(x**2 >= 4, x, relational=False) == Union(Interval(-oo, -2, True),
Interval(2, oo, False, True))
assert isolve(x**2 >= 4, x) == Or(And(Le(2, x), Lt(x, oo)), And(Le(x, -2),
Lt(-oo, x)))
assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x, relational=False) == \
Union(Interval(1, 2), Interval(3, oo, False, True))
assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x) == \
Or(And(Le(1, x), Le(x, 2)), And(Le(3, x), Lt(x, oo)))
# issue sympy/sympy#2785:
assert isolve(x**3 - 2*x - 1 > 0, x, relational=False) == \
Union(Interval(-1, -sqrt(5)/2 + Rational(1, 2), True, True),
Interval(Rational(1, 2) + sqrt(5)/2, oo, True, True))
# issue sympy/sympy#2794:
assert isolve(x**3 - x**2 + x - 1 > 0, x, relational=False) == \
Interval(1, oo, True, True)
# XXX should be limited in domain, e.g. between 0 and 2*pi
assert isolve(sin(x) < Rational(1, 2), x) == \
Or(And(-oo < x, x < pi/6), And(5*pi/6 < x, x < oo))
assert isolve(sin(x) > Rational(1, 2), x) == And(pi/6 < x, x < 5*pi/6)
# numerical testing in valid() is needed
assert isolve(x**7 - x - 2 > 0, x) == \
And(RootOf(x**7 - x - 2, 0) < x, x < oo)
# handle numerator and denominator; although these would be handled as
# rational inequalities, these test confirm that the right thing is done
# when the domain is EX (e.g. when 2 is replaced with sqrt(2))
assert isolve(1/(x - 2) > 0, x) == And(Integer(2) < x, x < oo)
den = ((x - 1)*(x - 2)).expand()
assert isolve((x - 1)/den <= 0, x) == \
Or(And(-oo < x, x < 1), And(Integer(1) < x, x < 2))
assert isolve(x > oo, x) is false
def test_slow_general_univariate():
r = RootOf(x**5 - x**2 + 1, 0)
assert reduce_inequalities(sqrt(x) + 1/root(x, 3) > 1) == \
Or(And(Integer(0) < x, x < r**6), And(r**6 < x, x < oo))
def test_sympyissue_8545():
eq = 1 - x - abs(1 - x)
ans = And(Lt(1, x), Lt(x, oo))
assert reduce_piecewise_inequality(eq, '<', x) == ans
eq = 1 - x - sqrt((1 - x)**2)
assert reduce_inequalities(eq < 0) == ans
def test_sympyissue_8974():
assert isolve(-oo < x, x) == And(-oo < x, x < oo)
assert isolve(oo > x, x) == And(-oo < x, x < oo)
def test_sympyissue_10196():
assert reduce_inequalities(x**2 >= 0)
assert reduce_inequalities(x**2 < 0) is false
def test_sympyissue_10268():
assert reduce_inequalities(log(x) < 300) == And(-oo < x, x < E**300)
def test_diofantissue_453():
x = Symbol('x', real=True)
assert isolve(abs((x - 1)/(x - 5)) <= Rational(1, 3),
x) == And(Integer(-1) <= x, x <= 2)
assert solve(abs((x - 1)/(x - 5)) - Rational(1, 3), x) == [{x: -1}, {x: 2}]
| bsd-3-clause |
andrewsmedina/django-admin2 | djadmin2/utils.py | 6646 | # -*- coding: utf-8 -*-
from __future__ import division, absolute_import, unicode_literals
from collections import defaultdict
from django.db.models.deletion import Collector, ProtectedError
from django.db.models.sql.constants import QUERY_TERMS
from django.utils import six
from django.utils.encoding import force_bytes, force_text
def lookup_needs_distinct(opts, lookup_path):
"""
Returns True if 'distinct()' should be used to query the given lookup path.
This is adopted from the Django core. django-admin2 mandates that code
doesn't depend on imports from django.contrib.admin.
https://github.com/django/django/blob/1.9.6/django/contrib/admin/utils.py#L22
"""
lookup_fields = lookup_path.split('__')
# Remove the last item of the lookup path if it is a query term
if lookup_fields[-1] in QUERY_TERMS:
lookup_fields = lookup_fields[:-1]
# Now go through the fields (following all relations) and look for an m2m
for field_name in lookup_fields:
field = opts.get_field(field_name)
if hasattr(field, 'get_path_info'):
# This field is a relation, update opts to follow the relation
path_info = field.get_path_info()
opts = path_info[-1].to_opts
if any(path.m2m for path in path_info):
# This field is a m2m relation so we know we need to call distinct
return True
return False
def model_options(model):
"""
Wrapper for accessing model._meta. If this access point changes in core
Django, this function allows django-admin2 to address the change with
what should hopefully be less disruption to the rest of the code base.
Works on model classes and objects.
"""
return model._meta
def admin2_urlname(view, action):
"""
Converts the view and the specified action into a valid namespaced URLConf name.
"""
return 'admin2:%s_%s_%s' % (view.app_label, view.model_name, action)
def model_verbose_name(model):
"""
Returns the verbose name of a model instance or class.
"""
return model_options(model).verbose_name
def model_verbose_name_plural(model):
"""
Returns the pluralized verbose name of a model instance or class.
"""
return model_options(model).verbose_name_plural
def model_field_verbose_name(model, field_name):
"""
Returns the verbose name of a model field.
"""
meta = model_options(model)
field = meta.get_field_by_name(field_name)[0]
return field.verbose_name
def model_method_verbose_name(model, method_name):
"""
Returns the verbose name / short description of a model field.
"""
method = getattr(model, method_name)
try:
return method.short_description
except AttributeError:
return method_name
def model_app_label(obj):
"""
Returns the app label of a model instance or class.
"""
return model_options(obj).app_label
def get_attr(obj, attr):
"""
Get the right value for the attribute. Handle special cases like callables
and the __str__ attribute.
"""
if attr == '__str__':
from builtins import str as text
value = text(obj)
else:
attribute = getattr(obj, attr)
value = attribute() if callable(attribute) else attribute
return value
class NestedObjects(Collector):
"""
This is adopted from the Django core. django-admin2 mandates that code
doesn't depend on imports from django.contrib.admin.
https://github.com/django/django/blob/1.9.6/django/contrib/admin/utils.py#L171-L231
"""
def __init__(self, *args, **kwargs):
super(NestedObjects, self).__init__(*args, **kwargs)
self.edges = {} # {from_instance: [to_instances]}
self.protected = set()
self.model_objs = defaultdict(set)
def add_edge(self, source, target):
self.edges.setdefault(source, []).append(target)
def collect(self, objs, source=None, source_attr=None, **kwargs):
for obj in objs:
if source_attr and not source_attr.endswith('+'):
related_name = source_attr % {
'class': source._meta.model_name,
'app_label': source._meta.app_label,
}
self.add_edge(getattr(obj, related_name), obj)
else:
self.add_edge(None, obj)
self.model_objs[obj._meta.model].add(obj)
try:
return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
except ProtectedError as e:
self.protected.update(e.protected_objects)
def related_objects(self, related, objs):
qs = super(NestedObjects, self).related_objects(related, objs)
return qs.select_related(related.field.name)
def _nested(self, obj, seen, format_callback):
if obj in seen:
return []
seen.add(obj)
children = []
for child in self.edges.get(obj, ()):
children.extend(self._nested(child, seen, format_callback))
if format_callback:
ret = [format_callback(obj)]
else:
ret = [obj]
if children:
ret.append(children)
return ret
def nested(self, format_callback=None):
"""
Return the graph as a nested list.
"""
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots
def can_fast_delete(self, *args, **kwargs):
"""
We always want to load the objects into memory so that we can display
them to the user in confirm page.
"""
return False
def quote(s):
"""
Ensure that primary key values do not confuse the admin URLs by escaping
any '/', '_' and ':' and similarly problematic characters.
Similar to urllib.quote, except that the quoting is slightly different so
that it doesn't get automatically unquoted by the Web browser.
This is adopted from the Django core. django-admin2 mandates that code
doesn't depend on imports from django.contrib.admin.
https://github.com/django/django/blob/1.9.6/django/contrib/admin/utils.py#L66-L73
"""
if not isinstance(s, six.string_types):
return s
res = list(s)
for i in range(len(res)):
c = res[i]
if c in """:/_#?;@&=+$,"[]<>%\n\\""":
res[i] = '_%02X' % ord(c)
return ''.join(res)
def type_str(text):
if six.PY2:
return force_bytes(text)
else:
return force_text(text)
| bsd-3-clause |
holisticon/skill-based-routing | skill-based-routing-plugin/skill-based-routing-plugin-impl/src/main/java/de/holisticon/bpm/sbr/plugin/setup/ShowcaseSetup.java | 1434 | package de.holisticon.bpm.sbr.plugin.setup;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import org.flywaydb.core.Flyway;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ShowcaseSetup implements Runnable {
private static final String LICENSE_PACKAGE = "de/holisticon/bpm/camunda/license";
private static final String LICENSE_LOCATION = "classpath:" + LICENSE_PACKAGE.replaceAll("/", ".");
private static final ClassLoader CLASS_LOADER = Flyway.class.getClassLoader();
@VisibleForTesting
static final boolean IS_LICENSE_PRESENT = CLASS_LOADER.getResource(LICENSE_PACKAGE) != null;
private final Flyway flyway = new Flyway();
public ShowcaseSetup() {
this(lookupDataSource());
}
public ShowcaseSetup(final DataSource dataSource) {
flyway.setDataSource(dataSource);
}
@Override
public void run() {
flyway.setClassLoader(Flyway.class.getClassLoader());
if (IS_LICENSE_PRESENT) {
flyway.setLocations(flyway.getLocations()[0], LICENSE_LOCATION);
}
flyway.clean();
flyway.migrate();
}
private static DataSource lookupDataSource() {
try {
String jndi = "java:jboss/datasources/ProcessEngine";
return (DataSource) new InitialContext().lookup(jndi);
} catch (NamingException e) {
throw Throwables.propagate(e);
}
}
}
| bsd-3-clause |
appleseedhq/gaffer | python/GafferArnoldUI/ArnoldTextureBakeUI.py | 5993 | ##########################################################################
#
# Copyright (c) 2018, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import Gaffer
import GafferArnold
Gaffer.Metadata.registerNode(
GafferArnold.ArnoldTextureBake,
"description",
"""
Render meshes in Arnold, storing the results into images in the texture space of the meshes.
Supports multiple meshes and UDIMs, and any AOVs output by Arnold. The file name and
resolution can be overridden per mesh using the "bake:fileName" and "bake:resolution" attributes.
""",
"layout:activator:medianActivator", lambda parent : parent["applyMedianFilter"].getValue(),
plugs = {
"in" : [
"description",
"""
The input scene containing the meshes to bake, and any lights which affect them.
""",
"nodule:type", "GafferUI::StandardNodule",
],
"filter" : [
"description",
"""
The filter used to control which meshes the textures will be baked for.
A Filter node should be connected here.
""",
"layout:section", "Filter",
"noduleLayout:section", "right",
"layout:index", -3, # Just before the enabled plug,
"nodule:type", "GafferUI::StandardNodule",
"plugValueWidget:type", "GafferSceneUI.FilterPlugValueWidget",
],
"bakeDirectory" : [
"description",
"""
Sets the Context Variable used in the default file name to control where all the bakes will be stored.
""",
],
"defaultFileName" : [
"description",
"""
The file name to use for each texture file written. <UDIM> will be replaced by the UDIM number,
and <AOV> will be replaced by the aov name specified in "aovs". If you want to do an animated bake,
you can also use #### which will be replaced by the frame number.
May be overridden per mesh by specifying the "bake:fileName" string attribute on the meshes to be baked.
""",
],
"defaultResolution" : [
"description",
"""
The resolution to use for each texture file written.
May be overridden per mesh by specifying the "bake:resolution" integer attribute on the meshes to be baked.
""",
],
"uvSet" : [
"description",
"""
The name of the primitive variable containing uvs which will determine how the mesh is unwrapped
for baking. Must be a Face-Varying or Vertex V2f primitive variable.
""",
],
"normalOffset" : [
"description",
"""
How far Arnold steps away from the surface before tracing back. If too large for your scene,
you will incorrectly capture occluders near the mesh instead of the mesh itself. If too small,
everything will go speckly because Arnold has insufficient precision to hit the mesh. For objects
which are fairly large and simple, the default 0.1 should work. Smaller objects may require smaller
values.
""",
],
"aovs" : [
"description",
"""
A space separated list of colon separated pairs of image name and data to render.
For example, you could set this to "myName1:RGBA myName2:diffuse myName3:diffuse_albedo", to
render 3 sets of images for every UDIM and mesh baked, containing all lighting, just diffuse
lighting, and the diffuse albedo.
""",
],
"tasks" : [
"description",
"""
How many tasks the bake process will be split into. UDIMs cannot be split across tasks, so if you
have few UDIMs available, the extra tasks won't do anything, but if you have a large number of
UDIMs, and are dispatching to a pool of machines, increasing the number of tasks used will speed
up bakes, at the cost of using more machines.
""",
],
"cleanupIntermediateFiles" : [
"description",
"""
During baking, we first render exrs ( potentially multiple EXRs per udim if multiple objects
are present ). We then combine them, fill in the background, and convert to textures. This
causes all intermediate EXRs, and the index txt file to be removed, and just the final .tx to be kept.
""",
"divider", True,
],
"applyMedianFilter" : [
"description",
"""
Adds a simple denoising filter to the texture bake. Mostly preserves high-contrast edges.
""",
],
"medianRadius" : [
"description",
"""
The radius of the median filter. Values greater than 1 will likely remove small details from the texture.
""",
"layout:activator", "medianActivator",
],
}
)
| bsd-3-clause |
SnakeDoc/GuestVM | guestvm~guestvm/com.oracle.max.ve.yanfs/src/com/sun/gssapi/dummy/DummyName.java | 5936 | /*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sun.gssapi.dummy;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import com.sun.gssapi.*;
/**
* Implements the GSSNameSpi for the dummy mechanism.
*/
public class DummyName implements GSSNameSpi {
/**
* Returns the default name for the dummy mechanism.
* It is the username@localDomain.
*/
static DummyName getDefault() {
StringBuffer res = new StringBuffer(System.getProperty("user.name", "unknown"));
res.append("@");
try {
res.append(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
res.append("unknown");
}
return (new DummyName(res.toString()));
}
/**
* Standard constructor - nop.
*/
public DummyName() { }
/**
* Creates a dummy name from the specified user name.
*/
DummyName(String userName) {
m_type = GSSName.NT_USER_NAME;
m_name = userName;
}
/**
* Initializer for the GSSNameSpi object using a byte array.
*
* @param byte[] name bytes which is to be interpreted based
* on the nameType
* @exception GSSException The major codes can be BAD_NAMETYPE,
* BAD_NAME, and FAILURE.
* @see #init(String,Oid)
*/
@Override
public void init(byte[] externalName, Oid nameType) throws GSSException {
throw new GSSException(GSSException.UNAVAILABLE);
}
/**
* Initializer for the GSSNameSpi object using a String.
*
* @param name string which is to be interpreted based
* on the nameType
* @exception GSSException The major codes can be BAD_NAMETYPE,
* BAD_NAME, and FAILURE.
* @see #init(String,Oid)
*/
@Override
public void init(String name, Oid nameType) throws GSSException {
m_name = name;
m_type = nameType;
}
/**
* Equal method for the GSSNameSpi objects.
* If either name denotes an anonymous principal, the call should
* return false.
*
* @param name to be compared with
* @returns true if they both refer to the same entity, else false
* @exception GSSException with major codes of BAD_NAMETYPE,
* BAD_NAME, FAILURE
*/
@Override
public boolean equals(GSSNameSpi name) throws GSSException {
if (!(name instanceof DummyName)) {
return (false);
}
return (m_name.equals(((DummyName)name).m_name));
}
/**
* Returns a flat name representation for this object. The name
* format is defined in RFC 2078.
*
* @return the flat name representation for this object
* @exception GSSException with major codes NAME_NOT_MN, BAD_NAME,
* BAD_NAME, FAILURE.
*/
@Override
public byte[] export() throws GSSException {
throw new GSSException(GSSException.UNAVAILABLE);
}
/**
* Get the mechanism type that this NameElement corresponds to.
*
* @return the Oid of the mechanism type
*/
@Override
public Oid getMech() {
return (Dummy.getMyOid());
}
/**
* Returns a string representation for this name. The printed
* name type can be obtained by calling getStringNameType().
*
* @return string form of this name
* @see #getStringNameType()
* @overrides Object#toString
*/
@Override
public String toString() {
return (m_name);
}
/**
* Returns the name type oid.
*/
@Override
public Oid getNameType() {
return (m_type);
}
/**
* Returns the oid describing the format of the printable name.
*
* @return the Oid for the format of the printed name
*/
@Override
public Oid getStringNameType() {
return (m_type);
}
/**
* Produces a copy of this object.
*/
@Override
public Object clone() {
return null;
}
/**
* Indicates if this name object represents an Anonymous name.
*/
@Override
public boolean isAnonymousName() {
if (m_type.equals(GSSName.NT_ANONYMOUS))
return (true);
return (false);
}
//instance variables
private String m_name;
private Oid m_type;
}
| bsd-3-clause |
SelvEsperer/aviacion | views/booking/update.php | 533 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Booking */
$this->title = 'Update Booking: ' . ' ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => 'Bookings', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="booking-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| bsd-3-clause |
phpwork1/k3lh | backend/themes/AceMaster/views/p3k-monitoring-detail/index.php | 2257 | <?php
use yii\helpers\Html;
use yii\grid\GridView;
use common\vendor\AppLabels;
/* @var $this yii\web\View */
/* @var $searchModel backend\models\P3kMonitoringDetailSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
/* @var $pmId int */
/* @var $powerPlantModel backend\models\PowerPlant */
$this->title = sprintf("Form %s %s", AppLabels::FORM_P3K_MONITORING_DETAIL, $powerPlantModel->getSummary());
$this->params['breadcrumbs'][] = ['label' => AppLabels::FORM_P3K_MONITORING, 'url' => ['p3k-monitoring/index', '_ppId' => $powerPlantModel->id]];
$this->params['breadcrumbs'][] = $this->title;
$actionColumn = Yii::$container->get('yii\grid\ActionColumn');
$buttons = array_merge($actionColumn->buttons, [
'update' => function ($url, $model) {
return Html::a('<i class="ace-icon fa fa-pencil bigger-120"></i> ' . AppLabels::BTN_UPDATE, ['p3k-monitoring-detail/update', '_ppId' => $model->p3kMonitoring->powerPlant->id, 'id' => $model->id, 'pmId' => $model->p3k_monitoring_id], ['class' => 'btn btn-xs btn-info']);
},
'update_xs' => function ($url, $model) {
return Html::a('<span class="green"><i class="ace-icon fa fa-pencil bigger-120"></i></span>', ['p3k-monitoring-detail/update', '_ppId' => $model->p3kMonitoring->powerPlant->id, 'id' => $model->id, 'pmId' => $model->p3k_monitoring_id], ['class' => 'tooltip-success', 'data-rel' => 'tooltip', 'data-original-title' => AppLabels::BTN_UPDATE]);
},
]);
?>
<div class="p3k-monitoring-detail-index">
<div class="page-header">
<h1><?= Html::encode($this->title) ?></h1>
</div>
<div class="clearfix">
<div class="pull-right">
<?= Html::a(AppLabels::BTN_ADD, ['create', '_ppId' => $powerPlantModel->id, 'pmId' => $pmId], ['class' => 'btn btn-sm btn-success']) ?>
</div>
</div>
<hr/>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'pmd_value',
'pmd_standard_amount',
'pmd_ref:ntext',
[
'class' => 'yii\grid\ActionColumn',
'buttons' => $buttons,
],
],
]); ?>
</div>
| bsd-3-clause |
MrEliasen/Zolid-Framework | app/controllers/admin/home.php | 2001 | <?php
/**
* Zolid Framework
* https://github.com/MrEliasen/Zolid-Framework
*
* @author Mark Eliasen (mark.eliasen@zolidsolutions.com)
* @copyright Copyright (c) 2014, Mark Eliasen
* @version 0.1.6.1
* @license http://opensource.org/licenses/MIT MIT License
*/
class ControllersAdminHome extends AppController
{
/**
* Loads from default statistics for the number of accounts in the system.
*
* @return array
*/
public function getStatistics()
{
return $this->model->getStatistics();
}
/**
* Checks if any new version is available for the Zolid Framework.
*
* @return array
*/
public function checkVersion()
{
$output = array(
'current' => ZF_VERSION,
'latest' => 'Unknown',
'upgrade' => false,
'release' => null,
'priority' => 0,
'message' => ''
);
$versiondata = file_get_contents('https://raw.github.com/MrEliasen/Zolid-Framework/master/latestversion', null, stream_context_create(array('http' => array('timeout' => 5))));
if( !empty($versiondata) )
{
$versiondata = @json_decode($versiondata, true);
if( !empty($versiondata) )
{
if( version_compare($output['current'], $versiondata['version'], '<') )
{
$output['upgrade'] = true;
}
$output['latest'] = Security::sanitize($versiondata['version'], 'mixedint');
$output['release'] = Security::sanitize($versiondata['date'], 'integer');
$output['message'] = Security::sanitize($versiondata['message'], 'string');
$output['priority'] = Security::sanitize($versiondata['priority'], 'string');
}
else
{
$output['latest'] = 'Failed (invalid response)';
}
}
else
{
$output['latest'] = 'Failed (timeout)';
}
return $output;
}
} | bsd-3-clause |
rgarro/zf2 | tests/Zend/Service/Technorati/TechnoratiTest.php | 24405 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service_Technorati
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* Test helper
*/
/**
* @category Zend
* @package Zend_Service_Technorati
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Service
* @group Zend_Service_Technorati
*/
class Zend_Service_Technorati_TechnoratiTest extends Zend_Service_Technorati_TestCase
{
const TEST_APY_KEY = 'somevalidapikey';
const TEST_PARAM_COSMOS = 'http://www.simonecarletti.com/blog/';
const TEST_PARAM_SEARCH = 'google';
const TEST_PARAM_TAG = 'google';
const TEST_PARAM_DAILYCOUNT = 'google';
const TEST_PARAM_GETINFO = 'weppos';
const TEST_PARAM_BLOGINFO = 'http://www.simonecarletti.com/blog/';
const TEST_PARAM_BLOGPOSTTAGS = 'http://www.simonecarletti.com/blog/';
public function setUp()
{
/**
* @see Zend_Http_Client_Adapter_Test
*/
$adapter = new Zend_Http_Client_Adapter_Test();
/**
* @see Zend_Http_Client
*/
$client = new Zend_Http_Client(Zend_Service_Technorati::API_URI_BASE, array(
'adapter' => $adapter
));
$this->technorati = new Zend_Service_Technorati(self::TEST_APY_KEY);
$this->adapter = $adapter;
$this->technorati->getRestClient()->setHttpClient($client);
}
public function testConstruct()
{
$this->_testConstruct('Zend_Service_Technorati', array(self::TEST_APY_KEY));
}
public function testApiKeyMatches()
{
$object = $this->technorati;
$this->assertEquals(self::TEST_APY_KEY, $object->getApiKey());
}
public function testSetGetApiKey()
{
$object = $this->technorati;
$set = 'just a test';
$get = $object->setApiKey($set)->getApiKey();
$this->assertEquals($set, $get);
}
public function testCosmos()
{
$result = $this->_setResponseFromFile('TestCosmosSuccess.xml')->cosmos(self::TEST_PARAM_COSMOS);
$this->assertType('Zend_Service_Technorati_CosmosResultSet', $result);
$this->assertEquals(2, $result->totalResults());
$result->seek(0);
$this->assertType('Zend_Service_Technorati_CosmosResult', $result->current());
// content is validated in Zend_Service_Technorati_CosmosResultSet tests
}
public function testCosmosThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestCosmosError.xml')->cosmos(self::TEST_PARAM_COSMOS);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Invalid request: url is required", $e->getMessage());
}
}
public function testCosmosThrowsExceptionWithInvalidUrl()
{
// url is mandatory --> validated by PHP interpreter
// url must not be empty
$this->_testThrowsExceptionWithInvalidMandatoryOption('cosmos', 'url');
}
public function testCosmosThrowsExceptionWithInvalidOption()
{
$options = array(
array('type' => 'foo'),
array('limit' => 'foo'),
array('limit' => 0),
array('limit' => 101),
array('start' => 0),
// 'current' => // cast to int
// 'claim' => // cast to int
// 'highlight' => // cast to int
);
$this->_testThrowsExceptionWithInvalidOption($options, 'TestCosmosSuccess.xml', 'cosmos', array(self::TEST_PARAM_COSMOS));
}
public function testCosmosOption()
{
$options = array(
array('type' => 'link'),
array('type' => 'weblog'),
array('limit' => 1),
array('limit' => 50),
array('limit' => 100),
array('start' => 1),
array('start' => 1000),
array('current' => false), // cast to int
array('current' => 0), // cast to int
array('claim' => false), // cast to int
array('claim' => 0), // cast to int
array('highlight' => false), // cast to int
array('highlight' => 0), // cast to int
);
$this->_testOption($options, 'TestCosmosSuccess.xml', 'cosmos', array(self::TEST_PARAM_COSMOS));
}
public function testSearch()
{
$result = $this->_setResponseFromFile('TestSearchSuccess.xml')->search(self::TEST_PARAM_SEARCH);
$this->assertType('Zend_Service_Technorati_SearchResultSet', $result);
$this->assertEquals(2, $result->totalResults());
$result->seek(0);
$this->assertType('Zend_Service_Technorati_SearchResult', $result->current());
// content is validated in Zend_Service_Technorati_SearchResultSet tests
}
/**
* @see /_files/MISSING
*
public function testSearchThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestSearchError.xml')->cosmos(self::TEST_PARAM_COSMOS);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Invalid request: url is required", $e->getMessage());
}
} */
public function testSearchThrowsExceptionWithInvalidQuery()
{
// query is mandatory --> validated by PHP interpreter
// query must not be empty
$this->_testThrowsExceptionWithInvalidMandatoryOption('search', 'query');
}
public function testSearchThrowsExceptionWithInvalidOption()
{
$options = array(
array('authority' => 'foo'),
array('limit' => 'foo'),
array('limit' => 0),
array('limit' => 101),
array('start' => 0),
// 'claim' => // cast to int
);
$this->_testThrowsExceptionWithInvalidOption($options, 'TestSearchSuccess.xml', 'search', array(self::TEST_PARAM_SEARCH));
}
public function testSearchOption()
{
$options = array(
array('language' => 'en'), // not validated
array('authority' => 'n'),
array('authority' => 'a1'),
array('authority' => 'a4'),
array('authority' => 'a7'),
array('limit' => 1),
array('limit' => 50),
array('limit' => 100),
array('start' => 1),
array('start' => 1000),
array('claim' => false), // cast to int
array('claim' => 0), // cast to int
);
$this->_testOption($options, 'TestSearchSuccess.xml', 'search', array(self::TEST_PARAM_SEARCH));
}
public function testTag()
{
$result = $this->_setResponseFromFile('TestTagSuccess.xml')->tag(self::TEST_PARAM_TAG);
$this->assertType('Zend_Service_Technorati_TagResultSet', $result);
$this->assertEquals(2, $result->totalResults());
$result->seek(0);
$this->assertType('Zend_Service_Technorati_TagResult', $result->current());
// content is validated in Zend_Service_Technorati_TagResultSet tests
}
public function testTagThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestTagError.xml')->tag(self::TEST_PARAM_TAG);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Invalid request.", $e->getMessage());
}
}
public function testTagThrowsExceptionWithInvalidTag()
{
// tag is mandatory --> validated by PHP interpreter
// tag must not be empty
$this->_testThrowsExceptionWithInvalidMandatoryOption('tag', 'tag');
}
public function testTagThrowsExceptionWithInvalidOption()
{
$options = array(
array('limit' => 'foo'),
array('limit' => 0),
array('limit' => 101),
array('start' => 0),
// 'excerptsize' => // cast to int
// 'topexcerptsize' => // cast to int
);
$this->_testThrowsExceptionWithInvalidOption($options, 'TestTagSuccess.xml', 'tag', array(self::TEST_PARAM_TAG));
}
public function testTagOption()
{
$options = array(
array('excerptsize' => 150), // cast to int
array('excerptsize' => '150'), // cast to int
array('topexcerptsize' => 150), // cast to int
array('topexcerptsize' => '150'), // cast to int
array('limit' => 1),
array('limit' => 50),
array('limit' => 100),
array('start' => 1),
array('start' => 1000),
);
$this->_testOption($options, 'TestTagSuccess.xml', 'tag', array(self::TEST_PARAM_TAG));
}
public function testDailyCounts()
{
$result = $this->_setResponseFromFile('TestDailyCountsSuccess.xml')->dailyCounts(self::TEST_PARAM_DAILYCOUNT);
$this->assertType('Zend_Service_Technorati_DailyCountsResultSet', $result);
$this->assertEquals(180, $result->totalResults());
$result->seek(0);
$this->assertType('Zend_Service_Technorati_DailyCountsResult', $result->current());
// content is validated in Zend_Service_Technorati_DailyCountsResultSet tests
}
public function testDailyCountsThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestDailyCountsError.xml')->dailyCounts(self::TEST_PARAM_DAILYCOUNT);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Missing required parameter", $e->getMessage());
}
}
public function testDailyCountsThrowsExceptionWithInvalidQuery()
{
// q is mandatory --> validated by PHP interpreter
// q must not be empty
$this->_testThrowsExceptionWithInvalidMandatoryOption('dailyCounts', 'q');
}
public function testDailyCountsThrowsExceptionWithInvalidOption()
{
$options = array(
array('days' => 0),
array('days' => '0'),
array('days' => 181),
array('days' => '181'),
);
$this->_testThrowsExceptionWithInvalidOption($options, 'TestDailyCountsSuccess.xml', 'dailyCounts', array(self::TEST_PARAM_DAILYCOUNT));
}
public function testDailyCountsOption()
{
$options = array(
array('days' => 120), // cast to int
array('days' => '120'), // cast to int
array('days' => 180), // cast to int
array('days' => '180'), // cast to int
);
$this->_testOption($options, 'TestDailyCountsSuccess.xml', 'dailyCounts', array(self::TEST_PARAM_DAILYCOUNT));
}
public function testBlogInfo()
{
$result = $this->_setResponseFromFile('TestBlogInfoSuccess.xml')->blogInfo(self::TEST_PARAM_BLOGINFO);
$this->assertType('Zend_Service_Technorati_BlogInfoResult', $result);
// content is validated in Zend_Service_Technorati_BlogInfoResult tests
}
public function testBlogInfoThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestBlogInfoError.xml')->blogInfo(self::TEST_PARAM_BLOGINFO);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Invalid request: url is required", $e->getMessage());
}
}
public function testBlogInfoThrowsExceptionWithInvalidUrl()
{
// url is mandatory --> validated by PHP interpreter
// url must not be empty
$this->_testThrowsExceptionWithInvalidMandatoryOption('blogInfo', 'url');
}
public function testBlogInfoThrowsExceptionWithUrlNotWeblog()
{
// emulate Technorati exception
// when URL is not a recognized weblog
try {
$this->_setResponseFromFile('TestBlogInfoErrorUrlNotWeblog.xml')->blogInfo('www.simonecarletti.com');
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Technorati weblog", $e->getMessage());
}
}
public function testBlogPostTags()
{
$result = $this->_setResponseFromFile('TestBlogPostTagsSuccess.xml')->blogPostTags(self::TEST_PARAM_BLOGPOSTTAGS);
$this->assertType('Zend_Service_Technorati_TagsResultSet', $result);
// content is validated in Zend_Service_Technorati_TagsResultSet tests
}
public function testBlogPostTagsThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestBlogPostTagsError.xml')->blogPostTags(self::TEST_PARAM_BLOGPOSTTAGS);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Invalid request: url is required", $e->getMessage());
}
}
public function testBlogPostTagsThrowsExceptionWithInvalidUrl()
{
// url is mandatory --> validated by PHP interpreter
// url must not be empty
$this->_testThrowsExceptionWithInvalidMandatoryOption('blogPostTags', 'url');
}
public function testBlogPostTagsThrowsExceptionWithInvalidOption()
{
$options = array(
array('limit' => 'foo'),
array('limit' => 0),
array('limit' => 101),
array('start' => 0),
);
$this->_testThrowsExceptionWithInvalidOption($options, 'TestBlogPostTagsSuccess.xml', 'blogPostTags', array(self::TEST_PARAM_BLOGPOSTTAGS));
}
public function testBlogPostTagsOption()
{
$options = array(
array('limit' => 1),
array('limit' => 50),
array('limit' => 100),
array('start' => 1),
array('start' => 1000),
);
$this->_testOption($options, 'TestBlogPostTagsSuccess.xml', 'blogPostTags', array(self::TEST_PARAM_BLOGPOSTTAGS));
}
public function testTopTags()
{
$result = $this->_setResponseFromFile('TestTopTagsSuccess.xml')->topTags();
$this->assertType('Zend_Service_Technorati_TagsResultSet', $result);
// content is validated in Zend_Service_Technorati_TagsResultSet tests
}
public function testTopTagsThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestTopTagsError.xml')->topTags();
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Invalid key.", $e->getMessage());
}
}
public function testTopTagsThrowsExceptionWithInvalidOption()
{
$options = array(
array('limit' => 'foo'),
array('limit' => 0),
array('limit' => 101),
array('start' => 0),
);
$this->_testThrowsExceptionWithInvalidOption($options, 'TestTopTagsSuccess.xml', 'topTags');
}
public function testTopTagsOption()
{
$options = array(
array('limit' => 1),
array('limit' => 50),
array('limit' => 100),
array('start' => 1),
array('start' => 1000),
);
$this->_testOption($options, 'TestTopTagsSuccess.xml', 'topTags');
}
public function testGetInfo()
{
$result = $this->_setResponseFromFile('TestGetInfoSuccess.xml')->getInfo(self::TEST_PARAM_GETINFO);
$this->assertType('Zend_Service_Technorati_GetInfoResult', $result);
// content is validated in Zend_Service_Technorati_GetInfoResult tests
}
public function testGetInfoThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestGetInfoError.xml')->getInfo(self::TEST_PARAM_GETINFO);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Username is a required field.", $e->getMessage());
}
}
public function testGetInfoThrowsExceptionWithInvalidUsername()
{
// username is mandatory --> validated by PHP interpreter
// username must not be empty
$this->_testThrowsExceptionWithInvalidMandatoryOption('getInfo', 'username');
}
public function testKeyInfo()
{
$result = $this->_setResponseFromFile('TestKeyInfoSuccess.xml')->keyInfo();
$this->assertType('Zend_Service_Technorati_KeyInfoResult', $result);
// content is validated in Zend_Service_Technorati_KeyInfoResult tests
}
public function testKeyInfoThrowsExceptionWithError()
{
try {
$this->_setResponseFromFile('TestKeyInfoError.xml')->keyInfo();
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("Invalid key.", $e->getMessage());
}
}
public function testAllThrowsExceptionWithInvalidOptionFormat()
{
$invalidFormatOption = array('format' => 'rss');
// format must be XML
$methods = array('cosmos' => self::TEST_PARAM_COSMOS,
'search' => self::TEST_PARAM_SEARCH,
'tag' => self::TEST_PARAM_TAG,
'dailyCounts' => self::TEST_PARAM_DAILYCOUNT,
'topTags' => null,
'blogInfo' => self::TEST_PARAM_BLOGINFO,
'blogPostTags' => self::TEST_PARAM_BLOGPOSTTAGS,
'getInfo' => self::TEST_PARAM_GETINFO);
$technorati = $this->technorati;
foreach ($methods as $method => $param) {
$options = array_merge((array) $param, array($invalidFormatOption));
try {
call_user_func_array(array($technorati, $method), $options);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("'format'", $e->getMessage());
}
}
}
public function testAllThrowsExceptionWithUnknownOption()
{
$invalidOption = array('foo' => 'bar');
$methods = array('cosmos' => self::TEST_PARAM_COSMOS,
'search' => self::TEST_PARAM_SEARCH,
'tag' => self::TEST_PARAM_TAG,
'dailyCounts' => self::TEST_PARAM_DAILYCOUNT,
'topTags' => null,
'blogInfo' => self::TEST_PARAM_BLOGINFO,
'blogPostTags' => self::TEST_PARAM_BLOGPOSTTAGS,
'getInfo' => self::TEST_PARAM_GETINFO);
$technorati = $this->technorati;
foreach ($methods as $method => $param) {
$options = array_merge((array) $param, array($invalidOption));
try {
call_user_func_array(array($technorati, $method), $options);
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("'foo'", $e->getMessage());
}
}
}
/**
* Tests whether $callbackMethod method throws an Exception
* with Invalid Url.
*
* @param string $callbackMethod
*/
private function _testThrowsExceptionWithInvalidMandatoryOption($callbackMethod, $name)
{
try {
$this->technorati->$callbackMethod('');
$this->fail('Expected Zend_Service_Technorati_Exception not thrown');
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("'$name'", $e->getMessage());
}
}
/**
* Tests whether for each $validOptions a method call is successful.
*
* @param array $validOptions
* @param string $xmlFile
* @param string $callbackMethod
* @param null|array $callbackRequiredOptions
*/
private function _testOption($validOptions, $xmlFile, $callbackMethod, $callbackRequiredOptions = null)
{
$technorati = $this->_setResponseFromFile($xmlFile);
foreach ($validOptions as $pair) {
list($option, $value) = each($pair);
$options = is_array($callbackRequiredOptions) ?
array_merge($callbackRequiredOptions, array($pair)) :
array($pair);
try {
call_user_func_array(array($technorati, $callbackMethod), $options);
} catch (Zend_Service_Technorati_Exception $e) {
$this->fail("Exception " . $e->getMessage() . " thrown " .
"for option '$option' value '$value'");
}
}
}
/**
* Tests whether for each $validOptions a method call is successful.
*
* @param array $invalidOptions
* @param string $xmlFile
* @param string $callbackMethod
* @param null|array $callbackRequiredOptions
*/
private function _testThrowsExceptionWithInvalidOption($invalidOptions, $xmlFile, $callbackMethod, $callbackRequiredOptions = null)
{
$technorati = $this->_setResponseFromFile($xmlFile);
foreach ($invalidOptions as $pair) {
list($option, $value) = each($pair);
$options = is_array($callbackRequiredOptions) ?
array_merge($callbackRequiredOptions, array($pair)) :
array($pair);
try {
call_user_func_array(array($technorati, $callbackMethod), $options);
$this->fail("Expected Zend_Service_Technorati_Exception not thrown " .
"for option '$option' value '$value'");
} catch (Zend_Service_Technorati_Exception $e) {
$this->assertContains("'$option'", $e->getMessage());
}
}
}
/**
* Loads a response content from a test case file
* and sets the content to current Test Adapter.
*
* Returns current Zend_Service_Technorati instance
* to let developers use the powerful chain call.
*
* Do not execute any file validation. Please use this method carefully.
*
* @params string $file
* @return Zend_Service_Technorati
*/
private function _setResponseFromFile($file)
{
$response = "HTTP/1.0 200 OK\r\n"
. "Date: " . date(DATE_RFC1123) . "\r\n"
. "Server: Apache\r\n"
. "Cache-Control: max-age=60\r\n"
. "Content-Type: text/xml; charset=UTF-8\r\n"
. "X-Powered-By: PHP/5.2.1\r\n"
. "Connection: close\r\n"
. "\r\n"
. file_get_contents(__DIR__ . '/_files/' . $file) ;
$this->adapter->setResponse($response);
return $this->technorati; // allow chain call
}
}
| bsd-3-clause |
DEVPAR/wigle-wifi-wardriving | wiglewifiwardriving/src/main/java/net/wigle/wigleandroid/MapFilterActivity.java | 5022 | package net.wigle.wigleandroid;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import net.wigle.wigleandroid.util.SettingsUtil;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Building a filter activity for the network list
* Created by arkasha on 8/1/17.
*/
@SuppressWarnings("deprecation")
public class MapFilterActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences prefs = this.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
final SharedPreferences.Editor editor = prefs.edit();
setContentView(R.layout.mapfilter);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
View view = findViewById(android.R.id.content);
MainActivity.info("Filter Fragment Selected");
final EditText regex = (EditText) findViewById( R.id.edit_regex );
final String regexKey = MappingFragment.MAP_DIALOG_PREFIX + ListFragment.PREF_MAPF_REGEX;
regex.setText( prefs.getString(regexKey, "") );
regex.addTextChangedListener( new SettingsFragment.SetWatcher() {
@Override
public void onTextChanged( final String s ) {
//DEBUG: MainActivity.info("regex update: "+s);
String currentValue = prefs.getString(regexKey, "");
if (currentValue.equals(s.trim())) {
return;
}
if (s.trim().isEmpty()) {
//ALIBI: empty values should unset
editor.remove(regexKey);
} else {
editor.putString(regexKey, s.trim());
}
editor.apply();
}
});
//TODO: DRY up with SettingsFragment
final String authUser = prefs.getString(ListFragment.PREF_AUTHNAME,"");
final String authToken = prefs.getString(ListFragment.PREF_TOKEN, "");
final boolean isAnonymous = prefs.getBoolean( ListFragment.PREF_BE_ANONYMOUS, false);
final String showDiscovered = prefs.getString( ListFragment.PREF_SHOW_DISCOVERED, ListFragment.PREF_MAP_NO_TILE);
final boolean isAuthenticated = (!authUser.isEmpty() && !authToken.isEmpty() && !isAnonymous);
final String[] mapModes = SettingsUtil.getMapModes(isAuthenticated);
final String[] mapModeName = SettingsUtil.getMapModeNames(isAuthenticated, MapFilterActivity.this);
if (!ListFragment.PREF_MAP_NO_TILE.equals(showDiscovered)) {
LinearLayout mainLayout = (LinearLayout) view.findViewById(R.id.show_map_discovered_since);
mainLayout.setVisibility(View.VISIBLE);
}
SettingsUtil.doMapSpinner( R.id.show_discovered, ListFragment.PREF_SHOW_DISCOVERED,
ListFragment.PREF_MAP_NO_TILE, mapModes, mapModeName, MapFilterActivity.this, view );
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
List<Long> yearValueBase = new ArrayList<Long>();
List<String> yearLabelBase = new ArrayList<String>();
for (int i = 2001; i <= thisYear; i++) {
yearValueBase.add((long)(i));
yearLabelBase.add(Integer.toString(i));
}
SettingsUtil.doSpinner( R.id.networks_discovered_since_year, view, ListFragment.PREF_SHOW_DISCOVERED_SINCE,
2001L, yearValueBase.toArray(new Long[0]),
yearLabelBase.toArray(new String[0]), MapFilterActivity.this );
MainActivity.prefBackedCheckBox(this , view, R.id.showinvert,
MappingFragment.MAP_DIALOG_PREFIX + ListFragment.PREF_MAPF_INVERT, false );
MainActivity.prefBackedCheckBox( this, view, R.id.showopen,
MappingFragment.MAP_DIALOG_PREFIX + ListFragment.PREF_MAPF_OPEN, true );
MainActivity.prefBackedCheckBox( this, view, R.id.showwep,
MappingFragment.MAP_DIALOG_PREFIX + ListFragment.PREF_MAPF_WEP, true );
MainActivity.prefBackedCheckBox( this, view, R.id.showwpa,
MappingFragment.MAP_DIALOG_PREFIX + ListFragment.PREF_MAPF_WPA, true );
MainActivity.prefBackedCheckBox( this, view, R.id.showcell,
MappingFragment.MAP_DIALOG_PREFIX + ListFragment.PREF_MAPF_CELL, true );
MainActivity.prefBackedCheckBox( this, view, R.id.enabled,
MappingFragment.MAP_DIALOG_PREFIX + ListFragment.PREF_MAPF_ENABLED, true );
}
}
| bsd-3-clause |
spkg/local | nullable_test.go | 6719 | package local
import (
"encoding/json"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestNullDateScan(t *testing.T) {
assert := assert.New(t)
testCases := []struct {
Input interface{}
ExpectedError string
ExpectedDate NullDate
}{
{
Input: time.Date(2091, 11, 14, 18, 47, 0, 0, time.UTC),
ExpectedDate: NullDate{DateFor(2091, 11, 14), true},
},
{
Input: "2091-11-14",
ExpectedDate: NullDate{DateFor(2091, 11, 14), true},
},
{
Input: []byte("2091-11-14"),
ExpectedDate: NullDate{DateFor(2091, 11, 14), true},
},
{
Input: "xxxx",
ExpectedError: "invalid date format",
},
{
Input: 24,
ExpectedError: "cannot convert to local.Date",
},
{
Input: nil,
ExpectedDate: NullDate{Valid: false},
},
}
for _, tc := range testCases {
var d NullDate
err := d.Scan(tc.Input)
if tc.ExpectedError != "" {
assert.Error(err, tc.ExpectedError)
assert.Equal(tc.ExpectedError, err.Error())
} else {
assert.NoError(err)
if tc.ExpectedDate.Valid {
assert.True(d.Valid)
assert.True(d.Date.Equal(tc.ExpectedDate.Date))
assert.NotNil(d.Ptr())
assert.True(d.Ptr().Equal(d.Date))
d2 := NullDateFrom(d.Ptr())
assert.True(d2.Valid)
assert.True(d2.Date.Equal(d.Date))
} else {
assert.False(d.Valid)
assert.Nil(d.Ptr())
d2 := NullDateFrom(d.Ptr())
assert.False(d2.Valid)
}
}
}
// check that nil NullDate does not panic but returns error
var nilND *NullDate
assert.Error(nilND.Scan(nil))
}
func TestNullDateValue(t *testing.T) {
assert := assert.New(t)
testCases := []struct {
NullDate NullDate
ExpectNil bool
ExpectedTime time.Time
}{
{
NullDate: NullDate{Date: DateFor(2087, 12, 16), Valid: true},
ExpectedTime: time.Date(2087, 12, 16, 0, 0, 0, 0, time.UTC),
},
{
NullDate: NullDate{Date: DateFor(2087, 12, 16), Valid: false},
ExpectNil: true,
},
{
NullDate: NullDate{},
ExpectNil: true,
},
}
for _, tc := range testCases {
v, err := tc.NullDate.Value()
assert.NoError(err)
if tc.ExpectNil {
assert.Nil(v)
} else {
t, ok := v.(time.Time)
assert.True(ok)
assert.True(tc.ExpectedTime.Equal(t))
}
}
}
func TestNullDateJSON(t *testing.T) {
assert := assert.New(t)
testCases := []struct {
Text string
NullDate NullDate
ExpectedError string
}{
{
Text: "null",
NullDate: NullDate{},
},
{
Text: `"2091-09-30"`,
NullDate: NullDate{Date: mustParseDate("2091-09-30"), Valid: true},
},
{
Text: `25`,
ExpectedError: "invalid date format",
},
}
for _, tc := range testCases {
var nd NullDate
err := json.Unmarshal([]byte(tc.Text), &nd)
if tc.ExpectedError != "" {
assert.Error(err)
assert.True(strings.Contains(err.Error(), tc.ExpectedError), err.Error())
} else {
assert.NoError(err)
assert.Equal(tc.NullDate.Valid, nd.Valid, tc.NullDate.Date.String())
assert.True(tc.NullDate.Date.Equal(nd.Date), tc.NullDate.Date.String(), nd.Date.String())
p, err := json.Marshal(tc.NullDate)
assert.NoError(err)
assert.Equal(tc.Text, string(p))
}
}
}
func TestNullDateTimeScan(t *testing.T) {
assert := assert.New(t)
testCases := []struct {
Input interface{}
ExpectedError string
ExpectedDateTime NullDateTime
}{
{
Input: time.Date(2091, 11, 14, 18, 47, 0, 0, time.UTC),
ExpectedDateTime: NullDateTime{DateTimeFor(2091, 11, 14, 18, 47, 0), true},
},
{
Input: "2091-11-14T12:34:56",
ExpectedDateTime: NullDateTime{DateTimeFor(2091, 11, 14, 12, 34, 56), true},
},
{
Input: []byte("2091-11-14T11:47"),
ExpectedDateTime: NullDateTime{DateTimeFor(2091, 11, 14, 11, 47, 0), true},
},
{
Input: "xxxx",
ExpectedError: "invalid date-time format",
},
{
Input: 24,
ExpectedError: "cannot convert to local.DateTime",
},
{
Input: nil,
ExpectedDateTime: NullDateTime{Valid: false},
},
}
for _, tc := range testCases {
var d NullDateTime
err := d.Scan(tc.Input)
if tc.ExpectedError != "" {
assert.Error(err, tc.ExpectedError)
assert.Equal(tc.ExpectedError, err.Error())
} else {
assert.NoError(err)
if tc.ExpectedDateTime.Valid {
assert.True(d.Valid)
assert.Equal(tc.ExpectedDateTime.DateTime, d.DateTime, tc.ExpectedDateTime.DateTime.String()+" vs "+d.DateTime.String())
assert.NotNil(d.Ptr())
assert.True(d.Ptr().Equal(d.DateTime))
d2 := NullDateTimeFrom(d.Ptr())
assert.True(d2.Valid)
assert.True(d2.DateTime.Equal(d.DateTime))
} else {
assert.False(d.Valid)
assert.Nil(d.Ptr())
d2 := NullDateTimeFrom(d.Ptr())
assert.False(d2.Valid)
}
}
}
// check that nil NullDate does not panic but returns error
var nilND *NullDateTime
assert.Error(nilND.Scan(nil))
}
func TestNullDateTimeValue(t *testing.T) {
assert := assert.New(t)
testCases := []struct {
NullDateTime NullDateTime
ExpectNil bool
ExpectedTime time.Time
}{
{
NullDateTime: NullDateTime{DateTime: DateTimeFor(2087, 12, 16, 11, 47, 42), Valid: true},
ExpectedTime: time.Date(2087, 12, 16, 11, 47, 42, 0, time.UTC),
},
{
NullDateTime: NullDateTime{DateTime: DateTimeFor(2087, 12, 16, 11, 47, 43), Valid: false},
ExpectNil: true,
},
{
NullDateTime: NullDateTime{},
ExpectNil: true,
},
}
for _, tc := range testCases {
v, err := tc.NullDateTime.Value()
assert.NoError(err)
if tc.ExpectNil {
assert.Nil(v)
} else {
t, ok := v.(time.Time)
assert.True(ok)
assert.True(tc.ExpectedTime.Equal(t))
}
}
}
func TestNullDateTimeJSON(t *testing.T) {
assert := assert.New(t)
testCases := []struct {
Text string
NullDateTime NullDateTime
ExpectedError string
}{
{
Text: "null",
NullDateTime: NullDateTime{},
},
{
Text: `"2091-01-30T22:02:00"`,
NullDateTime: NullDateTime{DateTime: mustParseDateTime("2091-01-30T22:02"), Valid: true},
},
{
Text: `25`,
ExpectedError: "invalid date-time format",
},
}
for _, tc := range testCases {
var nd NullDateTime
err := json.Unmarshal([]byte(tc.Text), &nd)
if tc.ExpectedError != "" {
assert.Error(err)
assert.True(strings.Contains(err.Error(), tc.ExpectedError), err.Error())
} else {
assert.NoError(err)
assert.Equal(tc.NullDateTime.Valid, nd.Valid, tc.NullDateTime.DateTime.String())
assert.True(tc.NullDateTime.DateTime.Equal(nd.DateTime), tc.NullDateTime.DateTime.String())
p, err := json.Marshal(tc.NullDateTime)
assert.NoError(err)
assert.Equal(tc.Text, string(p))
}
}
}
| bsd-3-clause |
zcbenz/cefode-chromium | chrome/browser/pepper_broker_infobar_delegate.cc | 6580 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/pepper_broker_infobar_delegate.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/api/infobars/infobar_service.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/plugins/plugin_finder.h"
#include "chrome/browser/plugins/plugin_metadata.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/plugins/webplugininfo.h"
// The URL for the "learn more" article about the PPAPI broker.
const char kPpapiBrokerLearnMoreUrl[] =
"https://support.google.com/chrome/?p=ib_pepper_broker";
using content::OpenURLParams;
using content::Referrer;
using content::WebContents;
// static
void PepperBrokerInfoBarDelegate::Create(
WebContents* web_contents,
const GURL& url,
const base::FilePath& plugin_path,
const base::Callback<void(bool)>& callback) {
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
// TODO(wad): Add ephemeral device ID support for broker in guest mode.
if (profile->IsGuestSession()) {
callback.Run(false);
return;
}
TabSpecificContentSettings* tab_content_settings =
TabSpecificContentSettings::FromWebContents(web_contents);
HostContentSettingsMap* content_settings =
profile->GetHostContentSettingsMap();
ContentSetting setting =
content_settings->GetContentSetting(url, url,
CONTENT_SETTINGS_TYPE_PPAPI_BROKER,
std::string());
switch (setting) {
case CONTENT_SETTING_ALLOW: {
content::RecordAction(
content::UserMetricsAction("PPAPI.BrokerSettingAllow"));
tab_content_settings->SetPepperBrokerAllowed(true);
callback.Run(true);
break;
}
case CONTENT_SETTING_BLOCK: {
content::RecordAction(
content::UserMetricsAction("PPAPI.BrokerSettingDeny"));
tab_content_settings->SetPepperBrokerAllowed(false);
callback.Run(false);
break;
}
case CONTENT_SETTING_ASK: {
content::RecordAction(
content::UserMetricsAction("PPAPI.BrokerInfobarDisplayed"));
InfoBarService* infobar_service =
InfoBarService::FromWebContents(web_contents);
std::string languages =
profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
infobar_service->AddInfoBar(scoped_ptr<InfoBarDelegate>(
new PepperBrokerInfoBarDelegate(
infobar_service, url, plugin_path, languages, content_settings,
tab_content_settings, callback)));
break;
}
default:
NOTREACHED();
}
}
string16 PepperBrokerInfoBarDelegate::GetMessageText() const {
content::PluginService* plugin_service =
content::PluginService::GetInstance();
webkit::WebPluginInfo plugin;
bool success = plugin_service->GetPluginInfoByPath(plugin_path_, &plugin);
DCHECK(success);
scoped_ptr<PluginMetadata> plugin_metadata(
PluginFinder::GetInstance()->GetPluginMetadata(plugin));
return l10n_util::GetStringFUTF16(IDS_PEPPER_BROKER_MESSAGE,
plugin_metadata->name(),
net::FormatUrl(url_.GetOrigin(),
languages_));
}
int PepperBrokerInfoBarDelegate::GetButtons() const {
return BUTTON_OK | BUTTON_CANCEL;
}
string16 PepperBrokerInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
switch (button) {
case BUTTON_OK:
return l10n_util::GetStringUTF16(IDS_PEPPER_BROKER_ALLOW_BUTTON);
case BUTTON_CANCEL:
return l10n_util::GetStringUTF16(IDS_PEPPER_BROKER_DENY_BUTTON);
default:
NOTREACHED();
return string16();
}
}
bool PepperBrokerInfoBarDelegate::Accept() {
DispatchCallback(true);
return true;
}
bool PepperBrokerInfoBarDelegate::Cancel() {
DispatchCallback(false);
return true;
}
string16 PepperBrokerInfoBarDelegate::GetLinkText() const {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
bool PepperBrokerInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
OpenURLParams params(
GURL(kPpapiBrokerLearnMoreUrl), Referrer(),
(disposition == CURRENT_TAB) ? NEW_FOREGROUND_TAB : disposition,
content::PAGE_TRANSITION_LINK,
false);
owner()->GetWebContents()->OpenURL(params);
return false;
}
gfx::Image* PepperBrokerInfoBarDelegate::GetIcon() const {
return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
IDR_INFOBAR_PLUGIN_INSTALL);
}
PepperBrokerInfoBarDelegate::PepperBrokerInfoBarDelegate(
InfoBarService* infobar_service,
const GURL& url,
const base::FilePath& plugin_path,
const std::string& languages,
HostContentSettingsMap* content_settings,
TabSpecificContentSettings* tab_content_settings,
const base::Callback<void(bool)>& callback)
: ConfirmInfoBarDelegate(infobar_service),
url_(url),
plugin_path_(plugin_path),
languages_(languages),
content_settings_(content_settings),
tab_content_settings_(tab_content_settings),
callback_(callback) {
}
PepperBrokerInfoBarDelegate::~PepperBrokerInfoBarDelegate() {
if (!callback_.is_null())
callback_.Run(false);
}
void PepperBrokerInfoBarDelegate::DispatchCallback(bool result) {
content::RecordAction(result ?
content::UserMetricsAction("PPAPI.BrokerInfobarClickedAllow") :
content::UserMetricsAction("PPAPI.BrokerInfobarClickedDeny"));
callback_.Run(result);
callback_ = base::Callback<void(bool)>();
content_settings_->SetContentSetting(
ContentSettingsPattern::FromURLNoWildcard(url_),
ContentSettingsPattern::Wildcard(),
CONTENT_SETTINGS_TYPE_PPAPI_BROKER,
std::string(), result ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK);
tab_content_settings_->SetPepperBrokerAllowed(result);
}
| bsd-3-clause |
byn9826/RapidSlides | main.js | 859 | const electron = require( 'electron' );
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require( 'path' );
const url = require( 'url' );
let mainWindow;
app.on('ready', () => {
mainWindow = new BrowserWindow({
height: 600,
width: 800
});
//mainWindow.setMenu( null );
mainWindow.maximize();
mainWindow.loadURL( url.format({
//pathname: path.join( __dirname, './workspace/slide.html' ),
pathname: path.join( __dirname, './index.html' ),
protocol: 'file:',
slashes: true
}));
mainWindow.on('closed', () => {
mainWindow = null;
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
}); | bsd-3-clause |
iotsap/FiWare-Template-Handler | NGSI910DatastructuresAndNGSI10Operations/target/generated-sources/xmlbeans/noNamespace/impl/UnsubscribeContextAvailabilityResponseDocumentImpl.java | 2969 | /*
* An XML document type.
* Localname: unsubscribeContextAvailabilityResponse
* Namespace:
* Java type: noNamespace.UnsubscribeContextAvailabilityResponseDocument
*
* Automatically generated - do not modify.
*/
package noNamespace.impl;
/**
* A document containing one unsubscribeContextAvailabilityResponse(@) element.
*
* This is a complex type.
*/
public class UnsubscribeContextAvailabilityResponseDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements noNamespace.UnsubscribeContextAvailabilityResponseDocument
{
private static final long serialVersionUID = 1L;
public UnsubscribeContextAvailabilityResponseDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName UNSUBSCRIBECONTEXTAVAILABILITYRESPONSE$0 =
new javax.xml.namespace.QName("", "unsubscribeContextAvailabilityResponse");
/**
* Gets the "unsubscribeContextAvailabilityResponse" element
*/
public noNamespace.UnsubscribeContextAvailabilityResponse getUnsubscribeContextAvailabilityResponse()
{
synchronized (monitor())
{
check_orphaned();
noNamespace.UnsubscribeContextAvailabilityResponse target = null;
target = (noNamespace.UnsubscribeContextAvailabilityResponse)get_store().find_element_user(UNSUBSCRIBECONTEXTAVAILABILITYRESPONSE$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "unsubscribeContextAvailabilityResponse" element
*/
public void setUnsubscribeContextAvailabilityResponse(noNamespace.UnsubscribeContextAvailabilityResponse unsubscribeContextAvailabilityResponse)
{
synchronized (monitor())
{
check_orphaned();
noNamespace.UnsubscribeContextAvailabilityResponse target = null;
target = (noNamespace.UnsubscribeContextAvailabilityResponse)get_store().find_element_user(UNSUBSCRIBECONTEXTAVAILABILITYRESPONSE$0, 0);
if (target == null)
{
target = (noNamespace.UnsubscribeContextAvailabilityResponse)get_store().add_element_user(UNSUBSCRIBECONTEXTAVAILABILITYRESPONSE$0);
}
target.set(unsubscribeContextAvailabilityResponse);
}
}
/**
* Appends and returns a new empty "unsubscribeContextAvailabilityResponse" element
*/
public noNamespace.UnsubscribeContextAvailabilityResponse addNewUnsubscribeContextAvailabilityResponse()
{
synchronized (monitor())
{
check_orphaned();
noNamespace.UnsubscribeContextAvailabilityResponse target = null;
target = (noNamespace.UnsubscribeContextAvailabilityResponse)get_store().add_element_user(UNSUBSCRIBECONTEXTAVAILABILITYRESPONSE$0);
return target;
}
}
}
| bsd-3-clause |
vitorismart/ChromeCast | target/client/services/local-device.js | 6882 | // Generated by CoffeeScript 1.8.0
/*
Copyright (c) 2014, Groupon
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function() {
angular.module("GScreen").factory("localDevice", function(Chromecast, sockets) {
var clearAlert, clearTimeoutId, createAlert, exports, listeners, loadChromecast, loadChromecastFromPersistence, updateAlert, updateChannelId, updateChromecast;
scheduledAlerts = {};
listeners = {
"change": []
};
loadChromecast = function(id) {
return Chromecast.get(id).$promise.then(function(c) {
console.log("loadChromecast", c);
updateChromecast(c);
return createAlert(c.alert);
});
};
updateChromecast = function(c) {
var l, _i, _len, _ref, _results;
exports.chromecast = c;
_ref = listeners.change;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
l = _ref[_i];
_results.push(l(c));
}
return _results;
};
updateChannelId = function(channelId) {
var k, newCast, v, _ref;
newCast = {};
_ref = exports.chromecast;
for (k in _ref) {
v = _ref[k];
newCast[k] = v;
}
newCast.channelId = channelId;
return updateChromecast(newCast);
};
updateAlert = function(alert) {
var k, newCast, v, _ref;
newCast = {};
_ref = exports.chromecast;
for (k in _ref) {
v = _ref[k];
newCast[k] = v;
}
if (!newCast.alerts)
newCast.alerts = {};
newCast.alerts[alert.expiresAt] = alert;
return updateChromecast(newCast);
};
loadChromecastFromPersistence = function() {
var id;
if (id = localStorage.getItem("chromecast-id")) {
return loadChromecast(id);
}
};
clearAlert = function(alertKey) {
console.log("Clearing the alert");
if (scheduledAlerts[alertKey]) {
createScheduledAlert(alertKey);
}
//this might be dangerous
var _chromeCastRef = exports.chromecast;
if(alertKey)
delete _chromeCastRef.alerts[alertKey];
return updateChromecast(_chromeCastRef);
};
createScheduledAlert = function(alertKey) {
var scheduledAlert = scheduledAlerts[alertKey];
if (scheduledAlert) {
setTimeout(function() {
if (scheduledAlert) {
scheduledAlert.expiresAt = new Date().getTime() + (scheduledAlert.duration * 1000);
createAlert(scheduledAlert);
delete scheduledAlerts[alertKey];
}
}, scheduledAlert.repeatTime * 1000);
}
};
createAlert = function(alert) {
var duration;
if (alert) {
duration = new Date(alert.expiresAt).getTime() - new Date().getTime();
if (duration > 0) {
updateAlert(alert);
console.log("duration", duration);
if (alert.repeatTime) {
scheduledAlerts[alert.expiresAt] = alert;
}
var clearTimeoutId = setTimeout(clearAlert, Math.ceil(duration), alert.expiresAt);
return clearTimeoutId;
} else {
return clearAlert();
}
}
};
clearAllAlerts = function() {
for (scheduledAlert in scheduledAlerts) {
delete scheduledAlerts[scheduledAlert];
}
var alerts = exports.chromecast.alerts ? exports.chromecast.alerts : null;
for (alertKey in alerts) {
clearAlert(alertKey);
}
};
sockets.on("receiver-updated", function(chromecast) {
if (exports.chromecast.id === chromecast.id) {
return updateChromecast(chromecast);
}
});
sockets.on("takeover-created", function(takeover) {
return updateChannelId(takeover.channelId);
});
sockets.on("takeover-updated", function(takeover) {
return updateChannelId(takeover.channelId);
});
sockets.on("takeover-deleted", function() {
return loadChromecastFromPersistence();
});
sockets.on("alert-deleted", function() {
return clearAllAlerts();
});
sockets.on("alert-created", function(alert) {
console.log("Creating alert", alert);
return createAlert(alert);
});
sockets.on("client-checkin", function(alert) {
createAlert(alert);
});
loadChromecastFromPersistence();
exports = {
setChromecastId: function(id) {
loadChromecast(id);
return localStorage.setItem("chromecast-id", id);
},
on: function(event, func) {
return listeners[event].push(func);
},
chromecast: null
};
return exports;
});
}).call(this);
| bsd-3-clause |
keverw/Random-Quotes | Upload/system/start.php | 1718 | <?php
session_start();
mb_language('uni');
mb_internal_encoding('UTF-8');
require 'config.php';
function create_slug($string)
{
$string = strtolower($string); //make loverspaces
$string = str_replace('\'s', 's', $string); //replace 's with just s
$string = preg_replace("/\ $/",'',$string); //remove last space
$string = preg_replace("/\.$/",'',$string); //remove last period
$slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $string); //convert spaces to dash
$slug = preg_replace("/\-$/",'',$slug); //remove last dash
return $slug;
}
function create_url($siteurl,$qid,$author,$text)
{
$author_slug = create_slug(substr($author, 0, 30));
$text_slug = create_slug(substr($text, 0, 50));
return $siteurl . 'q/' . $qid . '/' . $author_slug . '/' . $text_slug . '/';
}
function force_404($siteurl)
{
header('Location: ' . $siteurl . '404?url=' . $_SERVER['REQUEST_URI']);
die();
}
function formatMoney($number)
{
while (true)
{
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number)
{
$number = $replaced;
}
else
{
break;
}
}
return $number;
}
if ($_SESSION['uid'])
{
$uid = $_SESSION['uid'];
$admin_result = mysql_query("SELECT * FROM admins WHERE uid = $uid "); //kill session if account got deleted it
if(mysql_num_rows($admin_result) > 0)
{
$row = mysql_fetch_array($admin_result);
if ($_SESSION['uid'] == $row['uid'] && $_SESSION['user'] == $row['user'] && $_SESSION['pass'] == $row['pass']) //check if account details match the same as when they logged in
{
$isAdmin = 1;
}
else
{
session_destroy();
}
}
else
{
session_destroy();
}
}
?> | bsd-3-clause |
yungsters/relay | packages/relay-runtime/store/__tests__/RelayModernEnvironment-ExecuteWithMatchAdditionalArguments-test.js | 28070 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
* @emails oncall+relay
*/
// flowlint ambiguous-object-type:error
'use strict';
const RelayModernEnvironment = require('../RelayModernEnvironment');
const RelayModernStore = require('../RelayModernStore');
const RelayNetwork = require('../../network/RelayNetwork');
const RelayObservable = require('../../network/RelayObservable');
const RelayRecordSource = require('../RelayRecordSource');
const nullthrows = require('nullthrows');
const {graphql, getFragment, getRequest} = require('../../query/GraphQLTag');
const {
createOperationDescriptor,
} = require('../RelayModernOperationDescriptor');
const {getSingularSelector} = require('../RelayModernSelector');
import type {NormalizationRootNode} from '../../util/NormalizationNode';
describe('execute() a query with @match with additional arguments', () => {
let callbacks: {|
+complete: JestMockFn<$ReadOnlyArray<mixed>, mixed>,
+error: JestMockFn<$ReadOnlyArray<Error>, mixed>,
+next: JestMockFn<$ReadOnlyArray<mixed>, mixed>,
+start?: JestMockFn<$ReadOnlyArray<mixed>, mixed>,
+unsubscribe?: JestMockFn<$ReadOnlyArray<mixed>, mixed>,
|};
let complete;
let dataSource;
let environment;
let error;
let fetch;
let markdownRendererFragment;
let markdownRendererNormalizationFragment;
let MarkupHandler;
let next;
let operation;
let operationCallback;
let operationLoader: {|
get: (reference: mixed) => ?NormalizationRootNode,
load: JestMockFn<$ReadOnlyArray<mixed>, Promise<?NormalizationRootNode>>,
|};
let query;
let resolveFragment;
let source;
let store;
let variables;
beforeEach(() => {
jest.resetModules();
query = getRequest(graphql`
query RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery(
$id: ID!
) {
node(id: $id) {
... on User {
nameRendererForContext(context: HEADER) @match {
...RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestPlainUserNameRenderer_name
@module(name: "PlainUserNameRenderer.react")
...RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name
@module(name: "MarkdownUserNameRenderer.react")
}
}
}
}
`);
graphql`
fragment RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestPlainUserNameRenderer_name on PlainUserNameRenderer {
plaintext
data {
text
}
}
`;
markdownRendererNormalizationFragment = require('./__generated__/RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql');
markdownRendererFragment = getFragment(graphql`
fragment RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name on MarkdownUserNameRenderer {
__typename
markdown
data {
markup @__clientField(handle: "markup_handler")
}
}
`);
variables = {id: '1'};
operation = createOperationDescriptor(query, variables);
MarkupHandler = {
update(storeProxy, payload) {
const record = storeProxy.get(payload.dataID);
if (record != null) {
const markup = record.getValue(payload.fieldKey);
record.setValue(
typeof markup === 'string' ? markup.toUpperCase() : null,
payload.handleKey,
);
}
},
};
complete = jest.fn();
error = jest.fn();
next = jest.fn();
callbacks = {complete, error, next};
fetch = (_query, _variables, _cacheConfig) => {
return RelayObservable.create(sink => {
dataSource = sink;
});
};
operationLoader = {
load: jest.fn(moduleName => {
return new Promise(resolve => {
resolveFragment = resolve;
});
}),
get: jest.fn(),
};
source = RelayRecordSource.create();
store = new RelayModernStore(source);
environment = new RelayModernEnvironment({
network: RelayNetwork.create(fetch),
store,
operationLoader,
handlerProvider: name => {
switch (name) {
case 'markup_handler':
return MarkupHandler;
}
},
});
const operationSnapshot = environment.lookup(operation.fragment);
operationCallback = jest.fn();
environment.subscribe(operationSnapshot, operationCallback);
});
it('calls next() and publishes the initial payload to the store', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
expect(operationLoader.load).toBeCalledTimes(1);
expect(operationLoader.load.mock.calls[0][0]).toEqual(
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
);
expect(next.mock.calls.length).toBe(1);
expect(complete).not.toBeCalled();
expect(error).not.toBeCalled();
expect(operationCallback).toBeCalledTimes(1);
const operationSnapshot = operationCallback.mock.calls[0][0];
expect(operationSnapshot.isMissingData).toBe(false);
expect(operationSnapshot.data).toEqual({
node: {
nameRendererForContext: {
__id:
'client:1:nameRendererForContext(context:"HEADER",supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
__fragmentPropName: 'name',
__fragments: {
RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name: {},
},
__fragmentOwner: operation.request,
__module_component: 'MarkdownUserNameRenderer.react',
},
},
});
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data?.node: any)?.nameRendererForContext,
),
);
const matchSnapshot = environment.lookup(matchSelector);
// ref exists but match field data hasn't been processed yet
expect(matchSnapshot.isMissingData).toBe(true);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: undefined,
markdown: undefined,
});
});
it('loads the @match fragment and normalizes/publishes the field payload', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
// NOTE: should be uppercased when normalized (by MarkupHandler)
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
next.mockClear();
expect(operationCallback).toBeCalledTimes(1); // initial results tested above
const operationSnapshot = operationCallback.mock.calls[0][0];
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data?.node: any)?.nameRendererForContext,
),
);
// initial results tested above
const initialMatchSnapshot = environment.lookup(matchSelector);
expect(initialMatchSnapshot.isMissingData).toBe(true);
const matchCallback = jest.fn();
environment.subscribe(initialMatchSnapshot, matchCallback);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
// next() should not be called when @match resolves, no new GraphQLResponse
// was received for this case
expect(next).toBeCalledTimes(0);
expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
expect(matchCallback).toBeCalledTimes(1);
const matchSnapshot = matchCallback.mock.calls[0][0];
expect(matchSnapshot.isMissingData).toBe(false);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: {
// NOTE: should be uppercased by the MarkupHandler
markup: '<MARKUP/>',
},
markdown: 'markdown payload',
});
});
it('synchronously normalizes/publishes the field payload if @match fragment is available synchronously', () => {
environment.execute({operation}).subscribe(callbacks);
jest
.spyOn(operationLoader, 'get')
.mockImplementationOnce(() => markdownRendererNormalizationFragment);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
// NOTE: should be uppercased when normalized (by MarkupHandler)
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
expect(next).toBeCalledTimes(1);
next.mockClear();
expect(operationCallback).toBeCalledTimes(1); // initial results tested above
const operationSnapshot = operationCallback.mock.calls[0][0];
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data?.node: any)?.nameRendererForContext,
),
);
// At this point the matchSnapshot should contain all the data,
// since it should've been normalized synchronously
const matchSnapshot = environment.lookup(matchSelector);
expect(matchSnapshot.isMissingData).toBe(false);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: {
// NOTE: should be uppercased by the MarkupHandler
markup: '<MARKUP/>',
},
markdown: 'markdown payload',
});
});
it('loads the @match fragment and normalizes/publishes the field payload with scheduling', () => {
let taskID = 0;
const tasks = new Map();
const scheduler = {
cancel: id => {
tasks.delete(id);
},
schedule: task => {
const id = String(taskID++);
tasks.set(id, task);
return id;
},
};
const runTask = () => {
for (const [id, task] of tasks) {
tasks.delete(id);
task();
break;
}
};
environment = new RelayModernEnvironment({
network: environment.getNetwork(),
store: environment.getStore(),
operationLoader,
scheduler,
handlerProvider: name => {
switch (name) {
case 'markup_handler':
return MarkupHandler;
}
},
});
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
// NOTE: should be uppercased when normalized (by MarkupHandler)
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
expect(next).toBeCalledTimes(0);
expect(operationCallback).toBeCalledTimes(0);
expect(tasks.size).toBe(1);
runTask();
jest.runAllTimers();
next.mockClear();
expect(operationCallback).toBeCalledTimes(1); // initial results tested above
const operationSnapshot = operationCallback.mock.calls[0][0];
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data?.node: any)?.nameRendererForContext,
),
);
// initial results tested above
const initialMatchSnapshot = environment.lookup(matchSelector);
expect(initialMatchSnapshot.isMissingData).toBe(true);
const matchCallback = jest.fn();
environment.subscribe(initialMatchSnapshot, matchCallback);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
expect(matchCallback).toBeCalledTimes(0);
expect(tasks.size).toBe(1);
runTask();
// next() should not be called when @match resolves, no new GraphQLResponse
// was received for this case
expect(next).toBeCalledTimes(0);
expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
expect(matchCallback).toBeCalledTimes(1);
const matchSnapshot = matchCallback.mock.calls[0][0];
expect(matchSnapshot.isMissingData).toBe(false);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: {
// NOTE: should be uppercased by the MarkupHandler
markup: '<MARKUP/>',
},
markdown: 'markdown payload',
});
});
it('cancels processing of @match fragments with scheduling', () => {
let taskID = 0;
const tasks = new Map();
const scheduler = {
cancel: id => {
tasks.delete(id);
},
schedule: task => {
const id = String(taskID++);
tasks.set(id, task);
return id;
},
};
const runTask = () => {
for (const [id, task] of tasks) {
tasks.delete(id);
task();
break;
}
};
environment = new RelayModernEnvironment({
network: environment.getNetwork(),
store: environment.getStore(),
operationLoader,
scheduler,
handlerProvider: name => {
switch (name) {
case 'markup_handler':
return MarkupHandler;
}
},
});
const subscription = environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
// NOTE: should be uppercased when normalized (by MarkupHandler)
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
expect(next).toBeCalledTimes(0);
expect(operationCallback).toBeCalledTimes(0);
expect(tasks.size).toBe(1);
runTask();
jest.runAllTimers();
next.mockClear();
expect(operationCallback).toBeCalledTimes(1); // initial results tested above
const operationSnapshot = operationCallback.mock.calls[0][0];
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data?.node: any)?.nameRendererForContext,
),
);
// initial results tested above
const initialMatchSnapshot = environment.lookup(matchSelector);
expect(initialMatchSnapshot.isMissingData).toBe(true);
const matchCallback = jest.fn();
environment.subscribe(initialMatchSnapshot, matchCallback);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
expect(matchCallback).toBeCalledTimes(0);
expect(tasks.size).toBe(1);
subscription.unsubscribe();
expect(tasks.size).toBe(0);
expect(matchCallback).toBeCalledTimes(0);
expect(complete).toBeCalledTimes(0);
expect(error).toBeCalledTimes(0);
expect(next).toBeCalledTimes(0);
expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
});
it('calls complete() if the network completes before processing the match', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
dataSource.complete();
expect(callbacks.complete).toBeCalledTimes(0);
expect(callbacks.error).toBeCalledTimes(0);
expect(callbacks.next).toBeCalledTimes(1);
expect(operationLoader.load).toBeCalledTimes(1);
expect(operationLoader.load.mock.calls[0][0]).toBe(
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
expect(callbacks.complete).toBeCalledTimes(1);
expect(callbacks.error).toBeCalledTimes(0);
expect(callbacks.next).toBeCalledTimes(1);
});
it('calls complete() if the network completes after processing the match', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
expect(operationLoader.load).toBeCalledTimes(1);
expect(operationLoader.load.mock.calls[0][0]).toBe(
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
expect(callbacks.complete).toBeCalledTimes(0);
expect(callbacks.error).toBeCalledTimes(0);
expect(callbacks.next).toBeCalledTimes(1);
dataSource.complete();
expect(callbacks.complete).toBeCalledTimes(1);
expect(callbacks.error).toBeCalledTimes(0);
expect(callbacks.next).toBeCalledTimes(1);
});
it('calls error() if the operationLoader function throws synchronously', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
},
};
const loaderError = new Error();
operationLoader.load = jest.fn(() => {
throw loaderError;
});
dataSource.next(payload);
jest.runAllTimers();
expect(callbacks.error).toBeCalledTimes(1);
expect(callbacks.error.mock.calls[0][0]).toBe(loaderError);
});
it('calls error() if operationLoader.get function throws synchronously', () => {
environment.execute({operation}).subscribe(callbacks);
const loaderError = new Error();
jest.spyOn(operationLoader, 'get').mockImplementationOnce(() => {
throw loaderError;
});
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
expect(callbacks.error).toBeCalledTimes(1);
expect(callbacks.error.mock.calls[0][0]).toBe(loaderError);
});
it('calls error() if the operationLoader promise fails', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
},
};
const loaderError = new Error();
operationLoader.load = jest.fn(() => {
return Promise.reject(loaderError);
});
dataSource.next(payload);
jest.runAllTimers();
expect(callbacks.error).toBeCalledTimes(1);
expect(callbacks.error.mock.calls[0][0]).toBe(loaderError);
});
it('calls error() if processing a match payload throws', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
},
},
};
operationLoader.load = jest.fn(() => {
// Invalid fragment node, no 'selections' field
// This is to make sure that users implementing operationLoader
// incorrectly still get reasonable error handling
return Promise.resolve(({}: any));
});
dataSource.next(payload);
jest.runAllTimers();
expect(callbacks.error).toBeCalledTimes(1);
expect(callbacks.error.mock.calls[0][0].message).toBe(
"Cannot read property 'length' of undefined",
);
});
it('cancels @match processing if unsubscribed before match payload is processed', () => {
const subscription = environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRendererForContext: {
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestUserQuery:
'RelayModernEnvironmentExecuteWithMatchAdditionalArgumentsTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
// NOTE: should be uppercased when normalized (by MarkupHandler)
markup: '<markup/>',
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
next.mockClear();
expect(operationCallback).toBeCalledTimes(1); // initial results tested above
const operationSnapshot = operationCallback.mock.calls[0][0];
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data?.node: any)?.nameRendererForContext,
),
);
// initial results tested above
const initialMatchSnapshot = environment.lookup(matchSelector);
expect(initialMatchSnapshot.isMissingData).toBe(true);
const matchCallback = jest.fn();
environment.subscribe(initialMatchSnapshot, matchCallback);
subscription.unsubscribe();
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
// next() should not be called when @match resolves, no new GraphQLResponse
// was received for this case
expect(next).toBeCalledTimes(0);
expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
expect(matchCallback).toBeCalledTimes(0); // match result shouldn't change
});
});
| bsd-3-clause |
devbharat/gtsam | doc/html/a00448.js | 230 | var a00448 =
[
[ "EliminationTraits< GaussianFactorGraph >", "a00076.html", "a00076" ],
[ "GaussianFactorGraph", "a00108.html", "a00108" ],
[ "hasConstraints", "a00448.html#a35c269c3243cab16a7475239a9c91021", null ]
]; | bsd-3-clause |
hung101/kbs | frontend/views/ref-nama-pemeriksa-aduan/view.php | 1214 | <?php
use yii\helpers\Html;
use yii\widgets\DetailView;
// contant values
use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;
/* @var $this yii\web\View */
/* @var $model app\models\RefNamaPemeriksaAduan */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => GeneralLabel::nama_pemeriksa_aduan, 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ref-nama-pemeriksa-aduan-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(GeneralLabel::update, ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(GeneralLabel::delete, ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => GeneralMessage::confirmDelete,
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'desc',
//'aktif',
[
'attribute' => 'aktif',
'value' => $model->aktif == 1 ? GeneralLabel::yes : GeneralLabel::no,
],
],
]) ?>
</div>
| bsd-3-clause |
wsldl123292/jodd | jodd-core/src/main/java/jodd/JoddModule.java | 250 | // Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd;
/**
* Optional interface for Jodd modules.
*/
public interface JoddModule {
/**
* Invoked once when module has been created.
*/
public void start();
} | bsd-3-clause |
cga-harvard/geonode-client | app/static/script/app/geo-debug.js | 1220 | (function() {
var jsfiles = new Array(
"/static/src/script/app/GeoExplorer.js",
"/static/src/script/app/GeoExplorer/Viewer.js",
"/static/src/script/app/GeoExplorer/SearchBar.js",
"/static/src/script/app/GeoExplorer/SocialExplorer.js",
"/static/src/script/app/GeoExplorer/CapabilitiesRowExpander.js",
"/static/src/script/app/GeoExplorer/PicasaFeedOverlay.js",
"/static/src/script/app/GeoExplorer/YouTubeFeedOverlay.js"
);
var appendable = !((/MSIE/).test(navigator.userAgent) ||
(/Safari/).test(navigator.userAgent));
var pieces = new Array(jsfiles.length);
var element = document.getElementsByTagName("head").length ?
document.getElementsByTagName("head")[0] :
document.body;
var script;
for(var i=0; i<jsfiles.length; i++) {
if(!appendable) {
pieces[i] = "<script src='" + jsfiles[i] + "'></script>";
} else {
script = document.createElement("script");
script.src = jsfiles[i];
element.appendChild(script);
}
}
if(!appendable) {
document.write(pieces.join(""));
}
})();
| bsd-3-clause |
AsiaWebSolution/Yii2BasicTemplateADMINLTE | config/modules/modules.php | 569 | <?php
return [
'examples' => [
'class' => 'app\modules\examples\Examples',
],
'posts' => [
'class' => 'app\modules\posts\Posts',
'modules' => [
'article' => [
'class' => 'app\modules\posts\article\article',
],
],
],
'settings' => [
'class' => 'app\modules\settings\Settings',
'modules'=>[
'datamaster' => [
'class' => 'app\modules\settings\datamaster\Datamaster',
],
'regional' => [
'class' => 'app\modules\settings\regional\Regional',
],
]
],
]
?> | bsd-3-clause |
Blindinglight-Team5433/BlindingLight-Sheila | src/org/usfirst/frc5433/BlindingLight_Sheila/commands/Mecanum_Drive.java | 1561 | // RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc5433.BlindingLight_Sheila.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc5433.BlindingLight_Sheila.Robot;
/**
*
*/
public class Mecanum_Drive extends Command {
public Mecanum_Drive() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| bsd-3-clause |
Signbank/BSL-signbank | signbank/dictionary/forms.py | 4390 | from django import forms
from django.contrib.formtools.preview import FormPreview
from signbank.video.fields import VideoUploadToFLVField
from signbank.dictionary.models import Dialect, Gloss, Definition, Relation, Region, defn_role_choices, handshapeChoices, locationChoices
from django.conf import settings
from tagging.models import Tag
# category choices are tag values that we'll restrict search to
CATEGORY_CHOICES = (('all', 'All Signs'),
('semantic:health', 'Only Health Related Signs'),
('semantic:education', 'Only Education Related Signs'))
class UserSignSearchForm(forms.Form):
query = forms.CharField(label='Keywords starting with', max_length=100,
required=False, widget=forms.TextInput(attrs={'class': 'form-control'}))
category = forms.ChoiceField(label='Search', choices=CATEGORY_CHOICES, required=False,
widget=forms.Select(attrs={'class': 'form-control'}))
handshapeForUser = [(x,x) if x != 'notset' else (x, 'Any handshape') for x,y in handshapeChoices]
handshape = forms.ChoiceField(label='Handshape', choices=handshapeForUser, required=False,
widget=forms.Select(attrs={'class': 'form-control form-control-short'}))
location = forms.ChoiceField(label='Location', choices=locationChoices, required=False,
widget=forms.Select(attrs={'class': 'form-control form-control-short'}))
class GlossModelForm(forms.ModelForm):
class Meta:
model = Gloss
# fields are defined in settings.py
fields = settings.QUICK_UPDATE_GLOSS_FIELDS
class GlossCreateForm(forms.ModelForm):
"""Form for creating a new gloss from scratch"""
class Meta:
model = Gloss
fields = ['idgloss', 'annotation_idgloss', 'sn']
class VideoUpdateForm(forms.Form):
"""Form to allow update of the video for a sign"""
videofile = VideoUploadToFLVField()
class TagUpdateForm(forms.Form):
"""Form to add a new tag to a gloss"""
tag = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}),
choices=[(t, t) for t in settings.ALLOWED_TAGS])
delete = forms.BooleanField(required=False, widget=forms.HiddenInput)
YESNOCHOICES = (("unspecified", "Unspecified" ), ('yes', 'Yes'), ('no', 'No'))
ROLE_CHOICES = [('all', 'All')]
ROLE_CHOICES.extend(defn_role_choices)
class GlossSearchForm(forms.ModelForm):
search = forms.CharField(label="Search Gloss/SN")
tags = forms.MultipleChoiceField(choices=[(t, t) for t in settings.ALLOWED_TAGS])
nottags = forms.MultipleChoiceField(choices=[(t, t) for t in settings.ALLOWED_TAGS])
keyword = forms.CharField(label='Keyword')
hasvideo = forms.ChoiceField(label='Has Video', choices=YESNOCHOICES)
defspublished = forms.ChoiceField(label="All Definitions Published", choices=YESNOCHOICES)
defsearch = forms.CharField(label='Search Definition/Notes')
defrole = forms.ChoiceField(label='Search Definition/Note Type', choices=ROLE_CHOICES, widget=forms.Select(attrs={'class': 'form-control'}))
class Meta:
model = Gloss
fields = ('idgloss', 'annotation_idgloss', 'morph', 'sense',
'sn', 'StemSN', 'comptf', 'compound', 'language', 'dialect',
'inWeb', 'isNew',
'initial_relative_orientation', 'final_relative_orientation',
'initial_palm_orientation', 'final_palm_orientation',
'initial_secondary_loc', 'final_secondary_loc',
'domhndsh', 'subhndsh', 'locprim', 'locsecond',
'final_domhndsh', 'final_subhndsh', 'final_loc'
)
widgets = {
'inWeb': forms.Select(choices=YESNOCHOICES),
}
class DefinitionForm(forms.ModelForm):
class Meta:
model = Definition
fields = ('count', 'role', 'text')
widgets = {
'role': forms.Select(attrs={'class': 'form-control'}),
}
class RelationForm(forms.ModelForm):
sourceid = forms.CharField(label='Source Gloss')
targetid = forms.CharField(label='Target Gloss')
class Meta:
model = Relation
fields = ['role']
widgets = {
'role': forms.Select(attrs={'class': 'form-control'}),
}
| bsd-3-clause |
majuca/prado | framework/Web/UI/WebControls/TTabPanel.php | 20591 | <?php
/**
* TTabPanel class file.
*
* @author Tomasz Wolny <tomasz.wolny@polecam.to.pl> and Qiang Xue <qiang.xue@gmail.com>
* @link https://github.com/pradosoft/prado
* @copyright Copyright © 2005-2015 The PRADO Group
* @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT
* @package System.Web.UI.WebControls
* @since 3.1.1
*/
/**
* Class TTabPanel.
*
* TTabPanel displays a tabbed panel. Users can click on the tab bar to switching among
* different tab views. Each tab view is an independent panel that can contain arbitrary content.
*
* If the {@link setAutoSwitch AutoSwitch} property is enabled, the user will be able to switch the active view
* to another one just hovering its corresponding tab caption.
*
* A TTabPanel control consists of one or several {@link TTabView} controls representing the possible
* tab views. At any time, only one tab view is visible (active), which is specified by any of
* the following properties:
* - {@link setActiveViewIndex ActiveViewIndex} - the zero-based integer index of the view in the view collection.
* - {@link setActiveViewID ActiveViewID} - the text ID of the visible view.
* - {@link setActiveView ActiveView} - the visible view instance.
* If both {@link setActiveViewIndex ActiveViewIndex} and {@link setActiveViewID ActiveViewID}
* are set, the latter takes precedence.
*
* TTabPanel uses CSS to specify the appearance of the tab bar and panel. By default,
* an embedded CSS file will be published which contains the default CSS for TTabPanel.
* You may also use your own CSS file by specifying the {@link setCssUrl CssUrl} property.
* The following properties specify the CSS classes used for elements in a TTabPanel:
* - {@link setCssClass CssClass} - the CSS class name for the outer-most div element (defaults to 'tab-panel');
* - {@link setTabCssClass TabCssClass} - the CSS class name for nonactive tab div elements (defaults to 'tab-normal');
* - {@link setActiveTabCssClass ActiveTabCssClass} - the CSS class name for the active tab div element (defaults to 'tab-active');
* - {@link setViewCssClass ViewCssClass} - the CSS class for the div element enclosing view content (defaults to 'tab-view');
*
* To use TTabPanel, write a template like following:
* <code>
* <com:TTabPanel>
* <com:TTabView Caption="View 1">
* content for view 1
* </com:TTabView>
* <com:TTabView Caption="View 2">
* content for view 2
* </com:TTabView>
* <com:TTabView Caption="View 3">
* content for view 3
* </com:TTabView>
* </com:TTabPanel>
* </code>
*
* @author Tomasz Wolny <tomasz.wolny@polecam.to.pl> and Qiang Xue <qiang.xue@gmail.com>
* @package System.Web.UI.WebControls
* @since 3.1.1
*/
class TTabPanel extends TWebControl implements IPostBackDataHandler
{
private $_dataChanged=false;
/**
* @return string tag name for the control
*/
protected function getTagName()
{
return 'div';
}
/**
* Adds object parsed from template to the control.
* This method adds only {@link TTabView} objects into the {@link getViews Views} collection.
* All other objects are ignored.
* @param mixed object parsed from template
*/
public function addParsedObject($object)
{
if($object instanceof TTabView)
$this->getControls()->add($object);
}
/**
* Returns the index of the active tab view.
* Note, this property may not return the correct index.
* To ensure the correctness, call {@link getActiveView()} first.
* @return integer the zero-based index of the active tab view. If -1, it means no active tab view. Default is 0 (the first view is active).
*/
public function getActiveViewIndex()
{
return $this->getViewState('ActiveViewIndex',0);
}
/**
* @param integer the zero-based index of the current view in the view collection. -1 if no active view.
* @throws TInvalidDataValueException if the view index is invalid
*/
public function setActiveViewIndex($value)
{
$this->setViewState('ActiveViewIndex',TPropertyValue::ensureInteger($value),0);
}
/**
* Returns the ID of the active tab view.
* Note, this property may not return the correct ID.
* To ensure the correctness, call {@link getActiveView()} first.
* @return string The ID of the active tab view. Defaults to '', meaning not set.
*/
public function getActiveViewID()
{
return $this->getViewState('ActiveViewID','');
}
/**
* @param string The ID of the active tab view.
*/
public function setActiveViewID($value)
{
$this->setViewState('ActiveViewID',$value,'');
}
/**
* Returns the currently active view.
* This method will examin the ActiveViewID, ActiveViewIndex and Views collection to
* determine which view is currently active. It will update ActiveViewID and ActiveViewIndex accordingly.
* @return TTabView the currently active view, null if no active view
* @throws TInvalidDataValueException if the active view ID or index set previously is invalid
*/
public function getActiveView()
{
$activeView=null;
$views=$this->getViews();
if(($id=$this->getActiveViewID())!=='')
{
if(($index=$views->findIndexByID($id))>=0)
$activeView=$views->itemAt($index);
else
throw new TInvalidDataValueException('tabpanel_activeviewid_invalid',$id);
}
else if(($index=$this->getActiveViewIndex())>=0)
{
if($index<$views->getCount())
$activeView=$views->itemAt($index);
else
throw new TInvalidDataValueException('tabpanel_activeviewindex_invalid',$index);
}
else
{
foreach($views as $index=>$view)
{
if($view->getActive())
{
$activeView=$view;
break;
}
}
}
if($activeView!==null)
$this->activateView($activeView);
return $activeView;
}
/**
* @param TTabView the view to be activated
* @throws TInvalidOperationException if the view is not in the view collection
*/
public function setActiveView($view)
{
if($this->getViews()->indexOf($view)>=0)
$this->activateView($view);
else
throw new TInvalidOperationException('tabpanel_view_inexistent');
}
/**
* @return bool status of automatic tab switch on hover
*/
public function getAutoSwitch()
{
return TPropertyValue::ensureBoolean($this->getViewState('AutoSwitch'));
}
/**
* @param bool whether to enable automatic tab switch on hover
*/
public function setAutoSwitch($value)
{
$this->setViewState('AutoSwitch',TPropertyValue::ensureBoolean($value));
}
/**
* @return string URL for the CSS file including all relevant CSS class definitions. Defaults to ''.
*/
public function getCssUrl()
{
return $this->getViewState('CssUrl','default');
}
/**
* @param string URL for the CSS file including all relevant CSS class definitions.
*/
public function setCssUrl($value)
{
$this->setViewState('CssUrl',TPropertyValue::ensureString($value),'');
}
/**
* @return string CSS class for the whole tab control div. Defaults to 'tab-panel'.
*/
public function getCssClass()
{
$cssClass=parent::getCssClass();
return $cssClass===''?'tab-panel':$cssClass;
}
/**
* @return string CSS class for the currently displayed view div. Defaults to 'tab-view'.
*/
public function getViewCssClass()
{
return $this->getViewStyle()->getCssClass();
}
/**
* @param string CSS class for the currently displayed view div.
*/
public function setViewCssClass($value)
{
$this->getViewStyle()->setCssClass($value);
}
/**
* @return TStyle the style for all the view div
*/
public function getViewStyle()
{
if(($style=$this->getViewState('ViewStyle',null))===null)
{
$style=new TStyle;
$style->setCssClass('tab-view');
$this->setViewState('ViewStyle',$style,null);
}
return $style;
}
/**
* @return string CSS class for non-active tabs. Defaults to 'tab-normal'.
*/
public function getTabCssClass()
{
return $this->getTabStyle()->getCssClass();
}
/**
* @param string CSS class for non-active tabs.
*/
public function setTabCssClass($value)
{
$this->getTabStyle()->setCssClass($value);
}
/**
* @return TStyle the style for all the inactive tab div
*/
public function getTabStyle()
{
if(($style=$this->getViewState('TabStyle',null))===null)
{
$style=new TStyle;
$style->setCssClass('tab-normal');
$this->setViewState('TabStyle',$style,null);
}
return $style;
}
/**
* @return string CSS class for the active tab. Defaults to 'tab-active'.
*/
public function getActiveTabCssClass()
{
return $this->getActiveTabStyle()->getCssClass();
}
/**
* @param string CSS class for the active tab.
*/
public function setActiveTabCssClass($value)
{
$this->getActiveTabStyle()->setCssClass($value);
}
/**
* @return TStyle the style for the active tab div
*/
public function getActiveTabStyle()
{
if(($style=$this->getViewState('ActiveTabStyle',null))===null)
{
$style=new TStyle;
$style->setCssClass('tab-active');
$this->setViewState('ActiveTabStyle',$style,null);
}
return $style;
}
/**
* Activates the specified view.
* If there is any other view currently active, it will be deactivated.
* @param TTabView the view to be activated. If null, all views will be deactivated.
*/
protected function activateView($view)
{
$this->setActiveViewIndex(-1);
$this->setActiveViewID('');
foreach($this->getViews() as $index=>$v)
{
if($view===$v)
{
$this->setActiveViewIndex($index);
$this->setActiveViewID($view->getID(false));
$view->setActive(true);
}
else
$v->setActive(false);
}
}
/**
* Loads user input data.
* This method is primarly used by framework developers.
* @param string the key that can be used to retrieve data from the input data collection
* @param array the input data collection
* @return boolean whether the data of the control has been changed
*/
public function loadPostData($key,$values)
{
if(($index=$values[$this->getClientID().'_1'])!==null)
{
$index=(int)$index;
$currentIndex=$this->getActiveViewIndex();
if($currentIndex!==$index)
{
$this->setActiveViewID(''); // clear up view ID
$this->setActiveViewIndex($index);
return $this->_dataChanged=true;
}
}
return false;
}
/**
* Raises postdata changed event.
* This method is required by {@link IPostBackDataHandler} interface.
* It is invoked by the framework when {@link getActiveViewIndex ActiveViewIndex} property
* is changed on postback.
* This method is primarly used by framework developers.
*/
public function raisePostDataChangedEvent()
{
// do nothing
}
/**
* Returns a value indicating whether postback has caused the control data change.
* This method is required by the IPostBackDataHandler interface.
* @return boolean whether postback has caused the control data change. False if the page is not in postback mode.
*/
public function getDataChanged()
{
return $this->_dataChanged;
}
/**
* Adds attributes to renderer.
* @param THtmlWriter the renderer
*/
protected function addAttributesToRender($writer)
{
$writer->addAttribute('id',$this->getClientID());
$this->setCssClass($this->getCssClass());
parent::addAttributesToRender($writer);
}
/**
* Registers CSS and JS.
* This method is invoked right before the control rendering, if the control is visible.
* @param mixed event parameter
*/
public function onPreRender($param)
{
parent::onPreRender($param);
$this->getActiveView(); // determine the active view
$this->registerStyleSheet();
$page=$this->getPage();
$page->registerRequiresPostData($this);
$page->registerRequiresPostData($this->getClientID()."_1");
}
/**
* Registers the CSS relevant to the TTabControl.
* It will register the CSS file specified by {@link getCssUrl CssUrl}.
* If that is not set, it will use the default CSS.
*/
protected function registerStyleSheet()
{
$url = $this->getCssUrl();
if($url === '') {
return;
}
if($url === 'default') {
$url = $this->getApplication()->getAssetManager()->publishFilePath(dirname(__FILE__).DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'tabpanel.css');
}
if($url !== '') {
$this->getPage()->getClientScript()->registerStyleSheetFile($url, $url);
}
}
/**
* Registers the relevant JavaScript.
*/
protected function registerClientScript()
{
$id=$this->getClientID();
$options=TJavaScript::encode($this->getClientOptions());
$className=$this->getClientClassName();
$cs=$this->getPage()->getClientScript();
$cs->registerPradoScript('tabpanel');
$code="new $className($options);";
$cs->registerEndScript("prado:$id", $code);
// ensure an item is always active and visible
$index = $this->getActiveViewIndex();
if(!$this->getViews()->itemAt($index)->Visible)
$index=0;
$cs->registerHiddenField($id.'_1', $index);
}
/**
* Gets the name of the javascript class responsible for performing postback for this control.
* This method overrides the parent implementation.
* @return string the javascript class name
*/
protected function getClientClassName()
{
return 'Prado.WebUI.TTabPanel';
}
/**
* @return array the options for JavaScript
*/
protected function getClientOptions()
{
$options['ID'] = $this->getClientID();
$options['ActiveCssClass'] = $this->getActiveTabCssClass();
$options['NormalCssClass'] = $this->getTabCssClass();
$viewIDs = array();
$viewVis = array();
foreach($this->getViews() as $view)
{
$viewIDs[] = $view->getClientID();
$viewVis[] = $view->getVisible();
}
$options['Views'] = $viewIDs;
$options['ViewsVis'] = $viewVis;
$options['AutoSwitch'] = $this->getAutoSwitch();
return $options;
}
/**
* Creates a control collection object that is to be used to hold child controls
* @return TTabViewCollection control collection
*/
protected function createControlCollection()
{
return new TTabViewCollection($this);
}
/**
* @return TTabViewCollection list of {@link TTabView} controls
*/
public function getViews()
{
return $this->getControls();
}
public function render($writer)
{
$this->registerClientScript();
parent::render($writer);
}
/**
* Renders body contents of the tab control.
* @param THtmlWriter the writer used for the rendering purpose.
*/
public function renderContents($writer)
{
$views=$this->getViews();
if($views->getCount()>0)
{
$writer->writeLine();
// render tab bar
foreach($views as $view)
{
$view->renderTab($writer);
$writer->writeLine();
}
// render tab views
foreach($views as $view)
{
$view->renderControl($writer);
$writer->writeLine();
}
}
}
}
/**
* TTabView class.
*
* TTabView represents a view in a {@link TTabPanel} control.
*
* The content in a TTabView can be specified by the {@link setText Text} property
* or its child controls. In template syntax, the latter means enclosing the content
* within the TTabView component element. If both are set, {@link getText Text} takes precedence.
*
* Each TTabView is associated with a tab in the tab bar of the TTabPanel control.
* The tab caption is specified by {@link setCaption Caption}. If {@link setNavigateUrl NavigateUrl}
* is set, the tab will contain a hyperlink pointing to the specified URL. In this case,
* clicking on the tab will redirect the browser to the specified URL.
*
* TTabView may be toggled between visible (active) and invisible (inactive) by
* setting the {@link setActive Active} property.
*
* @author Tomasz Wolny <tomasz.wolny@polecam.to.pl> and Qiang Xue <qiang.xue@gmail.com>
* @package System.Web.UI.WebControls
* @since 3.1.1
*/
class TTabView extends TWebControl
{
private $_active=false;
/**
* @return the tag name for the view element
*/
protected function getTagName()
{
return 'div';
}
/**
* Adds attributes to renderer.
* @param THtmlWriter the renderer
*/
protected function addAttributesToRender($writer)
{
if(!$this->getActive() && $this->getPage()->getClientSupportsJavaScript())
$this->getStyle()->setStyleField('display','none');
$this->getStyle()->mergeWith($this->getParent()->getViewStyle());
parent::addAttributesToRender($writer);
$writer->addAttribute('id',$this->getClientID());
}
/**
* @return string the caption displayed on this tab. Defaults to ''.
*/
public function getCaption()
{
return $this->getViewState('Caption','');
}
/**
* @param string the caption displayed on this tab
*/
public function setCaption($value)
{
$this->setViewState('Caption',TPropertyValue::ensureString($value),'');
}
/**
* @return string the URL of the target page. Defaults to ''.
*/
public function getNavigateUrl()
{
return $this->getViewState('NavigateUrl','');
}
/**
* Sets the URL of the target page.
* If not empty, clicking on this tab will redirect the browser to the specified URL.
* @param string the URL of the target page.
*/
public function setNavigateUrl($value)
{
$this->setViewState('NavigateUrl',TPropertyValue::ensureString($value),'');
}
/**
* @return string the text content displayed on this view. Defaults to ''.
*/
public function getText()
{
return $this->getViewState('Text','');
}
/**
* Sets the text content to be displayed on this view.
* If this is not empty, the child content of the view will be ignored.
* @param string the text content displayed on this view
*/
public function setText($value)
{
$this->setViewState('Text',TPropertyValue::ensureString($value),'');
}
/**
* @return boolean whether this tab view is active. Defaults to false.
*/
public function getActive()
{
return $this->_active;
}
/**
* @param boolean whether this tab view is active.
*/
public function setActive($value)
{
$this->_active=TPropertyValue::ensureBoolean($value);
}
/**
* Renders body contents of the tab view.
* @param THtmlWriter the writer used for the rendering purpose.
*/
public function renderContents($writer)
{
if(($text=$this->getText())!=='')
$writer->write($text);
else if($this->getHasControls())
parent::renderContents($writer);
}
/**
* Renders the tab associated with the tab view.
* @param THtmlWriter the writer for rendering purpose.
*/
public function renderTab($writer)
{
if($this->getVisible(false) && $this->getPage()->getClientSupportsJavaScript())
{
$writer->addAttribute('id',$this->getClientID().'_0');
$style=$this->getActive()?$this->getParent()->getActiveTabStyle():$this->getParent()->getTabStyle();
$style->addAttributesToRender($writer);
$writer->renderBeginTag($this->getTagName());
$this->renderTabContent($writer);
$writer->renderEndTag();
}
}
/**
* Renders the content in the tab.
* By default, a hyperlink is displayed.
* @param THtmlWriter the HTML writer
*/
protected function renderTabContent($writer)
{
if(($url=$this->getNavigateUrl())==='')
$url='javascript://';
if(($caption=$this->getCaption())==='')
$caption=' ';
$writer->write("<a href=\"{$url}\">{$caption}</a>");
}
}
/**
* TTabViewCollection class.
*
* TTabViewCollection is used to maintain a list of views belong to a {@link TTabPanel}.
*
* @author Tomasz Wolny <tomasz.wolny@polecam.to.pl> and Qiang Xue <qiang.xue@gmail.com>
* @package System.Web.UI.WebControls
* @since 3.1.1
*/
class TTabViewCollection extends TControlCollection
{
/**
* Inserts an item at the specified position.
* This overrides the parent implementation by performing sanity check on the type of new item.
* @param integer the speicified position.
* @param mixed new item
* @throws TInvalidDataTypeException if the item to be inserted is not a {@link TTabView} object.
*/
public function insertAt($index,$item)
{
if($item instanceof TTabView)
parent::insertAt($index,$item);
else
throw new TInvalidDataTypeException('tabviewcollection_tabview_required');
}
/**
* Finds the index of the tab view whose ID is the same as the one being looked for.
* @param string the explicit ID of the tab view to be looked for
* @return integer the index of the tab view found, -1 if not found.
*/
public function findIndexByID($id)
{
foreach($this as $index=>$view)
{
if($view->getID(false)===$id)
return $index;
}
return -1;
}
}
| bsd-3-clause |
jacastaneda/hosouees | vendor/composer/autoload_static.php | 11367 | <?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit491b57259d26ede26f33eef9dd2178da
{
public static $files = array (
'2cffec82183ee1cea088009cef9a6fc3' => __DIR__ . '/..' . '/ezyang/htmlpurifier/library/HTMLPurifier.composer.php',
'2c102faa651ef8ea5874edb585946bce' => __DIR__ . '/..' . '/swiftmailer/swiftmailer/lib/swift_required.php',
);
public static $prefixLengthsPsr4 = array (
'y' =>
array (
'yii\\swiftmailer\\' => 16,
'yii\\jui\\' => 8,
'yii\\httpclient\\' => 15,
'yii\\gii\\' => 8,
'yii\\faker\\' => 10,
'yii\\debug\\' => 10,
'yii\\composer\\' => 13,
'yii\\codeception\\' => 16,
'yii\\bootstrap\\' => 14,
'yii\\authclient\\' => 15,
'yii\\' => 4,
),
'r' =>
array (
'rmrevin\\yii\\fontawesome\\' => 24,
),
'k' =>
array (
'kartik\\widgets\\' => 15,
'kartik\\typeahead\\' => 17,
'kartik\\touchspin\\' => 17,
'kartik\\time\\' => 12,
'kartik\\switchinput\\' => 19,
'kartik\\spinner\\' => 15,
'kartik\\sidenav\\' => 15,
'kartik\\select2\\' => 15,
'kartik\\rating\\' => 14,
'kartik\\range\\' => 13,
'kartik\\popover\\' => 15,
'kartik\\plugins\\popover\\' => 23,
'kartik\\plugins\\fileinput\\' => 25,
'kartik\\plugins\\depdrop\\' => 23,
'kartik\\mpdf\\' => 12,
'kartik\\growl\\' => 13,
'kartik\\grid\\' => 12,
'kartik\\form\\' => 12,
'kartik\\file\\' => 12,
'kartik\\editable\\' => 16,
'kartik\\depdrop\\' => 15,
'kartik\\datetime\\' => 16,
'kartik\\date\\' => 12,
'kartik\\color\\' => 13,
'kartik\\base\\' => 12,
'kartik\\alert\\' => 13,
'kartik\\affix\\' => 13,
),
'j' =>
array (
'johnitvn\\userplus\\' => 18,
'johnitvn\\rbacplus\\' => 18,
'johnitvn\\ajaxcrud\\' => 18,
),
'd' =>
array (
'dosamigos\\tinymce\\' => 18,
'dmstr\\' => 6,
),
'c' =>
array (
'cebe\\markdown\\' => 14,
),
'F' =>
array (
'Faker\\' => 6,
),
);
public static $prefixDirsPsr4 = array (
'yii\\swiftmailer\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-swiftmailer',
),
'yii\\jui\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-jui',
),
'yii\\httpclient\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-httpclient',
),
'yii\\gii\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-gii',
),
'yii\\faker\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-faker',
),
'yii\\debug\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-debug',
),
'yii\\composer\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-composer',
),
'yii\\codeception\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-codeception',
),
'yii\\bootstrap\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-bootstrap',
),
'yii\\authclient\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-authclient',
),
'yii\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2',
),
'rmrevin\\yii\\fontawesome\\' =>
array (
0 => __DIR__ . '/..' . '/rmrevin/yii2-fontawesome',
),
'kartik\\widgets\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widgets',
),
'kartik\\typeahead\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-typeahead',
),
'kartik\\touchspin\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-touchspin',
),
'kartik\\time\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-timepicker',
),
'kartik\\switchinput\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-switchinput',
),
'kartik\\spinner\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-spinner',
),
'kartik\\sidenav\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-sidenav',
),
'kartik\\select2\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-select2',
),
'kartik\\rating\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-rating',
),
'kartik\\range\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-rangeinput',
),
'kartik\\popover\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-popover-x',
),
'kartik\\plugins\\popover\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/bootstrap-popover-x',
),
'kartik\\plugins\\fileinput\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/bootstrap-fileinput',
),
'kartik\\plugins\\depdrop\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/dependent-dropdown',
),
'kartik\\mpdf\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-mpdf',
),
'kartik\\growl\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-growl',
),
'kartik\\grid\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-grid',
),
'kartik\\form\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-activeform',
),
'kartik\\file\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-fileinput',
),
'kartik\\editable\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-editable',
),
'kartik\\depdrop\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-depdrop',
),
'kartik\\datetime\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-datetimepicker',
),
'kartik\\date\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-datepicker',
),
'kartik\\color\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-colorinput',
),
'kartik\\base\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-krajee-base',
),
'kartik\\alert\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-alert',
),
'kartik\\affix\\' =>
array (
0 => __DIR__ . '/..' . '/kartik-v/yii2-widget-affix',
),
'johnitvn\\userplus\\' =>
array (
0 => __DIR__ . '/..' . '/johnitvn/yii2-user-plus/src',
),
'johnitvn\\rbacplus\\' =>
array (
0 => __DIR__ . '/..' . '/johnitvn/yii2-rbac-plus/src',
),
'johnitvn\\ajaxcrud\\' =>
array (
0 => __DIR__ . '/..' . '/johnitvn/yii2-ajaxcrud/src',
),
'dosamigos\\tinymce\\' =>
array (
0 => __DIR__ . '/..' . '/2amigos/yii2-tinymce-widget/src',
),
'dmstr\\' =>
array (
0 => __DIR__ . '/..' . '/dmstr/yii2-adminlte-asset',
),
'cebe\\markdown\\' =>
array (
0 => __DIR__ . '/..' . '/cebe/markdown',
),
'Faker\\' =>
array (
0 => __DIR__ . '/..' . '/fzaninotto/faker/src/Faker',
),
);
public static $prefixesPsr0 = array (
'c' =>
array (
'cebe\\gravatar\\' =>
array (
0 => __DIR__ . '/..' . '/cebe/yii2-gravatar',
),
),
'H' =>
array (
'HTMLPurifier' =>
array (
0 => __DIR__ . '/..' . '/ezyang/htmlpurifier/library',
),
),
'D' =>
array (
'Diff' =>
array (
0 => __DIR__ . '/..' . '/phpspec/php-diff/lib',
),
),
);
public static $classMap = array (
'CGIF' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/gif.php',
'CGIFCOLORTABLE' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/gif.php',
'CGIFFILEHEADER' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/gif.php',
'CGIFIMAGE' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/gif.php',
'CGIFIMAGEHEADER' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/gif.php',
'CGIFLZW' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/gif.php',
'INDIC' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/indic.php',
'MYANMAR' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/myanmar.php',
'OTLdump' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/otl_dump.php',
'PDFBarcode' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/barcode.php',
'SEA' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/sea.php',
'SVG' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/svg.php',
'TTFontFile' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/ttfontsuni.php',
'TTFontFile_Analysis' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/ttfontsuni_analysis.php',
'UCDN' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/ucdn.php',
'bmp' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/bmp.php',
'cssmgr' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/cssmgr.php',
'directw' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/directw.php',
'grad' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/grad.php',
'mPDF' => __DIR__ . '/..' . '/kartik-v/mpdf/mpdf.php',
'meter' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/meter.php',
'mpdfform' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/mpdfform.php',
'otl' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/otl.php',
'tocontents' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/tocontents.php',
'wmf' => __DIR__ . '/..' . '/kartik-v/mpdf/classes/wmf.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit491b57259d26ede26f33eef9dd2178da::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit491b57259d26ede26f33eef9dd2178da::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit491b57259d26ede26f33eef9dd2178da::$prefixesPsr0;
$loader->classMap = ComposerStaticInit491b57259d26ede26f33eef9dd2178da::$classMap;
}, null, ClassLoader::class);
}
}
| bsd-3-clause |
calcutec/aperturus | app/static/js/main.js | 20330 | window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
App.Router.MainRouter = Backbone.Router.extend({
routes: { // sets the routes
'': 'start', // http://netbard.com/photos/portfolio/
'create': 'create', // http://netbard.com/photos/portfolio/#create
'edit/:id': 'edit' // http://netbard.com/photos/portfolio/#edit/7
},
start: function(){
//console.log('now in view' + Backbone.history.location.href);
var page_mark = Backbone.history.location.pathname.split("/")[2];
if ( page_mark == "gallery") {
var photolist = new App.Collections.PhotoList(initialdata); // loaded from data.js
new App.Views.MainView({el: "#photoapp", collection: photolist, page_mark:page_mark});
window.s3formview = new App.Views.S3FormView();
} else if (page_mark == "login") {
window.loginview = new App.Views.LoginFormView({el:'#body-form'}).render();
}
//var pgurl = "#" + Backbone.history.location.pathname.split("/")[2];
//$("#nav ul li a").each(function(){
// console.log($(this).attr("href"))
// if($(this).attr("href") == pgurl) {
// $(this).addClass("active");
// }
//})
},
edit: function(id){
console.log('edit route with id: ' + id);
},
create: function(){
console.log('View for creating photos rendered');
}
});
App.Views.LoginFormView = Backbone.View.extend({
render: function() {
this.$el.html(nunjucks.render("assets/forms/login_form.html"));
return this;
},
unrender: function(){
$(this.el).remove();
}
});
App.Models.Photo = Backbone.Model.extend( {
defaults: {
author: '',
header: '',
body: '',
photo: '',
entryPhotoName: '',
subject: '',
read: false,
star: false,
selected:false,
archived:false,
label: '',
static_url: 'https://s3.amazonaws.com/aperturus/'
},
validate: function(attrs){
if (!attrs.header){
alert('Your post must have a title!');
}
if (!attrs.body){
alert('Your post must have a story');
}
},
markRead: function() {
this.save( {read: true } );
},
starMail: function() {
this.save( { star: !this.get("star")} );
},
archive: function(){
this.save( { archived: true, selected:false} );
},
selectMail: function() {
this.save( { selected: !this.get("selected")} );
},
setLabel: function(label){
this.save( { label: label } );
}
});
App.Views.PhotoMainView = Backbone.View.extend({
initialize: function() {
this.model.bind('change', this.render, this);
},
render: function() {
this.$el.html(nunjucks.render("main_entry.html", this.model.toJSON()));
return this;
},
unrender: function(){
$(this.el).remove();
}
});
App.Views.PhotoListView = Backbone.View.extend({
tagName: "li",
initialize: function() {
this.model.bind('change', this.render, this);
//this.listenTo(this.model, "change", this.savePost); // calls render function once name changed
//this.listenTo(this.model, "destroy", this.removejunk); // calls remove function once model deleted
//this.listenTo(this.model, "removeMe", this.removejunk); // calls remove function once model deleted
},
events: {
'click .edit': 'editPost',
'click .edit-button': 'editPost',
'click .submit-button': 'updatePost',
'click .delete-button': 'deletePost',
},
savePost: function(){
this.model.save(null, {
success: function (model, response) {
if (response.updatedsuccess == true){
return response;
}
if (response.savedsuccess == true){
new App.Views.Post({model:model}).render();
this.remove();
return response;
}
return response;
},
error: function () {
alert('your poem did not save properly..')
},
wait: true
});
},
editPost: function(e){
e.preventDefault();
if (!App.Views.Post.editable) {
var $target = $(e.target);
$target.closest("article").find(".edit-me").addClass('edit-selected');
var editSelected = $('.edit-selected');
App.Views.Post.currentwysihtml5 = editSelected.wysihtml5({
toolbar: {
"style": true,
"font-styles": true,
"emphasis": true,
"lists": true,
"html": false,
"link": false,
"image": false,
"color": false,
fa: true
}
});
$target.closest("article").find('.edit-button').html("Submit Changes").attr('class', 'submit-button').css({'color':'red', 'style':'bold'});
editSelected.css({"border": "2px #2237ff dotted"});
editSelected.attr('contenteditable', false);
App.Views.Post.editable = true;
}
},
updatePost: function(e){
e.preventDefault();
console.log('updating post..')
},
deletePost: function(e){
e.preventDefault();
alert("Do you really want to destroy this post?");
this.model.destroy({
success: function() {
console.log('model completely destroyed..');
}
});
},
removejunk: function(){
// same as this.$el.remove();
this.remove();
// unbind events that are set on this view
this.off();
// remove all models bindings made by this view
this.model.off( null, null, this );
},
render: function() {
this.$el.html(nunjucks.render("archive_entry.html", this.model.toJSON()));
return this;
},
unrender: function(){
$(this.el).remove();
}
});
App.Views.MainView = Backbone.View.extend({
initialize: function(options){
_.extend(this, _.pick(options, "page_mark"));
//this.collection.bind('change', this.renderSideMenu, this);
//this.renderSideMenu();
this.renderMainPhoto(this.collection.models[0]);
this.renderPhotoList(this.collection);
this.renderTitle();
},
events: {
"change #labeler" : "applyLabel",
"click #markallread" : "markallread",
"click #archive" : "archive",
"click #allmail" : "allmail",
"click #inbox": "inbox",
"click #starred": "starred",
"keyup #search" : "search"
},
search: function(){
this.render(this.collection.search($("#search").val()));
},
starred: function(){
this.render(this.collection.starred());
},
inbox: function(){
this.render(this.collection.inbox());
},
allmail: function(){
this.render(this.collection);
},
markallread : function(){
this.collection.each(function(item){
item.markRead();
}, this);
},
applyLabel: function(){
var label = $("#labeler").val();
this.collection.each(function(item){
if(item.get('selected') == true){
item.setLabel(label);
}
}, this);
},
archive: function(){
this.collection.each(function(item){
if(item.get('selected') == true){
item.archive();
}
}, this);
this.render(this.collection.inbox());
},
renderTitle: function(){
$("#headline").html(
nunjucks.render('title.html', {'page_mark': this.page_mark})
);
},
renderMainPhoto: function(latestrecord){
$('div#photo-main', this.el).html('');
var photoMainView = new App.Views.PhotoMainView({el:"#photo-main", model: latestrecord});
$('div#photo-main', this.el).append(photoMainView.render().el);
},
renderPhotoList: function(collection){
var target = $('ul#img-list', this.el);
target.html('');
var self = this;
_.each( collection.models.slice(1,7), function(model) {
//console.log(model.get("id"));
self.addOneToList(model);
}, this);
},
addOneToList: function (photo) {
var photoView = new App.Views.PhotoListView({ model: photo});
$('ul#img-list', this.el).append(photoView.render().el);
}
//renderSideMenu: function(){
// $("#summary").html(
// nunjucks.render('summary_template.html', {
// 'inbox': this.collection.unread_count(),
// 'starred':this.collection.starcount()
// })
// );
//},
});
App.Collections.PhotoList = Backbone.Collection.extend({
model: App.Models.Photo,
localStorage: new Backbone.LocalStorage("photos"),
parse: function(response){
return response.myPhotos
},
unread: function() {
return _(this.filter( function(photo) { return !photo.get('read');} ) );
},
inbox: function(){
return _(this.filter( function(photo) { return !photo.get('archived');}));
},
starred: function(){
return _(this.filter( function(photo) { return photo.get('star');}));
},
unread_count: function() {
return (this.filter ( function(photo) { return !photo.get('read');})).length;
},
labelled:function(label){
return _(this.filter( function(photo) { return label in photo.get('label') } ));
},
starcount: function(){
return (this.filter( function(photo) { return photo.get('star')})).length;
},
search: function(word){
if (word=="") return this;
var pat = new RegExp(word, 'gi');
return _(this.filter(function(photo) {
return pat.test(photo.get('subject')) || pat.test(photo.get('sender')); }));
},
byauthor: function (author_id) {
var filtered = this.filter(function (post) {
return photo.get("author") === author_id;
});
return new App.Collections.PhotoList(filtered);
},
comparator: function(photo){
return -photo.get('timestamp');
}
});
App.Views.PhotoTextFormView = Backbone.View.extend({
el: '#photo-form-target',
initialize: function(){
this.render()
},
events: {
'submit': 'postnewentry',
'click .submit-button': 'updatePost',
'click #test-button': 'testAlert'
},
postnewentry: function(e) {
e.preventDefault();
var newPostModel = new App.Models.Post(this.$el.find('form').serializeObject());
if (currentFile === null){
alert("file upload has failed")
} else {
var entryPhotoName = currentFile.name.split(".")[0]+"-hexgenerator."+currentFile.type.split("/")[1];
newPostModel.set({'entryPhotoName': entryPhotoName});
}
newPostModel.save(null, {
success: function (model, response) {
alert('saved');
new App.Views.Post({model:model}).render();
return response;
},
error: function () {
alert('your poem did not save properly..')
},
wait: true
});
},
render: function() {
this.$el.html(nunjucks.render('/assets/forms/photo_text_form.html', { "phototextform['csrf_token']": '12345' }));
return this;
}
});
App.Views.S3FormView = Backbone.View.extend({
el: '#s3-form',
events: {
'change #file-input': 'validateanddisplaysample'
},
validateanddisplaysample: function(e) {
e.preventDefault();
//Get reference of FileUpload.
var fileUpload = this.$el.find("#file-input")
//Check whether the file is valid Image.
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.jpeg)$");
if (regex.test(fileUpload.val().toLowerCase())) {
//Check whether HTML5 is supported.
if (fileUpload.prop('files') != "undefined") {
currentFile = e.target.files[0];
//Initiate the FileReader object.
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.prop('files')[0]);
var self = this;
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.height;
var width = this.width;
var size = currentFile.size;
if (width < 648 || height < 432) {
alert("Images must be at least 648px in width and 432px in height");
return false;
} else {
self.generateUploadFormThumb(self, currentFile);
}
if (height > 4896 || width > 4896 || size > 2000000) {
self.generateServerFile(currentFile);
}
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a jpeg or png image file.");
return false;
}
},
generateUploadFormThumb: function(self, currentFile){
loadImage(
currentFile,
function (img) {
if(img.type === "error") {
alert("Error loading image " + currentFile);
return false;
} else {
self.replaceResults(img, currentFile);
loadImage.parseMetaData(currentFile, function (data) {
if (data.exif) {
self.displayExifData(data.exif);
}
});
}
},
{maxWidth: 648}
);
},
generateServerFile: function(currentFile){
loadImage(
currentFile,
function (img) {
if(img.type === "error") {
console.log("Error loading image " + currentFile);
} else {
if (img.toBlob) {
img.toBlob(
function (blob) {
serverBlob = blob
},
'image/jpeg'
);
}
}
},
{maxWidth: 4896, canvas:true}
);
},
replaceResults: function (img, currentFile) {
var content;
if (!(img.src || img instanceof HTMLCanvasElement)) {
content = $('<span>Loading image file failed</span>')
} else {
content = $(img);
}
$('#result').children().replaceWith(content.addClass('u-full-width').removeAttr('width').removeAttr('height').fadeIn());
$('#photo-submit').removeClass("hide");
},
displayExifData: function (exif) { // Save Exif data to an entry model attribute to save on Flask model
var tags = exif.getAll(),
table = $('#exif').find('table').empty(),
row = $('<tr></tr>'),
cell = $('<td></td>'),
prop;
for (prop in tags) {
if (tags.hasOwnProperty(prop)) {
if(prop in {'Make':'', 'Model':'', 'DateTime':'', 'ExposureTime':'', 'ShutterSpeedValue':'',
'FNumber':'', 'ExposureProgram':'', 'MeteringMode':'', 'ExposureMode':'', 'WhiteBalance':'',
'PhotographicSensitivity':'', 'FocalLength':'', 'FocalLengthIn35mmFilm':'', 'LensModel':'',
'Sharpness':'', 'PixelXDimension':'', 'PixelYDimension':''}) {
table.append(
row.clone()
.append(cell.clone().text(prop))
.append(cell.clone().text(tags[prop]))
);
}
}
}
},
render: function() {
this.$el.html(this.template);
console.log('modal rendered');
return this;
}
});
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$.fn.submitData = function(e){
var data = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress',function(e){
console.log('now loading')
}, false);
xhr.onreadystatechange = function(e){
if(xhr.readyState == 4){
console.log(xhr.statusText) //complete! - check xhr.status
}
};
xhr.open('POST', 'https://aperturus.s3.amazonaws.com/', true);
xhr.send(data);
return false;
};
$(document).ready(function() {
$(function(){
$('#main-menu').slicknav({
prependTo:'#mobileMenu',
closeOnClick: true,
label: '',
brand: 'Gallery'
});
$(document).on('click', "#main-menu .scroll, .slicknav_menu .scroll", function(e) {
e.preventDefault();
var h = $('#nav').outerHeight();
if (!$('#main-menu').is(":visible")) {
h = $('.slicknav_menu .slicknav_btn').outerHeight();
}
//var link = this;
//$.smoothScroll({
// offset: -h,
// scrollTarget: link.hash
//});
});
});
var env = nunjucks.configure('/static/templates');
env.addGlobal("static_url", 'https://s3.amazonaws.com/aperturus/');
new App.Router.MainRouter();
Backbone.history.start();
var csrftoken = $('meta[name=csrf-token]').attr('content');
$(function(){
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken)
}
}
})
});
$( "#s3-form" ).submit(function( e ) {
e.preventDefault();
var data = new FormData(this);
if (typeof(serverBlob) !== "undefined") {
data.append('image', serverBlob);
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress',function(e){
$( "#progress-bar").html(e.loaded+" of "+e.total+" bytes loaded");
}, false);
xhr.onreadystatechange = function(e){
if(xhr.readyState == 4){
if(xhr.status == 200){
window.s3formview.$el.hide();
window.phototextformview = new App.Views.PhotoTextFormView();
} else {
console.log(xhr.statusText)
}
}
};
xhr.open('POST', 'https://aperturus.s3.amazonaws.com/', true);
xhr.send(data);
return false;
});
//App.Collections.Post.postCollection = new App.Collections.Post();
//App.Collections.Post.postCollection.fetch({
// success: function() {
// App.Views.Posts.poemListView = new App.Views.Posts({collection: App.Collections.Post.postCollection});
// App.Views.Posts.poemListView.attachToView();
// }
//});
}); | bsd-3-clause |