code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<input type="text" autocomplete="off" class="text" id="<?php wptouch_admin_the_setting_name(); ?>" name="<?php wptouch_admin_the_encoded_setting_name(); ?>" value="<?php wptouch_admin_the_setting_value(); ?>" placeholder="" /> <label class="text" for="<?php wptouch_admin_the_setting_name(); ?>"> <?php wptouch_admin_the_setting_desc(); ?> </label> <?php if ( wptouch_admin_setting_has_tooltip() ) { ?> <i class="wptouch-tooltip icon-question-sign" title="<?php wptouch_admin_the_setting_tooltip(); ?>"></i> <?php } ?> <?php if ( wptouch_admin_get_setting_level() == WPTOUCH_SETTING_ADVANCED ) { ?> <span class="advanced"><?php _e( 'Advanced', 'wptouch-pro' ); ?></span><?php } ?> <?php if ( wptouch_admin_is_setting_new() ) { ?> <span class="new"><?php _e( 'New', 'wptouch-pro' ); ?></span><?php } ?>
stevenjack/pjsdevelopments
wp-content/plugins/wptouch/admin/settings/html/text.php
PHP
gpl-2.0
806
// CS0205: Cannot call an abstract base member `A.Foobar' // Line: 15 public abstract class A { protected abstract int Foobar { get; } } public abstract class A1 : A { }
xen2/mcs
errors/CS0205-3-lib.cs
C#
gpl-2.0
180
require "katello_test_helper" #rubocop:disable Metrics/ModuleLength module Katello #rubocop:disable Metrics/BlockLength describe Api::Registry::RegistryProxiesController do include Support::ForemanTasks::Task def setup_models @docker_repo = katello_repositories(:busybox) @organization = @docker_repo.product.organization @docker_env_repo = katello_repositories(:busybox_view1) @rpm_repo = katello_repositories(:fedora_17_x86_64) @tag = katello_docker_tags(:one) @digest = 'sha256:somedigest' end def setup_permissions @read_permission = :view_products @create_permission = :create_products @update_permission = :edit_products @destroy_permission = :destroy_products @sync_permission = :sync_products end before do setup_models setup_permissions setup_controller_defaults_api SETTINGS[:katello][:container_image_registry] = {crane_url: 'https://localhost:5000', crane_ca_cert_file: '/etc/pki/katello/certs/katello-default-ca.crt', allow_push: true} File.delete("#{Rails.root}/tmp/manifest.json") if File.exist?("#{Rails.root}/tmp/manifest.json") end describe "docker login" do it "ping - with cert" do User.current = nil session[:user] = nil reset_api_credentials get :ping assert_response 401 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] assert_equal "Bearer realm=\"http://test.host/v2/token\"," \ "service=\"test.host\"," \ "scope=\"repository:registry:pull,push\"", response.headers['Www-Authenticate'] end it "ping - unauthorized" do User.current = nil session[:user] = nil reset_api_credentials get :ping assert_response 401 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] assert_equal "Bearer realm=\"http://test.host/v2/token\"," \ "service=\"test.host\"," \ "scope=\"repository:registry:pull,push\"", response.headers['Www-Authenticate'] end it "ping - basic unauthorized" do User.current = nil session[:user] = nil reset_api_credentials get :ping assert_response 401 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] assert_equal "Bearer realm=\"http://test.host/v2/token\"," \ "service=\"test.host\"," \ "scope=\"repository:registry:pull,push\"", response.headers['Www-Authenticate'] end it "ping - bearer bad token" do User.current = nil session[:user] = nil @request.env['HTTP_AUTHORIZATION'] = "Bearer 12345" get :ping assert_response 401 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] assert_equal "Bearer realm=\"http://test.host/v2/token\"," \ "service=\"test.host\"," \ "scope=\"repository:registry:pull,push\"", response.headers['Www-Authenticate'] end it "ping - bearer expired" do User.current = nil session[:user] = nil @request.env['HTTP_AUTHORIZATION'] = "Bearer 12345" token = mock('token') token.stubs('expired?').returns(true) PersonalAccessToken.expects(:find_by_token).with("12345").returns(token) get :ping assert_response 401 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] assert_equal "Bearer realm=\"http://test.host/v2/token\"," \ "service=\"test.host\"," \ "scope=\"repository:registry:pull,push\"", response.headers['Www-Authenticate'] end it "ping - bearer authorized" do user = User.current User.current = nil session[:user] = nil @request.env['HTTP_AUTHORIZATION'] = "Bearer 12345" token = mock('token') token.stubs('expired?').returns(false) token.stubs(:user_id).returns(user.id) PersonalAccessToken.expects(:find_by_token).with("12345").returns(token) get :ping assert_response 200 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] assert_nil response.headers['Www-Authenticate'] end it "ping - basic authorized" do get :ping assert_response 200 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] assert_nil response.headers['Www-Authenticate'] end it "token - no 'registry' token yet" do PersonalAccessToken.expects(:where) .with(user_id: User.current.id, name: 'registry') .returns([]) expiration = Time.now token = mock('token') token.stubs(:token).returns("12345") token.stubs(:generate_token).returns("12345") token.stubs(:user_id).returns(User.current.id) token.stubs(:expires_at).returns("#{expiration}") token.stubs(:created_at).returns("#{expiration}") token.stubs('save!').returns(true) PersonalAccessToken.expects(:new).returns(token) get :token, params: { account: User.name } assert_response 200 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] body = JSON.parse(response.body) assert_equal "12345", body['token'] assert_equal "#{expiration}", body['expires_at'] assert_equal "#{expiration}", body['issued_at'] end it "token - has 'registry' token" do expiration = Time.now token = mock('token') token.stubs(:token).returns("12345") token.stubs(:generate_token).returns("12345") token.stubs(:user_id).returns(User.current.id) token.stubs(:expires_at).returns("#{expiration}") token.stubs(:created_at).returns("#{expiration}") token.stubs('save!').returns(true) token.expects('expires_at=').returns(true) PersonalAccessToken.expects(:where) .with(user_id: User.current.id, name: 'registry') .returns([token]) PersonalAccessToken.expects(:new).never get :token, params: { account: User.name } assert_response 200 assert_equal 'registry/2.0', response.headers['Docker-Distribution-API-Version'] body = JSON.parse(response.body) assert_equal "12345", body['token'] assert_equal "#{expiration}", body['expires_at'] assert_equal "#{expiration}", body['issued_at'] end it "token - unscoped is authorized" do User.current = nil session[:user] = nil reset_api_credentials get :token assert_response 200 end it "token - allow unauthenticated pull" do @docker_repo.set_container_repository_name @docker_repo.save! @docker_repo.environment.registry_unauthenticated_pull = true @docker_repo.environment.save! User.current = nil session[:user] = nil reset_api_credentials get :token, params: { scope: "repository:#{@docker_repo.container_repository_name}:pull" } assert_response 200 end it "token - do not allow unauthenticated pull" do @docker_repo.set_container_repository_name @docker_repo.save! @docker_repo.environment.registry_unauthenticated_pull = false @docker_repo.environment.save! User.current = nil session[:user] = nil reset_api_credentials get :token, params: { scope: "repository:#{@docker_repo.container_repository_name}:pull" } assert_response 401 end it "token - allow cert-based pull" do @docker_repo.set_container_repository_name @docker_repo.save! @docker_repo.environment.registry_unauthenticated_pull = false @docker_repo.environment.save! User.current = nil session[:user] = nil reset_api_credentials request.headers.merge!(HTTP_SSL_CLIENT_VERIFY: 'SUCCESS', HTTP_SSL_CLIENT_S_DN: "O=#{@docker_repo.organization.label}") get :token, params: { scope: "repository:#{@docker_repo.container_repository_name}:pull" } assert_response 200 end it "token - do not allow unauthenticated push" do @docker_repo.set_container_repository_name @docker_repo.save! @docker_repo.environment.registry_unauthenticated_pull = true @docker_repo.environment.save! User.current = nil session[:user] = nil reset_api_credentials get :token, params: { scope: "repository:#{@docker_repo.container_repository_name}:push" } assert_response 401 end end describe "catalog" do it "displays all images for authenticated requests" do @docker_repo.set_container_repository_name @docker_env_repo.set_container_repository_name org = @docker_repo.organization repo = katello_repositories(:busybox_dev) repo.set_container_repository_name assert repo.save! repo.environment.registry_unauthenticated_pull = false assert repo.environment.save! get :catalog assert_response 200 body = JSON.parse(response.body) assert_equal(body['repositories'].compact.sort, ["busybox", "empty_organization-dev_label-published_dev_view-puppet_product-busybox", "#{org.label.downcase}-puppet_product-busybox"]) end it "shows only available images for unauthenticated requests" do @docker_repo.set_container_repository_name @docker_env_repo.set_container_repository_name @docker_repo.environment.registry_unauthenticated_pull = true assert @docker_repo.environment.save! User.current = nil session[:user] = nil reset_api_credentials get :catalog assert_response 200 body = JSON.parse(response.body) assert_equal(["busybox", "empty_organization-puppet_product-busybox"], body['repositories'].compact.sort) end end describe "docker search" do it "search" do @docker_repo.set_container_repository_name @docker_env_repo.set_container_repository_name org = @docker_repo.organization per_page = 25 scoped_results = { total: 100, subtotal: 2, page: 1, per_page: per_page, results: [@docker_repo, @docker_env_repo] } @controller.stubs(:scoped_search).returns(scoped_results) get :v1_search, params: { q: "abc", n: 2 } assert_response 200 body = JSON.parse(response.body) assert_equal(body, "num_results" => 2, "query" => "abc", "results" => [{ "name" => "#{org.label.downcase}-puppet_product-busybox", "description" => nil }, { "name" => "#{org.label.downcase}-published_library_view-1_0-puppet_product-busybox", "description" => nil }] ) end it "blocks search for podman" do @docker_repo.set_container_repository_name @docker_env_repo.set_container_repository_name @request.env['HTTP_USER_AGENT'] = "libpod/1.8.0" get :v1_search, params: { q: "abc", n: 2 } assert_response 404 end it "show unauthenticated repositories" do repo = katello_repositories(:busybox_dev) repo.set_container_repository_name assert repo.save! repo.environment.registry_unauthenticated_pull = true assert repo.environment.save! @controller.stubs(:authenticate).returns(false) User.current = nil get :v1_search, params: { n: 2 } assert true assert_response 200 body = JSON.parse(response.body) assert_equal 1, body["results"].length assert_equal "#{repo.organization.label.downcase}-dev_label-published_dev_view-puppet_product-busybox", body["results"][0]["name"] end it "show unauthenticated repositories for head requests" do repo = katello_repositories(:busybox_dev) repo.set_container_repository_name assert repo.save! repo.environment.registry_unauthenticated_pull = true assert repo.environment.save! @controller.stubs(:authenticate).returns(false) User.current = nil head :v1_search, params: { n: 2 } assert true assert_response 200 end it "does not show archived versions" do User.current = User.find(users('admin').id) repo = katello_repositories(:busybox) repo.set_container_repository_name repo.environment_id = nil assert repo.save! assert repo.archive? non_archive_repo = katello_repositories(:busybox_dev) non_archive_repo.set_container_repository_name non_archive_repo.save! refute non_archive_repo.archive? get :v1_search assert_response 200 body = JSON.parse(response.body) refute_includes body["results"], { "name" => repo.container_repository_name, "description" => nil } assert_includes body["results"], { "name" => non_archive_repo.container_repository_name, "description" => nil } end it "shows N repositories" do User.current = User.find(users('admin').id) get :v1_search, params: { n: 2 } assert_response 200 body = JSON.parse(response.body) assert_equal 2, body["results"].length end end describe "docker pull" do it "pull manifest - protected" do @controller.stubs(:registry_authorize).returns(true) @controller.stubs(:find_readable_repository).returns(@docker_repo) Resources::Registry::Proxy.stubs(:get).returns(stubbed: true) DockerMetaTag.stubs(:where).with(id: RepositoryDockerMetaTag. where(repository_id: @docker_repo.id). select(:docker_meta_tag_id), name: @tag.name).returns([@tag]) allowed_perms = [:create_personal_access_tokens] denied_perms = [] assert_protected_action(:pull_manifest, allowed_perms, denied_perms, [@organization]) do get :pull_manifest, params: { repository: @docker_repo.name, tag: @tag.name } end end it "pull manifest - success" do manifest = '{"mediaType":"MEDIATYPE"}' manifest.stubs(:headers).returns({docker_content_digest: @digest}) @controller.stubs(:registry_authorize).returns(true) @controller.stubs(:find_readable_repository).returns(@docker_repo) Resources::Registry::Proxy.stubs(:get).returns(manifest) DockerMetaTag.stubs(:where).with(id: RepositoryDockerMetaTag. where(repository_id: @docker_repo.id). select(:docker_meta_tag_id), name: @tag.name).returns([@tag]) get :pull_manifest, params: { repository: @docker_repo.name, tag: @tag.name } assert_response 200 assert_equal(manifest, response.body) assert response.header['Content-Type'] =~ /MEDIATYPE/ assert_equal @digest, response.header['Docker-Content-Digest'] end it "pull manifest - HTTPS Header" do #production installs include an HTTPS: 'on' header, which needs to be removed manifest = '{"mediaType":"MEDIATYPE"}' manifest.stubs(:headers).returns({docker_content_digest: @digest}) @controller.stubs(:registry_authorize).returns(true) @controller.stubs(:find_readable_repository).returns(@docker_repo) request.env['HTTPS'] = 'on' #should not be passed through request.env['HTTP_FOO'] = 'bar' #should be passed through expected_headers = {"HOST" => "test.host", "USER-AGENT" => "Rails Testing", "AUTHORIZATION" => "Basic YXBpYWRtaW46c2VjcmV0", "ACCEPT" => "application/json", "ACCEPT-LANGUAGE" => "en-US", "FOO" => "bar", "COOKIE" => ""} expected_headers['AUTHORIZATION'] = request.env['HTTP_AUTHORIZATION'] Resources::Registry::Proxy.stubs(:get).with('/v2/busybox/manifests/one', expected_headers).returns(manifest) DockerMetaTag.stubs(:where).with(id: RepositoryDockerMetaTag. where(repository_id: @docker_repo.id). select(:docker_meta_tag_id), name: @tag.name).returns([@tag]) get :pull_manifest, params: { repository: @docker_repo.name, tag: @tag.name } assert_response 200 assert_equal(manifest, response.body) assert response.header['Content-Type'] =~ /MEDIATYPE/ assert_equal @digest, response.header['Docker-Content-Digest'] end it "pull manifest - HTTP Header - v1+json" do manifest = '{}' manifest.stubs(:headers).returns({docker_content_digest: @digest}) @controller.stubs(:registry_authorize).returns(true) @controller.stubs(:find_readable_repository).returns(@docker_repo) Resources::Registry::Proxy.stubs(:get).returns(manifest) DockerMetaTag.stubs(:where).with(id: RepositoryDockerMetaTag. where(repository_id: @docker_repo.id). select(:docker_meta_tag_id), name: @tag.name).returns([@tag]) get :pull_manifest, params: { repository: @docker_repo.name, tag: @tag.name } assert_response 200 assert_equal(manifest, response.body) assert_includes response.header['Content-Type'], 'application/vnd.docker.distribution.manifest.v1+json' assert_equal @digest, response.header['Docker-Content-Digest'] end it "pull manifest - HTTP Header - with signatures" do manifest = '{"signatures": [{"signature":"...."}]}' manifest.stubs(:headers).returns({docker_content_digest: @digest}) @controller.stubs(:registry_authorize).returns(true) @controller.stubs(:find_readable_repository).returns(@docker_repo) Resources::Registry::Proxy.stubs(:get).returns(manifest) DockerMetaTag.stubs(:where).with(id: RepositoryDockerMetaTag. where(repository_id: @docker_repo.id). select(:docker_meta_tag_id), name: @tag.name).returns([@tag]) get :pull_manifest, params: { repository: @docker_repo.name, tag: @tag.name } assert_response 200 assert_equal(manifest, response.body) assert_includes response.header['Content-Type'], 'application/vnd.docker.distribution.manifest.v1+prettyjws' assert_equal @digest, response.header['Docker-Content-Digest'] end it "pull manifest no login - success" do manifest = '{"mediaType":"MEDIATYPE"}' manifest.stubs(:headers).returns({docker_content_digest: @digest}) @controller.stubs(:registry_authorize).returns(true) @controller.stubs(:find_readable_repository).returns(@docker_repo) Resources::Registry::Proxy.stubs(:get).returns(manifest) DockerMetaTag.stubs(:where).with(id: RepositoryDockerMetaTag. where(repository_id: @docker_repo.id). select(:docker_meta_tag_id), name: @tag.name).returns([@tag]) get :pull_manifest, params: { repository: @docker_repo.name, tag: @tag.name } assert_response 200 assert_equal(manifest, response.body) assert response.header['Content-Type'] =~ /MEDIATYPE/ assert_equal @digest, response.header['Docker-Content-Digest'] end it "pull manifest repo not found" do @controller.stubs(:registry_authorize).returns(true) @controller.stubs(:find_readable_repository).returns(nil) get :pull_manifest, params: { repository: "doesnotexist", tag: "latest" } assert_response 404 response_body = JSON.parse(response.body) assert response_body['errors'].length >= 1 response_body['errors'].first.assert_valid_keys('code', 'message', 'details') end it "pull manifest repo tag not found" do manifest = '{"mediaType":"MEDIATYPE"}' @controller.stubs(:registry_authorize).returns(true) @controller.stubs(:find_readable_repository).returns(@docker_repo) Resources::Registry::Proxy.stubs(:get).returns(manifest) get :pull_manifest, params: { repository: @docker_repo.name, tag: "doesnotexist" } assert_response 404 response_body = JSON.parse(response.body) assert response_body['errors'].length >= 1 response_body['errors'].first.assert_valid_keys('code', 'message', 'details') end end describe "docker push" do it "push manifest - error" do @controller.stubs(:authorize_repository_write).returns(true) put :push_manifest, params: { repository: 'repository', tag: 'tag' } assert_response 500 body = JSON.parse(response.body) assert_equal "Unsupported schema ", body['error']['message'] end it "push manifest - manifest.json exists" do File.open("#{Rails.root}/tmp/manifest.json", 'wb', 0600) do |file| file.write "empty manifest" end @controller.stubs(:authorize_repository_write).returns(true) put :push_manifest, params: { repository: 'repository', tag: 'tag' } assert_response 422 body = JSON.parse(response.body) assert_equal "Upload already in progress", body['error']['message'] end it "push manifest - success" do @repository = katello_repositories(:busybox) mock_pulp_server([ { name: :create_upload_request, result: { 'upload_id' => 123 }, count: 2 }, { name: :delete_upload_request, result: true, count: 2 }, { name: :upload_bits, result: true, count: 1 } ]) @controller.expects(:sync_task) .times(2) .returns(stub('task', :output => {'upload_results' => [{ 'digest' => 'sha256:1234' }]}), true) .with do |action_class, repository, uploads, params| assert_equal ::Actions::Katello::Repository::ImportUpload, action_class assert_equal @repository, repository assert_equal [123], uploads.pluck(:id) assert params[:generate_metadata] assert params[:sync_capsule] end manifest = { schemaVersion: 1 } @controller.stubs(:authorize).returns(true) @controller.stubs(:find_readable_repository).returns(@repository) @controller.stubs(:find_writable_repository).returns(@repository) put :push_manifest, params: { repository: 'repository', tag: 'tag' }, body: manifest.to_json assert_response 200 end it "push manifest - disabled with false" do SETTINGS[:katello][:container_image_registry] = {crane_url: 'https://localhost:5000', crane_ca_cert_file: '/etc/pki/katello/certs/katello-default-ca.crt', allow_push: false} put :push_manifest, params: { repository: 'repository', tag: 'tag' } assert_response 404 body = JSON.parse(response.body) assert_equal "Registry push not supported", body['error']['message'] end it "push manifest - disabled by omission" do SETTINGS[:katello][:container_image_registry] = {crane_url: 'https://localhost:5000', crane_ca_cert_file: '/etc/pki/katello/certs/katello-default-ca.crt'} put :push_manifest, params: { repository: 'repository', tag: 'tag' } assert_response 404 body = JSON.parse(response.body) assert_equal "Registry push not supported", body['error']['message'] end end def mock_pulp_server(content_hash) content = mock content_hash.each do |method| content.stubs(method[:name]).times(method[:count]).returns(method[:result]) end @controller.stubs(:pulp_content).returns(content) end end #rubocop:enable Metrics/BlockLength end
snagoor/katello
test/controllers/api/registry/registry_proxies_controller_test.rb
Ruby
gpl-2.0
24,665
/**** MarketPress Checkout JS *********/ jQuery(document).ready(function($) { //coupon codes $('#coupon-link').click(function() { $('#coupon-link').hide(); $('#coupon-code').show(); $('#coupon_code').focus(); return false; }); //payment method choice $('input.mp_choose_gateway').change(function() { var gid = $('input.mp_choose_gateway:checked').val(); $('div.mp_gateway_form').hide(); $('div#' + gid).show(); }); //province field choice $('#mp_country').change(function() { $("#mp_province_field").html('<img src="'+MP_Ajax.imgUrl+'" alt="Loading..." />'); var country = $(this).val(); $.post(MP_Ajax.ajaxUrl, {action: 'mp-province-field', country: country}, function(data) { $("#mp_province_field").html(data); //remap listener $('#mp_state').change(function() { if ($('#mp_city').val() && $('#mp_state').val() && $('#mp_zip').val()) mp_refresh_shipping(); }); }); }); //shipping field choice $('#mp-shipping-select').change(function() {mp_refresh_shipping();}); //refresh on blur if necessary 3 fields are set $('#mp_shipping_form .mp_shipping_field').change(function() { if ($('#mp_city').val() && $('#mp_state').val() && $('#mp_zip').val()) mp_refresh_shipping(); }); function mp_refresh_shipping() { $("#mp-shipping-select-holder").html('<img src="'+MP_Ajax.imgUrl+'" alt="Loading..." />'); var serializedForm = $('form#mp_shipping_form').serialize(); $.post(MP_Ajax.ajaxUrl, serializedForm, function(data) { $("#mp-shipping-select-holder").html(data); }); } });
RomainGoncalves/Vmall
wp-content/plugins/marketpress/marketpress-includes/js/store.js
JavaScript
gpl-2.0
1,665
/* Adept MobileRobots Robotics Interface for Applications (ARIA) Copyright (C) 2004-2005 ActivMedia Robotics LLC Copyright (C) 2006-2010 MobileRobots Inc. Copyright (C) 2011-2014 Adept Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960 */ #include "ArExport.h" #include "ariaOSDef.h" #include "ArActionKeydrive.h" #include "ArRobot.h" #include "ariaInternal.h" #include "ArKeyHandler.h" AREXPORT ArActionKeydrive::ArActionKeydrive(const char *name, double transVelMax, double turnAmountMax, double velIncrement, double turnIncrement) : ArAction(name, "This action reads the keyboard arrow keys and sets the translational and rotational velocities based on this."), myUpCB(this, &ArActionKeydrive::up), myDownCB(this, &ArActionKeydrive::down), myLeftCB(this, &ArActionKeydrive::left), myRightCB(this, &ArActionKeydrive::right), mySpaceCB(this, &ArActionKeydrive::space) { setNextArgument(ArArg("trans vel max", &myTransVelMax, "The maximum speed to go (mm/sec)")); myTransVelMax = transVelMax; setNextArgument(ArArg("turn amount max", &myTurnAmountMax, "The maximum amount to turn (deg/cycle)")); myTurnAmountMax = turnAmountMax; setNextArgument(ArArg("vel increment per keypress", &myVelIncrement, "The amount to increment velocity by per keypress (mm/sec)")); myVelIncrement = velIncrement; setNextArgument(ArArg("turn increment per keypress", &myVelIncrement, "The amount to turn by per keypress (deg)")); myTurnIncrement = turnIncrement; myDesiredSpeed = 0; myDeltaVel = 0; myTurnAmount = 0; mySpeedReset = true; } AREXPORT ArActionKeydrive::~ArActionKeydrive() { } AREXPORT void ArActionKeydrive::setRobot(ArRobot *robot) { ArKeyHandler *keyHandler; myRobot = robot; if (robot == NULL) return; // see if there is already a keyhandler, if not make one for ourselves if ((keyHandler = Aria::getKeyHandler()) == NULL) { keyHandler = new ArKeyHandler; Aria::setKeyHandler(keyHandler); myRobot->attachKeyHandler(keyHandler); } takeKeys(); } AREXPORT void ArActionKeydrive::takeKeys(void) { ArKeyHandler *keyHandler; if ((keyHandler = Aria::getKeyHandler()) == NULL) { ArLog::log(ArLog::Terse, "ArActionKeydrive::takeKeys: There is no key handler, keydrive will not work."); } // now that we have one, add our keys as callbacks, print out big // warning messages if they fail if (!keyHandler->addKeyHandler(ArKeyHandler::UP, &myUpCB)) ArLog::log(ArLog::Terse, "The key handler already has a key for up, keydrive will not work correctly."); if (!keyHandler->addKeyHandler(ArKeyHandler::DOWN, &myDownCB)) ArLog::log(ArLog::Terse, "The key handler already has a key for down, keydrive will not work correctly."); if (!keyHandler->addKeyHandler(ArKeyHandler::LEFT, &myLeftCB)) ArLog::log(ArLog::Terse, "The key handler already has a key for left, keydrive will not work correctly."); if (!keyHandler->addKeyHandler(ArKeyHandler::RIGHT, &myRightCB)) ArLog::log(ArLog::Terse, "The key handler already has a key for right, keydrive will not work correctly."); if (!keyHandler->addKeyHandler(ArKeyHandler::SPACE, &mySpaceCB)) ArLog::log(ArLog::Terse, "The key handler already has a key for space, keydrive will not work correctly."); } AREXPORT void ArActionKeydrive::giveUpKeys(void) { ArKeyHandler *keyHandler; if ((keyHandler = Aria::getKeyHandler()) == NULL) { ArLog::log(ArLog::Terse, "ArActionKeydrive::giveUpKeys: There is no key handler, something is probably horribly wrong ."); } // now that we have one, add our keys as callbacks, print out big // warning messages if they fail if (!keyHandler->remKeyHandler(&myUpCB)) ArLog::log(ArLog::Terse, "ArActionKeydrive: The key handler already didn't have a key for up, something is wrong."); if (!keyHandler->remKeyHandler(&myDownCB)) ArLog::log(ArLog::Terse, "ArActionKeydrive: The key handler already didn't have a key for down, something is wrong."); if (!keyHandler->remKeyHandler(&myLeftCB)) ArLog::log(ArLog::Terse, "ArActionKeydrive: The key handler already didn't have a key for left, something is wrong."); if (!keyHandler->remKeyHandler(&myRightCB)) ArLog::log(ArLog::Terse, "ArActionKeydrive: The key handler already didn't have a key for right, something is wrong."); if (!keyHandler->remKeyHandler(&mySpaceCB)) ArLog::log(ArLog::Terse, "ArActionKeydrive: The key handler didn't have a key for space, something is wrong."); } AREXPORT void ArActionKeydrive::setSpeeds(double transVelMax, double turnAmountMax) { myTransVelMax = transVelMax; myTurnAmountMax = turnAmountMax; } AREXPORT void ArActionKeydrive::setIncrements(double velIncrement, double turnIncrement) { myVelIncrement = velIncrement; myTurnIncrement = turnIncrement; } AREXPORT void ArActionKeydrive::up(void) { myDeltaVel += myVelIncrement; } AREXPORT void ArActionKeydrive::down(void) { myDeltaVel -= myVelIncrement; } AREXPORT void ArActionKeydrive::left(void) { myTurnAmount += myTurnIncrement; if (myTurnAmount > myTurnAmountMax) myTurnAmount = myTurnAmountMax; } AREXPORT void ArActionKeydrive::right(void) { myTurnAmount -= myTurnIncrement; if (myTurnAmount < -myTurnAmountMax) myTurnAmount = -myTurnAmountMax; } AREXPORT void ArActionKeydrive::space(void) { mySpeedReset = false; myDesiredSpeed = 0; myTurnAmount = 0; } AREXPORT void ArActionKeydrive::activate(void) { if (!myIsActive) takeKeys(); myIsActive = true; } AREXPORT void ArActionKeydrive::deactivate(void) { if (myIsActive) giveUpKeys(); myIsActive = false; myDesiredSpeed = 0; myTurnAmount = 0; } AREXPORT ArActionDesired *ArActionKeydrive::fire(ArActionDesired currentDesired) { myDesired.reset(); // if we don't have any strength left if (fabs(currentDesired.getVelStrength() - 1.0) < .0000000000001) { mySpeedReset = true; } // if our speed was reset, set our desired to how fast we're going now if (mySpeedReset && myDesiredSpeed > 0 && myDesiredSpeed > myRobot->getVel()) myDesiredSpeed = myRobot->getVel(); if (mySpeedReset && myDesiredSpeed < 0 && myDesiredSpeed < myRobot->getVel()) myDesiredSpeed = myRobot->getVel(); mySpeedReset = false; if (currentDesired.getMaxVelStrength() && myDesiredSpeed > currentDesired.getMaxVel()) myDesiredSpeed = currentDesired.getMaxVel(); if (currentDesired.getMaxNegVelStrength() && myDesiredSpeed < currentDesired.getMaxNegVel()) myDesiredSpeed = currentDesired.getMaxNegVel(); myDesiredSpeed += myDeltaVel; if (myDesiredSpeed > myTransVelMax) myDesiredSpeed = myTransVelMax; if (myDesiredSpeed < -myTransVelMax) myDesiredSpeed = -myTransVelMax; myDesired.setVel(myDesiredSpeed); myDeltaVel = 0; myDesired.setDeltaHeading(myTurnAmount); myTurnAmount = 0; return &myDesired; }
sfe1012/Robot
src/ArActionKeydrive.cpp
C++
gpl-2.0
7,915
/* * TimeLineWidget.cpp - class timeLine, representing a time-line with position marker * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program 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 * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #include <QDomElement> #include <QTimer> #include <QApplication> #include <QLayout> #include <QMouseEvent> #include <QPainter> #include <QToolBar> #include "TimeLineWidget.h" #include "embed.h" #include "NStateButton.h" #include "GuiApplication.h" #include "TextFloat.h" #include "SongEditor.h" QPixmap * TimeLineWidget::s_posMarkerPixmap = nullptr; TimeLineWidget::TimeLineWidget( const int xoff, const int yoff, const float ppb, Song::PlayPos & pos, const TimePos & begin, Song::PlayModes mode, QWidget * parent ) : QWidget( parent ), m_inactiveLoopColor( 52, 63, 53, 64 ), m_inactiveLoopBrush( QColor( 255, 255, 255, 32 ) ), m_inactiveLoopInnerColor( 255, 255, 255, 32 ), m_activeLoopColor( 52, 63, 53, 255 ), m_activeLoopBrush( QColor( 55, 141, 89 ) ), m_activeLoopInnerColor( 74, 155, 100, 255 ), m_loopRectangleVerticalPadding( 1 ), m_barLineColor( 192, 192, 192 ), m_barNumberColor( m_barLineColor.darker( 120 ) ), m_autoScroll( AutoScrollEnabled ), m_loopPoints( LoopPointsDisabled ), m_behaviourAtStop( BackToZero ), m_changedPosition( true ), m_xOffset( xoff ), m_posMarkerX( 0 ), m_ppb( ppb ), m_pos( pos ), m_begin( begin ), m_mode( mode ), m_savedPos( -1 ), m_hint( nullptr ), m_action( NoAction ), m_moveXOff( 0 ) { m_loopPos[0] = 0; m_loopPos[1] = DefaultTicksPerBar; if( s_posMarkerPixmap == nullptr ) { s_posMarkerPixmap = new QPixmap( embed::getIconPixmap( "playpos_marker" ) ); } setAttribute( Qt::WA_OpaquePaintEvent, true ); move( 0, yoff ); m_xOffset -= s_posMarkerPixmap->width() / 2; setMouseTracking(true); m_pos.m_timeLine = this; QTimer * updateTimer = new QTimer( this ); connect( updateTimer, SIGNAL( timeout() ), this, SLOT( updatePosition() ) ); updateTimer->start( 1000 / 60 ); // 60 fps connect( Engine::getSong(), SIGNAL( timeSignatureChanged( int,int ) ), this, SLOT( update() ) ); } TimeLineWidget::~TimeLineWidget() { if( getGUI()->songEditor() ) { m_pos.m_timeLine = nullptr; } delete m_hint; } void TimeLineWidget::setXOffset(const int x) { m_xOffset = x; if (s_posMarkerPixmap != nullptr) { m_xOffset -= s_posMarkerPixmap->width() / 2; } } void TimeLineWidget::addToolButtons( QToolBar * _tool_bar ) { NStateButton * autoScroll = new NStateButton( _tool_bar ); autoScroll->setGeneralToolTip( tr( "Auto scrolling" ) ); autoScroll->addState( embed::getIconPixmap( "autoscroll_on" ) ); autoScroll->addState( embed::getIconPixmap( "autoscroll_off" ) ); connect( autoScroll, SIGNAL( changedState( int ) ), this, SLOT( toggleAutoScroll( int ) ) ); NStateButton * loopPoints = new NStateButton( _tool_bar ); loopPoints->setGeneralToolTip( tr( "Loop points" ) ); loopPoints->addState( embed::getIconPixmap( "loop_points_off" ) ); loopPoints->addState( embed::getIconPixmap( "loop_points_on" ) ); connect( loopPoints, SIGNAL( changedState( int ) ), this, SLOT( toggleLoopPoints( int ) ) ); connect( this, SIGNAL( loopPointStateLoaded( int ) ), loopPoints, SLOT( changeState( int ) ) ); NStateButton * behaviourAtStop = new NStateButton( _tool_bar ); behaviourAtStop->addState( embed::getIconPixmap( "back_to_zero" ), tr( "After stopping go back to beginning" ) ); behaviourAtStop->addState( embed::getIconPixmap( "back_to_start" ), tr( "After stopping go back to " "position at which playing was " "started" ) ); behaviourAtStop->addState( embed::getIconPixmap( "keep_stop_position" ), tr( "After stopping keep position" ) ); connect( behaviourAtStop, SIGNAL( changedState( int ) ), this, SLOT( toggleBehaviourAtStop( int ) ) ); connect( this, SIGNAL( loadBehaviourAtStop( int ) ), behaviourAtStop, SLOT( changeState( int ) ) ); behaviourAtStop->changeState( BackToStart ); _tool_bar->addWidget( autoScroll ); _tool_bar->addWidget( loopPoints ); _tool_bar->addWidget( behaviourAtStop ); } void TimeLineWidget::saveSettings( QDomDocument & _doc, QDomElement & _this ) { _this.setAttribute( "lp0pos", (int) loopBegin() ); _this.setAttribute( "lp1pos", (int) loopEnd() ); _this.setAttribute( "lpstate", m_loopPoints ); _this.setAttribute( "stopbehaviour", m_behaviourAtStop ); } void TimeLineWidget::loadSettings( const QDomElement & _this ) { m_loopPos[0] = _this.attribute( "lp0pos" ).toInt(); m_loopPos[1] = _this.attribute( "lp1pos" ).toInt(); m_loopPoints = static_cast<LoopPointStates>( _this.attribute( "lpstate" ).toInt() ); update(); emit loopPointStateLoaded( m_loopPoints ); if( _this.hasAttribute( "stopbehaviour" ) ) { emit loadBehaviourAtStop( _this.attribute( "stopbehaviour" ).toInt() ); } } void TimeLineWidget::updatePosition( const TimePos & ) { const int new_x = markerX( m_pos ); if( new_x != m_posMarkerX ) { m_posMarkerX = new_x; m_changedPosition = true; emit positionChanged( m_pos ); update(); } } void TimeLineWidget::toggleAutoScroll( int _n ) { m_autoScroll = static_cast<AutoScrollStates>( _n ); } void TimeLineWidget::toggleLoopPoints( int _n ) { m_loopPoints = static_cast<LoopPointStates>( _n ); update(); } void TimeLineWidget::toggleBehaviourAtStop( int _n ) { m_behaviourAtStop = static_cast<BehaviourAtStopStates>( _n ); } void TimeLineWidget::paintEvent( QPaintEvent * ) { QPainter p( this ); // Draw background p.fillRect( 0, 0, width(), height(), p.background() ); // Clip so that we only draw everything starting from the offset const int leftMargin = m_xOffset + s_posMarkerPixmap->width() / 2; p.setClipRect(leftMargin, 0, width() - leftMargin, height() ); // Draw the loop rectangle int const & loopRectMargin = getLoopRectangleVerticalPadding(); int const loopRectHeight = this->height() - 2 * loopRectMargin; int const loopStart = markerX( loopBegin() ) + 8; int const loopEndR = markerX( loopEnd() ) + 9; int const loopRectWidth = loopEndR - loopStart; bool const loopPointsActive = loopPointsEnabled(); // Draw the main rectangle (inner fill only) QRect outerRectangle( loopStart, loopRectMargin, loopRectWidth - 1, loopRectHeight - 1 ); p.fillRect( outerRectangle, loopPointsActive ? getActiveLoopBrush() : getInactiveLoopBrush()); // Draw the bar lines and numbers // Activate hinting on the font QFont font = p.font(); font.setHintingPreference( QFont::PreferFullHinting ); p.setFont(font); int const fontAscent = p.fontMetrics().ascent(); int const fontHeight = p.fontMetrics().height(); QColor const & barLineColor = getBarLineColor(); QColor const & barNumberColor = getBarNumberColor(); bar_t barNumber = m_begin.getBar(); int const x = m_xOffset + s_posMarkerPixmap->width() / 2 - ( ( static_cast<int>( m_begin * m_ppb ) / TimePos::ticksPerBar() ) % static_cast<int>( m_ppb ) ); for( int i = 0; x + i * m_ppb < width(); ++i ) { ++barNumber; if( ( barNumber - 1 ) % qMax( 1, qRound( 1.0f / 3.0f * TimePos::ticksPerBar() / m_ppb ) ) == 0 ) { const int cx = x + qRound( i * m_ppb ); p.setPen( barLineColor ); p.drawLine( cx, 5, cx, height() - 6 ); const QString s = QString::number( barNumber ); p.setPen( barNumberColor ); p.drawText( cx + 5, ((height() - fontHeight) / 2) + fontAscent, s ); } } // Draw the main rectangle (outer border) p.setPen( loopPointsActive ? getActiveLoopColor() : getInactiveLoopColor() ); p.setBrush( Qt::NoBrush ); p.drawRect( outerRectangle ); // Draw the inner border outline (no fill) QRect innerRectangle = outerRectangle.adjusted( 1, 1, -1, -1 ); p.setPen( loopPointsActive ? getActiveLoopInnerColor() : getInactiveLoopInnerColor() ); p.setBrush( Qt::NoBrush ); p.drawRect( innerRectangle ); // Only draw the position marker if the position line is in view if (m_posMarkerX >= m_xOffset && m_posMarkerX < width() - s_posMarkerPixmap->width() / 2) { // Let the position marker extrude to the left p.setClipping(false); p.setOpacity(0.6); p.drawPixmap(m_posMarkerX, height() - s_posMarkerPixmap->height(), *s_posMarkerPixmap); } } void TimeLineWidget::mousePressEvent( QMouseEvent* event ) { if( event->x() < m_xOffset ) { return; } if( event->button() == Qt::LeftButton && !(event->modifiers() & Qt::ShiftModifier) ) { m_action = MovePositionMarker; if( event->x() - m_xOffset < s_posMarkerPixmap->width() ) { m_moveXOff = event->x() - m_xOffset; } else { m_moveXOff = s_posMarkerPixmap->width() / 2; } } else if( event->button() == Qt::LeftButton && (event->modifiers() & Qt::ShiftModifier) ) { m_action = SelectSongTCO; m_initalXSelect = event->x(); } else if( event->button() == Qt::RightButton ) { m_moveXOff = s_posMarkerPixmap->width() / 2; const TimePos t = m_begin + static_cast<int>( qMax( event->x() - m_xOffset - m_moveXOff, 0 ) * TimePos::ticksPerBar() / m_ppb ); const TimePos loopMid = ( m_loopPos[0] + m_loopPos[1] ) / 2; if( t < loopMid ) { m_action = MoveLoopBegin; } else if( t > loopMid ) { m_action = MoveLoopEnd; } if( m_loopPos[0] > m_loopPos[1] ) { qSwap( m_loopPos[0], m_loopPos[1] ); } m_loopPos[( m_action == MoveLoopBegin ) ? 0 : 1] = t; } if( m_action == MoveLoopBegin || m_action == MoveLoopEnd ) { delete m_hint; m_hint = TextFloat::displayMessage( tr( "Hint" ), tr( "Press <%1> to disable magnetic loop points." ).arg(UI_CTRL_KEY), embed::getIconPixmap( "hint" ), 0 ); } mouseMoveEvent( event ); } void TimeLineWidget::mouseMoveEvent( QMouseEvent* event ) { parentWidget()->update(); // essential for widgets that this timeline had taken their mouse move event from. const TimePos t = m_begin + static_cast<int>( qMax( event->x() - m_xOffset - m_moveXOff, 0 ) * TimePos::ticksPerBar() / m_ppb ); switch( m_action ) { case MovePositionMarker: m_pos.setTicks(t.getTicks()); Engine::getSong()->setToTime(t, m_mode); if (!( Engine::getSong()->isPlaying())) { //Song::Mode_None is used when nothing is being played. Engine::getSong()->setToTime(t, Song::Mode_None); } m_pos.setCurrentFrame( 0 ); m_pos.setJumped( true ); updatePosition(); positionMarkerMoved(); break; case MoveLoopBegin: case MoveLoopEnd: { const int i = m_action - MoveLoopBegin; // i == 0 || i == 1 if( event->modifiers() & Qt::ControlModifier ) { // no ctrl-press-hint when having ctrl pressed delete m_hint; m_hint = nullptr; m_loopPos[i] = t; } else { m_loopPos[i] = t.quantize(1.0); } // Catch begin == end if( m_loopPos[0] == m_loopPos[1] ) { // Note, swap 1 and 0 below and the behavior "skips" the other // marking instead of pushing it. if( m_action == MoveLoopBegin ) { m_loopPos[0] -= TimePos::ticksPerBar(); } else { m_loopPos[1] += TimePos::ticksPerBar(); } } update(); break; } case SelectSongTCO: emit regionSelectedFromPixels( m_initalXSelect , event->x() ); break; default: break; } } void TimeLineWidget::mouseReleaseEvent( QMouseEvent* event ) { delete m_hint; m_hint = nullptr; if ( m_action == SelectSongTCO ) { emit selectionFinished(); } m_action = NoAction; }
zonkmachine/lmms
src/gui/TimeLineWidget.cpp
C++
gpl-2.0
12,090
// Copyright 2010 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include <cassert> #include <cmath> #include <cstring> #include "Common/ChunkFile.h" #include "Common/CommonTypes.h" #include "Common/MathUtil.h" #include "Common/MsgHandler.h" #include "Core/ConfigManager.h" #include "Core/Core.h" #include "Core/HW/WiimoteEmu/Attachment/Classic.h" #include "Core/HW/WiimoteEmu/Attachment/Drums.h" #include "Core/HW/WiimoteEmu/Attachment/Guitar.h" #include "Core/HW/WiimoteEmu/Attachment/Nunchuk.h" #include "Core/HW/WiimoteEmu/Attachment/Turntable.h" #include "Core/HW/WiimoteEmu/MatrixMath.h" #include "Core/HW/WiimoteEmu/WiimoteEmu.h" #include "Core/HW/WiimoteEmu/WiimoteHid.h" #include "Core/HW/WiimoteReal/WiimoteReal.h" #include "Core/Host.h" #include "Core/Movie.h" #include "Core/NetPlayClient.h" namespace { // :) auto const TAU = 6.28318530717958647692; auto const PI = TAU / 2.0; } namespace WiimoteEmu { static const u8 eeprom_data_0[] = { // IR, maybe more // assuming last 2 bytes are checksum 0xA1, 0xAA, 0x8B, 0x99, 0xAE, 0x9E, 0x78, 0x30, 0xA7, /*0x74, 0xD3,*/ 0x00, 0x00, // messing up the checksum on purpose 0xA1, 0xAA, 0x8B, 0x99, 0xAE, 0x9E, 0x78, 0x30, 0xA7, /*0x74, 0xD3,*/ 0x00, 0x00, // Accelerometer // Important: checksum is required for tilt games ACCEL_ZERO_G, ACCEL_ZERO_G, ACCEL_ZERO_G, 0, ACCEL_ONE_G, ACCEL_ONE_G, ACCEL_ONE_G, 0, 0, 0xA3, ACCEL_ZERO_G, ACCEL_ZERO_G, ACCEL_ZERO_G, 0, ACCEL_ONE_G, ACCEL_ONE_G, ACCEL_ONE_G, 0, 0, 0xA3, }; static const u8 motion_plus_id[] = {0x00, 0x00, 0xA6, 0x20, 0x00, 0x05}; static const u8 eeprom_data_16D0[] = {0x00, 0x00, 0x00, 0xFF, 0x11, 0xEE, 0x00, 0x00, 0x33, 0xCC, 0x44, 0xBB, 0x00, 0x00, 0x66, 0x99, 0x77, 0x88, 0x00, 0x00, 0x2B, 0x01, 0xE8, 0x13}; static const ReportFeatures reporting_mode_features[] = { // 0x30: Core Buttons {2, 0, 0, 0, 4}, // 0x31: Core Buttons and Accelerometer {2, 4, 0, 0, 7}, // 0x32: Core Buttons with 8 Extension bytes {2, 0, 0, 4, 12}, // 0x33: Core Buttons and Accelerometer with 12 IR bytes {2, 4, 7, 0, 19}, // 0x34: Core Buttons with 19 Extension bytes {2, 0, 0, 4, 23}, // 0x35: Core Buttons and Accelerometer with 16 Extension Bytes {2, 4, 0, 7, 23}, // 0x36: Core Buttons with 10 IR bytes and 9 Extension Bytes {2, 0, 4, 14, 23}, // 0x37: Core Buttons and Accelerometer with 10 IR bytes and 6 Extension Bytes {2, 4, 7, 17, 23}, // UNSUPPORTED: // 0x3d: 21 Extension Bytes {0, 0, 0, 2, 23}, // 0x3e / 0x3f: Interleaved Core Buttons and Accelerometer with 36 IR bytes {0, 0, 0, 0, 23}, }; void EmulateShake(AccelData* const accel, ControllerEmu::Buttons* const buttons_group, u8* const shake_step) { // frame count of one up/down shake // < 9 no shake detection in "Wario Land: Shake It" auto const shake_step_max = 15; // peak G-force auto const shake_intensity = 3.0; // shake is a bitfield of X,Y,Z shake button states static const unsigned int btns[] = {0x01, 0x02, 0x04}; unsigned int shake = 0; buttons_group->GetState(&shake, btns); for (int i = 0; i != 3; ++i) { if (shake & (1 << i)) { (&(accel->x))[i] = std::sin(TAU * shake_step[i] / shake_step_max) * shake_intensity; shake_step[i] = (shake_step[i] + 1) % shake_step_max; } else shake_step[i] = 0; } } void EmulateTilt(AccelData* const accel, ControllerEmu::Tilt* const tilt_group, const bool sideways, const bool upright) { ControlState roll, pitch; // 180 degrees tilt_group->GetState(&roll, &pitch); roll *= PI; pitch *= PI; unsigned int ud = 0, lr = 0, fb = 0; // some notes that no one will understand but me :p // left, forward, up // lr/ left == negative for all orientations // ud/ up == negative for upright longways // fb/ forward == positive for (sideways flat) // determine which axis is which direction ud = upright ? (sideways ? 0 : 1) : 2; lr = sideways; fb = upright ? 2 : (sideways ? 0 : 1); int sgn[3] = {-1, 1, 1}; // sign fix if (sideways && !upright) sgn[fb] *= -1; if (!sideways && upright) sgn[ud] *= -1; (&accel->x)[ud] = (sin((PI / 2) - std::max(fabs(roll), fabs(pitch)))) * sgn[ud]; (&accel->x)[lr] = -sin(roll) * sgn[lr]; (&accel->x)[fb] = sin(pitch) * sgn[fb]; } #define SWING_INTENSITY 2.5 //-uncalibrated(aprox) 0x40-calibrated void EmulateSwing(AccelData* const accel, ControllerEmu::Force* const swing_group, const bool sideways, const bool upright) { ControlState swing[3]; swing_group->GetState(swing); s8 g_dir[3] = {-1, -1, -1}; u8 axis_map[3]; // determine which axis is which direction axis_map[0] = upright ? (sideways ? 0 : 1) : 2; // up/down axis_map[1] = sideways; // left|right axis_map[2] = upright ? 2 : (sideways ? 0 : 1); // forward/backward // some orientations have up as positive, some as negative // same with forward if (sideways && !upright) g_dir[axis_map[2]] *= -1; if (!sideways && upright) g_dir[axis_map[0]] *= -1; for (unsigned int i = 0; i < 3; ++i) (&accel->x)[axis_map[i]] += swing[i] * g_dir[i] * SWING_INTENSITY; } static const u16 button_bitmasks[] = { Wiimote::BUTTON_A, Wiimote::BUTTON_B, Wiimote::BUTTON_ONE, Wiimote::BUTTON_TWO, Wiimote::BUTTON_MINUS, Wiimote::BUTTON_PLUS, Wiimote::BUTTON_HOME}; static const u16 dpad_bitmasks[] = {Wiimote::PAD_UP, Wiimote::PAD_DOWN, Wiimote::PAD_LEFT, Wiimote::PAD_RIGHT}; static const u16 dpad_sideways_bitmasks[] = {Wiimote::PAD_RIGHT, Wiimote::PAD_LEFT, Wiimote::PAD_UP, Wiimote::PAD_DOWN}; static const char* const named_buttons[] = { "A", "B", "1", "2", "-", "+", "Home", }; void Wiimote::Reset() { m_reporting_mode = WM_REPORT_CORE; // i think these two are good m_reporting_channel = 0; m_reporting_auto = false; m_rumble_on = false; m_speaker_mute = false; m_motion_plus_present = false; m_motion_plus_active = false; // will make the first Update() call send a status request // the first call to RequestStatus() will then set up the status struct extension bit m_extension->active_extension = -1; // eeprom memset(m_eeprom, 0, sizeof(m_eeprom)); // calibration data memcpy(m_eeprom, eeprom_data_0, sizeof(eeprom_data_0)); // dunno what this is for, copied from old plugin memcpy(m_eeprom + 0x16D0, eeprom_data_16D0, sizeof(eeprom_data_16D0)); // set up the register memset(&m_reg_speaker, 0, sizeof(m_reg_speaker)); memset(&m_reg_ir, 0, sizeof(m_reg_ir)); memset(&m_reg_ext, 0, sizeof(m_reg_ext)); memset(&m_reg_motion_plus, 0, sizeof(m_reg_motion_plus)); memcpy(&m_reg_motion_plus.ext_identifier, motion_plus_id, sizeof(motion_plus_id)); // status memset(&m_status, 0, sizeof(m_status)); // Battery levels in voltage // 0x00 - 0x32: level 1 // 0x33 - 0x43: level 2 // 0x33 - 0x54: level 3 // 0x55 - 0xff: level 4 m_status.battery = (u8)(m_options->numeric_settings[1]->GetValue() * 100); memset(m_shake_step, 0, sizeof(m_shake_step)); // clear read request queue while (!m_read_requests.empty()) { delete[] m_read_requests.front().data; m_read_requests.pop(); } // Yamaha ADPCM state initialize m_adpcm_state.predictor = 0; m_adpcm_state.step = 127; } Wiimote::Wiimote(const unsigned int index) : m_index(index), ir_sin(0), ir_cos(1), m_last_connect_request_counter(0) { // ---- set up all the controls ---- // buttons groups.emplace_back(m_buttons = new Buttons("Buttons")); for (auto& named_button : named_buttons) m_buttons->controls.emplace_back(new ControlGroup::Input(named_button)); // ir groups.emplace_back(m_ir = new Cursor(_trans("IR"))); // swing groups.emplace_back(m_swing = new Force(_trans("Swing"))); // tilt groups.emplace_back(m_tilt = new Tilt(_trans("Tilt"))); // shake groups.emplace_back(m_shake = new Buttons(_trans("Shake"))); m_shake->controls.emplace_back(new ControlGroup::Input("X")); m_shake->controls.emplace_back(new ControlGroup::Input("Y")); m_shake->controls.emplace_back(new ControlGroup::Input("Z")); // extension groups.emplace_back(m_extension = new Extension(_trans("Extension"))); m_extension->attachments.emplace_back(new WiimoteEmu::None(m_reg_ext)); m_extension->attachments.emplace_back(new WiimoteEmu::Nunchuk(m_reg_ext)); m_extension->attachments.emplace_back(new WiimoteEmu::Classic(m_reg_ext)); m_extension->attachments.emplace_back(new WiimoteEmu::Guitar(m_reg_ext)); m_extension->attachments.emplace_back(new WiimoteEmu::Drums(m_reg_ext)); m_extension->attachments.emplace_back(new WiimoteEmu::Turntable(m_reg_ext)); m_extension->boolean_settings.emplace_back( std::make_unique<ControlGroup::BooleanSetting>(_trans("Motion Plus"), false)); // rumble groups.emplace_back(m_rumble = new ControlGroup(_trans("Rumble"))); m_rumble->controls.emplace_back(new ControlGroup::Output(_trans("Motor"))); // dpad groups.emplace_back(m_dpad = new Buttons("D-Pad")); for (auto& named_direction : named_directions) m_dpad->controls.emplace_back(new ControlGroup::Input(named_direction)); // options groups.emplace_back(m_options = new ControlGroup(_trans("Options"))); m_options->boolean_settings.emplace_back( std::make_unique<ControlGroup::BackgroundInputSetting>(_trans("Background Input"))); m_options->boolean_settings.emplace_back( std::make_unique<ControlGroup::BooleanSetting>(_trans("Sideways Wii Remote"), false)); m_options->boolean_settings.emplace_back( std::make_unique<ControlGroup::BooleanSetting>(_trans("Upright Wii Remote"), false)); m_options->boolean_settings.emplace_back(std::make_unique<ControlGroup::BooleanSetting>( _trans("Iterative Input"), false, ControlGroup::SettingType::VIRTUAL)); m_options->numeric_settings.emplace_back( std::make_unique<ControlGroup::NumericSetting>(_trans("Speaker Pan"), 0, -127, 127)); m_options->numeric_settings.emplace_back( std::make_unique<ControlGroup::NumericSetting>(_trans("Battery"), 95.0 / 100, 0, 255)); // hotkeys groups.emplace_back(m_hotkeys = new ModifySettingsButton(_trans("Hotkeys"))); // hotkeys to temporarily modify the Wii Remote orientation (sideways, upright) // this setting modifier is toggled m_hotkeys->AddInput(_trans("Sideways Toggle"), true); m_hotkeys->AddInput(_trans("Upright Toggle"), true); // this setting modifier is not toggled m_hotkeys->AddInput(_trans("Sideways Hold"), false); m_hotkeys->AddInput(_trans("Upright Hold"), false); // TODO: This value should probably be re-read if SYSCONF gets changed m_sensor_bar_on_top = SConfig::GetInstance().m_sensor_bar_position != 0; // --- reset eeprom/register/values to default --- Reset(); } std::string Wiimote::GetName() const { return std::string("Wiimote") + char('1' + m_index); } ControllerEmu::ControlGroup* Wiimote::GetWiimoteGroup(WiimoteGroup group) { switch (group) { case WiimoteGroup::Buttons: return m_buttons; case WiimoteGroup::DPad: return m_dpad; case WiimoteGroup::Shake: return m_shake; case WiimoteGroup::IR: return m_ir; case WiimoteGroup::Tilt: return m_tilt; case WiimoteGroup::Swing: return m_swing; case WiimoteGroup::Rumble: return m_rumble; case WiimoteGroup::Extension: return m_extension; case WiimoteGroup::Options: return m_options; case WiimoteGroup::Hotkeys: return m_hotkeys; default: assert(false); return nullptr; } } ControllerEmu::ControlGroup* Wiimote::GetNunchukGroup(NunchukGroup group) { return static_cast<Nunchuk*>(m_extension->attachments[EXT_NUNCHUK].get())->GetGroup(group); } ControllerEmu::ControlGroup* Wiimote::GetClassicGroup(ClassicGroup group) { return static_cast<Classic*>(m_extension->attachments[EXT_CLASSIC].get())->GetGroup(group); } ControllerEmu::ControlGroup* Wiimote::GetGuitarGroup(GuitarGroup group) { return static_cast<Guitar*>(m_extension->attachments[EXT_GUITAR].get())->GetGroup(group); } ControllerEmu::ControlGroup* Wiimote::GetDrumsGroup(DrumsGroup group) { return static_cast<Drums*>(m_extension->attachments[EXT_DRUMS].get())->GetGroup(group); } ControllerEmu::ControlGroup* Wiimote::GetTurntableGroup(TurntableGroup group) { return static_cast<Turntable*>(m_extension->attachments[EXT_TURNTABLE].get())->GetGroup(group); } bool Wiimote::Step() { // TODO: change this a bit m_motion_plus_present = m_extension->boolean_settings[0]->GetValue(); m_rumble->controls[0]->control_ref->State(m_rumble_on); // when a movie is active, this button status update is disabled (moved), because movies only // record data reports. if (!Core::g_want_determinism) { UpdateButtonsStatus(); } // check if there is a read data request if (!m_read_requests.empty()) { ReadRequest& rr = m_read_requests.front(); // send up to 16 bytes to the Wii SendReadDataReply(rr); // SendReadDataReply(rr.channel, rr); // if there is no more data, remove from queue if (0 == rr.size) { delete[] rr.data; m_read_requests.pop(); } // don't send any other reports return true; } // check if a status report needs to be sent // this happens on Wii Remote sync and when extensions are switched if (m_extension->active_extension != m_extension->switch_extension) { RequestStatus(); // WiiBrew: Following a connection or disconnection event on the Extension Port, // data reporting is disabled and the Data Reporting Mode must be reset before new data can // arrive. // after a game receives an unrequested status report, // it expects data reports to stop until it sets the reporting mode again m_reporting_auto = false; return true; } return false; } void Wiimote::UpdateButtonsStatus() { // update buttons in status struct m_status.buttons.hex = 0; const bool sideways_modifier_toggle = m_hotkeys->getSettingsModifier()[0]; const bool sideways_modifier_switch = m_hotkeys->getSettingsModifier()[2]; const bool is_sideways = m_options->boolean_settings[1]->GetValue() ^ sideways_modifier_toggle ^ sideways_modifier_switch; m_buttons->GetState(&m_status.buttons.hex, button_bitmasks); m_dpad->GetState(&m_status.buttons.hex, is_sideways ? dpad_sideways_bitmasks : dpad_bitmasks); } void Wiimote::GetButtonData(u8* const data) { // when a movie is active, the button update happens here instead of Wiimote::Step, to avoid // potential desync issues. if (Core::g_want_determinism) { UpdateButtonsStatus(); } ((wm_buttons*)data)->hex |= m_status.buttons.hex; } void Wiimote::GetAccelData(u8* const data, const ReportFeatures& rptf) { const bool sideways_modifier_toggle = m_hotkeys->getSettingsModifier()[0]; const bool upright_modifier_toggle = m_hotkeys->getSettingsModifier()[1]; const bool sideways_modifier_switch = m_hotkeys->getSettingsModifier()[2]; const bool upright_modifier_switch = m_hotkeys->getSettingsModifier()[3]; const bool is_sideways = m_options->boolean_settings[1]->GetValue() ^ sideways_modifier_toggle ^ sideways_modifier_switch; const bool is_upright = m_options->boolean_settings[2]->GetValue() ^ upright_modifier_toggle ^ upright_modifier_switch; EmulateTilt(&m_accel, m_tilt, is_sideways, is_upright); EmulateSwing(&m_accel, m_swing, is_sideways, is_upright); EmulateShake(&m_accel, m_shake, m_shake_step); wm_accel& accel = *(wm_accel*)(data + rptf.accel); wm_buttons& core = *(wm_buttons*)(data + rptf.core); // We now use 2 bits more precision, so multiply by 4 before converting to int s16 x = (s16)(4 * (m_accel.x * ACCEL_RANGE + ACCEL_ZERO_G)); s16 y = (s16)(4 * (m_accel.y * ACCEL_RANGE + ACCEL_ZERO_G)); s16 z = (s16)(4 * (m_accel.z * ACCEL_RANGE + ACCEL_ZERO_G)); x = MathUtil::Clamp<s16>(x, 0, 1024); y = MathUtil::Clamp<s16>(y, 0, 1024); z = MathUtil::Clamp<s16>(z, 0, 1024); accel.x = (x >> 2) & 0xFF; accel.y = (y >> 2) & 0xFF; accel.z = (z >> 2) & 0xFF; core.acc_x_lsb = x & 0x3; core.acc_y_lsb = (y >> 1) & 0x1; core.acc_z_lsb = (z >> 1) & 0x1; } inline void LowPassFilter(double& var, double newval, double period) { static const double CUTOFF_FREQUENCY = 5.0; double RC = 1.0 / CUTOFF_FREQUENCY; double alpha = period / (period + RC); var = newval * alpha + var * (1.0 - alpha); } void Wiimote::GetIRData(u8* const data, bool use_accel) { u16 x[4], y[4]; memset(x, 0xFF, sizeof(x)); ControlState xx = 10000, yy = 0, zz = 0; double nsin, ncos; if (use_accel) { double ax, az, len; ax = m_accel.x; az = m_accel.z; len = sqrt(ax * ax + az * az); if (len) { ax /= len; az /= len; // normalizing the vector nsin = ax; ncos = az; } else { nsin = 0; ncos = 1; } // PanicAlert("%d %d %d\nx:%f\nz:%f\nsin:%f\ncos:%f",accel->x,accel->y,accel->z,ax,az,sin,cos); // PanicAlert("%d %d %d\n%d %d %d\n%d %d // %d",accel->x,accel->y,accel->z,calib->zero_g.x,calib->zero_g.y,calib->zero_g.z, // calib->one_g.x,calib->one_g.y,calib->one_g.z); } else { nsin = 0; // m_tilt stuff here (can't figure it out yet....) ncos = 1; } LowPassFilter(ir_sin, nsin, 1.0 / 60); LowPassFilter(ir_cos, ncos, 1.0 / 60); m_ir->GetState(&xx, &yy, &zz, true); Vertex v[4]; static const int camWidth = 1024; static const int camHeight = 768; static const double bndup = -0.315447; static const double bnddown = 0.85; static const double bndleft = 0.443364; static const double bndright = -0.443364; static const double dist1 = 100.0 / camWidth; // this seems the optimal distance for zelda static const double dist2 = 1.2 * dist1; for (auto& vtx : v) { vtx.x = xx * (bndright - bndleft) / 2 + (bndleft + bndright) / 2; if (m_sensor_bar_on_top) vtx.y = yy * (bndup - bnddown) / 2 + (bndup + bnddown) / 2; else vtx.y = yy * (bndup - bnddown) / 2 - (bndup + bnddown) / 2; vtx.z = 0; } v[0].x -= (zz * 0.5 + 1) * dist1; v[1].x += (zz * 0.5 + 1) * dist1; v[2].x -= (zz * 0.5 + 1) * dist2; v[3].x += (zz * 0.5 + 1) * dist2; #define printmatrix(m) \ PanicAlert("%f %f %f %f\n%f %f %f %f\n%f %f %f %f\n%f %f %f %f\n", m[0][0], m[0][1], m[0][2], \ m[0][3], m[1][0], m[1][1], m[1][2], m[1][3], m[2][0], m[2][1], m[2][2], m[2][3], \ m[3][0], m[3][1], m[3][2], m[3][3]) Matrix rot, tot; static Matrix scale; MatrixScale(scale, 1, camWidth / camHeight, 1); // MatrixIdentity(scale); MatrixRotationByZ(rot, ir_sin, ir_cos); // MatrixIdentity(rot); MatrixMultiply(tot, scale, rot); for (int i = 0; i < 4; i++) { MatrixTransformVertex(tot, v[i]); if ((v[i].x < -1) || (v[i].x > 1) || (v[i].y < -1) || (v[i].y > 1)) continue; x[i] = (u16)lround((v[i].x + 1) / 2 * (camWidth - 1)); y[i] = (u16)lround((v[i].y + 1) / 2 * (camHeight - 1)); } // PanicAlert("%f %f\n%f %f\n%f %f\n%f %f\n%d %d\n%d %d\n%d %d\n%d %d", // v[0].x,v[0].y,v[1].x,v[1].y,v[2].x,v[2].y,v[3].x,v[3].y, // x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[38]); // Fill report with valid data when full handshake was done if (m_reg_ir.data[0x30]) // ir mode switch (m_reg_ir.mode) { // basic case 1: { memset(data, 0xFF, 10); wm_ir_basic* const irdata = (wm_ir_basic*)data; for (unsigned int i = 0; i < 2; ++i) { if (x[i * 2] < 1024 && y[i * 2] < 768) { irdata[i].x1 = static_cast<u8>(x[i * 2]); irdata[i].x1hi = x[i * 2] >> 8; irdata[i].y1 = static_cast<u8>(y[i * 2]); irdata[i].y1hi = y[i * 2] >> 8; } if (x[i * 2 + 1] < 1024 && y[i * 2 + 1] < 768) { irdata[i].x2 = static_cast<u8>(x[i * 2 + 1]); irdata[i].x2hi = x[i * 2 + 1] >> 8; irdata[i].y2 = static_cast<u8>(y[i * 2 + 1]); irdata[i].y2hi = y[i * 2 + 1] >> 8; } } } break; // extended case 3: { memset(data, 0xFF, 12); wm_ir_extended* const irdata = (wm_ir_extended*)data; for (unsigned int i = 0; i < 4; ++i) if (x[i] < 1024 && y[i] < 768) { irdata[i].x = static_cast<u8>(x[i]); irdata[i].xhi = x[i] >> 8; irdata[i].y = static_cast<u8>(y[i]); irdata[i].yhi = y[i] >> 8; irdata[i].size = 10; } } break; // full case 5: PanicAlert("Full IR report"); // UNSUPPORTED break; } } void Wiimote::GetExtData(u8* const data) { m_extension->GetState(data); // i dont think anything accesses the extension data like this, but ill support it. Indeed, // commercial games don't do this. // i think it should be unencrpyted in the register, encrypted when read. memcpy(m_reg_ext.controller_data, data, sizeof(wm_nc)); // TODO: Should it be nc specific? // motionplus pass-through modes if (m_motion_plus_active) { switch (m_reg_motion_plus.ext_identifier[0x4]) { // nunchuk pass-through mode // Bit 7 of byte 5 is moved to bit 6 of byte 5, overwriting it // Bit 0 of byte 4 is moved to bit 7 of byte 5 // Bit 3 of byte 5 is moved to bit 4 of byte 5, overwriting it // Bit 1 of byte 5 is moved to bit 3 of byte 5 // Bit 0 of byte 5 is moved to bit 2 of byte 5, overwriting it case 0x5: // data[5] & (1 << 7) // data[4] & (1 << 0) // data[5] & (1 << 3) // data[5] & (1 << 1) // data[5] & (1 << 0) break; // classic controller/musical instrument pass-through mode // Bit 0 of Byte 4 is overwritten // Bits 0 and 1 of Byte 5 are moved to bit 0 of Bytes 0 and 1, overwriting case 0x7: // data[4] & (1 << 0) // data[5] & (1 << 0) // data[5] & (1 << 1) break; // unknown pass-through mode default: break; } ((wm_motionplus_data*)data)->is_mp_data = 0; ((wm_motionplus_data*)data)->extension_connected = m_extension->active_extension; } if (0xAA == m_reg_ext.encryption) WiimoteEncrypt(&m_ext_key, data, 0x00, sizeof(wm_nc)); } void Wiimote::Update() { // no channel == not connected i guess if (0 == m_reporting_channel) return; // returns true if a report was sent { auto lock = ControllerEmu::GetStateLock(); if (Step()) return; } u8 data[MAX_PAYLOAD]; memset(data, 0, sizeof(data)); Movie::SetPolledDevice(); m_status.battery = (u8)(m_options->numeric_settings[1]->GetValue() * 100); const ReportFeatures& rptf = reporting_mode_features[m_reporting_mode - WM_REPORT_CORE]; s8 rptf_size = rptf.size; if (Movie::IsPlayingInput() && Movie::PlayWiimote(m_index, data, rptf, m_extension->active_extension, m_ext_key)) { if (rptf.core) m_status.buttons = *(wm_buttons*)(data + rptf.core); } else { data[0] = 0xA1; data[1] = m_reporting_mode; auto lock = ControllerEmu::GetStateLock(); // hotkey/settings modifier m_hotkeys->GetState(); // data is later accessed in UpdateButtonsStatus and GetAccelData // core buttons if (rptf.core) GetButtonData(data + rptf.core); // acceleration if (rptf.accel) GetAccelData(data, rptf); // IR if (rptf.ir) GetIRData(data + rptf.ir, (rptf.accel != 0)); // extension if (rptf.ext) GetExtData(data + rptf.ext); // hybrid Wii Remote stuff (for now, it's not supported while recording) if (WIIMOTE_SRC_HYBRID == g_wiimote_sources[m_index] && !Movie::IsRecordingInput()) { using namespace WiimoteReal; std::lock_guard<std::mutex> lk(g_wiimotes_mutex); if (g_wiimotes[m_index]) { const Report& rpt = g_wiimotes[m_index]->ProcessReadQueue(); if (!rpt.empty()) { const u8* real_data = rpt.data(); switch (real_data[1]) { // use data reports default: if (real_data[1] >= WM_REPORT_CORE) { const ReportFeatures& real_rptf = reporting_mode_features[real_data[1] - WM_REPORT_CORE]; // force same report type from real-Wiimote if (&real_rptf != &rptf) rptf_size = 0; // core // mix real-buttons with emu-buttons in the status struct, and in the report if (real_rptf.core && rptf.core) { m_status.buttons.hex |= ((wm_buttons*)(real_data + real_rptf.core))->hex; *(wm_buttons*)(data + rptf.core) = m_status.buttons; } // accel // use real-accel data always i guess if (real_rptf.accel && rptf.accel) memcpy(data + rptf.accel, real_data + real_rptf.accel, sizeof(wm_accel)); // ir // TODO // ext // use real-ext data if an emu-extention isn't chosen if (real_rptf.ext && rptf.ext && (0 == m_extension->switch_extension)) memcpy(data + rptf.ext, real_data + real_rptf.ext, sizeof(wm_nc)); // TODO: Why NC specific? } else if (WM_ACK_DATA != real_data[1] || m_extension->active_extension > 0) rptf_size = 0; else // use real-acks if an emu-extension isn't chosen rptf_size = -1; break; // use all status reports, after modification of the extension bit case WM_STATUS_REPORT: // if (m_extension->switch_extension) //((wm_status_report*)(real_data + 2))->extension = (m_extension->active_extension > 0); if (m_extension->active_extension) ((wm_status_report*)(real_data + 2))->extension = 1; rptf_size = -1; break; // use all read-data replies case WM_READ_DATA_REPLY: rptf_size = -1; break; } // copy over report from real-Wiimote if (-1 == rptf_size) { std::copy(rpt.begin(), rpt.end(), data); rptf_size = (s8)(rpt.size()); } } } } Movie::CallWiiInputManip(data, rptf, m_index, m_extension->active_extension, m_ext_key); } if (NetPlay::IsNetPlayRunning()) { NetPlay_GetWiimoteData(m_index, data, rptf.size, m_reporting_mode); if (rptf.core) m_status.buttons = *(wm_buttons*)(data + rptf.core); } Movie::CheckWiimoteStatus(m_index, data, rptf, m_extension->active_extension, m_ext_key); // don't send a data report if auto reporting is off if (false == m_reporting_auto && data[1] >= WM_REPORT_CORE) return; // send data report if (rptf_size) { Core::Callback_WiimoteInterruptChannel(m_index, m_reporting_channel, data, rptf_size); } } void Wiimote::ControlChannel(const u16 _channelID, const void* _pData, u32 _Size) { // Check for custom communication if (99 == _channelID) { // Wii Remote disconnected // reset eeprom/register/reporting mode Reset(); if (WIIMOTE_SRC_REAL & g_wiimote_sources[m_index]) WiimoteReal::ControlChannel(m_index, _channelID, _pData, _Size); return; } // this all good? m_reporting_channel = _channelID; const hid_packet* const hidp = (hid_packet*)_pData; DEBUG_LOG(WIIMOTE, "Emu ControlChannel (page: %i, type: 0x%02x, param: 0x%02x)", m_index, hidp->type, hidp->param); switch (hidp->type) { case HID_TYPE_HANDSHAKE: PanicAlert("HID_TYPE_HANDSHAKE - %s", (hidp->param == HID_PARAM_INPUT) ? "INPUT" : "OUPUT"); break; case HID_TYPE_SET_REPORT: if (HID_PARAM_INPUT == hidp->param) { PanicAlert("HID_TYPE_SET_REPORT - INPUT"); } else { // AyuanX: My experiment shows Control Channel is never used // shuffle2: but lwbt uses this, so we'll do what we must :) HidOutputReport((wm_report*)hidp->data); u8 handshake = HID_HANDSHAKE_SUCCESS; Core::Callback_WiimoteInterruptChannel(m_index, _channelID, &handshake, 1); } break; case HID_TYPE_DATA: PanicAlert("HID_TYPE_DATA - %s", (hidp->param == HID_PARAM_INPUT) ? "INPUT" : "OUTPUT"); break; default: PanicAlert("HidControlChannel: Unknown type %x and param %x", hidp->type, hidp->param); break; } } void Wiimote::InterruptChannel(const u16 _channelID, const void* _pData, u32 _Size) { // this all good? m_reporting_channel = _channelID; const hid_packet* const hidp = (hid_packet*)_pData; switch (hidp->type) { case HID_TYPE_DATA: switch (hidp->param) { case HID_PARAM_OUTPUT: { const wm_report* const sr = (wm_report*)hidp->data; if (WIIMOTE_SRC_REAL & g_wiimote_sources[m_index]) { switch (sr->wm) { // these two types are handled in RequestStatus() & ReadData() case WM_REQUEST_STATUS: case WM_READ_DATA: if (WIIMOTE_SRC_REAL == g_wiimote_sources[m_index]) WiimoteReal::InterruptChannel(m_index, _channelID, _pData, _Size); break; default: WiimoteReal::InterruptChannel(m_index, _channelID, _pData, _Size); break; } HidOutputReport(sr, m_extension->switch_extension > 0); } else HidOutputReport(sr); } break; default: PanicAlert("HidInput: HID_TYPE_DATA - param 0x%02x", hidp->param); break; } break; default: PanicAlert("HidInput: Unknown type 0x%02x and param 0x%02x", hidp->type, hidp->param); break; } } void Wiimote::ConnectOnInput() { if (m_last_connect_request_counter > 0) { --m_last_connect_request_counter; return; } u16 buttons = 0; auto lock = ControllerEmu::GetStateLock(); m_buttons->GetState(&buttons, button_bitmasks); m_dpad->GetState(&buttons, dpad_bitmasks); if (buttons != 0 || m_extension->IsButtonPressed()) { Host_ConnectWiimote(m_index, true); // arbitrary value so it doesn't try to send multiple requests before Dolphin can react // if Wii Remotes are polled at 200Hz then this results in one request being sent per 500ms m_last_connect_request_counter = 100; } } void Wiimote::LoadDefaults(const ControllerInterface& ciface) { ControllerEmu::LoadDefaults(ciface); // Buttons #if defined HAVE_X11 && HAVE_X11 m_buttons->SetControlExpression(0, "Click 1"); // A m_buttons->SetControlExpression(1, "Click 3"); // B #else m_buttons->SetControlExpression(0, "Click 0"); // A m_buttons->SetControlExpression(1, "Click 1"); // B #endif m_buttons->SetControlExpression(2, "1"); // 1 m_buttons->SetControlExpression(3, "2"); // 2 m_buttons->SetControlExpression(4, "Q"); // - m_buttons->SetControlExpression(5, "E"); // + #ifdef _WIN32 m_buttons->SetControlExpression(6, "!LMENU & RETURN"); // Home #else m_buttons->SetControlExpression(6, "!`Alt_L` & Return"); // Home #endif // Shake for (int i = 0; i < 3; ++i) m_shake->SetControlExpression(i, "Click 2"); // IR m_ir->SetControlExpression(0, "Cursor Y-"); m_ir->SetControlExpression(1, "Cursor Y+"); m_ir->SetControlExpression(2, "Cursor X-"); m_ir->SetControlExpression(3, "Cursor X+"); // DPad #ifdef _WIN32 m_dpad->SetControlExpression(0, "UP"); // Up m_dpad->SetControlExpression(1, "DOWN"); // Down m_dpad->SetControlExpression(2, "LEFT"); // Left m_dpad->SetControlExpression(3, "RIGHT"); // Right #elif __APPLE__ m_dpad->SetControlExpression(0, "Up Arrow"); // Up m_dpad->SetControlExpression(1, "Down Arrow"); // Down m_dpad->SetControlExpression(2, "Left Arrow"); // Left m_dpad->SetControlExpression(3, "Right Arrow"); // Right #else m_dpad->SetControlExpression(0, "Up"); // Up m_dpad->SetControlExpression(1, "Down"); // Down m_dpad->SetControlExpression(2, "Left"); // Left m_dpad->SetControlExpression(3, "Right"); // Right #endif // ugly stuff // enable nunchuk m_extension->switch_extension = 1; // set nunchuk defaults m_extension->attachments[1]->LoadDefaults(ciface); } }
EmptyChaos/dolphin
Source/Core/Core/HW/WiimoteEmu/WiimoteEmu.cpp
C++
gpl-2.0
32,622
<?php use Maps\Element; use Maps\Elements\Line; use Maps\Elements\Location; /** * Class handling the #display_map rendering. * * @licence GNU GPL v2+ * @author Jeroen De Dauw < jeroendedauw@gmail.com > * @author Kim Eik */ class MapsDisplayMapRenderer { /** * @since 2.0 * * @var iMappingService */ protected $service; /** * Constructor. * * @param iMappingService $service */ public function __construct( iMappingService $service ) { $this->service = $service; } /** * Returns the HTML to display the map. * * @since 2.0 * * @param array $params * @param Parser $parser * @param string $mapName * * @return string */ protected function getMapHTML( array $params, Parser $parser, $mapName ) { return Html::rawElement( 'div', [ 'id' => $mapName, 'style' => "width: {$params['width']}; height: {$params['height']}; background-color: #cccccc; overflow: hidden;", 'class' => 'maps-map maps-' . $this->service->getName() ], wfMessage( 'maps-loading-map' )->inContentLanguage()->escaped() . Html::element( 'div', [ 'style' => 'display:none', 'class' => 'mapdata' ], FormatJson::encode( $this->getJSONObject( $params, $parser ) ) ) ); } /** * Returns a PHP object to encode to JSON with the map data. * * @since 2.0 * * @param array $params * @param Parser $parser * * @return mixed */ protected function getJSONObject( array $params, Parser $parser ) { return $params; } /** * Handles the request from the parser hook by doing the work that's common for all * mapping services, calling the specific methods and finally returning the resulting output. * * @param array $params * @param Parser $parser * * @return string */ public final function renderMap( array $params, Parser $parser ) { $this->handleMarkerData( $params, $parser ); $mapName = $this->service->getMapId(); $output = $this->getMapHTML( $params, $parser, $mapName ); $configVars = Skin::makeVariablesScript( $this->service->getConfigVariables() ); $this->service->addDependencies( $parser ); $parser->getOutput()->addHeadItem( $configVars ); return $output; } /** * Converts the data in the coordinates parameter to JSON-ready objects. * These get stored in the locations parameter, and the coordinates on gets deleted. * * FIXME: complexity * * @since 1.0 * * @param array &$params * @param Parser $parser */ protected function handleMarkerData( array &$params, Parser $parser ) { if ( is_object( $params['centre'] ) ) { $params['centre'] = $params['centre']->getJSONObject(); } $parserClone = clone $parser; if ( is_object( $params['wmsoverlay'] ) ) { $params['wmsoverlay'] = $params['wmsoverlay']->getJSONObject(); } $iconUrl = MapsMapper::getFileUrl( $params['icon'] ); $visitedIconUrl = MapsMapper::getFileUrl( $params['visitedicon'] ); $params['locations'] = []; /** * @var Location $location */ foreach ( $params['coordinates'] as $location ) { $jsonObj = $location->getJSONObject( $params['title'], $params['label'], $iconUrl, '', '',$visitedIconUrl); $jsonObj['title'] = $parserClone->parse( $jsonObj['title'], $parserClone->getTitle(), new ParserOptions() )->getText(); $jsonObj['text'] = $parserClone->parse( $jsonObj['text'], $parserClone->getTitle(), new ParserOptions() )->getText(); $jsonObj['inlineLabel'] = strip_tags($parserClone->parse( $jsonObj['inlineLabel'], $parserClone->getTitle(), new ParserOptions() )->getText(),'<a><img>'); $hasTitleAndtext = $jsonObj['title'] !== '' && $jsonObj['text'] !== ''; $jsonObj['text'] = ( $hasTitleAndtext ? '<b>' . $jsonObj['title'] . '</b><hr />' : $jsonObj['title'] ) . $jsonObj['text']; $jsonObj['title'] = strip_tags( $jsonObj['title'] ); $params['locations'][] = $jsonObj; } unset( $params['coordinates'] ); $this->handleShapeData( $params, $parserClone ); if ( $params['mappingservice'] === 'openlayers' ) { $params['layers'] = self::evilOpenLayersHack( $params['layers'] ); } } protected function handleShapeData( array &$params, Parser $parserClone ) { $textContainers = [ &$params['lines'] , &$params['polygons'] , &$params['circles'] , &$params['rectangles'], &$params['imageoverlays'], // FIXME: this is Google Maps specific!! ]; foreach ( $textContainers as &$textContainer ) { if ( is_array( $textContainer ) ) { foreach ( $textContainer as &$obj ) { if ( $obj instanceof Element ) { $obj = $obj->getArrayValue(); } $obj['title'] = $parserClone->parse( $obj['title'] , $parserClone->getTitle() , new ParserOptions() )->getText(); $obj['text'] = $parserClone->parse( $obj['text'] , $parserClone->getTitle() , new ParserOptions() )->getText(); $hasTitleAndtext = $obj['title'] !== '' && $obj['text'] !== ''; $obj['text'] = ( $hasTitleAndtext ? '<b>' . $obj['title'] . '</b><hr />' : $obj['title'] ) . $obj['text']; $obj['title'] = strip_tags( $obj['title'] ); } } } } /** * FIXME * * Temporary hack until the mapping service handling gets a proper refactor * This kind of JS construction is also rather evil and should not be done at this point * * @since 3.0 * @deprecated * * @param string[] $layers * * @return string[] */ public static function evilOpenLayersHack( $layers ) { global $egMapsOLLayerGroups, $egMapsOLAvailableLayers; $layerDefs = []; $layerNames = []; foreach ( $layers as $layerOrGroup ) { $lcLayerOrGroup = strtolower( $layerOrGroup ); // Layer groups. Loop over all items and add them if not present yet: if ( array_key_exists( $lcLayerOrGroup, $egMapsOLLayerGroups ) ) { foreach ( $egMapsOLLayerGroups[$lcLayerOrGroup] as $layerName ) { if ( !in_array( $layerName, $layerNames ) ) { if ( is_array( $egMapsOLAvailableLayers[$layerName] ) ) { $layerDefs[] = 'new ' . $egMapsOLAvailableLayers[$layerName][0]; } else { $layerDefs[] = 'new ' . $egMapsOLAvailableLayers[$layerName]; } $layerNames[] = $layerName; } } } // Single layers. Add them if not present yet: elseif ( array_key_exists( $lcLayerOrGroup, $egMapsOLAvailableLayers ) ) { if ( !in_array( $lcLayerOrGroup, $layerNames ) ) { if ( is_array( $egMapsOLAvailableLayers[$lcLayerOrGroup] ) ) { $layerDefs[] = 'new ' . $egMapsOLAvailableLayers[$lcLayerOrGroup][0]; } else { $layerDefs[] = 'new ' . $egMapsOLAvailableLayers[$lcLayerOrGroup]; } $layerNames[] = $lcLayerOrGroup; } } // Image layers. Check validity and add if not present yet: else { $layerParts = explode( ';', $layerOrGroup, 2 ); $layerGroup = $layerParts[0]; $layerName = count( $layerParts ) > 1 ? $layerParts[1] : null; $title = Title::newFromText( $layerGroup, Maps_NS_LAYER ); if ( $title !== null && $title->getNamespace() == Maps_NS_LAYER ) { // TODO: FIXME: This shouldn't be here and using $wgParser, instead it should // be somewhere around MapsBaseMap::renderMap. But since we do a lot more than // 'parameter manipulation' in here, we already diminish the information needed // for this which will never arrive there. global $wgParser; // add dependency to the layer page so if the layer definition gets updated, // the page where it is used will be updated as well: $rev = Revision::newFromTitle( $title ); $revId = null; if( $rev !== null ) { $revId = $rev->getId(); } $wgParser->getOutput()->addTemplate( $title, $title->getArticleID(), $revId ); // if the whole layer group is not yet loaded into the map and the group exists: if( !in_array( $layerGroup, $layerNames ) && $title->exists() ) { if( $layerName !== null ) { // load specific layer with name: $layer = MapsLayers::loadLayer( $title, $layerName ); $layers = new MapsLayerGroup( $layer ); $usedLayer = $layerOrGroup; } else { // load all layers from group: $layers = MapsLayers::loadLayerGroup( $title ); $usedLayer = $layerGroup; } foreach( $layers->getLayers() as $layer ) { if( ( // make sure named layer is only taken once (in case it was requested on its own before) $layer->getName() === null || !in_array( $layerGroup . ';' . $layer->getName(), $layerNames ) ) && $layer->isOk() ) { $layerDefs[] = $layer->getJavaScriptDefinition(); } } $layerNames[] = $usedLayer; // have to add this after loop of course! } } else { wfWarn( "Invalid layer ($layerOrGroup) encountered after validation." ); } } } MapsMappingServices::getServiceInstance( 'openlayers' )->addLayerDependencies( self::getLayerDependencies( $layerNames ) ); // print_r( $layerDefs ); // die(); return $layerDefs; } /** * FIXME * @see evilOpenLayersHack */ private static function getLayerDependencies( array $layerNames ) { global $egMapsOLLayerDependencies, $egMapsOLAvailableLayers; $layerDependencies = []; foreach ( $layerNames as $layerName ) { if ( array_key_exists( $layerName, $egMapsOLAvailableLayers ) // The layer must be defined in php && is_array( $egMapsOLAvailableLayers[$layerName] ) // The layer must be an array... && count( $egMapsOLAvailableLayers[$layerName] ) > 1 // ...with a second element... && array_key_exists( $egMapsOLAvailableLayers[$layerName][1], $egMapsOLLayerDependencies ) ) { //...that is a dependency. $layerDependencies[] = $egMapsOLLayerDependencies[$egMapsOLAvailableLayers[$layerName][1]]; } } return array_unique( $layerDependencies ); } }
robksawyer/preciousplasticwiki
extensions/extensions/Maps/includes/Maps_DisplayMapRenderer.php
PHP
gpl-2.0
9,780
using System.Threading.Tasks; using AnimeLists; using MediaBrowser.Controller.Providers; using MediaBrowser.Plugins.Anime.Configuration; namespace MediaBrowser.Plugins.Anime.Providers.AniDB.Converter { public class AnidbTvdbEpisodeConverter : IItemIdentityConverter<EpisodeInfo> { private readonly Mapper _mapper; public AnidbTvdbEpisodeConverter() { _mapper = AnidbConverter.DefaultInstance.Mapper; } public async Task<bool> Convert(EpisodeInfo info) { var anidb = info.ProviderIds.GetOrDefault(ProviderNames.AniDb); var tvdb = info.ProviderIds.GetOrDefault("Tvdb-Full"); if (string.IsNullOrEmpty(anidb) && !string.IsNullOrEmpty(tvdb)) { var converted = TvdbToAnidb(tvdb); if (converted != null) { info.ProviderIds.Add(ProviderNames.AniDb, converted); return true; } } var overrideTvdb = string.IsNullOrEmpty(tvdb) || info.ParentIndexNumber == null || (info.ParentIndexNumber < 2 && PluginConfiguration.Instance().UseAnidbOrderingWithSeasons); if (!string.IsNullOrEmpty(anidb) && overrideTvdb) { var converted = AnidbToTvdb(anidb); if (converted != null && converted != tvdb) { info.ProviderIds["Tvdb-Full"] = converted; return tvdb != converted; } } return false; } private string TvdbToAnidb(string tvdb) { var tvdbId = TvdbEpisodeIdentity.Parse(tvdb); if (tvdbId == null) return null; var converted = _mapper.ToAnidb(new TvdbEpisode { Series = tvdbId.Value.SeriesId, Season = tvdbId.Value.SeasonIndex, Index = tvdbId.Value.EpisodeNumber }); if (converted == null) return null; int? end = null; if (tvdbId.Value.EpisodeNumberEnd != null) { var convertedEnd = _mapper.ToAnidb(new TvdbEpisode { Series = tvdbId.Value.SeriesId, Season = tvdbId.Value.SeasonIndex, Index = tvdbId.Value.EpisodeNumberEnd.Value }); if (convertedEnd != null && convertedEnd.Season == converted.Season) end = convertedEnd.Index; } var id = new AnidbEpisodeIdentity(converted.Series, converted.Index, end, null); return id.ToString(); } private string AnidbToTvdb(string anidb) { var anidbId = AnidbEpisodeIdentity.Parse(anidb); if (anidbId == null) return null; var converted = _mapper.ToTvdb(new AnidbEpisode { Series = anidbId.Value.SeriesId, Season = string.IsNullOrEmpty(anidbId.Value.EpisodeType) ? 1 : 0, Index = anidbId.Value.EpisodeNumber }); int? end = null; if (anidbId.Value.EpisodeNumberEnd != null) { var convertedEnd = _mapper.ToAnidb(new TvdbEpisode { Series = anidbId.Value.SeriesId, Season = string.IsNullOrEmpty(anidbId.Value.EpisodeType) ? 1 : 0, Index = anidbId.Value.EpisodeNumberEnd.Value }); if (convertedEnd.Season == converted.Season) end = convertedEnd.Index; } var id = new TvdbEpisodeIdentity(converted.Series, converted.Season, converted.Index, end); return id.ToString(); } } }
TomGillen/MediaBrowser.Plugins.Anime
MediaBrowser.Plugins.Anime/Providers/AniDB/Converter/AnidbTvdbEpisodeConverter.cs
C#
gpl-2.0
3,899
/* * Copyright 1997-2004 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.doclets.formats.html; import com.sun.javadoc.*; import com.sun.tools.doclets.internal.toolkit.util.*; import java.io.*; /** * This abstract class exists to provide functionality needed in the * the formatting of member information. Since AbstractSubWriter and its * subclasses control this, they would be the logical place to put this. * However, because each member type has its own subclass, subclassing * can not be used effectively to change formatting. The concrete * class subclass of this class can be subclassed to change formatting. * * @see AbstractMemberWriter * @see ClassWriterImpl * * @author Robert Field * @author Atul M Dambalkar */ public abstract class SubWriterHolderWriter extends HtmlDocletWriter { public SubWriterHolderWriter(ConfigurationImpl configuration, String filename) throws IOException { super(configuration, filename); } public SubWriterHolderWriter(ConfigurationImpl configuration, String path, String filename, String relpath) throws IOException { super(configuration, path, filename, relpath); } public void printTypeSummaryHeader() { tdIndex(); font("-1"); code(); } public void printTypeSummaryFooter() { codeEnd(); fontEnd(); tdEnd(); } public void printSummaryHeader(AbstractMemberWriter mw, ClassDoc cd) { mw.printSummaryAnchor(cd); tableIndexSummary(); tableHeaderStart("#CCCCFF"); mw.printSummaryLabel(cd); tableHeaderEnd(); } public void printTableHeadingBackground(String str) { tableIndexDetail(); tableHeaderStart("#CCCCFF", 1); bold(str); tableHeaderEnd(); tableEnd(); } public void printInheritedSummaryHeader(AbstractMemberWriter mw, ClassDoc cd) { mw.printInheritedSummaryAnchor(cd); tableIndexSummary(); tableInheritedHeaderStart("#EEEEFF"); mw.printInheritedSummaryLabel(cd); tableInheritedHeaderEnd(); trBgcolorStyle("white", "TableRowColor"); summaryRow(0); code(); } public void printSummaryFooter(AbstractMemberWriter mw, ClassDoc cd) { tableEnd(); space(); } public void printInheritedSummaryFooter(AbstractMemberWriter mw, ClassDoc cd) { codeEnd(); summaryRowEnd(); trEnd(); tableEnd(); space(); } protected void printIndexComment(Doc member) { printIndexComment(member, member.firstSentenceTags()); } protected void printIndexComment(Doc member, Tag[] firstSentenceTags) { Tag[] deprs = member.tags("deprecated"); if (Util.isDeprecated((ProgramElementDoc) member)) { boldText("doclet.Deprecated"); space(); if (deprs.length > 0) { printInlineDeprecatedComment(member, deprs[0]); } return; } else { ClassDoc cd = ((ProgramElementDoc)member).containingClass(); if (cd != null && Util.isDeprecated(cd)) { boldText("doclet.Deprecated"); space(); } } printSummaryComment(member, firstSentenceTags); } public void printSummaryLinkType(AbstractMemberWriter mw, ProgramElementDoc member) { trBgcolorStyle("white", "TableRowColor"); mw.printSummaryType(member); summaryRow(0); code(); } public void printSummaryLinkComment(AbstractMemberWriter mw, ProgramElementDoc member) { printSummaryLinkComment(mw, member, member.firstSentenceTags()); } public void printSummaryLinkComment(AbstractMemberWriter mw, ProgramElementDoc member, Tag[] firstSentenceTags) { codeEnd(); println(); br(); printNbsps(); printIndexComment(member, firstSentenceTags); summaryRowEnd(); trEnd(); } public void printInheritedSummaryMember(AbstractMemberWriter mw, ClassDoc cd, ProgramElementDoc member, boolean isFirst) { if (! isFirst) { mw.print(", "); } mw.writeInheritedSummaryLink(cd, member); } public void printMemberHeader() { hr(); } public void printMemberFooter() { } }
infinity0/proxy-doclet
src.orig/openjdk-6-src-b16-24_apr_2009/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java
Java
gpl-2.0
5,757
<?php function event_espresso_questions_config_mnu() { global $wpdb; //Update the questions when re-ordering if (!empty($_REQUEST['update_sequence'])) { $rows = explode(",", $_POST['row_ids']); for ($i = 0; $i < count($rows); $i++) { $wpdb->query("UPDATE " . EVENTS_QUESTION_TABLE . " SET sequence=" . $i . " WHERE id='" . $rows[$i] . "'"); } die(); } // get counts $sql = "SELECT id FROM " . EVENTS_QUESTION_TABLE; $wpdb->get_results($sql); $total_questions = $wpdb->num_rows; if (function_exists('espresso_is_admin') && espresso_is_admin() == true) { $sql .= " WHERE "; if (espresso_member_data('id') == 0 || espresso_member_data('id') == 1) { $sql .= " (wp_user = '0' OR wp_user = '1') "; } else { $sql .= " wp_user = '" . espresso_member_data('id') . "' "; } } $wpdb->get_results($sql); $total_self_questions = $wpdb->num_rows; ?> <div class="wrap"> <div id="icon-options-event" class="icon32"> </div> <h2><?php echo _e('Manage Questions', 'event_espresso') ?> <?php if (!isset($_REQUEST['action']) || ($_REQUEST['action'] != 'edit_question' && $_REQUEST['action'] != 'new_question')) { echo '<a href="admin.php?page=form_builder&action=new_question" class="button add-new-h2" style="margin-left: 20px;">' . __('Add New Question', 'event_espresso') . '</a>'; } ?> </h2> <div id="poststuff" class="metabox-holder has-right-sidebar"> <?php event_espresso_display_right_column(); ?> <div id="post-body"> <?php if (function_exists('espresso_is_admin') && espresso_is_admin() == true) { ?> <div style="margin-bottom: 10px;"> <ul class="subsubsub" style="margin-bottom: 0;clear:both;"> <li><strong><?php _e('Questions', 'event_espresso'); ?>: </strong> </li> <li><a <?php echo ( (!isset($_REQUEST['self']) && !isset($_REQUEST['all']) ) || ( isset($_REQUEST['self']) && $_REQUEST['self'] == 'true') ) ? ' class="current" ' : '' ?> href="admin.php?page=form_builder&self=true"><?php _e('My Questions', 'event_espresso'); ?> <span class="count">(<?php echo $total_self_questions; ?>)</span> </a> | </li> <li><a <?php echo (isset($_REQUEST['all']) && $_REQUEST['all'] == 'true') ? ' class="current" ' : '' ?> href="admin.php?page=form_builder&all=true"><?php _e('All Questions', 'event_espresso'); ?> <span class="count">(<?php echo $total_questions; ?>)</span> </a></li> </ul> <div class="clear"></div> </div> <?php } ?> <div id="post-body-content"> <div class="meta-box-sortables ui-sortables"> <?php //Update the question if (isset($_REQUEST['edit_action']) && $_REQUEST['edit_action'] == 'update') { require_once("questions/update_question.php"); event_espresso_form_builder_update(); } //Figure out which view to display if(isset($_REQUEST['action'])) { switch ($_REQUEST['action']) { case 'insert': if (file_exists(EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/admin-files/form-builder/questions/insert_question.php')) { require_once(EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/admin-files/form-builder/questions/insert_question.php'); event_espresso_form_builder_insert(); } else { require_once(EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/pricing_table.php'); } break; case 'new_question': if (file_exists(EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/admin-files/form-builder/questions/new_question.php')) { require_once(EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/admin-files/form-builder/questions/new_question.php'); event_espresso_form_builder_new(); } else { require_once(EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/pricing_table.php'); } break; case 'edit_question': require_once("questions/edit_question.php"); event_espresso_form_builder_edit(); break; case 'delete_question': if (file_exists(EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/admin-files/form-builder/questions/delete_question.php')) { require_once(EVENT_ESPRESSO_PLUGINFULLPATH . 'includes/admin-files/form-builder/questions/delete_question.php'); event_espresso_form_builder_delete(); } else { ?> <div id="message" class="updated fade"> <p><strong> <?php _e('This function is not available in the free version of Event Espresso.', 'event_espresso'); ?> </strong></p> </div> <?php } break; } } ?> <form id="form1" name="form1" method="post" action="<?php echo $_SERVER["REQUEST_URI"] ?>"> <table id="table" class="widefat manage-questions"> <thead> <tr> <th class="manage-column" id="cb" scope="col" ><input type="checkbox"></th> <th class="manage-column column-title" id="values" scope="col" title="Click to Sort" style="width:25%;"> <?php _e('Question', 'event_espresso'); ?> </th> <th class="manage-column column-title" id="values" scope="col" title="Click to Sort" style="width:20%;"> <?php _e('Values', 'event_espresso'); ?> </th> <?php if (function_exists('espresso_is_admin') && espresso_is_admin() == true) { ?> <th class="manage-column column-creator" id="creator" scope="col" title="Click to Sort" style="width:10%;"> <?php _e('Creator', 'event_espresso'); ?> </th> <?php } ?> <th class="manage-column column-title" id="values" scope="col" title="Click to Sort" style="width:10%;"> <?php _e('Type', 'event_espresso'); ?> </th> <th class="manage-column column-title" id="values" scope="col" title="Click to Sort" style="width:10%;"> <?php _e('Required', 'event_espresso'); ?> </th> <th class="manage-column column-title" id="values" scope="col" title="Click to Sort" style="width:10%;"> <?php _e('Admin Only', 'event_espresso'); ?> </th> </tr> </thead> <tbody> <?php $sql = "SELECT * FROM " . EVENTS_QUESTION_TABLE; $sql .= " WHERE "; if (function_exists('espresso_member_data') && !isset($_REQUEST['all'])) { if (espresso_member_data('id') == 0 || espresso_member_data('id') == 1) { $sql .= " (wp_user = '0' OR wp_user = '1') "; } else { $sql .= " wp_user = '" . espresso_member_data('id') . "' "; } }else{ $sql .= " (wp_user = '0' OR wp_user = '1') "; } $sql .= " ORDER BY sequence"; $questions = $wpdb->get_results($sql); if ($wpdb->num_rows > 0) { foreach ($questions as $question) { $question_id = $question->id; $question_name = stripslashes($question->question); $values = stripslashes($question->response); $question_type = stripslashes($question->question_type); $required = stripslashes($question->required); $system_name = $question->system_name; $sequence = $question->sequence; $admin_only = $question->admin_only; $wp_user = $question->wp_user == 0 ? 1 : $question->wp_user; ?> <tr style="cursor: move" id="<?php echo $question_id ?>"> <td class="checkboxcol"><input name="row_id" type="hidden" value="<?php echo $question_id ?>" /> <?php if ($system_name == '') : ?> <input style="margin:7px 0 22px 8px; vertical-align:top;" name="checkbox[<?php echo $question_id ?>]" type="checkbox" title="Delete <?php echo $question_name ?>"> <?php else: ?> <span><?php echo '<img style="margin:7px 0 22px 8px; vertical-align:top;" src="' . EVENT_ESPRESSO_PLUGINFULLURL . 'images/icons/lock.png" alt="System Questions" title="System Questions" />'; ?></span> <?php endif; ?> </td> <td class="post-title page-title column-title"><strong><a href="admin.php?page=form_builder&amp;action=edit_question&amp;question_id=<?php echo $question_id ?>"><?php echo $question_name ?></a></strong> <div class="row-actions"> <span class="edit"><a href="admin.php?page=form_builder&amp;action=edit_question&amp;question_id=<?php echo $question_id ?>"><?php _e('Edit', 'event_espresso'); ?></a> | </span> <?php if ($system_name == ''): ?><span class="delete"><a onclick="return confirmDelete();" class="submitdelete" href="admin.php?page=form_builder&amp;action=delete_question&amp;question_id=<?php echo $question_id ?>"><?php _e('Delete', 'event_espresso'); ?></a></span><?php endif; ?> </div> </td> <td class="author column-author"><?php echo $values ?></td> <?php if (function_exists('espresso_is_admin') && espresso_is_admin() == true) { ?> <td><?php echo espresso_user_meta($wp_user, 'user_firstname') != '' ? espresso_user_meta($wp_user, 'user_firstname') . ' ' . espresso_user_meta($wp_user, 'user_lastname') : espresso_user_meta($wp_user, 'display_name'); ?></td> <?php } ?> <td class="author column-author"><?php echo $question_type ?></td> <td class="author column-author"><?php echo $required ?></td> <td class="author column-author"><?php echo $admin_only ?></td> </tr> <?php } } ?> </tbody> </table> <div> <p><input type="checkbox" name="sAll" onclick="selectAll(this)" /> <strong> <?php _e('Check All', 'event_espresso'); ?> </strong> <input type="hidden" name="action" value="delete_question" /> <input name="delete_question" type="submit" class="button-secondary" id="delete_question" value="<?php _e('Delete Question', 'event_espresso'); ?>" style="margin-left:10px 0 0 10px;" onclick="return confirmDelete();"> <a style="margin-left:5px"class="button-primary" href="admin.php?page=form_builder&amp;action=new_question"><?php _e('Add New Question', 'event_espresso'); ?></a> <a style="margin-left:5px"class="button-primary" href="admin.php?page=form_groups"><?php _e('Question Groups', 'event_espresso'); ?></a> <a style="color:#FFF; text-decoration:none; margin-left:5px"class="button-primary thickbox" href="#TB_inline?height=400&width=500&inlineId=question_info">Help</a> </p> </div> </form> </div> </div> </div> </div> </div> <div id="question_info" class="pop-help" style="display:none"> <div class="TB-ee-frame"> <h2><?php _e('Manage Questions Overview', 'event_espresso'); ?></h2> <p><?php _e('The <code>Questions</code> page shows your list of available questions to add to your registration forms for events', 'event_espresso'); ?> <p><?php _e('Use the add new question button at the top of the page to create a new question to add to the list ', 'event_espresso'); ?><a href="admin.php?page=form_builder&amp;action=new_question"><?php _e('Add New Question', 'event_espresso'); ?></a></p> <p><?php _e('Once you have a built a list of questions you may further organize your questions into <code>Groups.</code> These', 'event_espresso')?> <a href="admin.php?page=form_groups"><?php _e('Question Groups ', 'event_espresso'); ?></a><?php _e('allow you to easily and conveniently add a group to a registration that will have a pre populated set of questions, this is especially handy when creating many registration forms, saving time, by being able to re-use specific groups of questions repetedly.', 'event_espresso') ?></p> </div> </div> <script type="text/javascript"> jQuery(document).ready(function($) { /* show the table data */ var mytable = $('#table').dataTable( { "bStateSave": true, "sPaginationType": "full_numbers", "oLanguage": { "sSearch": "<strong><?php _e('Live Search Filter', 'event_espresso'); ?>:</strong>", "sZeroRecords": "<?php _e('No Records Found!', 'event_espresso'); ?>" }, "aoColumns": [ { "bSortable": true }, null, null, null, null, <?php echo function_exists('espresso_is_admin') && espresso_is_admin() == true ? 'null,' : ''; ?> null ] } ); var startPosition; var endPosition; $("#table tbody").sortable({ cursor: "move", start:function(event, ui){ startPosition = ui.item.prevAll().length + 1; }, update: function(event, ui) { endPosition = ui.item.prevAll().length + 1; //alert('Start Position: ' + startPosition + ' End Position: ' + endPosition); var row_ids=""; $('#table tbody input[name="row_id"]').each(function(i){ row_ids= row_ids + ',' + $(this).val(); }); $.post(EEGlobals.ajaxurl, { action: "update_sequence", row_ids: row_ids, update_sequence: "true"} ); } }); postboxes.add_postbox_toggles('form_builder'); } ); // Remove li parent for input 'values' from page if 'text' box or 'textarea' are selected var selectValue = jQuery('select#question_type option:selected').val(); //alert(selectValue + ' - this is initial value'); // hide values field on initial page view if(selectValue == 'TEXT' || selectValue == 'TEXTAREA' || selectValue == 'DATE'){ jQuery('#add-question-values').hide(); // we don't want the values field trying to validate if not displayed, remove its name jQuery('#add-question-values td input').attr("name","notrequired") } jQuery('select#question_type').bind('change', function() { var selectValue = jQuery('select#question_type option:selected').val(); if (selectValue == 'TEXT' || selectValue == 'TEXTAREA' || selectValue == 'DATE') { jQuery('#add-question-values').fadeOut('slow'); // we don't want the values field trying to validate if not displayed, remove its name jQuery('#add-question-values td input').attr("name","notrequired") //alert(selectValue); } else{ //alert(selectValue); jQuery('#add-question-values').fadeIn('slow'); // add the correct name value back in so we can run validation check. jQuery('#add-question-values td input').attr("name","values"); } }); // Add new question or question group form validation jQuery(function(){ jQuery('#new-question-form').validate({ rules: { question: "required", values: "required" }, messages: { question: "Please add a title for your question", values: "Please add a list of values for your question" } }); }); </script> <?php }
TheOrchardSolutions/WordPress
wp-content/plugins/event-disabled/event-espresso.3.1.21.P/includes/form-builder/index.php
PHP
gpl-2.0
18,973
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2016 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef XCSOAR_FLARM_NAME_DATABASE_HPP #define XCSOAR_FLARM_NAME_DATABASE_HPP #include "Util/StaticString.hxx" #include "Util/StaticArray.hxx" #include "FlarmId.hpp" #include "Util/Compiler.h" #include <cassert> #include <tchar.h> class FlarmNameDatabase { public: struct Record { FlarmId id; StaticString<21> name; Record() = default; Record(FlarmId _id, const TCHAR *_name) :id(_id), name(_name) {} }; private: typedef StaticArray<Record, 200> Array; typedef Array::iterator iterator; Array data; public: typedef Array::const_iterator const_iterator; gcc_pure const_iterator begin() const { return data.begin(); } gcc_pure const_iterator end() const { return data.end(); } gcc_pure const TCHAR *Get(FlarmId id) const; gcc_pure FlarmId Get(const TCHAR *name) const; /** * Look up all records with the specified name. * * @param max the maximum size of the given buffer * @return the number of items copied to the given buffer */ unsigned Get(const TCHAR *name, FlarmId *buffer, unsigned max) const; bool Set(FlarmId id, const TCHAR *name); protected: gcc_pure int Find(FlarmId id) const; gcc_pure int Find(const TCHAR *name) const; }; #endif
fberst/xcsoar
src/FLARM/NameDatabase.hpp
C++
gpl-2.0
2,150
<?php /* * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures * all the essential functionalities required for any enterprise. * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com * * OrangeHRM is free software; you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * OrangeHRM 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA */ class SearchParameterHolderExeption extends Exception { }
monokal/docker-orangehrm
www/symfony/plugins/orangehrmCorePlugin/lib/parameterholder/SearchParameterHolderException.php
PHP
gpl-2.0
1,008
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * (C) 2006 Alexey Proskuryakov (ap@webkit.org) * Copyright (C) 2004-2009, 2011-2012, 2015-2016 Apple Inc. All rights reserved. * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved. * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "StyleScope.h" #include "CSSStyleSheet.h" #include "Element.h" #include "ElementChildIterator.h" #include "ExtensionStyleSheets.h" #include "HTMLIFrameElement.h" #include "HTMLLinkElement.h" #include "HTMLSlotElement.h" #include "HTMLStyleElement.h" #include "InspectorInstrumentation.h" #include "ProcessingInstruction.h" #include "SVGStyleElement.h" #include "Settings.h" #include "ShadowRoot.h" #include "StyleInvalidationAnalysis.h" #include "StyleResolver.h" #include "StyleSheetContents.h" #include "StyleSheetList.h" #include "UserContentController.h" #include "UserContentURLPattern.h" #include "UserStyleSheet.h" #include <wtf/SetForScope.h> namespace WebCore { using namespace ContentExtensions; using namespace HTMLNames; namespace Style { Scope::Scope(Document& document) : m_document(document) , m_pendingUpdateTimer(*this, &Scope::pendingUpdateTimerFired) { } Scope::Scope(ShadowRoot& shadowRoot) : m_document(shadowRoot.documentScope()) , m_shadowRoot(&shadowRoot) , m_pendingUpdateTimer(*this, &Scope::pendingUpdateTimerFired) { } Scope::~Scope() { } bool Scope::shouldUseSharedUserAgentShadowTreeStyleResolver() const { if (!m_shadowRoot) return false; if (m_shadowRoot->mode() != ShadowRootMode::UserAgent) return false; // If we have stylesheets in the user agent shadow tree use per-scope resolver. if (!m_styleSheetCandidateNodes.isEmpty()) return false; return true; } StyleResolver& Scope::resolver() { if (shouldUseSharedUserAgentShadowTreeStyleResolver()) return m_document.userAgentShadowTreeStyleResolver(); if (!m_resolver) { SetForScope<bool> isUpdatingStyleResolver { m_isUpdatingStyleResolver, true }; m_resolver = std::make_unique<StyleResolver>(m_document); m_resolver->appendAuthorStyleSheets(m_activeStyleSheets); } ASSERT(!m_shadowRoot || &m_document == &m_shadowRoot->document()); ASSERT(&m_resolver->document() == &m_document); return *m_resolver; } StyleResolver* Scope::resolverIfExists() { if (shouldUseSharedUserAgentShadowTreeStyleResolver()) return &m_document.userAgentShadowTreeStyleResolver(); return m_resolver.get(); } void Scope::clearResolver() { m_resolver = nullptr; if (!m_shadowRoot) m_document.didClearStyleResolver(); } Scope& Scope::forNode(Node& node) { ASSERT(node.isConnected()); auto* shadowRoot = node.containingShadowRoot(); if (shadowRoot) return shadowRoot->styleScope(); return node.document().styleScope(); } Scope* Scope::forOrdinal(Element& element, ScopeOrdinal ordinal) { switch (ordinal) { case ScopeOrdinal::Element: return &forNode(element); case ScopeOrdinal::ContainingHost: { auto* containingShadowRoot = element.containingShadowRoot(); if (!containingShadowRoot) return nullptr; return &forNode(*containingShadowRoot->host()); } case ScopeOrdinal::Shadow: { auto* shadowRoot = element.shadowRoot(); if (!shadowRoot) return nullptr; return &shadowRoot->styleScope(); } default: { ASSERT(ordinal >= ScopeOrdinal::FirstSlot); auto slotIndex = ScopeOrdinal::FirstSlot; for (auto* slot = element.assignedSlot(); slot; slot = slot->assignedSlot(), ++slotIndex) { if (slotIndex == ordinal) return &forNode(*slot); } return nullptr; } } } void Scope::setPreferredStylesheetSetName(const String& name) { if (m_preferredStylesheetSetName == name) return; m_preferredStylesheetSetName = name; didChangeActiveStyleSheetCandidates(); } void Scope::setSelectedStylesheetSetName(const String& name) { if (m_selectedStylesheetSetName == name) return; m_selectedStylesheetSetName = name; didChangeActiveStyleSheetCandidates(); } // This method is called whenever a top-level stylesheet has finished loading. void Scope::removePendingSheet() { // Make sure we knew this sheet was pending, and that our count isn't out of sync. ASSERT(m_pendingStyleSheetCount > 0); m_pendingStyleSheetCount--; if (m_pendingStyleSheetCount) return; didChangeActiveStyleSheetCandidates(); if (!m_shadowRoot) m_document.didRemoveAllPendingStylesheet(); } void Scope::addStyleSheetCandidateNode(Node& node, bool createdByParser) { if (!node.isConnected()) return; // Until the <body> exists, we have no choice but to compare document positions, // since styles outside of the body and head continue to be shunted into the head // (and thus can shift to end up before dynamically added DOM content that is also // outside the body). if ((createdByParser && m_document.bodyOrFrameset()) || m_styleSheetCandidateNodes.isEmpty()) { m_styleSheetCandidateNodes.add(&node); return; } // Determine an appropriate insertion point. auto begin = m_styleSheetCandidateNodes.begin(); auto end = m_styleSheetCandidateNodes.end(); auto it = end; Node* followingNode = nullptr; do { --it; Node* n = *it; unsigned short position = n->compareDocumentPosition(node); if (position == Node::DOCUMENT_POSITION_FOLLOWING) { m_styleSheetCandidateNodes.insertBefore(followingNode, &node); return; } followingNode = n; } while (it != begin); m_styleSheetCandidateNodes.insertBefore(followingNode, &node); } void Scope::removeStyleSheetCandidateNode(Node& node) { if (m_styleSheetCandidateNodes.remove(&node)) didChangeActiveStyleSheetCandidates(); } void Scope::collectActiveStyleSheets(Vector<RefPtr<StyleSheet>>& sheets) { if (!m_document.settings().authorAndUserStylesEnabled()) return; for (auto& node : m_styleSheetCandidateNodes) { StyleSheet* sheet = nullptr; if (is<ProcessingInstruction>(*node)) { // Processing instruction (XML documents only). // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion. ProcessingInstruction& pi = downcast<ProcessingInstruction>(*node); sheet = pi.sheet(); #if ENABLE(XSLT) // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806> if (pi.isXSL() && !m_document.transformSourceDocument()) { // Don't apply XSL transforms until loading is finished. if (!m_document.parsing()) m_document.applyXSLTransform(&pi); return; } #endif } else if (is<HTMLLinkElement>(*node) || is<HTMLStyleElement>(*node) || is<SVGStyleElement>(*node)) { Element& element = downcast<Element>(*node); AtomicString title = element.attributeWithoutSynchronization(titleAttr); bool enabledViaScript = false; if (is<HTMLLinkElement>(element)) { // <LINK> element HTMLLinkElement& linkElement = downcast<HTMLLinkElement>(element); if (linkElement.isDisabled()) continue; enabledViaScript = linkElement.isEnabledViaScript(); if (linkElement.styleSheetIsLoading()) { // it is loading but we should still decide which style sheet set to use if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSetName.isEmpty()) { if (!linkElement.attributeWithoutSynchronization(relAttr).contains("alternate")) { m_preferredStylesheetSetName = title; m_selectedStylesheetSetName = title; } } continue; } if (!linkElement.sheet()) title = nullAtom; } // Get the current preferred styleset. This is the // set of sheets that will be enabled. if (is<SVGStyleElement>(element)) sheet = downcast<SVGStyleElement>(element).sheet(); else if (is<HTMLLinkElement>(element)) sheet = downcast<HTMLLinkElement>(element).sheet(); else sheet = downcast<HTMLStyleElement>(element).sheet(); // Check to see if this sheet belongs to a styleset // (thus making it PREFERRED or ALTERNATE rather than // PERSISTENT). auto& rel = element.attributeWithoutSynchronization(relAttr); if (!enabledViaScript && !title.isEmpty()) { // Yes, we have a title. if (m_preferredStylesheetSetName.isEmpty()) { // No preferred set has been established. If // we are NOT an alternate sheet, then establish // us as the preferred set. Otherwise, just ignore // this sheet. if (is<HTMLStyleElement>(element) || !rel.contains("alternate")) m_preferredStylesheetSetName = m_selectedStylesheetSetName = title; } if (title != m_preferredStylesheetSetName) sheet = nullptr; } if (rel.contains("alternate") && title.isEmpty()) sheet = nullptr; } if (sheet) sheets.append(sheet); } } Scope::StyleResolverUpdateType Scope::analyzeStyleSheetChange(const Vector<RefPtr<CSSStyleSheet>>& newStylesheets, bool& requiresFullStyleRecalc) { requiresFullStyleRecalc = true; unsigned newStylesheetCount = newStylesheets.size(); if (!resolverIfExists()) return Reconstruct; auto& styleResolver = *resolverIfExists(); // Find out which stylesheets are new. unsigned oldStylesheetCount = m_activeStyleSheets.size(); if (newStylesheetCount < oldStylesheetCount) return Reconstruct; Vector<StyleSheetContents*> addedSheets; unsigned newIndex = 0; for (unsigned oldIndex = 0; oldIndex < oldStylesheetCount; ++oldIndex) { if (newIndex >= newStylesheetCount) return Reconstruct; while (m_activeStyleSheets[oldIndex] != newStylesheets[newIndex]) { addedSheets.append(&newStylesheets[newIndex]->contents()); ++newIndex; if (newIndex == newStylesheetCount) return Reconstruct; } ++newIndex; } bool hasInsertions = !addedSheets.isEmpty(); while (newIndex < newStylesheetCount) { addedSheets.append(&newStylesheets[newIndex]->contents()); ++newIndex; } // If all new sheets were added at the end of the list we can just add them to existing StyleResolver. // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly. auto styleResolverUpdateType = hasInsertions ? Reset : Additive; // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs. if (!m_document.bodyOrFrameset() || m_document.hasNodesWithPlaceholderStyle()) return styleResolverUpdateType; StyleInvalidationAnalysis invalidationAnalysis(addedSheets, styleResolver.mediaQueryEvaluator()); if (invalidationAnalysis.dirtiesAllStyle()) return styleResolverUpdateType; if (m_shadowRoot) invalidationAnalysis.invalidateStyle(*m_shadowRoot); else invalidationAnalysis.invalidateStyle(m_document); requiresFullStyleRecalc = false; return styleResolverUpdateType; } static void filterEnabledNonemptyCSSStyleSheets(Vector<RefPtr<CSSStyleSheet>>& result, const Vector<RefPtr<StyleSheet>>& sheets) { for (auto& sheet : sheets) { if (!is<CSSStyleSheet>(*sheet)) continue; CSSStyleSheet& styleSheet = downcast<CSSStyleSheet>(*sheet); if (styleSheet.isLoading()) continue; if (styleSheet.disabled()) continue; if (!styleSheet.length()) continue; result.append(&styleSheet); } } void Scope::updateActiveStyleSheets(UpdateType updateType) { ASSERT(!m_pendingUpdate); if (!m_document.hasLivingRenderTree()) return; if (m_document.inStyleRecalc() || m_document.inRenderTreeUpdate()) { // Protect against deleting style resolver in the middle of a style resolution. // Crash stacks indicate we can get here when a resource load fails synchronously (for example due to content blocking). // FIXME: These kind of cases should be eliminated and this path replaced by an assert. m_pendingUpdate = UpdateType::ContentsOrInterpretation; m_document.scheduleForcedStyleRecalc(); return; } Vector<RefPtr<StyleSheet>> activeStyleSheets; collectActiveStyleSheets(activeStyleSheets); Vector<RefPtr<CSSStyleSheet>> activeCSSStyleSheets; activeCSSStyleSheets.appendVector(m_document.extensionStyleSheets().injectedAuthorStyleSheets()); activeCSSStyleSheets.appendVector(m_document.extensionStyleSheets().authorStyleSheetsForTesting()); filterEnabledNonemptyCSSStyleSheets(activeCSSStyleSheets, activeStyleSheets); bool requiresFullStyleRecalc = true; StyleResolverUpdateType styleResolverUpdateType = Reconstruct; if (updateType == UpdateType::ActiveSet) styleResolverUpdateType = analyzeStyleSheetChange(activeCSSStyleSheets, requiresFullStyleRecalc); updateStyleResolver(activeCSSStyleSheets, styleResolverUpdateType); m_weakCopyOfActiveStyleSheetListForFastLookup = nullptr; m_activeStyleSheets.swap(activeCSSStyleSheets); m_styleSheetsForStyleSheetList.swap(activeStyleSheets); InspectorInstrumentation::activeStyleSheetsUpdated(m_document); for (const auto& sheet : m_activeStyleSheets) { if (sheet->contents().usesStyleBasedEditability()) m_usesStyleBasedEditability = true; } // FIXME: Move this code somewhere else. if (requiresFullStyleRecalc) { if (m_shadowRoot) { for (auto& shadowChild : childrenOfType<Element>(*m_shadowRoot)) shadowChild.invalidateStyleForSubtree(); if (m_shadowRoot->host()) { if (!resolver().ruleSets().authorStyle().hostPseudoClassRules().isEmpty()) m_shadowRoot->host()->invalidateStyle(); if (!resolver().ruleSets().authorStyle().slottedPseudoElementRules().isEmpty()) { for (auto& shadowChild : childrenOfType<Element>(*m_shadowRoot->host())) shadowChild.invalidateStyle(); } } } else m_document.scheduleForcedStyleRecalc(); } } void Scope::updateStyleResolver(Vector<RefPtr<CSSStyleSheet>>& activeStyleSheets, StyleResolverUpdateType updateType) { if (updateType == Reconstruct) { clearResolver(); return; } auto& styleResolver = resolver(); SetForScope<bool> isUpdatingStyleResolver { m_isUpdatingStyleResolver, true }; if (updateType == Reset) { styleResolver.ruleSets().resetAuthorStyle(); styleResolver.appendAuthorStyleSheets(activeStyleSheets); } else { ASSERT(updateType == Additive); unsigned firstNewIndex = m_activeStyleSheets.size(); Vector<RefPtr<CSSStyleSheet>> newStyleSheets; newStyleSheets.appendRange(activeStyleSheets.begin() + firstNewIndex, activeStyleSheets.end()); styleResolver.appendAuthorStyleSheets(newStyleSheets); } } const Vector<RefPtr<CSSStyleSheet>> Scope::activeStyleSheetsForInspector() { Vector<RefPtr<CSSStyleSheet>> result; result.appendVector(m_document.extensionStyleSheets().injectedAuthorStyleSheets()); result.appendVector(m_document.extensionStyleSheets().authorStyleSheetsForTesting()); for (auto& styleSheet : m_styleSheetsForStyleSheetList) { if (!is<CSSStyleSheet>(*styleSheet)) continue; CSSStyleSheet& sheet = downcast<CSSStyleSheet>(*styleSheet); if (sheet.disabled()) continue; result.append(&sheet); } return result; } bool Scope::activeStyleSheetsContains(const CSSStyleSheet* sheet) const { if (!m_weakCopyOfActiveStyleSheetListForFastLookup) { m_weakCopyOfActiveStyleSheetListForFastLookup = std::make_unique<HashSet<const CSSStyleSheet*>>(); for (auto& activeStyleSheet : m_activeStyleSheets) m_weakCopyOfActiveStyleSheetListForFastLookup->add(activeStyleSheet.get()); } return m_weakCopyOfActiveStyleSheetListForFastLookup->contains(sheet); } void Scope::flushPendingSelfUpdate() { ASSERT(m_pendingUpdate); auto updateType = *m_pendingUpdate; clearPendingUpdate(); updateActiveStyleSheets(updateType); } void Scope::flushPendingDescendantUpdates() { ASSERT(m_hasDescendantWithPendingUpdate); ASSERT(!m_shadowRoot); for (auto* descendantShadowRoot : m_document.inDocumentShadowRoots()) descendantShadowRoot->styleScope().flushPendingUpdate(); m_hasDescendantWithPendingUpdate = false; } void Scope::clearPendingUpdate() { m_pendingUpdateTimer.stop(); m_pendingUpdate = { }; } void Scope::scheduleUpdate(UpdateType update) { // FIXME: The m_isUpdatingStyleResolver test is here because extension stylesheets can get us here from StyleResolver::appendAuthorStyleSheets. if (update == UpdateType::ContentsOrInterpretation && !m_isUpdatingStyleResolver) clearResolver(); if (!m_pendingUpdate || *m_pendingUpdate < update) { m_pendingUpdate = update; if (m_shadowRoot) m_document.styleScope().m_hasDescendantWithPendingUpdate = true; } if (m_pendingUpdateTimer.isActive()) return; m_pendingUpdateTimer.startOneShot(0); } void Scope::didChangeActiveStyleSheetCandidates() { scheduleUpdate(UpdateType::ActiveSet); } void Scope::didChangeStyleSheetContents() { scheduleUpdate(UpdateType::ContentsOrInterpretation); } void Scope::didChangeStyleSheetEnvironment() { if (!m_shadowRoot) { for (auto* descendantShadowRoot : m_document.inDocumentShadowRoots()) { // Stylesheets is author shadow roots are are potentially affected. if (descendantShadowRoot->mode() != ShadowRootMode::UserAgent) descendantShadowRoot->styleScope().scheduleUpdate(UpdateType::ContentsOrInterpretation); } } scheduleUpdate(UpdateType::ContentsOrInterpretation); } void Scope::pendingUpdateTimerFired() { flushPendingUpdate(); } const Vector<RefPtr<StyleSheet>>& Scope::styleSheetsForStyleSheetList() { // FIXME: StyleSheetList content should be updated separately from style resolver updates. flushPendingUpdate(); return m_styleSheetsForStyleSheetList; } } }
Debian/openjfx
modules/web/src/main/native/Source/WebCore/style/StyleScope.cpp
C++
gpl-2.0
20,417
<?php /** * Retrieves and creates the wp-config.php file. * * The permissions for the base directory must allow for writing files in order * for the wp-config.php to be created using this page. * * @internal This file must be parsable by PHP4. * * @package WordPress * @subpackage Administration */ /** * We are installing. */ define('WP_INSTALLING', true); /** * We are blissfully unaware of anything. */ define('WP_SETUP_CONFIG', true); /** * Disable error reporting * * Set this to error_reporting( -1 ) for debugging */ error_reporting(0); define( 'ABSPATH', dirname( dirname( __FILE__ ) ) . '/' ); require( ABSPATH . 'wp-settings.php' ); /** Load WordPress Administration Upgrade API */ require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); /** Load WordPress Translation Install API */ require_once( ABSPATH . 'wp-admin/includes/translation-install.php' ); nocache_headers(); // Support wp-config-sample.php one level up, for the develop repo. if ( file_exists( ABSPATH . 'wp-config-sample.php' ) ) $config_file = file( ABSPATH . 'wp-config-sample.php' ); elseif ( file_exists( dirname( ABSPATH ) . '/wp-config-sample.php' ) ) $config_file = file( dirname( ABSPATH ) . '/wp-config-sample.php' ); else wp_die( __( 'Sorry, I need a wp-config-sample.php file to work from. Please re-upload this file from your WordPress installation.' ) ); // Check if wp-config.php has been created if ( file_exists( ABSPATH . 'wp-config.php' ) ) wp_die( '<p>' . sprintf( __( "The file 'wp-config.php' already exists. If you need to reset any of the configuration items in this file, please delete it first. You may try <a href='%s'>installing now</a>." ), 'install.php' ) . '</p>' ); // Check if wp-config.php exists above the root directory but is not part of another install if ( file_exists(ABSPATH . '../wp-config.php' ) && ! file_exists( ABSPATH . '../wp-settings.php' ) ) wp_die( '<p>' . sprintf( __( "The file 'wp-config.php' already exists one level above your WordPress installation. If you need to reset any of the configuration items in this file, please delete it first. You may try <a href='install.php'>installing now</a>."), 'install.php' ) . '</p>' ); $step = isset( $_GET['step'] ) ? (int) $_GET['step'] : -1; /** * Display setup wp-config.php file header. * * @ignore * @since 2.3.0 * * @global string $wp_local_package * @global WP_Locale $wp_locale * * @param string|array $body_classes */ function setup_config_display_header( $body_classes = array() ) { $body_classes = (array) $body_classes; $body_classes[] = 'wp-core-ui'; if ( is_rtl() ) { $body_classes[] = 'rtl'; } header( 'Content-Type: text/html; charset=utf-8' ); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>> <head> <meta name="viewport" content="width=device-width" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php _e( 'WordPress &rsaquo; Setup Configuration File' ); ?></title> <?php wp_admin_css( 'install', true ); ?> </head> <body class="<?php echo implode( ' ', $body_classes ); ?>"> <h1 id="logo"><a href="<?php esc_attr_e( 'https://wordpress.org/' ); ?>" tabindex="-1"><?php _e( 'WordPress' ); ?></a></h1> <?php } // end function setup_config_display_header(); $language = ''; if ( ! empty( $_REQUEST['language'] ) ) { $language = preg_replace( '/[^a-zA-Z_]/', '', $_REQUEST['language'] ); } elseif ( isset( $GLOBALS['wp_local_package'] ) ) { $language = $GLOBALS['wp_local_package']; } switch($step) { case -1: if ( wp_can_install_language_pack() && empty( $language ) && ( $languages = wp_get_available_translations() ) ) { setup_config_display_header( 'language-chooser' ); echo '<form id="setup" method="post" action="?step=0">'; wp_install_language_form( $languages ); echo '</form>'; break; } // Deliberately fall through if we can't reach the translations API. case 0: if ( ! empty( $language ) ) { $loaded_language = wp_download_language_pack( $language ); if ( $loaded_language ) { load_default_textdomain( $loaded_language ); $GLOBALS['wp_locale'] = new WP_Locale(); } } setup_config_display_header(); $step_1 = 'setup-config.php?step=1'; if ( isset( $_REQUEST['noapi'] ) ) { $step_1 .= '&amp;noapi'; } if ( ! empty( $loaded_language ) ) { $step_1 .= '&amp;language=' . $loaded_language; } ?> <p><?php _e( 'Welcome to WordPress. Before getting started, we need some information on the database. You will need to know the following items before proceeding.' ) ?></p> <ol> <li><?php _e( 'Database name' ); ?></li> <li><?php _e( 'Database username' ); ?></li> <li><?php _e( 'Database password' ); ?></li> <li><?php _e( 'Database host' ); ?></li> <li><?php _e( 'Table prefix (if you want to run more than one WordPress in a single database)' ); ?></li> </ol> <p> <?php _e( 'We&#8217;re going to use this information to create a <code>wp-config.php</code> file.' ); ?> <strong><?php _e( "If for any reason this automatic file creation doesn&#8217;t work, don&#8217;t worry. All this does is fill in the database information to a configuration file. You may also simply open <code>wp-config-sample.php</code> in a text editor, fill in your information, and save it as <code>wp-config.php</code>." ); ?></strong> <?php _e( "Need more help? <a href='https://codex.wordpress.org/Editing_wp-config.php'>We got it</a>." ); ?> </p> <p><?php _e( "In all likelihood, these items were supplied to you by your Web Host. If you do not have this information, then you will need to contact them before you can continue. If you&#8217;re all ready&hellip;" ); ?></p> <p class="step"><a href="<?php echo $step_1; ?>" class="button button-large"><?php _e( 'Let&#8217;s go!' ); ?></a></p> <?php break; case 1: load_default_textdomain( $language ); $GLOBALS['wp_locale'] = new WP_Locale(); setup_config_display_header(); ?> <form method="post" action="setup-config.php?step=2"> <p><?php _e( "Below you should enter your database connection details. If you&#8217;re not sure about these, contact your host." ); ?></p> <table class="form-table"> <tr> <th scope="row"><label for="dbname"><?php _e( 'Database Name' ); ?></label></th> <td><input name="dbname" id="dbname" type="text" size="25" value="wordpress" /></td> <td><?php _e( 'The name of the database you want to run WP in.' ); ?></td> </tr> <tr> <th scope="row"><label for="uname"><?php _e( 'User Name' ); ?></label></th> <td><input name="uname" id="uname" type="text" size="25" value="<?php echo htmlspecialchars( _x( 'username', 'example username' ), ENT_QUOTES ); ?>" /></td> <td><?php _e( 'Your MySQL username' ); ?></td> </tr> <tr> <th scope="row"><label for="pwd"><?php _e( 'Password' ); ?></label></th> <td><input name="pwd" id="pwd" type="text" size="25" value="<?php echo htmlspecialchars( _x( 'password', 'example password' ), ENT_QUOTES ); ?>" autocomplete="off" /></td> <td><?php _e( '&hellip;and your MySQL password.' ); ?></td> </tr> <tr> <th scope="row"><label for="dbhost"><?php _e( 'Database Host' ); ?></label></th> <td><input name="dbhost" id="dbhost" type="text" size="25" value="localhost" /></td> <td><?php _e( 'You should be able to get this info from your web host, if <code>localhost</code> does not work.' ); ?></td> </tr> <tr> <th scope="row"><label for="prefix"><?php _e( 'Table Prefix' ); ?></label></th> <td><input name="prefix" id="prefix" type="text" value="wp_" size="25" /></td> <td><?php _e( 'If you want to run multiple WordPress installations in a single database, change this.' ); ?></td> </tr> </table> <?php if ( isset( $_GET['noapi'] ) ) { ?><input name="noapi" type="hidden" value="1" /><?php } ?> <input type="hidden" name="language" value="<?php echo esc_attr( $language ); ?>" /> <p class="step"><input name="submit" type="submit" value="<?php echo htmlspecialchars( __( 'Submit' ), ENT_QUOTES ); ?>" class="button button-large" /></p> </form> <?php break; case 2: load_default_textdomain( $language ); $GLOBALS['wp_locale'] = new WP_Locale(); $dbname = trim( wp_unslash( $_POST[ 'dbname' ] ) ); $uname = trim( wp_unslash( $_POST[ 'uname' ] ) ); $pwd = trim( wp_unslash( $_POST[ 'pwd' ] ) ); $dbhost = trim( wp_unslash( $_POST[ 'dbhost' ] ) ); $prefix = trim( wp_unslash( $_POST[ 'prefix' ] ) ); $step_1 = 'setup-config.php?step=1'; $install = 'install.php'; if ( isset( $_REQUEST['noapi'] ) ) { $step_1 .= '&amp;noapi'; } if ( ! empty( $language ) ) { $step_1 .= '&amp;language=' . $language; $install .= '?language=' . $language; } else { $install .= '?language=en_US'; } $tryagain_link = '</p><p class="step"><a href="' . $step_1 . '" onclick="javascript:history.go(-1);return false;" class="button button-large">' . __( 'Try again' ) . '</a>'; if ( empty( $prefix ) ) wp_die( __( '<strong>ERROR</strong>: "Table Prefix" must not be empty.' . $tryagain_link ) ); // Validate $prefix: it can only contain letters, numbers and underscores. if ( preg_match( '|[^a-z0-9_]|i', $prefix ) ) wp_die( __( '<strong>ERROR</strong>: "Table Prefix" can only contain numbers, letters, and underscores.' . $tryagain_link ) ); // Test the db connection. /**#@+ * @ignore */ define('DB_NAME', $dbname); define('DB_USER', $uname); define('DB_PASSWORD', $pwd); define('DB_HOST', $dbhost); /**#@-*/ // Re-construct $wpdb with these new values. unset( $wpdb ); require_wp_db(); /* * The wpdb constructor bails when WP_SETUP_CONFIG is set, so we must * fire this manually. We'll fail here if the values are no good. */ $wpdb->db_connect(); if ( ! empty( $wpdb->error ) ) wp_die( $wpdb->error->get_error_message() . $tryagain_link ); // Fetch or generate keys and salts. $no_api = isset( $_POST['noapi'] ); if ( ! $no_api ) { $secret_keys = wp_remote_get( 'https://api.wordpress.org/secret-key/1.1/salt/' ); } if ( $no_api || is_wp_error( $secret_keys ) ) { $secret_keys = array(); for ( $i = 0; $i < 8; $i++ ) { $secret_keys[] = wp_generate_password( 64, true, true ); } } else { $secret_keys = explode( "\n", wp_remote_retrieve_body( $secret_keys ) ); foreach ( $secret_keys as $k => $v ) { $secret_keys[$k] = substr( $v, 28, 64 ); } } $key = 0; // Not a PHP5-style by-reference foreach, as this file must be parseable by PHP4. foreach ( $config_file as $line_num => $line ) { if ( '$table_prefix =' == substr( $line, 0, 16 ) ) { $config_file[ $line_num ] = '$table_prefix = \'' . addcslashes( $prefix, "\\'" ) . "';\r\n"; continue; } if ( ! preg_match( '/^define\(\'([A-Z_]+)\',([ ]+)/', $line, $match ) ) continue; $constant = $match[1]; $padding = $match[2]; switch ( $constant ) { case 'DB_NAME' : case 'DB_USER' : case 'DB_PASSWORD' : case 'DB_HOST' : $config_file[ $line_num ] = "define('" . $constant . "'," . $padding . "'" . addcslashes( constant( $constant ), "\\'" ) . "');\r\n"; break; case 'DB_CHARSET' : if ( 'utf8mb4' === $wpdb->charset || ( ! $wpdb->charset && $wpdb->has_cap( 'utf8mb4' ) ) ) { $config_file[ $line_num ] = "define('" . $constant . "'," . $padding . "'utf8mb4');\r\n"; } break; case 'AUTH_KEY' : case 'SECURE_AUTH_KEY' : case 'LOGGED_IN_KEY' : case 'NONCE_KEY' : case 'AUTH_SALT' : case 'SECURE_AUTH_SALT' : case 'LOGGED_IN_SALT' : case 'NONCE_SALT' : $config_file[ $line_num ] = "define('" . $constant . "'," . $padding . "'" . $secret_keys[$key++] . "');\r\n"; break; } } unset( $line ); if ( ! is_writable(ABSPATH) ) : setup_config_display_header(); ?> <p><?php _e( "Sorry, but I can&#8217;t write the <code>wp-config.php</code> file." ); ?></p> <p><?php _e( 'You can create the <code>wp-config.php</code> manually and paste the following text into it.' ); ?></p> <textarea id="wp-config" cols="98" rows="15" class="code" readonly="readonly"><?php foreach( $config_file as $line ) { echo htmlentities($line, ENT_COMPAT, 'UTF-8'); } ?></textarea> <p><?php _e( 'After you&#8217;ve done that, click &#8220;Run the install.&#8221;' ); ?></p> <p class="step"><a href="<?php echo $install; ?>" class="button button-large"><?php _e( 'Run the install' ); ?></a></p> <script> (function(){ if ( ! /iPad|iPod|iPhone/.test( navigator.userAgent ) ) { var el = document.getElementById('wp-config'); el.focus(); el.select(); } })(); </script> <?php else : /* * If this file doesn't exist, then we are using the wp-config-sample.php * file one level up, which is for the develop repo. */ if ( file_exists( ABSPATH . 'wp-config-sample.php' ) ) $path_to_wp_config = ABSPATH . 'wp-config.php'; else $path_to_wp_config = dirname( ABSPATH ) . '/wp-config.php'; $handle = fopen( $path_to_wp_config, 'w' ); foreach( $config_file as $line ) { fwrite( $handle, $line ); } fclose( $handle ); chmod( $path_to_wp_config, 0666 ); setup_config_display_header(); ?> <p><?php _e( "All right, sparky! You&#8217;ve made it through this part of the installation. WordPress can now communicate with your database. If you are ready, time now to&hellip;" ); ?></p> <p class="step"><a href="<?php echo $install; ?>" class="button button-large"><?php _e( 'Run the install' ); ?></a></p> <?php endif; break; } ?> <?php wp_print_scripts( 'language-chooser' ); ?> </body> </html>
casedot/AllYourBaseTemplate
wp-admin/setup-config.php
PHP
gpl-2.0
13,802
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.beans.tests.support.mock; public class MockNullSubClass extends MockNullSuperClass{ }
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/beans/src/test/support/java/org/apache/harmony/beans/tests/support/mock/MockNullSubClass.java
Java
gpl-2.0
943
/** * $RCSfile$ * $Revision: $ * $Date: $ * * Copyright (C) 2006 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.multiplexer; import org.dom4j.Element; import org.dom4j.io.XMPPPacketReader; import org.jivesoftware.multiplexer.net.SocketConnection; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.Log; import java.io.IOException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Reads and processes stanzas sent from the server. Each connection to the server will * have an instance of this class. Read packets will be processed using a thread pool. * By default, the thread pool will have 5 processing threads. Configure the property * <tt>xmpp.manager.incoming.threads</tt> to change the number of processing threads * per connection to the server. * * @author Gaston Dombiak */ class ServerPacketReader implements SocketStatistic { private boolean open = true; private XMPPPacketReader reader = null; /** * Pool of threads that will process incoming stanzas from the server. */ private ThreadPoolExecutor threadPool; /** * Actual object responsible for handling incoming traffic. */ private ServerPacketHandler packetsHandler; public ServerPacketReader(XMPPPacketReader reader, SocketConnection connection, String address) { this.reader = reader; packetsHandler = new ServerPacketHandler(connection, address); init(); } private void init() { // Create a pool of threads that will process incoming packets. int maxThreads = JiveGlobals.getIntProperty("xmpp.manager.incoming.threads", 5); if (maxThreads < 1) { // Ensure that the max number of threads in the pool is at least 1 maxThreads = 1; } threadPool = new ThreadPoolExecutor(maxThreads, maxThreads, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy()); // Create a thread that will read and store DOM Elements. Thread thread = new Thread("Server Packet Reader") { public void run() { while (open) { Element doc; try { doc = reader.parseDocument().getRootElement(); if (doc == null) { // Stop reading the stream since the remote server has sent an end of // stream element and probably closed the connection. shutdown(); } else { // Queue task that process incoming stanzas threadPool.execute(new ProcessStanzaTask(packetsHandler, doc)); } } catch (IOException e) { Log.debug("Finishing Incoming Server Stanzas Reader.", e); shutdown(); } catch (Exception e) { Log.error("Finishing Incoming Server Stanzas Reader.", e); shutdown(); } } } }; thread.setDaemon(true); thread.start(); } public long getLastActive() { return reader.getLastActive(); } public void shutdown() { open = false; threadPool.shutdown(); } /** * Task that processes incoming stanzas from the server. */ private class ProcessStanzaTask implements Runnable { /** * Incoming stanza to process. */ private Element stanza; /** * Actual object responsible for handling incoming traffic. */ private ServerPacketHandler handler; public ProcessStanzaTask(ServerPacketHandler handler, Element stanza) { this.handler = handler; this.stanza = stanza; } public void run() { handler.handle(stanza); } } }
xiupitter/XiuConnectionManager
src/java/org/jivesoftware/multiplexer/ServerPacketReader.java
Java
gpl-2.0
4,394
<?php /** * Canadian states * * @author WooThemes * @category i18n * @package WooCommerce/i18n * @version 2.0.0 */ global $states; $states['CA'] = array( 'AB' => __( 'Alberta', 'woocommerce' ), 'BC' => __( 'British Columbia', 'woocommerce' ), 'MB' => __( 'Manitoba', 'woocommerce' ), 'NB' => __( 'New Brunswick', 'woocommerce' ), 'NL' => __( 'Newfoundland', 'woocommerce' ), 'NT' => __( 'Northwest Territories', 'woocommerce' ), 'NS' => __( 'Nova Scotia', 'woocommerce' ), 'NU' => __( 'Nunavut', 'woocommerce' ), 'ON' => __( 'Ontario', 'woocommerce' ), 'PE' => __( 'Prince Edward Island', 'woocommerce' ), 'QC' => __( 'Quebec', 'woocommerce' ), 'SK' => __( 'Saskatchewan', 'woocommerce' ), 'YT' => __( 'Yukon Territory', 'woocommerce' ) );
mickburgs/sjaaktramper
wp-content/plugins/woocommerce/i18n/states/CA.php
PHP
gpl-2.0
795
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.oscarMessenger.pageUtil; import java.io.IOException; import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.oscarehr.managers.SecurityInfoManager; import org.oscarehr.util.LoggedInInfo; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.SpringUtils; import oscar.util.Doc2PDF; public class MsgViewPDFAction extends Action { private SecurityInfoManager securityInfoManager = SpringUtils.getBean(SecurityInfoManager.class); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { MsgViewPDFForm frm = (MsgViewPDFForm) form; if(!securityInfoManager.hasPrivilege(LoggedInInfo.getLoggedInInfoFromSession(request), "_msg", "r", null)) { throw new SecurityException("missing required security object (_msg)"); } try { String pdfAttachment = ( String) request.getSession().getAttribute("PDFAttachment"); String id = frm.getFile_id(); int fileID = Integer.parseInt(id ); if ( pdfAttachment != null && pdfAttachment.length() != 0) { Vector attVector = Doc2PDF.getXMLTagValue(pdfAttachment, "CONTENT" ); String pdfFile = ( String) attVector.elementAt(fileID); Doc2PDF.PrintPDFFromBin ( response, pdfFile ); } } catch(Exception e) { MiscUtils.getLogger().error("Error", e); return ( mapping.findForward("success")); } return ( mapping.findForward("success")); } }
scoophealth/oscar
src/main/java/oscar/oscarMessenger/pageUtil/MsgViewPDFAction.java
Java
gpl-2.0
2,991
<?php /** * Indonesia Provinces * * Credit to WooThemes, mikejolly and shivapoudel. This is shamelessly based on their implementation in WooCommerce. * * @since 1.0.0 * @package Charitable/i18n * @author Eric Daams * @copyright Copyright (c) 2015, Studio 164a * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License */ return array( 'AC' => __( 'Daerah Istimewa Aceh', 'charitable' ), 'SU' => __( 'Sumatera Utara', 'charitable' ), 'SB' => __( 'Sumatera Barat', 'charitable' ), 'RI' => __( 'Riau', 'charitable' ), 'KR' => __( 'Kepulauan Riau', 'charitable' ), 'JA' => __( 'Jambi', 'charitable' ), 'SS' => __( 'Sumatera Selatan', 'charitable' ), 'BB' => __( 'Bangka Belitung', 'charitable' ), 'BE' => __( 'Bengkulu', 'charitable' ), 'LA' => __( 'Lampung', 'charitable' ), 'JK' => __( 'DKI Jakarta', 'charitable' ), 'JB' => __( 'Jawa Barat', 'charitable' ), 'BT' => __( 'Banten', 'charitable' ), 'JT' => __( 'Jawa Tengah', 'charitable' ), 'JI' => __( 'Jawa Timur', 'charitable' ), 'YO' => __( 'Daerah Istimewa Yogyakarta', 'charitable' ), 'BA' => __( 'Bali', 'charitable' ), 'NB' => __( 'Nusa Tenggara Barat', 'charitable' ), 'NT' => __( 'Nusa Tenggara Timur', 'charitable' ), 'KB' => __( 'Kalimantan Barat', 'charitable' ), 'KT' => __( 'Kalimantan Tengah', 'charitable' ), 'KI' => __( 'Kalimantan Timur', 'charitable' ), 'KS' => __( 'Kalimantan Selatan', 'charitable' ), 'KU' => __( 'Kalimantan Utara', 'charitable' ), 'SA' => __( 'Sulawesi Utara', 'charitable' ), 'ST' => __( 'Sulawesi Tengah', 'charitable' ), 'SG' => __( 'Sulawesi Tenggara', 'charitable' ), 'SR' => __( 'Sulawesi Barat', 'charitable' ), 'SN' => __( 'Sulawesi Selatan', 'charitable' ), 'GO' => __( 'Gorontalo', 'charitable' ), 'MA' => __( 'Maluku', 'charitable' ), 'MU' => __( 'Maluku Utara', 'charitable' ), 'PA' => __( 'Papua', 'charitable' ), 'PB' => __( 'Papua Barat', 'charitable' ) );
ajumapao/team-hunatv1
wp-content/plugins/charitable/i18n/states/ID.php
PHP
gpl-2.0
1,931
/* * Copyright (C) 2005-2008 Team XBMC * http://www.xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include "system.h" #include "GUIWindowVideoBase.h" #include "Util.h" #include "video/VideoInfoDownloader.h" #include "utils/RegExp.h" #include "utils/Variant.h" #include "addons/AddonManager.h" #include "addons/IAddon.h" #include "video/dialogs/GUIDialogVideoInfo.h" #include "GUIWindowVideoNav.h" #include "dialogs/GUIDialogFileBrowser.h" #include "video/dialogs/GUIDialogVideoScan.h" #include "dialogs/GUIDialogSmartPlaylistEditor.h" #include "dialogs/GUIDialogProgress.h" #include "dialogs/GUIDialogYesNo.h" #include "playlists/PlayListFactory.h" #include "Application.h" #include "NfoFile.h" #include "PlayListPlayer.h" #include "GUIPassword.h" #include "filesystem/ZipManager.h" #include "filesystem/StackDirectory.h" #include "filesystem/MultiPathDirectory.h" #include "video/dialogs/GUIDialogFileStacking.h" #include "dialogs/GUIDialogMediaSource.h" #include "windows/GUIWindowFileManager.h" #include "filesystem/VideoDatabaseDirectory.h" #include "PartyModeManager.h" #include "guilib/GUIWindowManager.h" #include "dialogs/GUIDialogOK.h" #include "dialogs/GUIDialogSelect.h" #include "dialogs/GUIDialogKeyboard.h" #include "filesystem/Directory.h" #include "playlists/PlayList.h" #include "settings/Settings.h" #include "settings/AdvancedSettings.h" #include "settings/GUISettings.h" #include "settings/GUIDialogContentSettings.h" #include "guilib/LocalizeStrings.h" #include "utils/StringUtils.h" #include "utils/log.h" #include "utils/FileUtils.h" #include "interfaces/AnnouncementManager.h" #include "pvr/PVRManager.h" #include "pvr/recordings/PVRRecordings.h" #include "utils/URIUtils.h" #include "GUIUserMessages.h" #include "addons/Skin.h" #include "storage/MediaManager.h" #include "Autorun.h" using namespace std; using namespace XFILE; using namespace PLAYLIST; using namespace VIDEODATABASEDIRECTORY; using namespace VIDEO; using namespace ADDON; using namespace PVR; #define CONTROL_BTNVIEWASICONS 2 #define CONTROL_BTNSORTBY 3 #define CONTROL_BTNSORTASC 4 #define CONTROL_BTNTYPE 5 #define CONTROL_LABELFILES 12 #define CONTROL_PLAY_DVD 6 #define CONTROL_STACK 7 #define CONTROL_BTNSCAN 8 CGUIWindowVideoBase::CGUIWindowVideoBase(int id, const CStdString &xmlFile) : CGUIMediaWindow(id, xmlFile) { m_thumbLoader.SetObserver(this); m_thumbLoader.SetStreamDetailsObserver(this); m_stackingAvailable = true; } CGUIWindowVideoBase::~CGUIWindowVideoBase() { } bool CGUIWindowVideoBase::OnAction(const CAction &action) { if (action.GetID() == ACTION_SCAN_ITEM) return OnContextButton(m_viewControl.GetSelectedItem(),CONTEXT_BUTTON_SCAN); return CGUIMediaWindow::OnAction(action); } bool CGUIWindowVideoBase::OnMessage(CGUIMessage& message) { switch ( message.GetMessage() ) { case GUI_MSG_WINDOW_DEINIT: if (m_thumbLoader.IsLoading()) m_thumbLoader.StopThread(); m_database.Close(); break; case GUI_MSG_WINDOW_INIT: { m_database.Open(); m_dlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS); // save current window, unless the current window is the video playlist window if (GetID() != WINDOW_VIDEO_PLAYLIST && g_settings.m_iVideoStartWindow != GetID()) { g_settings.m_iVideoStartWindow = GetID(); g_settings.Save(); } return CGUIMediaWindow::OnMessage(message); } break; case GUI_MSG_CLICKED: { int iControl = message.GetSenderId(); if (iControl == CONTROL_STACK) { g_settings.m_videoStacking = !g_settings.m_videoStacking; g_settings.Save(); UpdateButtons(); Update( m_vecItems->GetPath() ); } #if defined(HAS_DVD_DRIVE) else if (iControl == CONTROL_PLAY_DVD) { // play movie... MEDIA_DETECT::CAutorun::PlayDiscAskResume(g_mediaManager.TranslateDevicePath("")); } #endif else if (iControl == CONTROL_BTNTYPE) { CGUIMessage msg(GUI_MSG_ITEM_SELECTED, GetID(), CONTROL_BTNTYPE); g_windowManager.SendMessage(msg); int nSelected = msg.GetParam1(); int nNewWindow = WINDOW_VIDEO_FILES; switch (nSelected) { case 0: // Movies nNewWindow = WINDOW_VIDEO_FILES; break; case 1: // Library nNewWindow = WINDOW_VIDEO_NAV; break; } if (nNewWindow != GetID()) { g_settings.m_iVideoStartWindow = nNewWindow; g_settings.Save(); g_windowManager.ChangeActiveWindow(nNewWindow); CGUIMessage msg2(GUI_MSG_SETFOCUS, nNewWindow, CONTROL_BTNTYPE); g_windowManager.SendMessage(msg2); } return true; } else if (m_viewControl.HasControl(iControl)) // list/thumb control { // get selected item int iItem = m_viewControl.GetSelectedItem(); int iAction = message.GetParam1(); // iItem is checked for validity inside these routines if (iAction == ACTION_QUEUE_ITEM || iAction == ACTION_MOUSE_MIDDLE_CLICK) { OnQueueItem(iItem); return true; } else if (iAction == ACTION_SHOW_INFO) { return OnInfo(iItem); } else if (iAction == ACTION_PLAYER_PLAY && !g_application.IsPlayingVideo()) { return OnResumeItem(iItem); } else if (iAction == ACTION_DELETE_ITEM) { // is delete allowed? if (g_settings.GetCurrentProfile().canWriteDatabases()) { // must be at the title window if (GetID() == WINDOW_VIDEO_NAV) OnDeleteItem(iItem); // or be at the files window and have file deletion enabled else if (GetID() == WINDOW_VIDEO_FILES && g_guiSettings.GetBool("filelists.allowfiledeletion")) OnDeleteItem(iItem); // or be at the video playlists location else if (m_vecItems->GetPath().Equals("special://videoplaylists/")) OnDeleteItem(iItem); else return false; return true; } } } } break; case GUI_MSG_SEARCH: OnSearch(); break; } return CGUIMediaWindow::OnMessage(message); } void CGUIWindowVideoBase::UpdateButtons() { // Remove labels from the window selection CGUIMessage msg(GUI_MSG_LABEL_RESET, GetID(), CONTROL_BTNTYPE); g_windowManager.SendMessage(msg); // Add labels to the window selection CStdString strItem = g_localizeStrings.Get(744); // Files CGUIMessage msg2(GUI_MSG_LABEL_ADD, GetID(), CONTROL_BTNTYPE); msg2.SetLabel(strItem); g_windowManager.SendMessage(msg2); strItem = g_localizeStrings.Get(14022); // Library msg2.SetLabel(strItem); g_windowManager.SendMessage(msg2); // Select the current window as default item int nWindow = g_settings.m_iVideoStartWindow-WINDOW_VIDEO_FILES; CONTROL_SELECT_ITEM(CONTROL_BTNTYPE, nWindow); CONTROL_ENABLE(CONTROL_BTNSCAN); SET_CONTROL_LABEL(CONTROL_STACK, 14000); // Stack SET_CONTROL_SELECTED(GetID(), CONTROL_STACK, g_settings.m_videoStacking); CONTROL_ENABLE_ON_CONDITION(CONTROL_STACK, m_stackingAvailable); CGUIMediaWindow::UpdateButtons(); } void CGUIWindowVideoBase::OnInfo(CFileItem* pItem, const ADDON::ScraperPtr& scraper) { if (!pItem) return; if (pItem->IsParentFolder() || pItem->m_bIsShareOrDrive || pItem->GetPath().Equals("add") || (pItem->IsPlayList() && !URIUtils::GetExtension(pItem->GetPath()).Equals(".strm"))) return; // ShowIMDB can kill the item as this window can be closed while we do it, // so take a copy of the item now CFileItem item(*pItem); if (item.IsVideoDb() && item.HasVideoInfoTag()) { item.SetPath(item.GetVideoInfoTag()->GetPath()); } else { if (item.m_bIsFolder && scraper && scraper->Content() != CONTENT_TVSHOWS) { CFileItemList items; CDirectory::GetDirectory(item.GetPath(), items, g_settings.m_videoExtensions,true,false,DIR_CACHE_ONCE,true,true); items.Stack(); // check for media files bool bFoundFile(false); for (int i = 0; i < items.Size(); ++i) { CFileItemPtr item2 = items[i]; if (item2->IsVideo() && !item2->IsPlayList() && !CUtil::ExcludeFileOrFolder(item2->GetPath(), g_advancedSettings.m_moviesExcludeFromScanRegExps)) { item.SetPath(item2->GetPath()); item.m_bIsFolder = false; bFoundFile = true; break; } } // no video file in this folder if (!bFoundFile) { CGUIDialogOK::ShowAndGetInput(13346,20349,20022,20022); return; } } } // we need to also request any thumbs be applied to the folder item if (pItem->m_bIsFolder) item.SetProperty("set_folder_thumb", pItem->GetPath()); bool modified = ShowIMDB(&item, scraper); if (modified && (g_windowManager.GetActiveWindow() == WINDOW_VIDEO_FILES || g_windowManager.GetActiveWindow() == WINDOW_VIDEO_NAV)) // since we can be called from the music library we need this check { int itemNumber = m_viewControl.GetSelectedItem(); Update(m_vecItems->GetPath()); m_viewControl.SetSelectedItem(itemNumber); } } // ShowIMDB is called as follows: // 1. To lookup info on a file. // 2. To lookup info on a folder (which may or may not contain a file) // 3. To lookup info just for fun (no file or folder related) // We just need the item object for this. // A "blank" item object is sent for 3. // If a folder is sent, currently it sets strFolder and bFolder // this is only used for setting the folder thumb, however. // Steps should be: // 1. Check database to see if we have this information already // 2. Else, check for a nfoFile to get the URL // 3. Run a loop to check for refresh // 4. If no URL is present do a search to get the URL // 4. Once we have the URL, download the details // 5. Once we have the details, add to the database if necessary (case 1,2) // and show the information. // 6. Check for a refresh, and if so, go to 3. bool CGUIWindowVideoBase::ShowIMDB(CFileItem *item, const ScraperPtr &info2) { /* CLog::Log(LOGDEBUG,"CGUIWindowVideoBase::ShowIMDB"); CLog::Log(LOGDEBUG," strMovie = [%s]", strMovie.c_str()); CLog::Log(LOGDEBUG," strFile = [%s]", strFile.c_str()); CLog::Log(LOGDEBUG," strFolder = [%s]", strFolder.c_str()); CLog::Log(LOGDEBUG," bFolder = [%s]", ((int)bFolder ? "true" : "false")); */ CGUIDialogProgress* pDlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS); CGUIDialogSelect* pDlgSelect = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT); CGUIDialogVideoInfo* pDlgInfo = (CGUIDialogVideoInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_INFO); ScraperPtr info(info2); // use this as nfo might change it.. if (!pDlgProgress) return false; if (!pDlgSelect) return false; if (!pDlgInfo) return false; // 1. Check for already downloaded information, and if we have it, display our dialog // Return if no Refresh is needed. bool bHasInfo=false; CVideoInfoTag movieDetails; movieDetails.Reset(); if (info) { m_database.Open(); // since we can be called from the music library if (info->Content() == CONTENT_MOVIES) { bHasInfo = m_database.GetMovieInfo(item->GetPath(), movieDetails); } if (info->Content() == CONTENT_TVSHOWS) { if (item->m_bIsFolder) { bHasInfo = m_database.GetTvShowInfo(item->GetPath(), movieDetails); } else { int EpisodeHint=-1; if (item->HasVideoInfoTag()) EpisodeHint = item->GetVideoInfoTag()->m_iEpisode; int idEpisode=-1; if ((idEpisode = m_database.GetEpisodeId(item->GetPath(),EpisodeHint)) > -1) { bHasInfo = true; m_database.GetEpisodeInfo(item->GetPath(), movieDetails, idEpisode); } else { // !! WORKAROUND !! // As we cannot add an episode to a non-existing tvshow entry, we have to check the parent directory // to see if it`s already in our video database. If it's not yet part of the database we will exit here. // (Ticket #4764) // // NOTE: This will fail for episodes on multipath shares, as the parent path isn't what is stored in the // database. Possible solutions are to store the paths in the db separately and rely on the show // stacking stuff, or to modify GetTvShowId to do support multipath:// shares CStdString strParentDirectory; URIUtils::GetParentPath(item->GetPath(), strParentDirectory); if (m_database.GetTvShowId(strParentDirectory) < 0) { CLog::Log(LOGERROR,"%s: could not add episode [%s]. tvshow does not exist yet..", __FUNCTION__, item->GetPath().c_str()); return false; } } } } if (info->Content() == CONTENT_MUSICVIDEOS) { bHasInfo = m_database.GetMusicVideoInfo(item->GetPath(), movieDetails); } m_database.Close(); } else if(item->HasVideoInfoTag()) { bHasInfo = true; movieDetails = *item->GetVideoInfoTag(); } bool needsRefresh = false; if (bHasInfo) { if (!info || info->Content() == CONTENT_NONE) // disable refresh button movieDetails.m_strIMDBNumber = "xx"+movieDetails.m_strIMDBNumber; *item->GetVideoInfoTag() = movieDetails; pDlgInfo->SetMovie(item); pDlgInfo->DoModal(); needsRefresh = pDlgInfo->NeedRefresh(); if (!needsRefresh) return pDlgInfo->HasUpdatedThumb(); } // quietly return if Internet lookups are disabled if (!g_settings.GetCurrentProfile().canWriteDatabases() && !g_passwordManager.bMasterUser) return false; if(!info) return false; CGUIDialogVideoScan* pDialog = (CGUIDialogVideoScan*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN); if (pDialog && pDialog->IsScanning()) { CGUIDialogOK::ShowAndGetInput(13346,14057,-1,-1); return false; } m_database.Open(); // 2. Look for a nfo File to get the search URL SScanSettings settings; info = m_database.GetScraperForPath(item->GetPath(),settings); if (!info) return false; // Get the correct movie title CStdString movieName = item->GetMovieName(settings.parent_name); CScraperUrl scrUrl; CVideoInfoScanner scanner; bool hasDetails = false; bool listNeedsUpdating = false; bool ignoreNfo = false; // 3. Run a loop so that if we Refresh we re-run this block do { if (!ignoreNfo) { CNfoFile::NFOResult nfoResult = scanner.CheckForNFOFile(item,settings.parent_name_root,info,scrUrl); if (nfoResult == CNfoFile::ERROR_NFO) ignoreNfo = true; else if (nfoResult != CNfoFile::NO_NFO) hasDetails = true; if (needsRefresh) { bHasInfo = true; if (nfoResult == CNfoFile::URL_NFO || nfoResult == CNfoFile::COMBINED_NFO || nfoResult == CNfoFile::FULL_NFO) { if (CGUIDialogYesNo::ShowAndGetInput(13346,20446,20447,20022)) { hasDetails = false; ignoreNfo = true; scrUrl.Clear(); info = info2; } } } } // 4. if we don't have an url, or need to refresh the search // then do the web search MOVIELIST movielist; if (info->Content() == CONTENT_TVSHOWS && !item->m_bIsFolder) hasDetails = true; if (!hasDetails && (scrUrl.m_url.size() == 0 || needsRefresh)) { // 4a. show dialog that we're busy querying www.imdb.com CStdString strHeading; strHeading.Format(g_localizeStrings.Get(197),info->Name().c_str()); pDlgProgress->SetHeading(strHeading); pDlgProgress->SetLine(0, movieName); pDlgProgress->SetLine(1, ""); pDlgProgress->SetLine(2, ""); pDlgProgress->StartModal(); pDlgProgress->Progress(); // 4b. do the websearch info->ClearCache(); CVideoInfoDownloader imdb(info); int returncode = imdb.FindMovie(movieName, movielist, pDlgProgress); if (returncode > 0) { pDlgProgress->Close(); if (movielist.size() > 0) { int iString = 196; if (info->Content() == CONTENT_TVSHOWS) iString = 20356; pDlgSelect->SetHeading(iString); pDlgSelect->Reset(); for (unsigned int i = 0; i < movielist.size(); ++i) pDlgSelect->Add(movielist[i].strTitle); pDlgSelect->EnableButton(true, 413); // manual pDlgSelect->DoModal(); // and wait till user selects one int iSelectedMovie = pDlgSelect->GetSelectedLabel(); if (iSelectedMovie >= 0) { scrUrl = movielist[iSelectedMovie]; CLog::Log(LOGDEBUG, "%s: user selected movie '%s' with URL '%s'", __FUNCTION__, scrUrl.strTitle.c_str(), scrUrl.m_url[0].m_url.c_str()); } else if (!pDlgSelect->IsButtonPressed()) { m_database.Close(); return listNeedsUpdating; // user backed out } } } else if (returncode == -1 || !CVideoInfoScanner::DownloadFailed(pDlgProgress)) { pDlgProgress->Close(); return false; } } // 4c. Check if url is still empty - occurs if user has selected to do a manual // lookup, or if the IMDb lookup failed or was cancelled. if (!hasDetails && scrUrl.m_url.size() == 0) { // Check for cancel of the progress dialog pDlgProgress->Close(); if (pDlgProgress->IsCanceled()) { m_database.Close(); return listNeedsUpdating; } // Prompt the user to input the movieName int iString = 16009; if (info->Content() == CONTENT_TVSHOWS) iString = 20357; if (!CGUIDialogKeyboard::ShowAndGetInput(movieName, g_localizeStrings.Get(iString), false)) { m_database.Close(); return listNeedsUpdating; // user backed out } needsRefresh = true; } else { // 5. Download the movie information // show dialog that we're downloading the movie info CFileItemList list; CStdString strPath=item->GetPath(); if (item->IsVideoDb()) { CFileItemPtr newItem(new CFileItem(*item->GetVideoInfoTag())); list.Add(newItem); strPath = item->GetVideoInfoTag()->m_strPath; } else { CFileItemPtr newItem(new CFileItem(*item)); list.Add(newItem); } if (item->m_bIsFolder) list.SetPath(URIUtils::GetParentPath(strPath)); else { CStdString path; URIUtils::GetDirectory(strPath, path); list.SetPath(path); } int iString=198; if (info->Content() == CONTENT_TVSHOWS) { if (item->m_bIsFolder) iString = 20353; else iString = 20361; } if (info->Content() == CONTENT_MUSICVIDEOS) iString = 20394; pDlgProgress->SetHeading(iString); pDlgProgress->SetLine(0, movieName); pDlgProgress->SetLine(1, scrUrl.strTitle); pDlgProgress->SetLine(2, ""); pDlgProgress->StartModal(); pDlgProgress->Progress(); if (bHasInfo) { if (info->Content() == CONTENT_MOVIES) m_database.DeleteMovie(item->GetPath()); if (info->Content() == CONTENT_TVSHOWS && !item->m_bIsFolder) m_database.DeleteEpisode(item->GetPath(),movieDetails.m_iDbId); if (info->Content() == CONTENT_MUSICVIDEOS) m_database.DeleteMusicVideo(item->GetPath()); if (info->Content() == CONTENT_TVSHOWS && item->m_bIsFolder) { if (pDlgInfo->RefreshAll()) m_database.DeleteTvShow(item->GetPath()); else m_database.DeleteDetailsForTvShow(item->GetPath()); } } if (scanner.RetrieveVideoInfo(list,settings.parent_name_root,info->Content(),!ignoreNfo,&scrUrl,pDlgInfo->RefreshAll(),pDlgProgress)) { if (info->Content() == CONTENT_MOVIES) m_database.GetMovieInfo(item->GetPath(),movieDetails); if (info->Content() == CONTENT_MUSICVIDEOS) m_database.GetMusicVideoInfo(item->GetPath(),movieDetails); if (info->Content() == CONTENT_TVSHOWS) { // update tvshow info to get updated episode numbers if (item->m_bIsFolder) m_database.GetTvShowInfo(item->GetPath(),movieDetails); else m_database.GetEpisodeInfo(item->GetPath(),movieDetails); } // got all movie details :-) OutputDebugString("got details\n"); pDlgProgress->Close(); // now show the imdb info OutputDebugString("show info\n"); // remove directory caches and reload images CUtil::DeleteVideoDatabaseDirectoryCache(); CGUIMessage reload(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_REFRESH_THUMBS); OnMessage(reload); *item->GetVideoInfoTag() = movieDetails; pDlgInfo->SetMovie(item); pDlgInfo->DoModal(); item->SetThumbnailImage(pDlgInfo->GetThumbnail()); needsRefresh = pDlgInfo->NeedRefresh(); listNeedsUpdating = true; } else { pDlgProgress->Close(); if (pDlgProgress->IsCanceled()) { m_database.Close(); return listNeedsUpdating; // user cancelled } CGUIDialogOK::ShowAndGetInput(195, movieName, 0, 0); m_database.Close(); return listNeedsUpdating; } } // 6. Check for a refresh } while (needsRefresh); m_database.Close(); return listNeedsUpdating; } void CGUIWindowVideoBase::OnQueueItem(int iItem) { // don't re-queue items from playlist window if ( iItem < 0 || iItem >= m_vecItems->Size() || GetID() == WINDOW_VIDEO_PLAYLIST ) return ; // we take a copy so that we can alter the queue state CFileItemPtr item(new CFileItem(*m_vecItems->Get(iItem))); if (item->IsRAR() || item->IsZIP()) return; // Allow queuing of unqueueable items // when we try to queue them directly if (!item->CanQueue()) item->SetCanQueue(true); CFileItemList queuedItems; AddItemToPlayList(item, queuedItems); // if party mode, add items but DONT start playing if (g_partyModeManager.IsEnabled(PARTYMODECONTEXT_VIDEO)) { g_partyModeManager.AddUserSongs(queuedItems, false); return; } g_playlistPlayer.Add(PLAYLIST_VIDEO, queuedItems); g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_VIDEO); // video does not auto play on queue like music m_viewControl.SetSelectedItem(iItem + 1); } void CGUIWindowVideoBase::AddItemToPlayList(const CFileItemPtr &pItem, CFileItemList &queuedItems) { if (!pItem->CanQueue() || pItem->IsRAR() || pItem->IsZIP() || pItem->IsParentFolder()) // no zip/rar enques thank you! return; if (pItem->m_bIsFolder) { if (pItem->IsParentFolder()) return; // Check if we add a locked share if ( pItem->m_bIsShareOrDrive ) { CFileItem item = *pItem; if ( !g_passwordManager.IsItemUnlocked( &item, "video" ) ) return; } // recursive CFileItemList items; GetDirectory(pItem->GetPath(), items); FormatAndSort(items); int watchedMode = g_settings.GetWatchMode(m_vecItems->GetContent()); bool unwatchedOnly = watchedMode == VIDEO_SHOW_UNWATCHED; bool watchedOnly = watchedMode == VIDEO_SHOW_WATCHED; for (int i = 0; i < items.Size(); ++i) { if (items[i]->m_bIsFolder) { CStdString strPath = items[i]->GetPath(); URIUtils::RemoveSlashAtEnd(strPath); strPath.ToLower(); if (strPath.size() > 6) { CStdString strSub = strPath.substr(strPath.size()-6); if (strPath.Mid(strPath.size()-6).Equals("sample")) // skip sample folders continue; } } else if (items[i]->HasVideoInfoTag() && ((unwatchedOnly && items[i]->GetVideoInfoTag()->m_playCount > 0) || (watchedOnly && items[i]->GetVideoInfoTag()->m_playCount <= 0))) continue; AddItemToPlayList(items[i], queuedItems); } } else { // just an item if (pItem->IsPlayList()) { auto_ptr<CPlayList> pPlayList (CPlayListFactory::Create(*pItem)); if (pPlayList.get()) { // load it if (!pPlayList->Load(pItem->GetPath())) { CGUIDialogOK::ShowAndGetInput(6, 0, 477, 0); return; //hmmm unable to load playlist? } CPlayList playlist = *pPlayList; for (int i = 0; i < (int)playlist.size(); ++i) { AddItemToPlayList(playlist[i], queuedItems); } return; } } else if(pItem->IsInternetStream()) { // just queue the internet stream, it will be expanded on play queuedItems.Add(pItem); } else if (pItem->IsPlugin() && pItem->GetProperty("isplayable") == "true") { // a playable python files queuedItems.Add(pItem); } else if (pItem->IsVideoDb()) { // this case is needed unless we allow IsVideo() to return true for videodb items, // but then we have issues with playlists of videodb items CFileItemPtr item(new CFileItem(*pItem->GetVideoInfoTag())); queuedItems.Add(item); } else if (!pItem->IsNFO() && pItem->IsVideo()) { queuedItems.Add(pItem); } } } int CGUIWindowVideoBase::GetResumeItemOffset(const CFileItem *item) { // do not resume livetv if (item->IsLiveTV()) return 0; CVideoDatabase db; db.Open(); long startoffset = 0; if (item->IsStack() && (!g_guiSettings.GetBool("myvideos.treatstackasfile") || CFileItem(CStackDirectory::GetFirstStackedFile(item->GetPath()),false).IsDVDImage()) ) { CStdStringArray movies; GetStackedFiles(item->GetPath(), movies); /* check if any of the stacked files have a resume bookmark */ for (unsigned i = 0; i<movies.size();i++) { CBookmark bookmark; if (db.GetResumeBookMark(movies[i], bookmark)) { startoffset = (long)(bookmark.timeInSeconds*75); startoffset += 0x10000000 * (i+1); /* store file number in here */ break; } } } else if (!item->IsNFO() && !item->IsPlayList()) { if (item->HasVideoInfoTag() && item->GetVideoInfoTag()->m_resumePoint.timeInSeconds > 0.0) startoffset = (long)(item->GetVideoInfoTag()->m_resumePoint.timeInSeconds*75); else { CBookmark bookmark; CStdString strPath = item->GetPath(); if ((item->IsVideoDb() || item->IsDVD()) && item->HasVideoInfoTag()) strPath = item->GetVideoInfoTag()->m_strFileNameAndPath; if (db.GetResumeBookMark(strPath, bookmark)) startoffset = (long)(bookmark.timeInSeconds*75); } } db.Close(); return startoffset; } bool CGUIWindowVideoBase::OnClick(int iItem) { return CGUIMediaWindow::OnClick(iItem); } bool CGUIWindowVideoBase::OnSelect(int iItem) { if (iItem < 0 || iItem >= m_vecItems->Size()) return false; CFileItemPtr item = m_vecItems->Get(iItem); CStdString path = item->GetPath(); if (!item->m_bIsFolder && path != "add" && path != "addons://more/video" && path.Left(19) != "newsmartplaylist://" && path.Left(14) != "newplaylist://") return OnFileAction(iItem, g_guiSettings.GetInt("myvideos.selectaction")); return CGUIMediaWindow::OnSelect(iItem); } bool CGUIWindowVideoBase::OnFileAction(int iItem, int action) { CFileItemPtr item = m_vecItems->Get(iItem); // Reset the current start offset. The actual resume // option is set in the switch, based on the action passed. item->m_lStartOffset = 0; switch (action) { case SELECT_ACTION_CHOOSE: { CContextButtons choices; bool resume = false; if (!item->IsLiveTV()) { CStdString resumeString = GetResumeString(*item); if (!resumeString.IsEmpty()) { resume = true; choices.Add(SELECT_ACTION_RESUME, resumeString); choices.Add(SELECT_ACTION_PLAY, 12021); // Start from beginning } } if (!resume) choices.Add(SELECT_ACTION_PLAY, 208); // Play choices.Add(SELECT_ACTION_INFO, 22081); // Info choices.Add(SELECT_ACTION_MORE, 22082); // More int value = CGUIDialogContextMenu::ShowAndGetChoice(choices); if (value < 0) return true; return OnFileAction(iItem, value); } break; case SELECT_ACTION_PLAY_OR_RESUME: return OnResumeItem(iItem); case SELECT_ACTION_INFO: if (OnInfo(iItem)) return true; break; case SELECT_ACTION_MORE: OnPopupMenu(iItem); return true; case SELECT_ACTION_RESUME: item->m_lStartOffset = STARTOFFSET_RESUME; break; case SELECT_ACTION_PLAY: default: break; } return OnClick(iItem); } bool CGUIWindowVideoBase::OnInfo(int iItem) { if (iItem < 0 || iItem >= m_vecItems->Size()) return false; CFileItemPtr item = m_vecItems->Get(iItem); if (item->GetPath().Equals("add") || item->IsParentFolder() || (item->IsPlayList() && !URIUtils::GetExtension(item->GetPath()).Equals(".strm"))) return false; ADDON::ScraperPtr scraper; if (!m_vecItems->IsPlugin() && !m_vecItems->IsRSS() && !m_vecItems->IsLiveTV()) { CStdString strDir; if (item->IsVideoDb() && item->HasVideoInfoTag() && !item->GetVideoInfoTag()->m_strPath.IsEmpty()) { strDir = item->GetVideoInfoTag()->m_strPath; } else URIUtils::GetDirectory(item->GetPath(),strDir); SScanSettings settings; bool foundDirectly = false; scraper = m_database.GetScraperForPath(strDir, settings, foundDirectly); if (!scraper && !(m_database.HasMovieInfo(item->GetPath()) || m_database.HasTvShowInfo(strDir) || m_database.HasEpisodeInfo(item->GetPath()))) { return false; } if (scraper && scraper->Content() == CONTENT_TVSHOWS && foundDirectly && !settings.parent_name_root) // dont lookup on root tvshow folder return true; } OnInfo(item.get(), scraper); return true; } void CGUIWindowVideoBase::OnRestartItem(int iItem) { CGUIMediaWindow::OnClick(iItem); } CStdString CGUIWindowVideoBase::GetResumeString(CFileItem item) { CStdString resumeString; CVideoDatabase db; if (db.Open()) { CBookmark bookmark; CStdString itemPath(item.GetPath()); if (item.IsVideoDb() || item.IsDVD()) itemPath = item.GetVideoInfoTag()->m_strFileNameAndPath; if (db.GetResumeBookMark(itemPath, bookmark) ) resumeString.Format(g_localizeStrings.Get(12022).c_str(), StringUtils::SecondsToTimeString(lrint(bookmark.timeInSeconds)).c_str()); db.Close(); } return resumeString; } bool CGUIWindowVideoBase::ShowResumeMenu(CFileItem &item) { if (!item.m_bIsFolder && !item.IsLiveTV()) { CStdString resumeString = GetResumeString(item); if (!resumeString.IsEmpty()) { // prompt user whether they wish to resume CContextButtons choices; choices.Add(1, resumeString); choices.Add(2, 12021); // start from the beginning int retVal = CGUIDialogContextMenu::ShowAndGetChoice(choices); if (retVal < 0) return false; // don't do anything if (retVal == 1) item.m_lStartOffset = STARTOFFSET_RESUME; } } return true; } bool CGUIWindowVideoBase::OnResumeItem(int iItem) { if (iItem < 0 || iItem >= m_vecItems->Size()) return true; CFileItemPtr item = m_vecItems->Get(iItem); if (item->m_bIsFolder) { // resuming directories isn't supported yet. play. PlayItem(iItem); return true; } CStdString resumeString = GetResumeString(*item); if (!resumeString.IsEmpty()) { CContextButtons choices; choices.Add(SELECT_ACTION_RESUME, resumeString); choices.Add(SELECT_ACTION_PLAY, 12021); // Start from beginning int value = CGUIDialogContextMenu::ShowAndGetChoice(choices); if (value < 0) return true; return OnFileAction(iItem, value); } return OnFileAction(iItem, SELECT_ACTION_PLAY); } void CGUIWindowVideoBase::OnStreamDetails(const CStreamDetails &details, const CStdString &strFileName, long lFileId) { CVideoDatabase db; if (db.Open()) { if (lFileId < 0) db.SetStreamDetailsForFile(details, strFileName); else db.SetStreamDetailsForFileId(details, lFileId); db.Close(); } } void CGUIWindowVideoBase::GetContextButtons(int itemNumber, CContextButtons &buttons) { CFileItemPtr item; if (itemNumber >= 0 && itemNumber < m_vecItems->Size()) item = m_vecItems->Get(itemNumber); // contextual buttons if (item && !item->GetProperty("pluginreplacecontextitems").asBoolean()) { if (!item->IsParentFolder()) { CStdString path(item->GetPath()); if (item->IsVideoDb() && item->HasVideoInfoTag()) path = item->GetVideoInfoTag()->m_strFileNameAndPath; if (!item->IsPlugin() && !item->IsScript() && !item->IsAddonsPath() && !item->IsLiveTV()) { if (URIUtils::IsStack(path)) { vector<int> times; if (m_database.GetStackTimes(path,times)) buttons.Add(CONTEXT_BUTTON_PLAY_PART, 20324); } if (!m_vecItems->GetPath().IsEmpty() && !item->GetPath().Left(19).Equals("newsmartplaylist://") && !m_vecItems->IsSourcesPath()) { buttons.Add(CONTEXT_BUTTON_QUEUE_ITEM, 13347); // Add to Playlist } // allow a folder to be ad-hoc queued and played by the default player if (item->m_bIsFolder || (item->IsPlayList() && !g_advancedSettings.m_playlistAsFolders)) { buttons.Add(CONTEXT_BUTTON_PLAY_ITEM, 208); } } if (!item->m_bIsFolder && !(item->IsPlayList() && !g_advancedSettings.m_playlistAsFolders)) { // get players VECPLAYERCORES vecCores; if (item->IsVideoDb()) { CFileItem item2(item->GetVideoInfoTag()->m_strFileNameAndPath, false); CPlayerCoreFactory::GetPlayers(item2, vecCores); } else CPlayerCoreFactory::GetPlayers(*item, vecCores); if (vecCores.size() > 1) buttons.Add(CONTEXT_BUTTON_PLAY_WITH, 15213); } if (item->IsSmartPlayList()) { buttons.Add(CONTEXT_BUTTON_PLAY_PARTYMODE, 15216); // Play in Partymode } // if autoresume is enabled then add restart video button // check to see if the Resume Video button is applicable // only if the video is NOT a DVD (in that case the resume button will be added by CGUIDialogContextMenu::GetContextButtons) if (!item->IsDVD() && GetResumeItemOffset(item.get()) > 0) { buttons.Add(CONTEXT_BUTTON_RESUME_ITEM, GetResumeString(*(item.get()))); // Resume Video } if (item->HasVideoInfoTag() && !item->m_bIsFolder && m_vecItems->Size() > 1 && itemNumber < m_vecItems->Size()-1) { buttons.Add(CONTEXT_BUTTON_PLAY_AND_QUEUE, 13412); } if (item->IsSmartPlayList() || m_vecItems->IsSmartPlayList()) buttons.Add(CONTEXT_BUTTON_EDIT_SMART_PLAYLIST, 586); } } CGUIMediaWindow::GetContextButtons(itemNumber, buttons); } void CGUIWindowVideoBase::GetNonContextButtons(int itemNumber, CContextButtons &buttons) { if (g_playlistPlayer.GetPlaylist(PLAYLIST_VIDEO).size() > 0) buttons.Add(CONTEXT_BUTTON_NOW_PLAYING, 13350); } bool CGUIWindowVideoBase::OnContextButton(int itemNumber, CONTEXT_BUTTON button) { CFileItemPtr item; if (itemNumber >= 0 && itemNumber < m_vecItems->Size()) item = m_vecItems->Get(itemNumber); switch (button) { case CONTEXT_BUTTON_SET_CONTENT: { OnAssignContent(item->HasVideoInfoTag() && !item->GetVideoInfoTag()->m_strPath.IsEmpty() ? item->GetVideoInfoTag()->m_strPath : item->GetPath()); return true; } case CONTEXT_BUTTON_PLAY_PART: { CFileItemList items; CStdString path(item->GetPath()); if (item->IsVideoDb()) path = item->GetVideoInfoTag()->m_strFileNameAndPath; CDirectory::GetDirectory(path,items); CGUIDialogFileStacking* dlg = (CGUIDialogFileStacking*)g_windowManager.GetWindow(WINDOW_DIALOG_FILESTACKING); if (!dlg) return true; dlg->SetNumberOfFiles(items.Size()); dlg->DoModal(); int btn2 = dlg->GetSelectedFile(); if (btn2 > 0) { if (btn2 > 1) { vector<int> times; if (m_database.GetStackTimes(path,times)) item->m_lStartOffset = times[btn2-2]*75; // wtf? } else item->m_lStartOffset = 0; // call CGUIMediaWindow::OnClick() as otherwise autoresume will kick in CGUIMediaWindow::OnClick(itemNumber); } return true; } case CONTEXT_BUTTON_QUEUE_ITEM: OnQueueItem(itemNumber); return true; case CONTEXT_BUTTON_PLAY_ITEM: PlayItem(itemNumber); return true; case CONTEXT_BUTTON_PLAY_WITH: { VECPLAYERCORES vecCores; if (item->IsVideoDb()) { CFileItem item2(*item->GetVideoInfoTag()); CPlayerCoreFactory::GetPlayers(item2, vecCores); } else CPlayerCoreFactory::GetPlayers(*item, vecCores); g_application.m_eForcedNextPlayer = CPlayerCoreFactory::SelectPlayerDialog(vecCores); if (g_application.m_eForcedNextPlayer != EPC_NONE) OnClick(itemNumber); return true; } case CONTEXT_BUTTON_PLAY_PARTYMODE: g_partyModeManager.Enable(PARTYMODECONTEXT_VIDEO, m_vecItems->Get(itemNumber)->GetPath()); return true; case CONTEXT_BUTTON_RESTART_ITEM: OnRestartItem(itemNumber); return true; case CONTEXT_BUTTON_RESUME_ITEM: return OnFileAction(itemNumber, SELECT_ACTION_RESUME); case CONTEXT_BUTTON_NOW_PLAYING: g_windowManager.ActivateWindow(WINDOW_VIDEO_PLAYLIST); return true; case CONTEXT_BUTTON_INFO: OnInfo(itemNumber); return true; case CONTEXT_BUTTON_STOP_SCANNING: { CGUIDialogVideoScan *pScanDlg = (CGUIDialogVideoScan *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN); if (pScanDlg && pScanDlg->IsScanning()) pScanDlg->StopScanning(); return true; } case CONTEXT_BUTTON_SCAN: case CONTEXT_BUTTON_UPDATE_TVSHOW: { if( !item) return false; ADDON::ScraperPtr info; SScanSettings settings; GetScraperForItem(item.get(), info, settings); CStdString strPath = item->GetPath(); if (item->IsVideoDb() && (!item->m_bIsFolder || item->GetVideoInfoTag()->m_strPath.IsEmpty())) return false; if (item->IsVideoDb()) strPath = item->GetVideoInfoTag()->m_strPath; if (!info || info->Content() == CONTENT_NONE) return false; if (item->m_bIsFolder) { m_database.SetPathHash(strPath,""); // to force scan OnScan(strPath); } else OnInfo(item.get(),info); return true; } case CONTEXT_BUTTON_DELETE: OnDeleteItem(itemNumber); return true; case CONTEXT_BUTTON_EDIT_SMART_PLAYLIST: { CStdString playlist = m_vecItems->Get(itemNumber)->IsSmartPlayList() ? m_vecItems->Get(itemNumber)->GetPath() : m_vecItems->GetPath(); // save path as activatewindow will destroy our items if (CGUIDialogSmartPlaylistEditor::EditPlaylist(playlist, "video")) { // need to update m_vecItems->RemoveDiscCache(GetID()); Update(m_vecItems->GetPath()); } return true; } case CONTEXT_BUTTON_RENAME: OnRenameItem(itemNumber); return true; case CONTEXT_BUTTON_MARK_WATCHED: { int newSelection = m_viewControl.GetSelectedItem() + 1; MarkWatched(item,true); m_viewControl.SetSelectedItem(newSelection); CUtil::DeleteVideoDatabaseDirectoryCache(); Update(m_vecItems->GetPath()); return true; } case CONTEXT_BUTTON_MARK_UNWATCHED: MarkWatched(item,false); CUtil::DeleteVideoDatabaseDirectoryCache(); Update(m_vecItems->GetPath()); return true; case CONTEXT_BUTTON_PLAY_AND_QUEUE: return OnPlayAndQueueMedia(item); default: break; } return CGUIMediaWindow::OnContextButton(itemNumber, button); } void CGUIWindowVideoBase::GetStackedFiles(const CStdString &strFilePath1, vector<CStdString> &movies) { CStdString strFilePath = strFilePath1; // we're gonna be altering it movies.clear(); CURL url(strFilePath); if (url.GetProtocol() == "stack") { CStackDirectory dir; CFileItemList items; dir.GetDirectory(strFilePath, items); for (int i = 0; i < items.Size(); ++i) movies.push_back(items[i]->GetPath()); } if (movies.empty()) movies.push_back(strFilePath); } bool CGUIWindowVideoBase::OnPlayMedia(int iItem) { if ( iItem < 0 || iItem >= (int)m_vecItems->Size() ) return false; CFileItemPtr pItem = m_vecItems->Get(iItem); // party mode if (g_partyModeManager.IsEnabled(PARTYMODECONTEXT_VIDEO)) { CPlayList playlistTemp; playlistTemp.Add(pItem); g_partyModeManager.AddUserSongs(playlistTemp, true); return true; } // Reset Playlistplayer, playback started now does // not use the playlistplayer. g_playlistPlayer.Reset(); g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_NONE); CFileItem item(*pItem); if (pItem->IsVideoDb()) { item.SetPath(pItem->GetVideoInfoTag()->m_strFileNameAndPath); item.SetProperty("original_listitem_url", pItem->GetPath()); } CLog::Log(LOGDEBUG, "%s %s", __FUNCTION__, item.GetPath().c_str()); if (item.GetPath().Left(17) == "pvr://recordings/") { if (!g_PVRManager.IsStarted()) return false; /* For recordings we check here for a available stream URL */ CPVRRecording *tag = g_PVRRecordings->GetByPath(item.GetPath()); if (tag && !tag->m_strStreamURL.IsEmpty()) { CStdString stream = tag->m_strStreamURL; /* Isolate the folder from the filename */ size_t found = stream.find_last_of("/"); if (found == CStdString::npos) found = stream.find_last_of("\\"); if (found != CStdString::npos) { /* Check here for asterix at the begin of the filename */ if (stream[found+1] == '*') { /* Create a "stack://" url with all files matching the extension */ CStdString ext = URIUtils::GetExtension(stream); CStdString dir = stream.substr(0, found).c_str(); CFileItemList items; CDirectory::GetDirectory(dir, items); items.Sort(SORT_METHOD_FILE ,SORT_ORDER_ASC); vector<int> stack; for (int i = 0; i < items.Size(); ++i) { if (URIUtils::GetExtension(items[i]->GetPath()) == ext) stack.push_back(i); } if (stack.size() > 0) { /* If we have a stack change the path of the item to it */ CStackDirectory dir; CStdString stackPath = dir.ConstructStackPath(items, stack); item.SetPath(stackPath); } } else { /* If no asterix is present play only the given stream URL */ item.SetPath(stream); } } else { CLog::Log(LOGERROR, "CGUIWindowTV: Can't open recording, no valid filename!"); CGUIDialogOK::ShowAndGetInput(19033,0,19036,0); return false; } } } PlayMovie(&item); return true; } bool CGUIWindowVideoBase::OnPlayAndQueueMedia(const CFileItemPtr &item) { // Get the current playlist and make sure it is not shuffled int iPlaylist = m_guiState->GetPlaylist(); if (iPlaylist != PLAYLIST_NONE && g_playlistPlayer.IsShuffled(iPlaylist)) g_playlistPlayer.SetShuffle(iPlaylist, false); // Call the base method to actually queue the items // and start playing the given item return CGUIMediaWindow::OnPlayAndQueueMedia(item); } void CGUIWindowVideoBase::PlayMovie(const CFileItem *item) { CFileItemList movieList; int selectedFile = 1; long startoffset = item->m_lStartOffset; if (item->IsStack() && (!g_guiSettings.GetBool("myvideos.treatstackasfile") || CFileItem(CStackDirectory::GetFirstStackedFile(item->GetPath()),false).IsDVDImage()) ) { CStdStringArray movies; GetStackedFiles(item->GetPath(), movies); if (item->m_lStartOffset == STARTOFFSET_RESUME) { startoffset = GetResumeItemOffset(item); if (startoffset & 0xF0000000) /* file is specified as a flag */ { selectedFile = (startoffset>>28); startoffset = startoffset & ~0xF0000000; } else { /* attempt to start on a specific time in a stack */ /* if we are lucky, we might have stored timings for */ /* this stack at some point */ m_database.Open(); /* figure out what file this time offset is */ vector<int> times; m_database.GetStackTimes(item->GetPath(), times); long totaltime = 0; for (unsigned i = 0; i < times.size(); i++) { totaltime += times[i]*75; if (startoffset < totaltime ) { selectedFile = i+1; startoffset -= totaltime - times[i]*75; /* rebase agains selected file */ break; } } m_database.Close(); } } else { // show file stacking dialog CGUIDialogFileStacking* dlg = (CGUIDialogFileStacking*)g_windowManager.GetWindow(WINDOW_DIALOG_FILESTACKING); if (dlg) { dlg->SetNumberOfFiles(movies.size()); dlg->DoModal(); selectedFile = dlg->GetSelectedFile(); if (selectedFile < 1) return; } } // add to our movie list for (unsigned int i = 0; i < movies.size(); i++) { CFileItemPtr movieItem(new CFileItem(movies[i], false)); movieList.Add(movieItem); } } else { CFileItemPtr movieItem(new CFileItem(*item)); movieList.Add(movieItem); } g_playlistPlayer.Reset(); g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_VIDEO); CPlayList& playlist = g_playlistPlayer.GetPlaylist(PLAYLIST_VIDEO); playlist.Clear(); for (int i = selectedFile - 1; i < (int)movieList.Size(); ++i) { if (i == selectedFile - 1) movieList[i]->m_lStartOffset = startoffset; playlist.Add(movieList[i]); } if(m_thumbLoader.IsLoading()) m_thumbLoader.StopAsync(); // play movie... g_playlistPlayer.Play(0); if(!g_application.IsPlayingVideo()) m_thumbLoader.Load(*m_vecItems); } void CGUIWindowVideoBase::OnDeleteItem(int iItem) { if ( iItem < 0 || iItem >= m_vecItems->Size()) return; OnDeleteItem(m_vecItems->Get(iItem)); m_vecItems->RemoveDiscCache(GetID()); Update(m_vecItems->GetPath()); m_viewControl.SetSelectedItem(iItem); } void CGUIWindowVideoBase::OnDeleteItem(CFileItemPtr item) { // HACK: stacked files need to be treated as folders in order to be deleted if (item->IsStack()) item->m_bIsFolder = true; if (g_settings.GetCurrentProfile().getLockMode() != LOCK_MODE_EVERYONE && g_settings.GetCurrentProfile().filesLocked()) { if (!g_passwordManager.IsMasterLockUnlocked(true)) return; } if (g_guiSettings.GetBool("filelists.allowfiledeletion") && CUtil::SupportsFileOperations(item->GetPath())) CFileUtils::DeleteItem(item); } void CGUIWindowVideoBase::MarkWatched(const CFileItemPtr &item, bool bMark) { if (!g_settings.GetCurrentProfile().canWriteDatabases()) return; // dont allow update while scanning CGUIDialogVideoScan* pDialogScan = (CGUIDialogVideoScan*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN); if (pDialogScan && pDialogScan->IsScanning()) { CGUIDialogOK::ShowAndGetInput(257, 0, 14057, 0); return; } CVideoDatabase database; if (database.Open()) { CFileItemList items; if (item->m_bIsFolder) { CStdString strPath = item->GetPath(); CDirectory::GetDirectory(strPath, items); } else items.Add(item); for (int i=0;i<items.Size();++i) { CFileItemPtr pItem=items[i]; if (pItem->m_bIsFolder) { MarkWatched(pItem, bMark); continue; } if (pItem->HasVideoInfoTag() && (( bMark && pItem->GetVideoInfoTag()->m_playCount) || (!bMark && !(pItem->GetVideoInfoTag()->m_playCount)))) continue; // Clear resume bookmark if (bMark) database.ClearBookMarksOfFile(pItem->GetPath(), CBookmark::RESUME); database.SetPlayCount(*pItem, bMark ? 1 : 0); } database.Close(); } } //Add change a title's name void CGUIWindowVideoBase::UpdateVideoTitle(const CFileItem* pItem) { // dont allow update while scanning CGUIDialogVideoScan* pDialogScan = (CGUIDialogVideoScan*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN); if (pDialogScan && pDialogScan->IsScanning()) { CGUIDialogOK::ShowAndGetInput(257, 0, 14057, 0); return; } CVideoInfoTag detail; CVideoDatabase database; database.Open(); CVideoDatabaseDirectory dir; CQueryParams params; dir.GetQueryParams(pItem->GetPath(),params); int iDbId = pItem->GetVideoInfoTag()->m_iDbId; VIDEODB_CONTENT_TYPE iType=VIDEODB_CONTENT_MOVIES; if (pItem->HasVideoInfoTag() && (!pItem->GetVideoInfoTag()->m_strShowTitle.IsEmpty() || pItem->GetVideoInfoTag()->m_iEpisode > 0)) { iType = VIDEODB_CONTENT_TVSHOWS; } if (pItem->HasVideoInfoTag() && pItem->GetVideoInfoTag()->m_iSeason > -1 && !pItem->m_bIsFolder) iType = VIDEODB_CONTENT_EPISODES; if (pItem->HasVideoInfoTag() && !pItem->GetVideoInfoTag()->m_strArtist.IsEmpty()) iType = VIDEODB_CONTENT_MUSICVIDEOS; if (params.GetSetId() != -1 && params.GetMovieId() == -1) iType = VIDEODB_CONTENT_MOVIE_SETS; if (iType == VIDEODB_CONTENT_MOVIES) database.GetMovieInfo("", detail, pItem->GetVideoInfoTag()->m_iDbId); if (iType == VIDEODB_CONTENT_MOVIE_SETS) database.GetSetInfo(params.GetSetId(), detail); if (iType == VIDEODB_CONTENT_EPISODES) database.GetEpisodeInfo(pItem->GetPath(),detail,pItem->GetVideoInfoTag()->m_iDbId); if (iType == VIDEODB_CONTENT_TVSHOWS) database.GetTvShowInfo(pItem->GetVideoInfoTag()->m_strFileNameAndPath,detail,pItem->GetVideoInfoTag()->m_iDbId); if (iType == VIDEODB_CONTENT_MUSICVIDEOS) database.GetMusicVideoInfo(pItem->GetVideoInfoTag()->m_strFileNameAndPath,detail,pItem->GetVideoInfoTag()->m_iDbId); CStdString strInput; strInput = detail.m_strTitle; //Get the new title if (!CGUIDialogKeyboard::ShowAndGetInput(strInput, g_localizeStrings.Get(16105), false)) return; database.UpdateMovieTitle(iDbId, strInput, iType); } void CGUIWindowVideoBase::LoadPlayList(const CStdString& strPlayList, int iPlayList /* = PLAYLIST_VIDEO */) { // if partymode is active, we disable it if (g_partyModeManager.IsEnabled()) g_partyModeManager.Disable(); // load a playlist like .m3u, .pls // first get correct factory to load playlist auto_ptr<CPlayList> pPlayList (CPlayListFactory::Create(strPlayList)); if (pPlayList.get()) { // load it if (!pPlayList->Load(strPlayList)) { CGUIDialogOK::ShowAndGetInput(6, 0, 477, 0); return; //hmmm unable to load playlist? } } if (g_application.ProcessAndStartPlaylist(strPlayList, *pPlayList, iPlayList)) { if (m_guiState.get()) m_guiState->SetPlaylistDirectory("playlistvideo://"); } } void CGUIWindowVideoBase::PlayItem(int iItem) { // restrictions should be placed in the appropiate window code // only call the base code if the item passes since this clears // the currently playing temp playlist const CFileItemPtr pItem = m_vecItems->Get(iItem); // if its a folder, build a temp playlist if (pItem->m_bIsFolder && !pItem->IsPlugin()) { // take a copy so we can alter the queue state CFileItemPtr item(new CFileItem(*m_vecItems->Get(iItem))); // Allow queuing of unqueueable items // when we try to queue them directly if (!item->CanQueue()) item->SetCanQueue(true); // skip ".." if (item->IsParentFolder()) return; // recursively add items to list CFileItemList queuedItems; AddItemToPlayList(item, queuedItems); g_playlistPlayer.ClearPlaylist(PLAYLIST_VIDEO); g_playlistPlayer.Reset(); g_playlistPlayer.Add(PLAYLIST_VIDEO, queuedItems); g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_VIDEO); g_playlistPlayer.Play(); } else if (pItem->IsPlayList()) { // load the playlist the old way LoadPlayList(pItem->GetPath(), PLAYLIST_VIDEO); } else { // single item, play it OnClick(iItem); } } bool CGUIWindowVideoBase::Update(const CStdString &strDirectory) { if (m_thumbLoader.IsLoading()) m_thumbLoader.StopThread(); if (!CGUIMediaWindow::Update(strDirectory)) return false; m_thumbLoader.Load(*m_vecItems); return true; } bool CGUIWindowVideoBase::GetDirectory(const CStdString &strDirectory, CFileItemList &items) { bool bResult = CGUIMediaWindow::GetDirectory(strDirectory,items); // add in the "New Playlist" item if we're in the playlists folder if ((items.GetPath() == "special://videoplaylists/") && !items.Contains("newplaylist://")) { CFileItemPtr newPlaylist(new CFileItem(g_settings.GetUserDataItem("PartyMode-Video.xsp"),false)); newPlaylist->SetLabel(g_localizeStrings.Get(16035)); newPlaylist->SetLabelPreformated(true); newPlaylist->m_bIsFolder = true; items.Add(newPlaylist); /* newPlaylist.reset(new CFileItem("newplaylist://", false)); newPlaylist->SetLabel(g_localizeStrings.Get(525)); newPlaylist->SetLabelPreformated(true); items.Add(newPlaylist); */ newPlaylist.reset(new CFileItem("newsmartplaylist://video", false)); newPlaylist->SetLabel(g_localizeStrings.Get(21437)); // "new smart playlist..." newPlaylist->SetLabelPreformated(true); items.Add(newPlaylist); } m_stackingAvailable = StackingAvailable(items); // we may also be in a tvshow files listing // (ideally this should be removed, and our stack regexps tidied up if necessary // No "normal" episodes should stack, and multi-parts should be supported) ADDON::ScraperPtr info = m_database.GetScraperForPath(strDirectory); if (info && info->Content() == CONTENT_TVSHOWS) m_stackingAvailable = false; if (m_stackingAvailable && !items.IsStack() && g_settings.m_videoStacking) items.Stack(); return bResult; } bool CGUIWindowVideoBase::StackingAvailable(const CFileItemList &items) const { return !(items.IsTuxBox() || items.IsPlugin() || items.IsAddonsPath() || items.IsRSS() || items.IsInternetStream() || items.IsVideoDb()); } void CGUIWindowVideoBase::OnPrepareFileItems(CFileItemList &items) { if (!items.GetPath().Equals("plugin://video/")) items.SetCachedVideoThumbs(); if (items.GetContent() != "episodes") { // we don't set cached fanart for episodes, as this requires a db fetch per episode for (int i = 0; i < items.Size(); ++i) { CFileItemPtr item = items[i]; if (!item->HasProperty("fanart_image")) { CStdString art = item->GetCachedFanart(); if (CFile::Exists(art)) item->SetProperty("fanart_image", art); } } } } void CGUIWindowVideoBase::AddToDatabase(int iItem) { if (iItem < 0 || iItem >= m_vecItems->Size()) return; CFileItemPtr pItem = m_vecItems->Get(iItem); if (pItem->IsParentFolder() || pItem->m_bIsFolder) return; CVideoInfoTag movie; movie.Reset(); // prompt for data // enter a new title CStdString strTitle = pItem->GetLabel(); if (!CGUIDialogKeyboard::ShowAndGetInput(strTitle, g_localizeStrings.Get(528), false)) // Enter Title return; // pick genre CGUIDialogSelect* pSelect = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT); if (!pSelect) return; pSelect->SetHeading(530); // Select Genre pSelect->Reset(); CFileItemList items; if (!CDirectory::GetDirectory("videodb://1/1/", items)) return; pSelect->SetItems(&items); pSelect->EnableButton(true, 531); // New Genre pSelect->DoModal(); CStdString strGenre; int iSelected = pSelect->GetSelectedLabel(); if (iSelected >= 0) strGenre = items[iSelected]->GetLabel(); else if (!pSelect->IsButtonPressed()) return; // enter new genre string if (strGenre.IsEmpty()) { strGenre = g_localizeStrings.Get(532); // Manual Addition if (!CGUIDialogKeyboard::ShowAndGetInput(strGenre, g_localizeStrings.Get(533), false)) // Enter Genre return; // user backed out if (strGenre.IsEmpty()) return; // no genre string } // set movie info movie.m_strTitle = strTitle; movie.m_strGenre = strGenre; // everything is ok, so add to database m_database.Open(); int idMovie = m_database.AddMovie(pItem->GetPath()); movie.m_strIMDBNumber.Format("xx%08i", idMovie); m_database.SetDetailsForMovie(pItem->GetPath(), movie); m_database.Close(); // done... CGUIDialogOK::ShowAndGetInput(20177, movie.m_strTitle, movie.m_strGenre, movie.m_strIMDBNumber); // library view cache needs to be cleared CUtil::DeleteVideoDatabaseDirectoryCache(); } /// \brief Search the current directory for a string got from the virtual keyboard void CGUIWindowVideoBase::OnSearch() { CStdString strSearch; if (!CGUIDialogKeyboard::ShowAndGetInput(strSearch, g_localizeStrings.Get(16017), false)) return ; strSearch.ToLower(); if (m_dlgProgress) { m_dlgProgress->SetHeading(194); m_dlgProgress->SetLine(0, strSearch); m_dlgProgress->SetLine(1, ""); m_dlgProgress->SetLine(2, ""); m_dlgProgress->StartModal(); m_dlgProgress->Progress(); } CFileItemList items; DoSearch(strSearch, items); if (m_dlgProgress) m_dlgProgress->Close(); if (items.Size()) { CGUIDialogSelect* pDlgSelect = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT); pDlgSelect->Reset(); pDlgSelect->SetHeading(283); for (int i = 0; i < (int)items.Size(); i++) { CFileItemPtr pItem = items[i]; pDlgSelect->Add(pItem->GetLabel()); } pDlgSelect->DoModal(); int iItem = pDlgSelect->GetSelectedLabel(); if (iItem < 0) return; CFileItemPtr pSelItem = items[iItem]; OnSearchItemFound(pSelItem.get()); } else { CGUIDialogOK::ShowAndGetInput(194, 284, 0, 0); } } /// \brief React on the selected search item /// \param pItem Search result item void CGUIWindowVideoBase::OnSearchItemFound(const CFileItem* pSelItem) { if (pSelItem->m_bIsFolder) { CStdString strPath = pSelItem->GetPath(); CStdString strParentPath; URIUtils::GetParentPath(strPath, strParentPath); Update(strParentPath); if (pSelItem->IsVideoDb() && g_settings.m_bMyVideoNavFlatten) SetHistoryForPath(""); else SetHistoryForPath(strParentPath); strPath = pSelItem->GetPath(); CURL url(strPath); if (pSelItem->IsSmb() && !URIUtils::HasSlashAtEnd(strPath)) strPath += "/"; for (int i = 0; i < m_vecItems->Size(); i++) { CFileItemPtr pItem = m_vecItems->Get(i); if (pItem->GetPath() == strPath) { m_viewControl.SetSelectedItem(i); break; } } } else { CStdString strPath; URIUtils::GetDirectory(pSelItem->GetPath(), strPath); Update(strPath); if (pSelItem->IsVideoDb() && g_settings.m_bMyVideoNavFlatten) SetHistoryForPath(""); else SetHistoryForPath(strPath); for (int i = 0; i < (int)m_vecItems->Size(); i++) { CFileItemPtr pItem = m_vecItems->Get(i); if (pItem->GetPath() == pSelItem->GetPath()) { m_viewControl.SetSelectedItem(i); break; } } } m_viewControl.SetFocused(); } int CGUIWindowVideoBase::GetScraperForItem(CFileItem *item, ADDON::ScraperPtr &info, SScanSettings& settings) { if (!item) return 0; if (m_vecItems->IsPlugin() || m_vecItems->IsRSS()) { info.reset(); return 0; } else if(m_vecItems->IsLiveTV()) { info.reset(); return 0; } bool foundDirectly = false; info = m_database.GetScraperForPath(item->HasVideoInfoTag() && !item->GetVideoInfoTag()->m_strPath.IsEmpty() ? item->GetVideoInfoTag()->m_strPath : item->GetPath(), settings, foundDirectly); return foundDirectly ? 1 : 0; } void CGUIWindowVideoBase::OnScan(const CStdString& strPath, bool scanAll) { CGUIDialogVideoScan* pDialog = (CGUIDialogVideoScan*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN); if (pDialog) pDialog->StartScanning(strPath, scanAll); } CStdString CGUIWindowVideoBase::GetStartFolder(const CStdString &dir) { if (dir.Equals("$PLAYLISTS") || dir.Equals("Playlists")) return "special://videoplaylists/"; else if (dir.Equals("Plugins") || dir.Equals("Addons")) return "addons://sources/video/"; return CGUIMediaWindow::GetStartFolder(dir); } void CGUIWindowVideoBase::AppendAndClearSearchItems(CFileItemList &searchItems, const CStdString &prependLabel, CFileItemList &results) { if (!searchItems.Size()) return; searchItems.Sort(g_guiSettings.GetBool("filelists.ignorethewhensorting") ? SORT_METHOD_LABEL_IGNORE_THE : SORT_METHOD_LABEL, SORT_ORDER_ASC); for (int i = 0; i < searchItems.Size(); i++) searchItems[i]->SetLabel(prependLabel + searchItems[i]->GetLabel()); results.Append(searchItems); searchItems.Clear(); } bool CGUIWindowVideoBase::OnUnAssignContent(const CStdString &path, int label1, int label2, int label3) { bool bCanceled; CVideoDatabase db; db.Open(); if (CGUIDialogYesNo::ShowAndGetInput(label1,label2,label3,20022,bCanceled)) { db.RemoveContentForPath(path); db.Close(); CUtil::DeleteVideoDatabaseDirectoryCache(); return true; } else { if (!bCanceled) { ADDON::ScraperPtr info; SScanSettings settings; settings.exclude = true; db.SetScraperForPath(path,info,settings); } } db.Close(); return false; } void CGUIWindowVideoBase::OnAssignContent(const CStdString &path) { bool bScan=false; CVideoDatabase db; db.Open(); SScanSettings settings; ADDON::ScraperPtr info = db.GetScraperForPath(path, settings); ADDON::ScraperPtr info2(info); if (CGUIDialogContentSettings::Show(info, settings, bScan)) { if(settings.exclude || (!info && info2)) { OnUnAssignContent(path,20375,20340,20341); } else if (info != info2) { if (OnUnAssignContent(path,20442,20443,20444)) bScan = true; } } db.SetScraperForPath(path,info,settings); if (bScan) { CGUIDialogVideoScan* pDialog = (CGUIDialogVideoScan*)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_SCAN); if (pDialog) pDialog->StartScanning(path, true); } }
opdenkamp/xbmc
xbmc/video/windows/GUIWindowVideoBase.cpp
C++
gpl-2.0
63,899
<?php function commpress_init() { $labels = array( 'name' => __('Casts', 'easel'), 'singular_name' => __('Cast', 'easel'), 'add_new' => __('Add New', 'easel'), 'add_new_item' => __('Add New Cast', 'easel'), 'edit_item' => __('Edit Cast', 'easel'), 'edit' => _x('Edit', 'casts', 'easel'), 'new_item' => __('New Cast', 'easel'), 'view_item' => __('View Cast', 'easel'), 'search_items' => __('Search Casts', 'easel'), 'not_found' => __('No casts found', 'easel'), 'not_found_in_trash' => __('No casts found in Trash', 'easel'), 'view' => __('View Cast', 'easel'), 'parent_item_colon' => '' ); register_post_type( 'casts', array( 'labels' => $labels, 'public' => true, 'public_queryable' => true, 'show_ui' => true, 'query_var' => true, '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'rewrite' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => array( 'title', 'editor', 'excerpt', 'author', 'trackbacks', 'comments', 'thumbnail' ) ) ); $labels = array( 'name' => __( 'Tags', 'easel' ), 'singular_name' => __( 'Tag', 'easel' ), 'search_items' => __( 'Search Tags', 'easel' ), 'popular_items' => __( 'Popular Tags', 'easel' ), 'all_items' => __( 'All Tags', 'easel' ), 'parent_item' => __( 'Parent Tag', 'easel' ), 'parent_item_colon' => __( 'Parent Tag:', 'easel' ), 'edit_item' => __( 'Edit Tag', 'easel' ), 'update_item' => __( 'Update Tag', 'easel' ), 'add_new_item' => __( 'Add New Tag', 'easel' ), 'new_item_name' => __( 'New Tag Name', 'easel' ), ); register_taxonomy('cast-tag',array('casts'), array( 'hierarchical' => false, 'labels' => $labels, 'public' => true, 'show_ui' => true, 'query_var' => true, 'show_tagcloud' => true, 'rewrite' => array( 'slug' => 'cast-tag' ), )); $labels = array( 'name' => __( 'Guests', 'easel' ), 'singular_name' => __( 'Guest', 'easel' ), 'search_items' => __( 'Search Guests', 'easel' ), 'popular_items' => __( 'Popular Guests', 'easel' ), 'all_items' => __( 'All Guests', 'easel' ), 'parent_item' => __( 'Parent Guest', 'easel' ), 'parent_item_colon' => __( 'Parent Guest:', 'easel' ), 'edit_item' => __( 'Edit Guest', 'easel' ), 'update_item' => __( 'Update Guest', 'easel' ), 'add_new_item' => __( 'Add New Guest', 'easel' ), 'new_item_name' => __( 'New Guest Name', 'easel' ), ); register_taxonomy('cast-guest',array('casts'), array( 'hierarchical' => false, 'labels' => $labels, 'public' => true, 'show_ui' => true, 'query_var' => true, 'show_tagcloud' => true, 'rewrite' => array( 'slug' => 'cast-guest' ), )); $labels = array( 'name' => __( 'Audience', 'easel' ), 'singular_name' => __( 'Audience', 'easel' ), 'search_items' => __( 'Search Audience', 'easel' ), 'popular_items' => __( 'Popular Audience', 'easel' ), 'all_items' => __( 'All Audience', 'easel' ), 'parent_item' => __( 'Parent Audience', 'easel' ), 'parent_item_colon' => __( 'Parent Audience:', 'easel' ), 'edit_item' => __( 'Edit Audience', 'easel' ), 'update_item' => __( 'Update Audience', 'easel' ), 'add_new_item' => __( 'Add New Audience', 'easel' ), 'new_item_name' => __( 'New Audience Name', 'easel' ), ); register_taxonomy('cast-audience',array('casts'), array( 'hierarchical' => false, 'labels' => $labels, 'public' => true, 'show_ui' => true, 'query_var' => true, 'show_tagcloud' => true, 'rewrite' => array( 'slug' => 'cast-audience' ), )); $labels = array( 'name' => __( 'Hosts', 'easel' ), 'singular_name' => __( 'Host', 'easel' ), 'search_items' => __( 'Search Hosts', 'easel' ), 'popular_items' => __( 'Popular Host', 'easel' ), 'all_items' => __( 'All Hosts', 'easel' ), 'parent_item' => __( 'Parent Host', 'easel' ), 'parent_item_colon' => __( 'Parent Host:', 'easel' ), 'edit_item' => __( 'Edit Host', 'easel' ), 'update_item' => __( 'Update Host', 'easel' ), 'add_new_item' => __( 'Add New Host', 'easel' ), 'new_item_name' => __( 'New Host Name', 'easel' ), ); register_taxonomy('cast-host',array('casts'), array( 'hierarchical' => false, 'public' => true, 'labels' => $labels, 'show_ui' => true, 'query_var' => true, 'show_tagcloud' => true, 'rewrite' => array( 'slug' => 'host' ), )); $labels = array( 'name' => __( 'Show', 'easel' ), 'singular_name' => __( 'Show', 'easel' ), 'search_items' => __( 'Search Shows', 'easel' ), 'popular_items' => __( 'Popular Shows', 'easel' ), 'all_items' => __( 'All Shows', 'easel' ), 'parent_item' => __( 'Parent Show', 'easel' ), 'parent_item_colon' => __( 'Parent Show:', 'easel' ), 'edit_item' => __( 'Edit Show', 'easel' ), 'update_item' => __( 'Update Show', 'easel' ), 'add_new_item' => __( 'Add New Show', 'easel' ), 'new_item_name' => __( 'New Show Name', 'easel' ), ); register_taxonomy('cast-show',array('casts'), array( 'hierarchical' => true, 'labels' => $labels, 'public' => true, 'show_ui' => true, 'query_var' => true, 'show_tagcloud' => true, 'rewrite' => array( 'slug' => 'cast-show' ), )); register_taxonomy_for_object_type('cast-host', 'casts'); register_taxonomy_for_object_type('cast-guest', 'casts'); register_taxonomy_for_object_type('cast-tag', 'casts'); register_taxonomy_for_object_type('cast-audience', 'casts'); register_taxonomy_for_object_type('cast-show', 'casts'); } add_action('init', 'commpress_init'); add_action('easel-post-info', 'commpress_display_hosts'); if (!function_exists('commpress_display_hosts')) { function commpress_display_hosts() { global $post; if ($post->post_type == 'casts') { $before = '<div class="casts-hosts">With Host(s): '; $sep = ', '; $after = '</div>'; $output = get_the_term_list( $post->ID, 'cast-host', $before, $sep, $after ); if (!empty($output)) echo $output; } } } add_action('easel-post-info', 'commpress_display_guests'); if (!function_exists('commpress_display_guests')) { function commpress_display_guests() { global $post; if ($post->post_type == 'casts') { $before = '<div class="casts-guests">With Guest(s): '; $sep = ', '; $after = '</div>'; $output = get_the_term_list( $post->ID, 'cast-guest', $before, $sep, $after ); if (!empty($output)) echo $output; } } } add_action('easel-post-extras', 'commpress_display_audience'); if (!function_exists('commpress_display_audience')) { function commpress_display_audience() { global $post; if ($post->post_type == 'casts') { $before = '<div class="casts-audience">Audience: '; $sep = ', '; $after = '</div>'; $output = get_the_term_list( $post->ID, 'cast-audience', $before, $sep, $after ); if (!empty($output)) echo $output; } } } // Injections add_filter('easel_display_post_category', 'commpress_display_cast_show'); // TODO: Make this actually output a chapter set that the comic is in, instead of the post-type function commpress_display_cast_show($post_show) { global $post; if ($post->post_type == 'casts') { $before = '<div class="casts-show"> '; $sep = ', '; $after = '</div>'; $post_show = get_the_term_list( $post->ID, 'cast-show', $before, $sep, $after ); } return $post_show; } add_action('easel-post-extras', 'commpress_display_cast_tags'); if (!function_exists('commpress_display_cast_tags')) { function commpress_display_cast_tags() { global $post; if ($post->post_type == 'casts') { $before = '<div class="cast-tags">'.__('&#9492; Tags: ','easel'); $sep = ","; $after = '</div>'; $output = get_the_term_list( $post->ID, 'cast-tag', $before, $sep, $after ); if (!empty($output)) echo $output; } } } add_action('easel-narrowcolumn-area', 'commpress_display_cast'); function commpress_display_cast() { global $wp_query, $post; if (!is_paged() && is_home()) { Protect(); $cast_args = array( 'posts_per_page' => 1, 'post_type' => 'casts' ); $wp_query->in_the_loop = true; $castFrontpage = new WP_Query(); $castFrontpage->query($cast_args); while ($castFrontpage->have_posts()) : $castFrontpage->the_post(); easel_display_post(); endwhile; UnProtect(); } } // Navigation function easel_commpress_get_first_cast() { return easel_commpress_get_terminal_post_of_casts(true); } function easel_commpress_get_first_cast_permalink() { $terminal = easel_commpress_get_first_cast(); return !empty($terminal) ? get_permalink($terminal->ID) : false; } function easel_commpress_get_last_cast() { return easel_commpress_get_terminal_post_of_casts(false); } function easel_commpress_get_last_cast_permalink() { $terminal = easel_commpress_get_last_cast(); return !empty($terminal) ? get_permalink($terminal->ID) : false; } function easel_commpress_get_previous_cast() { return easel_get_adjacent_post_type(true, 'casts'); } function easel_commpress_get_previous_cast_permalink() { $prev_cast = easel_commpress_get_previous_cast(); if (is_object($prev_cast)) { if (isset($prev_cast->ID)) { return get_permalink($prev_cast->ID); } } return false; } function easel_commpress_get_next_cast() { return easel_get_adjacent_post_type(false, 'casts'); } function easel_commpress_get_next_cast_permalink() { $next_cast = easel_commpress_get_next_cast(); if (is_object($next_cast)) { if (isset($next_cast->ID)) { return get_permalink($next_cast->ID); } } return false; } function easel_commpress_get_terminal_post_of_casts($first = true) { $sortOrder = $first ? "asc" : "desc"; $args = array( 'order' => $sortOrder, 'posts_per_page' => 1, 'post_type' => 'casts' ); $terminalComicQuery = new WP_Query($args); $terminalPost = false; if ($terminalComicQuery->have_posts()) { $terminalPost = reset($terminalComicQuery->posts); } return $terminalPost; } add_action('easel-post-foot', 'easel_commpress_display_navigation'); if (!function_exists('easel_commpress_display_navigation')) { function easel_commpress_display_navigation() { global $post, $wp_query; if ($post->post_type == 'casts' && !is_archive() && !is_search()) { $first_cast = easel_commpress_get_first_cast_permalink(); $first_text = __('&lsaquo;&lsaquo; First','easel'); $last_cast = easel_commpress_get_last_cast_permalink(); $last_text = __('Last &rsaquo;&rsaquo;','easel'); $next_cast = easel_commpress_get_next_cast_permalink(); $next_text = __('Next &rsaquo;','easel'); $prev_cast = easel_commpress_get_previous_cast_permalink(); $prev_text = __('&lsaquo; Prev','easel'); ?> <div id="casts-nav-wrapper"> <div class="casts-nav"> <div class="casts-nav-base casts-nav-first"><?php if ( get_permalink() != $first_cast ) { ?><a href="<?php echo $first_cast ?>"><?php echo $first_text; ?></a><?php } else { echo $first_text; } ?></div> <div class="casts-nav-base casts-nav-previous"><?php if ($prev_cast) { ?><a href="<?php echo $prev_cast ?>"><?php echo $prev_text; ?></a><?php } else { echo $prev_text; } ?></div> <div class="casts-nav-base casts-nav-last"><?php if ( get_permalink() != $last_cast ) { ?><a href="<?php echo $last_cast ?>"><?php echo $last_text; ?></a><?php } else { echo $last_text; } ?></div> <div class="casts-nav-base casts-nav-next"><?php if ($next_cast) { ?><a href="<?php echo $next_cast ?>"><?php echo $next_text; ?></a><?php } else { echo $next_text; } ?></div> <div class="clear"></div> </div> </div> <?php } } } add_action('easel-post-foot', 'commpress_display_edit_link'); function commpress_display_edit_link() { global $post; if ($post->post_type == 'casts') { edit_post_link(__('<br />Edit Cast','comiceasel'), '', ''); } } // Widgets class easel_latest_casts_widget extends WP_Widget { function easel_latest_casts_widget($skip_widget_init = false) { if (!$skip_widget_init) { $widget_ops = array('classname' => __CLASS__, 'description' => __('Display a list of the latest Media Casts','easel') ); $this->WP_Widget(__CLASS__, __('Latest Media Casts','easel'), $widget_ops); } } function widget($args, $instance) { global $post; extract($args, EXTR_SKIP); Protect(); echo $before_widget; $title = empty($instance['title']) ? __('Latest Media Cast','easel') : apply_filters('widget_title', $instance['title']); if ( !empty( $title ) ) { echo $before_title . $title . $after_title; }; $latestmusic = get_posts('numberposts=5&post_type=casts'); ?> <ul> <?php foreach($latestmusic as $post) : ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> </ul> <?php UnProtect(); echo $after_widget; } function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); return $instance; } function form($instance) { $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); $title = strip_tags($instance['title']); ?> <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:','easel'); ?> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></label></p> <?php } } register_widget('easel_latest_casts_widget'); ?>
zadav/wp_test
wp-content/themes/easel/addons/commpress.php
PHP
gpl-2.0
13,769
<?php /* * This file is part of EC-CUBE * * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved. * * http://www.lockon.co.jp/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ namespace Eccube\Framework\Api\Operation; /** * APIの基本クラス * * @package Api * @author LOCKON CO.,LTD. */ class Operation extends Base { protected $operation_name = 'Default'; protected $operation_description = 'Default Operation'; protected $default_auth_types = '99'; protected $default_enable = '1'; protected $default_is_log = '0'; protected $default_sub_data = ''; public function doAction($arrParam) { $this->arrResponse = array('DefaultEmpty' => array()); return true; } public function getRequestValidate() { return array('DefaultResponse' => array()); } public function getResponseGroupName() { return 'DefaultResponse'; } protected function lfInitParam(&$objFormParam) { } }
nanapon/ec-cube-test2
src/Eccube/Framework/Api/Operation/Default.php
PHP
gpl-2.0
1,672
// OsmSharp - OpenStreetMap (OSM) SDK // Copyright (C) 2015 Abelshausen Ben // // This file is part of OsmSharp. // // OsmSharp is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // OsmSharp 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with OsmSharp. If not, see <http://www.gnu.org/licenses/>. using OsmSharp.IO.MemoryMappedFiles; namespace OsmSharp.Collections.Arrays.MemoryMapped { /// <summary> /// Represents a memory mapped huge array of floats. /// </summary> public class MemoryMappedHugeArraySingle : MemoryMappedHugeArray<float> { /// <summary> /// Creates a memory mapped huge array. /// </summary> /// <param name="file">The the memory mapped file.</param> /// <param name="size">The initial size of the array.</param> public MemoryMappedHugeArraySingle(MemoryMappedFile file, long size) : base(file, 4, size, DefaultFileElementSize, (int)DefaultFileElementSize / DefaultBufferSize, DefaultCacheSize) { } /// <summary> /// Creates a memory mapped huge array. /// </summary> /// <param name="file">The the memory mapped file.</param> /// <param name="size">The initial size of the array.</param> /// <param name="arraySize">The size of an indivdual array block.</param> public MemoryMappedHugeArraySingle(MemoryMappedFile file, long size, long arraySize) : base(file, 4, size, arraySize, (int)arraySize / DefaultBufferSize, DefaultCacheSize) { } /// <summary> /// Creates a memorymapped huge array. /// </summary> /// <param name="file">The the memory mapped file.</param> /// <param name="size">The initial size of the array.</param> /// <param name="arraySize">The size of an indivdual array block.</param> /// <param name="bufferSize">The buffer size.</param> public MemoryMappedHugeArraySingle(MemoryMappedFile file, long size, long arraySize, int bufferSize) : base(file, 4, size, arraySize, bufferSize, DefaultCacheSize) { } /// <summary> /// Creates a memorymapped huge array. /// </summary> /// <param name="file">The the memory mapped file.</param> /// <param name="size">The initial size of the array.</param> /// <param name="arraySize">The size of an indivdual array block.</param> /// <param name="bufferSize">The buffer size.</param> /// <param name="cacheSize">The size of the LRU cache to keep buffers.</param> public MemoryMappedHugeArraySingle(MemoryMappedFile file, long size, long arraySize, int bufferSize, int cacheSize) : base(file, 4, size, arraySize, bufferSize, cacheSize) { } /// <summary> /// Creates a new memory mapped accessor. /// </summary> /// <param name="file"></param> /// <param name="sizeInBytes"></param> /// <returns></returns> protected override MemoryMappedAccessor<float> CreateAccessor(MemoryMappedFile file, long sizeInBytes) { return file.CreateSingle(sizeInBytes); } } }
ryfx/OsmSharp
OsmSharp/Collections/Arrays/MemoryMapped/MemoryMappedHugeArraySingle.cs
C#
gpl-2.0
3,660
/* * Copyright © 2020 Luciano Iam <oss@lucianoiam.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import { ChildComponent } from '../base/component.js'; import { StateNode } from '../base/protocol.js'; import Strip from './strip.js'; export default class Mixer extends ChildComponent { constructor (parent) { super(parent); this._strips = {}; this._ready = false; } get ready () { return this._ready; } get strips () { return Object.values(this._strips); } getStripByName (name) { name = name.trim().toLowerCase(); return this.strips.find(strip => strip.name.trim().toLowerCase() == name); } handle (node, addr, val) { if (node.startsWith('strip')) { if (node == StateNode.STRIP_DESCRIPTION) { this._strips[addr] = new Strip(this, addr, val); this.notifyPropertyChanged('strips'); return true; } else { const stripAddr = [addr[0]]; if (stripAddr in this._strips) { return this._strips[stripAddr].handle(node, addr, val); } } } else { // all initial strip description messages have been received at this point if (!this._ready) { this.updateLocal('ready', true); // passthrough by allowing to return false } } return false; } }
Ardour/ardour
share/web_surfaces/shared/components/mixer.js
JavaScript
gpl-2.0
1,925
import itertools import sys from flask import abort, g, render_template, request, redirect, Blueprint, flash, url_for, current_app from flask.ext.login import login_required, current_user from realms.lib.util import to_canonical, remove_ext, gravatar_url from .models import PageNotFound blueprint = Blueprint('wiki', __name__) @blueprint.route("/_commit/<sha>/<path:name>") def commit(name, sha): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() cname = to_canonical(name) data = g.current_wiki.get_page(cname, sha=sha) if not data: abort(404) return render_template('wiki/page.html', name=name, page=data, commit=sha) @blueprint.route(r"/_compare/<path:name>/<regex('\w+'):fsha><regex('\.{2,3}'):dots><regex('\w+'):lsha>") def compare(name, fsha, dots, lsha): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() diff = g.current_wiki.compare(name, fsha, lsha) return render_template('wiki/compare.html', name=name, diff=diff, old=fsha, new=lsha) @blueprint.route("/_revert", methods=['POST']) @login_required def revert(): cname = to_canonical(request.form.get('name')) commit = request.form.get('commit') message = request.form.get('message', "Reverting %s" % cname) if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous(): return dict(error=True, message="Anonymous posting not allowed"), 403 if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message="Page is locked"), 403 try: sha = g.current_wiki.revert_page(cname, commit, message=message, username=current_user.username, email=current_user.email) except PageNotFound as e: return dict(error=True, message=e.message), 404 if sha: flash("Page reverted") return dict(sha=sha) @blueprint.route("/_history/<path:name>") def history(name): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() hist = g.current_wiki.get_history(name) for item in hist: item['gravatar'] = gravatar_url(item['author_email']) return render_template('wiki/history.html', name=name, history=hist) @blueprint.route("/_edit/<path:name>") @login_required def edit(name): cname = to_canonical(name) page = g.current_wiki.get_page(name) if not page: # Page doesn't exist return redirect(url_for('wiki.create', name=cname)) name = remove_ext(page['path']) g.assets['js'].append('editor.js') return render_template('wiki/edit.html', name=name, content=page.get('data'), info=page.get('info'), sha=page.get('sha'), partials=page.get('partials')) @blueprint.route("/_create/", defaults={'name': None}) @blueprint.route("/_create/<path:name>") @login_required def create(name): cname = to_canonical(name) if name else "" if cname and g.current_wiki.get_page(cname): # Page exists, edit instead return redirect(url_for('wiki.edit', name=cname)) g.assets['js'].append('editor.js') return render_template('wiki/edit.html', name=cname, content="", info={}) def _get_subdir(path, depth): parts = path.split('/', depth) if len(parts) > depth: return parts[-2] def _tree_index(items, path=""): depth = len(path.split("/")) items = filter(lambda x: x['name'].startswith(path), items) items = sorted(items, key=lambda x: x['name']) for subdir, items in itertools.groupby(items, key=lambda x: _get_subdir(x['name'], depth)): if not subdir: for item in items: yield dict(item, dir=False) else: size = 0 ctime = sys.maxint mtime = 0 for item in items: size += item['size'] ctime = min(item['ctime'], ctime) mtime = max(item['mtime'], mtime) yield dict(name=path + subdir + "/", mtime=mtime, ctime=ctime, size=size, dir=True) @blueprint.route("/_index", defaults={"path": ""}) @blueprint.route("/_index/<path:path>") def index(path): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() items = g.current_wiki.get_index() if path: path = to_canonical(path) + "/" return render_template('wiki/index.html', index=_tree_index(items, path=path), path=path) @blueprint.route("/<path:name>", methods=['POST', 'PUT', 'DELETE']) @login_required def page_write(name): cname = to_canonical(name) if not cname: return dict(error=True, message="Invalid name") if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous(): return dict(error=True, message="Anonymous posting not allowed"), 403 if request.method == 'POST': # Create if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message="Page is locked"), 403 sha = g.current_wiki.write_page(cname, request.form['content'], message=request.form['message'], create=True, username=current_user.username, email=current_user.email) elif request.method == 'PUT': edit_cname = to_canonical(request.form['name']) if edit_cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message="Page is locked"), 403 if edit_cname != cname: g.current_wiki.rename_page(cname, edit_cname) sha = g.current_wiki.write_page(edit_cname, request.form['content'], message=request.form['message'], username=current_user.username, email=current_user.email) return dict(sha=sha) elif request.method == 'DELETE': # DELETE if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message="Page is locked"), 403 sha = g.current_wiki.delete_page(cname, username=current_user.username, email=current_user.email) return dict(sha=sha) @blueprint.route("/", defaults={'name': 'home'}) @blueprint.route("/<path:name>") def page(name): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() cname = to_canonical(name) if cname != name: return redirect(url_for('wiki.page', name=cname)) data = g.current_wiki.get_page(cname) if data: return render_template('wiki/page.html', name=cname, page=data, partials=data.get('partials')) else: return redirect(url_for('wiki.create', name=cname))
drptbl/realms-wiki-vagrant
realms/modules/wiki/views.py
Python
gpl-2.0
7,675
<?php function pmxe_wp_loaded() { }
markredballoon/clivemizen
wp-content/plugins/wp-all-export/actions/wp_loaded.php
PHP
gpl-2.0
44
/*! * VisualEditor MediaWiki Initialization class. * * @copyright 2011-2015 VisualEditor Team and others; see AUTHORS.txt * @license The MIT License (MIT); see LICENSE.txt */ /** * Initialization MediaWiki Target Analytics. * * @class * * @constructor * @param {ve.init.mw.Target} target Target class to log events for */ ve.init.mw.TargetEvents = function VeInitMwTargetEvents( target ) { this.target = target; this.timings = { saveRetries: 0 }; // Events this.target.connect( this, { saveWorkflowBegin: 'onSaveWorkflowBegin', saveWorkflowEnd: 'onSaveWorkflowEnd', saveInitiated: 'onSaveInitated', save: 'onSaveComplete', saveReview: 'onSaveReview', saveErrorEmpty: [ 'trackSaveError', 'empty' ], saveErrorSpamBlacklist: [ 'trackSaveError', 'spamblacklist' ], saveErrorAbuseFilter: [ 'trackSaveError', 'abusefilter' ], saveErrorBadToken: [ 'trackSaveError', 'badtoken' ], saveErrorNewUser: [ 'trackSaveError', 'newuser' ], saveErrorPageDeleted: [ 'trackSaveError', 'pagedeleted' ], saveErrorTitleBlacklist: [ 'trackSaveError', 'titleblacklist' ], saveErrorCaptcha: [ 'trackSaveError', 'captcha' ], saveErrorUnknown: [ 'trackSaveError', 'unknown' ], editConflict: [ 'trackSaveError', 'editconflict' ], surfaceReady: 'onSurfaceReady', showChanges: 'onShowChanges', showChangesError: 'onShowChangesError', noChanges: 'onNoChanges', serializeComplete: 'onSerializeComplete', serializeError: 'onSerializeError' } ); }; /** * Target specific ve.track wrapper * * @param {string} topic Event name * @param {Object} data Additional data describing the event, encoded as an object */ ve.init.mw.TargetEvents.prototype.track = function ( topic, data ) { data.targetName = this.target.constructor.static.name; ve.track( 'mwtiming.' + topic, data ); if ( topic.indexOf( 'performance.system.serializeforcache' ) === 0 ) { // HACK: track serializeForCache duration here, because there's no event for that this.timings.serializeForCache = data.duration; } }; /** * Track when user begins the save workflow */ ve.init.mw.TargetEvents.prototype.onSaveWorkflowBegin = function () { this.timings.saveWorkflowBegin = ve.now(); this.track( 'behavior.lastTransactionTillSaveDialogOpen', { duration: this.timings.saveWorkflowBegin - this.timings.lastTransaction } ); ve.track( 'mwedit.saveIntent' ); }; /** * Track when user ends the save workflow */ ve.init.mw.TargetEvents.prototype.onSaveWorkflowEnd = function () { this.track( 'behavior.saveDialogClose', { duration: ve.now() - this.timings.saveWorkflowBegin } ); this.timings.saveWorkflowBegin = null; }; /** * Track when document save is initiated */ ve.init.mw.TargetEvents.prototype.onSaveInitated = function () { this.timings.saveInitiated = ve.now(); this.timings.saveRetries++; this.track( 'behavior.saveDialogOpenTillSave', { duration: this.timings.saveInitiated - this.timings.saveWorkflowBegin } ); ve.track( 'mwedit.saveAttempt' ); }; /** * Track when the save is complete * * @param {string} content * @param {string} categoriesHtml * @param {number} newRevId */ ve.init.mw.TargetEvents.prototype.onSaveComplete = function ( content, categoriesHtml, newRevId ) { this.track( 'performance.user.saveComplete', { duration: ve.now() - this.timings.saveInitiated } ); this.timings.saveRetries = 0; ve.track( 'mwedit.saveSuccess', { timing: ve.now() - this.timings.saveInitiated + ( this.timings.serializeForCache || 0 ), 'page.revid': newRevId } ); }; /** * Track a save error by type * * @method * @param {string} type Text for error type */ ve.init.mw.TargetEvents.prototype.trackSaveError = function ( type ) { var key, data, failureArguments = [], // Maps mwtiming types to mwedit types typeMap = { badtoken: 'userBadToken', newuser: 'userNewUser', abusefilter: 'extensionAbuseFilter', captcha: 'extensionCaptcha', spamblacklist: 'extensionSpamBlacklist', empty: 'responseEmpty', unknown: 'responseUnknown', pagedeleted: 'editPageDeleted', titleblacklist: 'extensionTitleBlacklist', editconflict: 'editConflict' }, // Types that are logged as performance.user.saveError.{type} // (for historical reasons; this sucks) specialTypes = [ 'editconflict' ]; if ( arguments ) { failureArguments = Array.prototype.slice.call( arguments, 1 ); } key = 'performance.user.saveError'; if ( specialTypes.indexOf( type ) !== -1 ) { key += '.' + type; } this.track( key, { duration: ve.now() - this.timings.saveInitiated, retries: this.timings.saveRetries, type: type } ); data = { type: typeMap[ type ] || 'responseUnknown', timing: ve.now() - this.timings.saveInitiated + ( this.timings.serializeForCache || 0 ) }; if ( type === 'unknown' && failureArguments[ 1 ].error && failureArguments[ 1 ].error.code ) { data.message = failureArguments[ 1 ].error.code; } ve.track( 'mwedit.saveFailure', data ); }; /** * Record activation having started. * * @param {number} [startTime] Timestamp activation started. Defaults to current time */ ve.init.mw.TargetEvents.prototype.trackActivationStart = function ( startTime ) { this.timings.activationStart = startTime || ve.now(); }; /** * Record activation being complete. */ ve.init.mw.TargetEvents.prototype.trackActivationComplete = function () { this.track( 'performance.system.activation', { duration: ve.now() - this.timings.activationStart } ); }; /** * Record the time of the last transaction in response to a 'transact' event on the document. */ ve.init.mw.TargetEvents.prototype.recordLastTransactionTime = function () { this.timings.lastTransaction = ve.now(); }; /** * Track time elapsed from beginning of save workflow to review */ ve.init.mw.TargetEvents.prototype.onSaveReview = function () { this.timings.saveReview = ve.now(); this.track( 'behavior.saveDialogOpenTillReview', { duration: this.timings.saveReview - this.timings.saveWorkflowBegin } ); }; ve.init.mw.TargetEvents.prototype.onSurfaceReady = function () { this.target.surface.getModel().getDocument().connect( this, { transact: 'recordLastTransactionTime' } ); }; /** * Track when the user enters the review workflow */ ve.init.mw.TargetEvents.prototype.onShowChanges = function () { this.track( 'performance.user.reviewComplete', { duration: ve.now() - this.timings.saveReview } ); }; /** * Track when the diff request fails in the review workflow */ ve.init.mw.TargetEvents.prototype.onShowChangesError = function () { this.track( 'performance.user.reviewError', { duration: ve.now() - this.timings.saveReview } ); }; /** * Track when the diff request detects no changes */ ve.init.mw.TargetEvents.prototype.onNoChanges = function () { this.track( 'performance.user.reviewComplete', { duration: ve.now() - this.timings.saveReview } ); }; /** * Track whe serilization is complete in review workflow */ ve.init.mw.TargetEvents.prototype.onSerializeComplete = function () { this.track( 'performance.user.reviewComplete', { duration: ve.now() - this.timings.saveReview } ); }; /** * Track when there is a serlization error */ ve.init.mw.TargetEvents.prototype.onSerializeError = function () { if ( this.timings.saveWorkflowBegin ) { // This function can be called by the switch to wikitext button as well, so only log // reviewError if we actually got here from the save workflow this.track( 'performance.user.reviewError', { duration: ve.now() - this.timings.saveReview } ); } };
tbs-sct/gcpedia
extensions/VisualEditor/modules/ve-mw/init/ve.init.mw.TargetEvents.js
JavaScript
gpl-2.0
7,477
/* * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.web; import javafx.css.CssMetaData; import javafx.css.StyleableBooleanProperty; import javafx.css.StyleableDoubleProperty; import javafx.css.StyleableObjectProperty; import javafx.css.StyleableProperty; import javafx.css.converter.BooleanConverter; import javafx.css.converter.EnumConverter; import javafx.css.converter.SizeConverter; import com.sun.javafx.geom.BaseBounds; import com.sun.javafx.geom.PickRay; import com.sun.javafx.geom.transform.Affine3D; import com.sun.javafx.geom.transform.BaseTransform; import com.sun.javafx.scene.DirtyBits; import com.sun.javafx.scene.NodeHelper; import com.sun.javafx.scene.input.PickResultChooser; import com.sun.java.scene.web.WebViewHelper; import com.sun.javafx.scene.SceneHelper; import com.sun.javafx.sg.prism.NGNode; import com.sun.javafx.tk.TKPulseListener; import com.sun.javafx.tk.Toolkit; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javafx.beans.property.*; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.css.Styleable; import javafx.geometry.Bounds; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.text.FontSmoothingType; /** * {@code WebView} is a {@link javafx.scene.Node} that manages a * {@link WebEngine} and displays its content. The associated {@code WebEngine} * is created automatically at construction time and cannot be changed * afterwards. {@code WebView} handles mouse and some keyboard events, and * manages scrolling automatically, so there's no need to put it into a * {@code ScrollPane}. * * <p>{@code WebView} objects must be created and accessed solely from the * FX thread. * @since JavaFX 2.0 */ final public class WebView extends Parent { static { WebViewHelper.setWebViewAccessor(new WebViewHelper.WebViewAccessor() { @Override public NGNode doCreatePeer(Node node) { return ((WebView) node).doCreatePeer(); } @Override public void doUpdatePeer(Node node) { ((WebView) node).doUpdatePeer(); } @Override public void doTransformsChanged(Node node) { ((WebView) node).doTransformsChanged(); } @Override public BaseBounds doComputeGeomBounds(Node node, BaseBounds bounds, BaseTransform tx) { return ((WebView) node).doComputeGeomBounds(bounds, tx); } @Override public boolean doComputeContains(Node node, double localX, double localY) { return ((WebView) node).doComputeContains(localX, localY); } @Override public void doPickNodeLocal(Node node, PickRay localPickRay, PickResultChooser result) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); } private static final boolean DEFAULT_CONTEXT_MENU_ENABLED = true; private static final FontSmoothingType DEFAULT_FONT_SMOOTHING_TYPE = FontSmoothingType.LCD; private static final double DEFAULT_ZOOM = 1.0; private static final double DEFAULT_FONT_SCALE = 1.0; private static final double DEFAULT_MIN_WIDTH = 0; private static final double DEFAULT_MIN_HEIGHT = 0; private static final double DEFAULT_PREF_WIDTH = 800; private static final double DEFAULT_PREF_HEIGHT = 600; private static final double DEFAULT_MAX_WIDTH = Double.MAX_VALUE; private static final double DEFAULT_MAX_HEIGHT = Double.MAX_VALUE; private final WebEngine engine; // pointer to native WebViewImpl private final long handle; /** * The stage pulse listener registered with the toolkit. * This field guarantees that the listener will exist throughout * the whole lifetime of the WebView node. This field is necessary * because the toolkit references its stage pulse listeners weakly. */ private final TKPulseListener stagePulseListener; /** * Returns the {@code WebEngine} object. */ public final WebEngine getEngine() { return engine; } private final ReadOnlyDoubleWrapper width = new ReadOnlyDoubleWrapper(this, "width"); /** * Returns width of this {@code WebView}. */ public final double getWidth() { return width.get(); } /** * Width of this {@code WebView}. */ public ReadOnlyDoubleProperty widthProperty() { return width.getReadOnlyProperty(); } private final ReadOnlyDoubleWrapper height = new ReadOnlyDoubleWrapper(this, "height"); /** * Returns height of this {@code WebView}. */ public final double getHeight() { return height.get(); } /** * Height of this {@code WebView}. */ public ReadOnlyDoubleProperty heightProperty() { return height.getReadOnlyProperty(); } /** * Zoom factor applied to the whole page contents. * * @defaultValue 1.0 */ private DoubleProperty zoom; /** * Sets current zoom factor applied to the whole page contents. * @param value zoom factor to be set * @see #zoomProperty() * @see #getZoom() * @since JavaFX 8.0 */ public final void setZoom(double value) { WebEngine.checkThread(); zoomProperty().set(value); } /** * Returns current zoom factor applied to the whole page contents. * @return current zoom factor * @see #zoomProperty() * @see #setZoom(double value) * @since JavaFX 8.0 */ public final double getZoom() { return (this.zoom != null) ? this.zoom.get() : DEFAULT_ZOOM; } /** * Returns zoom property object. * @return zoom property object * @see #getZoom() * @see #setZoom(double value) * @since JavaFX 8.0 */ public final DoubleProperty zoomProperty() { if (zoom == null) { zoom = new StyleableDoubleProperty(DEFAULT_ZOOM) { @Override public void invalidated() { Toolkit.getToolkit().checkFxUserThread(); } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.ZOOM; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "zoom"; } }; } return zoom; } /** * Specifies scale factor applied to font. This setting affects * text content but not images and fixed size elements. * * @defaultValue 1.0 */ private DoubleProperty fontScale; public final void setFontScale(double value) { WebEngine.checkThread(); fontScaleProperty().set(value); } public final double getFontScale() { return (this.fontScale != null) ? this.fontScale.get() : DEFAULT_FONT_SCALE; } public DoubleProperty fontScaleProperty() { if (fontScale == null) { fontScale = new StyleableDoubleProperty(DEFAULT_FONT_SCALE) { @Override public void invalidated() { Toolkit.getToolkit().checkFxUserThread(); } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.FONT_SCALE; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "fontScale"; } }; } return fontScale; } /** * Creates a {@code WebView} object. */ public WebView() { long[] nativeHandle = new long[1]; _initWebView(nativeHandle); getStyleClass().add("web-view"); handle = nativeHandle[0]; engine = new WebEngine(); engine.setView(this); stagePulseListener = () -> { handleStagePulse(); }; focusedProperty().addListener((ov, t, t1) -> { }); Toolkit.getToolkit().addStageTkPulseListener(stagePulseListener); final ChangeListener<Bounds> chListener = new ChangeListener<Bounds>() { @Override public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) { NodeHelper.transformsChanged(WebView.this); } }; parentProperty().addListener(new ChangeListener<Parent>(){ @Override public void changed(ObservableValue<? extends Parent> observable, Parent oldValue, Parent newValue) { if (oldValue != null && newValue == null) { // webview has been removed from scene _removeWebView(handle); } if (oldValue != null) { do { oldValue.boundsInParentProperty().removeListener(chListener); oldValue = oldValue.getParent(); } while (oldValue != null); } if (newValue != null) { do { final Node n = newValue; newValue.boundsInParentProperty().addListener(chListener); newValue = newValue.getParent(); } while (newValue != null); } } }); layoutBoundsProperty().addListener(new ChangeListener<Bounds>() { @Override public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) { Affine3D trans = calculateNodeToSceneTransform(WebView.this); _setTransform(handle, trans.getMxx(), trans.getMxy(), trans.getMxz(), trans.getMxt(), trans.getMyx(), trans.getMyy(), trans.getMyz(), trans.getMyt(), trans.getMzx(), trans.getMzy(), trans.getMzz(), trans.getMzt()); } }); impl_treeVisibleProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { _setVisible(handle, newValue); } }); } // Resizing support. Allows arbitrary growing and shrinking. // Designed after javafx.scene.control.Control @Override public boolean isResizable() { return true; } @Override public void resize(double width, double height) { this.width.set(width); this.height.set(height); NodeHelper.markDirty(this, DirtyBits.NODE_GEOMETRY); NodeHelper.geomChanged(this); _setWidth(handle, width); _setHeight(handle, height); } /** * Called during layout to determine the minimum width for this node. * * @return the minimum width that this node should be resized to during layout */ @Override public final double minWidth(double height) { return getMinWidth(); } /** * Called during layout to determine the minimum height for this node. * * @return the minimum height that this node should be resized to during layout */ @Override public final double minHeight(double width) { return getMinHeight(); } /** * Called during layout to determine the preferred width for this node. * * @return the preferred width that this node should be resized to during layout */ @Override public final double prefWidth(double height) { return getPrefWidth(); } /** * Called during layout to determine the preferred height for this node. * * @return the preferred height that this node should be resized to during layout */ @Override public final double prefHeight(double width) { return getPrefHeight(); } /** * Called during layout to determine the maximum width for this node. * * @return the maximum width that this node should be resized to during layout */ @Override public final double maxWidth(double height) { return getMaxWidth(); } /** * Called during layout to determine the maximum height for this node. * * @return the maximum height that this node should be resized to during layout */ @Override public final double maxHeight(double width) { return getMaxHeight(); } /** * Minimum width property. */ public DoubleProperty minWidthProperty() { if (minWidth == null) { minWidth = new StyleableDoubleProperty(DEFAULT_MIN_WIDTH) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.MIN_WIDTH; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "minWidth"; } }; } return minWidth; } private DoubleProperty minWidth; /** * Sets minimum width. */ public final void setMinWidth(double value) { minWidthProperty().set(value); _setWidth(handle, value); } /** * Returns minimum width. */ public final double getMinWidth() { return (this.minWidth != null) ? this.minWidth.get() : DEFAULT_MIN_WIDTH; } /** * Minimum height property. */ public DoubleProperty minHeightProperty() { if (minHeight == null) { minHeight = new StyleableDoubleProperty(DEFAULT_MIN_HEIGHT) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.MIN_HEIGHT; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "minHeight"; } }; } return minHeight; } private DoubleProperty minHeight; /** * Sets minimum height. */ public final void setMinHeight(double value) { minHeightProperty().set(value); _setHeight(handle, value); } /** * Sets minimum height. */ public final double getMinHeight() { return (this.minHeight != null) ? this.minHeight.get() : DEFAULT_MIN_HEIGHT; } /** * Convenience method for setting minimum width and height. */ public void setMinSize(double minWidth, double minHeight) { setMinWidth(minWidth); setMinHeight(minHeight); _setWidth(handle, minWidth); _setHeight(handle, minHeight); } /** * Preferred width property. */ public DoubleProperty prefWidthProperty() { if (prefWidth == null) { prefWidth = new StyleableDoubleProperty(DEFAULT_PREF_WIDTH) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.PREF_WIDTH; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "prefWidth"; } }; } return prefWidth; } private DoubleProperty prefWidth; /** * Sets preferred width. */ public final void setPrefWidth(double value) { prefWidthProperty().set(value); _setWidth(handle, value); } /** * Returns preferred width. */ public final double getPrefWidth() { return (this.prefWidth != null) ? this.prefWidth.get() : DEFAULT_PREF_WIDTH; } /** * Preferred height property. */ public DoubleProperty prefHeightProperty() { if (prefHeight == null) { prefHeight = new StyleableDoubleProperty(DEFAULT_PREF_HEIGHT) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.PREF_HEIGHT; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "prefHeight"; } }; } return prefHeight; } private DoubleProperty prefHeight; /** * Sets preferred height. */ public final void setPrefHeight(double value) { prefHeightProperty().set(value); _setHeight(handle, value); } /** * Returns preferred height. */ public final double getPrefHeight() { return (this.prefHeight != null) ? this.prefHeight.get() : DEFAULT_PREF_HEIGHT; } /** * Convenience method for setting preferred width and height. */ public void setPrefSize(double prefWidth, double prefHeight) { setPrefWidth(prefWidth); setPrefHeight(prefHeight); _setWidth(handle, prefWidth); _setHeight(handle, prefHeight); } /** * Maximum width property. */ public DoubleProperty maxWidthProperty() { if (maxWidth == null) { maxWidth = new StyleableDoubleProperty(DEFAULT_MAX_WIDTH) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.MAX_WIDTH; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "maxWidth"; } }; } return maxWidth; } private DoubleProperty maxWidth; /** * Sets maximum width. */ public final void setMaxWidth(double value) { maxWidthProperty().set(value); _setWidth(handle, value); } /** * Returns maximum width. */ public final double getMaxWidth() { return (this.maxWidth != null) ? this.maxWidth.get() : DEFAULT_MAX_WIDTH; } /** * Maximum height property. */ public DoubleProperty maxHeightProperty() { if (maxHeight == null) { maxHeight = new StyleableDoubleProperty(DEFAULT_MAX_HEIGHT) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.MAX_HEIGHT; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "maxHeight"; } }; } return maxHeight; } private DoubleProperty maxHeight; /** * Sets maximum height. */ public final void setMaxHeight(double value) { maxHeightProperty().set(value); _setHeight(handle, value); } /** * Returns maximum height. */ public final double getMaxHeight() { return (this.maxHeight != null) ? this.maxHeight.get() : DEFAULT_MAX_HEIGHT; } /** * Convenience method for setting maximum width and height. */ public void setMaxSize(double maxWidth, double maxHeight) { setMaxWidth(maxWidth); setMaxHeight(maxHeight); _setWidth(handle, maxWidth); _setHeight(handle, maxHeight); } /** * Specifies a requested font smoothing type : gray or LCD. * * The width of the bounding box is defined by the widest row. * * Note: LCD mode doesn't apply in numerous cases, such as various * compositing modes, where effects are applied and very large glyphs. * * @defaultValue FontSmoothingType.LCD * @since JavaFX 2.2 */ private ObjectProperty<FontSmoothingType> fontSmoothingType; public final void setFontSmoothingType(FontSmoothingType value) { fontSmoothingTypeProperty().set(value); } public final FontSmoothingType getFontSmoothingType() { return (this.fontSmoothingType != null) ? this.fontSmoothingType.get() : DEFAULT_FONT_SMOOTHING_TYPE; } public final ObjectProperty<FontSmoothingType> fontSmoothingTypeProperty() { if (this.fontSmoothingType == null) { this.fontSmoothingType = new StyleableObjectProperty<FontSmoothingType>(DEFAULT_FONT_SMOOTHING_TYPE) { @Override public void invalidated() { Toolkit.getToolkit().checkFxUserThread(); } @Override public CssMetaData<WebView, FontSmoothingType> getCssMetaData() { return StyleableProperties.FONT_SMOOTHING_TYPE; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "fontSmoothingType"; } }; } return this.fontSmoothingType; } /** * Specifies whether context menu is enabled. * * @defaultValue true * @since JavaFX 2.2 */ private BooleanProperty contextMenuEnabled; public final void setContextMenuEnabled(boolean value) { contextMenuEnabledProperty().set(value); } public final boolean isContextMenuEnabled() { return contextMenuEnabled == null ? DEFAULT_CONTEXT_MENU_ENABLED : contextMenuEnabled.get(); } public final BooleanProperty contextMenuEnabledProperty() { if (contextMenuEnabled == null) { contextMenuEnabled = new StyleableBooleanProperty(DEFAULT_CONTEXT_MENU_ENABLED) { @Override public void invalidated() { Toolkit.getToolkit().checkFxUserThread(); } @Override public CssMetaData<WebView, Boolean> getCssMetaData() { return StyleableProperties.CONTEXT_MENU_ENABLED; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "contextMenuEnabled"; } }; } return contextMenuEnabled; } /** * Super-lazy instantiation pattern from Bill Pugh. */ private static final class StyleableProperties { private static final CssMetaData<WebView, Boolean> CONTEXT_MENU_ENABLED = new CssMetaData<WebView, Boolean>( "-fx-context-menu-enabled", BooleanConverter.getInstance(), DEFAULT_CONTEXT_MENU_ENABLED) { @Override public boolean isSettable(WebView view) { return view.contextMenuEnabled == null || !view.contextMenuEnabled.isBound(); } @Override public StyleableProperty<Boolean> getStyleableProperty(WebView view) { return (StyleableProperty<Boolean>)view.contextMenuEnabledProperty(); } }; private static final CssMetaData<WebView, FontSmoothingType> FONT_SMOOTHING_TYPE = new CssMetaData<WebView, FontSmoothingType>( "-fx-font-smoothing-type", new EnumConverter<FontSmoothingType>(FontSmoothingType.class), DEFAULT_FONT_SMOOTHING_TYPE) { @Override public boolean isSettable(WebView view) { return view.fontSmoothingType == null || !view.fontSmoothingType.isBound(); } @Override public StyleableProperty<FontSmoothingType> getStyleableProperty(WebView view) { return (StyleableProperty<FontSmoothingType>)view.fontSmoothingTypeProperty(); } }; private static final CssMetaData<WebView, Number> ZOOM = new CssMetaData<WebView, Number>( "-fx-zoom", SizeConverter.getInstance(), DEFAULT_ZOOM) { @Override public boolean isSettable(WebView view) { return view.zoom == null || !view.zoom.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.zoomProperty(); } }; private static final CssMetaData<WebView, Number> FONT_SCALE = new CssMetaData<WebView, Number>( "-fx-font-scale", SizeConverter.getInstance(), DEFAULT_FONT_SCALE) { @Override public boolean isSettable(WebView view) { return view.fontScale == null || !view.fontScale.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.fontScaleProperty(); } }; private static final CssMetaData<WebView, Number> MIN_WIDTH = new CssMetaData<WebView, Number>( "-fx-min-width", SizeConverter.getInstance(), DEFAULT_MIN_WIDTH) { @Override public boolean isSettable(WebView view) { return view.minWidth == null || !view.minWidth.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.minWidthProperty(); } }; private static final CssMetaData<WebView, Number> MIN_HEIGHT = new CssMetaData<WebView, Number>( "-fx-min-height", SizeConverter.getInstance(), DEFAULT_MIN_HEIGHT) { @Override public boolean isSettable(WebView view) { return view.minHeight == null || !view.minHeight.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.minHeightProperty(); } }; private static final CssMetaData<WebView, Number> MAX_WIDTH = new CssMetaData<WebView, Number>( "-fx-max-width", SizeConverter.getInstance(), DEFAULT_MAX_WIDTH) { @Override public boolean isSettable(WebView view) { return view.maxWidth == null || !view.maxWidth.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.maxWidthProperty(); } }; private static final CssMetaData<WebView, Number> MAX_HEIGHT = new CssMetaData<WebView, Number>( "-fx-max-height", SizeConverter.getInstance(), DEFAULT_MAX_HEIGHT) { @Override public boolean isSettable(WebView view) { return view.maxHeight == null || !view.maxHeight.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.maxHeightProperty(); } }; private static final CssMetaData<WebView, Number> PREF_WIDTH = new CssMetaData<WebView, Number>( "-fx-pref-width", SizeConverter.getInstance(), DEFAULT_PREF_WIDTH) { @Override public boolean isSettable(WebView view) { return view.prefWidth == null || !view.prefWidth.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.prefWidthProperty(); } }; private static final CssMetaData<WebView, Number> PREF_HEIGHT = new CssMetaData<WebView, Number>( "-fx-pref-height", SizeConverter.getInstance(), DEFAULT_PREF_HEIGHT) { @Override public boolean isSettable(WebView view) { return view.prefHeight == null || !view.prefHeight.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.prefHeightProperty(); } }; private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; static { List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<CssMetaData<? extends Styleable, ?>>(Parent.getClassCssMetaData()); styleables.add(CONTEXT_MENU_ENABLED); styleables.add(FONT_SMOOTHING_TYPE); styleables.add(ZOOM); styleables.add(FONT_SCALE); styleables.add(MIN_WIDTH); styleables.add(PREF_WIDTH); styleables.add(MAX_WIDTH); styleables.add(MIN_HEIGHT); styleables.add(PREF_HEIGHT); styleables.add(MAX_HEIGHT); STYLEABLES = Collections.unmodifiableList(styleables); } } /** * @return The CssMetaData associated with this class, which may include the * CssMetaData of its superclasses. * @since JavaFX 8.0 */ public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return StyleableProperties.STYLEABLES; } /** * {@inheritDoc} * @since JavaFX 8.0 */ @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return getClassCssMetaData(); } // event handling private void handleStagePulse() { // The stage pulse occurs before the scene pulse. // Here the page content is updated before CSS/Layout/Sync pass // is initiated by the scene pulse. The update may // change the WebView children and, if so, the children should be // processed right away during the scene pulse. // The WebView node does not render its pending render queues // while it is invisible. Therefore, we should not schedule new // render queues while the WebView is invisible to prevent // the list of render queues from growing infinitely. // Also, if and when the WebView becomes invisible, the currently // pending render queues, if any, become obsolete and should be // discarded. boolean reallyVisible = impl_isTreeVisible() && getScene() != null && getScene().getWindow() != null && getScene().getWindow().isShowing(); if (reallyVisible) { if (NodeHelper.isDirty(this, DirtyBits.WEBVIEW_VIEW)) { SceneHelper.setAllowPGAccess(true); //getPGWebView().update(); // creates new render queues SceneHelper.setAllowPGAccess(false); } } else { _setVisible(handle, false); } } @Override protected ObservableList<Node> getChildren() { return super.getChildren(); } // Node stuff /* * Note: This method MUST only be called via its accessor method. */ private NGNode doCreatePeer() { // return new NGWebView(); return null; // iOS doesn't need this method. } /* * Note: This method MUST only be called via its accessor method. */ private BaseBounds doComputeGeomBounds(BaseBounds bounds, BaseTransform tx) { bounds.deriveWithNewBounds(0, 0, 0, (float) getWidth(), (float)getHeight(), 0); tx.transform(bounds, bounds); return bounds; } /* * Note: This method MUST only be called via its accessor method. */ private boolean doComputeContains(double localX, double localY) { // Note: Local bounds contain test is already done by the caller. (Node.contains()). return true; } /* * Note: This method MUST only be called via its accessor method. */ private void doUpdatePeer() { //PGWebView peer = getPGWebView(); if (NodeHelper.isDirty(this, DirtyBits.NODE_GEOMETRY)) { //peer.resize((float)getWidth(), (float)getHeight()); } if (NodeHelper.isDirty(this, DirtyBits.WEBVIEW_VIEW)) { //peer.requestRender(); } } private static Affine3D calculateNodeToSceneTransform(Node node) { final Affine3D transform = new Affine3D(); do { transform.preConcatenate(NodeHelper.getLeafTransform(node)); node = node.getParent(); } while (node != null); return transform; } /* * Note: This method MUST only be called via its accessor method. */ private void doTransformsChanged() { Affine3D trans = calculateNodeToSceneTransform(this); _setTransform(handle, trans.getMxx(), trans.getMxy(), trans.getMxz(), trans.getMxt(), trans.getMyx(), trans.getMyy(), trans.getMyz(), trans.getMyt(), trans.getMzx(), trans.getMzy(), trans.getMzz(), trans.getMzt()); } long getNativeHandle() { return handle; } // native callbacks private void notifyLoadStarted() { engine.notifyLoadStarted(); } private void notifyLoadFinished(String loc, String content) { engine.notifyLoadFinished(loc, content); } private void notifyLoadFailed() { engine.notifyLoadFailed(); } private void notifyJavaCall(String arg) { engine.notifyJavaCall(arg); } /* Inits native WebView and returns its pointer in the given array */ private native void _initWebView(long[] nativeHandle); /* Sets width of the native WebView */ private native void _setWidth(long handle, double w); /* Sets height of the native WebView */ private native void _setHeight(long handle, double h); /* Sets visibility of the native WebView */ private native void _setVisible(long handle, boolean v); /* Removes the native WebView from scene */ private native void _removeWebView(long handle); /* Applies transform on the native WebView */ private native void _setTransform(long handle, double mxx, double mxy, double mxz, double mxt, double myx, double myy, double myz, double myt, double mzx, double mzy, double mzz, double mzt); }
teamfx/openjfx-9-dev-rt
modules/javafx.web/src/ios/java/javafx/scene/web/WebView.java
Java
gpl-2.0
38,327
// -*- mode: cpp; mode: fold -*- // Description /*{{{*/ // $Id: mirror.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $ /* ###################################################################### Mirror Aquire Method - This is the Mirror aquire method for APT. ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ #include <apt-pkg/fileutl.h> #include <apt-pkg/acquire-method.h> #include <apt-pkg/acquire-item.h> #include <apt-pkg/acquire.h> #include <apt-pkg/error.h> #include <apt-pkg/hashes.h> #include <apt-pkg/sourcelist.h> #include <fstream> #include <iostream> #include <stdarg.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> using namespace std; #include<sstream> #include "mirror.h" #include "http.h" #include "apti18n.h" /*}}}*/ /* Done: * - works with http (only!) * - always picks the first mirror from the list * - call out to problem reporting script * - supports "deb mirror://host/path/to/mirror-list/// dist component" * - uses pkgAcqMethod::FailReason() to have a string representation * of the failure that is also send to LP * * TODO: * - deal with runing as non-root because we can't write to the lists dir then -> use the cached mirror file * - better method to download than having a pkgAcquire interface here * and better error handling there! * - support more than http * - testing :) */ MirrorMethod::MirrorMethod() : HttpMethod(), DownloadedMirrorFile(false) { }; // HttpMethod::Configuration - Handle a configuration message /*{{{*/ // --------------------------------------------------------------------- /* We stash the desired pipeline depth */ bool MirrorMethod::Configuration(string Message) { if (pkgAcqMethod::Configuration(Message) == false) return false; Debug = _config->FindB("Debug::Acquire::mirror",false); return true; } /*}}}*/ // clean the mirrors dir based on ttl information bool MirrorMethod::Clean(string Dir) { vector<metaIndex *>::const_iterator I; if(Debug) clog << "MirrorMethod::Clean(): " << Dir << endl; if(Dir == "/") return _error->Error("will not clean: '/'"); // read sources.list pkgSourceList list; list.ReadMainList(); DIR *D = opendir(Dir.c_str()); if (D == 0) return _error->Errno("opendir",_("Unable to read %s"),Dir.c_str()); string StartDir = SafeGetCWD(); if (chdir(Dir.c_str()) != 0) { closedir(D); return _error->Errno("chdir",_("Unable to change to %s"),Dir.c_str()); } for (struct dirent *Dir = readdir(D); Dir != 0; Dir = readdir(D)) { // Skip some files.. if (strcmp(Dir->d_name,"lock") == 0 || strcmp(Dir->d_name,"partial") == 0 || strcmp(Dir->d_name,".") == 0 || strcmp(Dir->d_name,"..") == 0) continue; // see if we have that uri for(I=list.begin(); I != list.end(); I++) { string uri = (*I)->GetURI(); if(uri.find("mirror://") != 0) continue; string BaseUri = uri.substr(0,uri.size()-1); if (URItoFileName(BaseUri) == Dir->d_name) break; } // nothing found, nuke it if (I == list.end()) unlink(Dir->d_name); }; chdir(StartDir.c_str()); closedir(D); return true; } bool MirrorMethod::DownloadMirrorFile(string mirror_uri_str) { if(Debug) clog << "MirrorMethod::DownloadMirrorFile(): " << endl; // not that great to use pkgAcquire here, but we do not have // any other way right now string fetch = BaseUri; fetch.replace(0,strlen("mirror://"),"http://"); pkgAcquire Fetcher; new pkgAcqFile(&Fetcher, fetch, "", 0, "", "", "", MirrorFile); bool res = (Fetcher.Run() == pkgAcquire::Continue); if(res) DownloadedMirrorFile = true; Fetcher.Shutdown(); return res; } /* convert a the Queue->Uri back to the mirror base uri and look * at all mirrors we have for this, this is needed as queue->uri * may point to different mirrors (if TryNextMirror() was run) */ void MirrorMethod::CurrentQueueUriToMirror() { // already in mirror:// style so nothing to do if(Queue->Uri.find("mirror://") == 0) return; // find current mirror and select next one for (vector<string>::const_iterator mirror = AllMirrors.begin(); mirror != AllMirrors.end(); ++mirror) { if (Queue->Uri.find(*mirror) == 0) { Queue->Uri.replace(0, mirror->length(), BaseUri); return; } } _error->Error("Internal error: Failed to convert %s back to %s", Queue->Uri.c_str(), BaseUri.c_str()); } bool MirrorMethod::TryNextMirror() { // find current mirror and select next one for (vector<string>::const_iterator mirror = AllMirrors.begin(); mirror != AllMirrors.end(); ++mirror) { if (Queue->Uri.find(*mirror) != 0) continue; vector<string>::const_iterator nextmirror = mirror + 1; if (nextmirror != AllMirrors.end()) break; Queue->Uri.replace(0, mirror->length(), *nextmirror); if (Debug) clog << "TryNextMirror: " << Queue->Uri << endl; return true; } if (Debug) clog << "TryNextMirror could not find another mirror to try" << endl; return false; } bool MirrorMethod::InitMirrors() { // if we do not have a MirrorFile, fallback if(!FileExists(MirrorFile)) { // FIXME: fallback to a default mirror here instead // and provide a config option to define that default return _error->Error(_("No mirror file '%s' found "), MirrorFile.c_str()); } // FIXME: make the mirror selection more clever, do not // just use the first one! // BUT: we can not make this random, the mirror has to be // stable accross session, because otherwise we can // get into sync issues (got indexfiles from mirror A, // but packages from mirror B - one might be out of date etc) ifstream in(MirrorFile.c_str()); string s; while (!in.eof()) { getline(in, s); if (s.size() > 0) AllMirrors.push_back(s); } Mirror = AllMirrors[0]; UsedMirror = Mirror; return true; } string MirrorMethod::GetMirrorFileName(string mirror_uri_str) { /* - a mirror_uri_str looks like this: mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors/dists/feisty/Release.gpg - the matching source.list entry deb mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors feisty main - we actually want to go after: http://people.ubuntu.com/~mvo/apt/mirror/mirrors And we need to save the BaseUri for later: - mirror://people.ubuntu.com/~mvo/apt/mirror/mirrors FIXME: what if we have two similar prefixes? mirror://people.ubuntu.com/~mvo/mirror mirror://people.ubuntu.com/~mvo/mirror2 then mirror_uri_str looks like: mirror://people.ubuntu.com/~mvo/apt/mirror/dists/feisty/Release.gpg mirror://people.ubuntu.com/~mvo/apt/mirror2/dists/feisty/Release.gpg we search sources.list and find: mirror://people.ubuntu.com/~mvo/apt/mirror in both cases! So we need to apply some domain knowledge here :( and check for /dists/ or /Release.gpg as suffixes */ string name; if(Debug) std::cerr << "GetMirrorFileName: " << mirror_uri_str << std::endl; // read sources.list and find match vector<metaIndex *>::const_iterator I; pkgSourceList list; list.ReadMainList(); for(I=list.begin(); I != list.end(); I++) { string uristr = (*I)->GetURI(); if(Debug) std::cerr << "Checking: " << uristr << std::endl; if(uristr.substr(0,strlen("mirror://")) != string("mirror://")) continue; // find matching uri in sources.list if(mirror_uri_str.substr(0,uristr.size()) == uristr) { if(Debug) std::cerr << "found BaseURI: " << uristr << std::endl; BaseUri = uristr.substr(0,uristr.size()-1); } } // get new file name = _config->FindDir("Dir::State::mirrors") + URItoFileName(BaseUri); if(Debug) { cerr << "base-uri: " << BaseUri << endl; cerr << "mirror-file: " << name << endl; } return name; } // MirrorMethod::Fetch - Fetch an item /*{{{*/ // --------------------------------------------------------------------- /* This adds an item to the pipeline. We keep the pipeline at a fixed depth. */ bool MirrorMethod::Fetch(FetchItem *Itm) { if(Debug) clog << "MirrorMethod::Fetch()" << endl; // the http method uses Fetch(0) as a way to update the pipeline, // just let it do its work in this case - Fetch() with a valid // Itm will always run before the first Fetch(0) if(Itm == NULL) return HttpMethod::Fetch(Itm); // if we don't have the name of the mirror file on disk yet, // calculate it now (can be derived from the uri) if(MirrorFile.empty()) MirrorFile = GetMirrorFileName(Itm->Uri); // download mirror file once (if we are after index files) if(Itm->IndexFile && !DownloadedMirrorFile) { Clean(_config->FindDir("Dir::State::mirrors")); DownloadMirrorFile(Itm->Uri); } if(AllMirrors.empty()) { if(!InitMirrors()) { // no valid mirror selected, something went wrong downloading // from the master mirror site most likely and there is // no old mirror file availalbe return false; } } if(Itm->Uri.find("mirror://") != string::npos) Itm->Uri.replace(0,BaseUri.size(), Mirror); if(Debug) clog << "Fetch: " << Itm->Uri << endl << endl; // now run the real fetcher return HttpMethod::Fetch(Itm); }; void MirrorMethod::Fail(string Err,bool Transient) { // FIXME: TryNextMirror is not ideal for indexfile as we may // run into auth issues if (Debug) clog << "Failure to get " << Queue->Uri << endl; // try the next mirror on fail (if its not a expected failure, // e.g. translations are ok to ignore) if (!Queue->FailIgnore && TryNextMirror()) return; // all mirrors failed, so bail out string s; strprintf(s, _("[Mirror: %s]"), Mirror.c_str()); SetIP(s); CurrentQueueUriToMirror(); pkgAcqMethod::Fail(Err, Transient); } void MirrorMethod::URIStart(FetchResult &Res) { CurrentQueueUriToMirror(); pkgAcqMethod::URIStart(Res); } void MirrorMethod::URIDone(FetchResult &Res,FetchResult *Alt) { CurrentQueueUriToMirror(); pkgAcqMethod::URIDone(Res, Alt); } int main() { setlocale(LC_ALL, ""); MirrorMethod Mth; return Mth.Loop(); }
AskDrCatcher/apt-src
methods/mirror.cc
C++
gpl-2.0
10,450
/****************************************************************************** * Warmux is a convivial mass murder game. * Copyright (C) 2001-2010 Warmux Team. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA ****************************************************************************** * Game menu *****************************************************************************/ #include <WARMUX_index_server.h> #include <WARMUX_team_config.h> #include "menu/network_menu.h" #include "menu/network_teams_selection_box.h" #include "menu/map_selection_box.h" #include "game/config.h" #include "game/game.h" #include "game/game_mode.h" #include "graphic/video.h" #include "gui/button.h" #include "gui/check_box.h" #include "gui/combo_box.h" #include "gui/grid_box.h" #include "gui/label.h" #include "gui/msg_box.h" #include "gui/picture_widget.h" #include "gui/spin_button.h" #include "gui/tabs.h" #include "gui/talk_box.h" #include "gui/text_box.h" #include "include/action_handler.h" #include "include/app.h" #include "include/constant.h" #include "network/network.h" #include "network/network_client.h" #include "network/network_server.h" #include "sound/jukebox.h" #include "team/teams_list.h" #include "team/team.h" #include "tool/resource_manager.h" static const uint MARGIN_TOP = 5; static const uint MARGIN_SIDE = 5; static const uint MARGIN_BOTTOM = 40; NetworkMenu::NetworkMenu() : Menu("menu/bg_network") { waiting_for_server = false; Profile *res = GetResourceManager().LoadXMLProfile( "graphism.xml",false); Point2i pointZero(W_UNDEF, W_UNDEF); Surface& window = GetMainWindow(); // Calculate main box size int chat_box_height = window.GetHeight()/4; int team_box_height = 180; int mainBoxWidth = window.GetWidth() - 2*MARGIN_SIDE; int mainBoxHeight = window.GetHeight() - MARGIN_TOP - MARGIN_BOTTOM - 2*MARGIN_SIDE - chat_box_height; int mapsHeight = mainBoxHeight - team_box_height - 60; int multitabsWidth = mainBoxWidth; bool multitabs = false; if (window.GetWidth() > 640 && mapsHeight > 200) { multitabs = true; multitabsWidth = mainBoxWidth - 20; mapsHeight = 200; team_box_height = mainBoxHeight - 200 - 60; } else { mapsHeight = mainBoxHeight - 60; team_box_height = mainBoxHeight - 60; } MultiTabs * tabs = new MultiTabs(Point2i(mainBoxWidth, mainBoxHeight)); // ################################################ // ## TEAM AND MAP SELECTION // ################################################ team_box = new NetworkTeamsSelectionBox(Point2i(multitabsWidth-4, team_box_height), multitabs); map_box = new MapSelectionBox(Point2i(multitabsWidth, mapsHeight), multitabs, !Network::GetInstance()->IsGameMaster()); if (!multitabs) { tabs->AddNewTab("TAB_Team", _("Teams"), team_box); tabs->AddNewTab("TAB_Map", _("Map"), map_box); } else { VBox *box = new VBox(mainBoxWidth, false, false, true); std::string tabs_title = _("Teams") + std::string(" - "); tabs_title += _("Map"); box->AddWidget(team_box); box->AddWidget(map_box); tabs->AddNewTab("TAB_Team_Map", tabs_title, box); } // ################################################ // ## GAME OPTIONS // ################################################ if (Network::GetInstance()->IsGameMaster()) { // Using the game mode editor but currently we are not able to send // custom parameters to client Box *box = new GridBox(4, 4, 0, false); Point2i option_size(114, 114); std::string selected_gamemode = Config::GetInstance()->GetGameMode(); opt_game_mode = new ComboBox(_("Game mode"), "menu/game_mode", option_size, GameMode::ListGameModes(), selected_gamemode); box->AddWidget(opt_game_mode); tabs->AddNewTab("TAB_Game", _("Game"), box); } tabs->SetPosition(MARGIN_SIDE, MARGIN_TOP); widgets.AddWidget(tabs); widgets.Pack(); Box* bottom_box = new HBox(chat_box_height, false, false, true); bottom_box->SetNoBorder(); Box* options_box = new VBox(200, true, true); mode_label = new Label("", 0, Font::FONT_MEDIUM, Font::FONT_BOLD, primary_red_color, Text::ALIGN_LEFT_TOP, true); options_box->AddWidget(mode_label); play_in_loop = new CheckBox(_("Play several times"), W_UNDEF, true); options_box->AddWidget(play_in_loop); connected_players = new Label(Format(ngettext("%i player connected", "%i players connected", 0), 0), 0, Font::FONT_SMALL, Font::FONT_BOLD); options_box->AddWidget(connected_players); initialized_players = new Label(Format(ngettext("%i player ready", "%i players ready", 0), 0), 0, Font::FONT_SMALL, Font::FONT_BOLD); options_box->AddWidget(initialized_players); options_box->Pack(); bottom_box->AddWidget(options_box); // ################################################ // ## CHAT BOX // ################################################ msg_box = new TalkBox(Point2i(mainBoxWidth - options_box->GetSizeX() - MARGIN_SIDE, chat_box_height), Font::FONT_SMALL, Font::FONT_BOLD); msg_box->SetPosition(options_box->GetPositionX() + options_box->GetSizeX() + MARGIN_SIDE, options_box->GetPositionY()); bottom_box->AddWidget(msg_box); bottom_box->SetPosition(MARGIN_SIDE, tabs->GetPositionY() + tabs->GetSizeY() + MARGIN_SIDE); widgets.AddWidget(bottom_box); widgets.Pack(); GetResourceManager().UnLoadXMLProfile(res); if (!Network::GetInstance()->IsServer()) { // First %s will be replaced with the name of the network game, // second %s by the server hostname msg_box->NewMessage(Format(_("Welcome to %s on %s!"), Network::GetInstance()->GetGameName().c_str(), ((NetworkClient*)Network::GetInstance())->GetServerAddress().c_str()) , c_red); } if (!Network::GetInstance()->IsGameMaster()) { // Client Mode mode_label->SetText(_("Client mode")); initialized_players->SetVisible(false); msg_box->NewMessage(_("Don't forget to validate once you have selected your team(s)!"), c_red); } else if (Network::GetInstance()->IsServer()) { // Server Mode mode_label->SetText(_("Server mode")); } else { // The first player to connect to a headless server asumes the game master role SetGameMasterCallback(); } } void NetworkMenu::signal_begin_run() { ActionHandler::GetInstance()->ExecFrameLessActions(); RequestSavedTeams(); } void NetworkMenu::RequestSavedTeams() { const std::list<ConfigTeam> & team_list = Config::GetInstance()->AccessNetworkTeamsList(); std::list<ConfigTeam>::const_iterator it; if (team_list.size() > 0) { for (it = team_list.begin(); it != team_list.end(); it++) { ActionHandler::GetInstance()->NewRequestTeamAction(*it); } } else { team_box->RequestTeam(); } } void NetworkMenu::SaveOptions() { // map map_box->ValidMapSelection(); // team team_box->ValidTeamsSelection(); //Save options in XML // Config::GetInstance()->Save(); if (Network::GetInstance()->IsGameMaster()) { Config::GetInstance()->SetGameMode(opt_game_mode->GetValue()); } } void NetworkMenu::PrepareForNewGame() { msg_box->Clear(); b_ok->SetVisible(true); Network::GetInstance()->SetState(WNet::NETWORK_NEXT_GAME); Network::GetInstance()->SendNetworkState(); // to choose another random map if (Network::GetInstance()->IsGameMaster()) map_box->ChangeMapDelta(0); RedrawMenu(); } bool NetworkMenu::signal_ok() { if (!Network::GetInstance()->IsGameMaster()) { // Check the user have selected a team: bool found = false; for(std::vector<Team*>::iterator team = GetTeamsList().playing_list.begin(); team != GetTeamsList().playing_list.end(); team++) { if((*team)->IsLocalHuman()) { found = true; break; } } if(!found) { msg_box->NewMessage(_("You won't be able to play before selecting a team!")); goto error; } // Wait for the game master, and stay in the menu map / team can still be changed WaitingForGameMaster(); if (Network::GetInstance()->IsGameMaster()) { goto error; } } else { if (GetTeamsList().playing_list.size() <= 1) { msg_box->NewMessage(Format(ngettext("There is only %i team.", "There are only %i teams.", GetTeamsList().playing_list.size()), GetTeamsList().playing_list.size()), c_red); goto error; } if (Network::GetInstance()->GetNbPlayersConnected() == 0) { msg_box->NewMessage(_("You are alone. :-/"), c_red); goto error; } if (Network::GetInstance()->GetNbPlayersConnected() != Network::GetInstance()->GetNbPlayersWithState(Player::STATE_INITIALIZED)) { int nbr = Network::GetInstance()->GetNbPlayersConnected() - Network::GetInstance()->GetNbPlayersWithState(Player::STATE_INITIALIZED); std::string pl = Format(ngettext("Wait! %i player is not ready yet!", "Wait! %i players are not ready yet!", nbr), nbr); msg_box->NewMessage(pl, c_red); goto error; } } // Disconnection :-/ if (!Network::IsConnected()) { Network::GetInstance()->network_menu = NULL; return true; } else { // Starting the game :-) SaveOptions(); play_ok_sound(); if (Network::GetInstance()->IsServer()) IndexServer::GetInstance()->Disconnect(); if (Network::GetInstance()->IsGameMaster()) GameMode::GetInstance()->Load(); Game::GetInstance()->Start(); if (Network::GetInstance()->IsConnected() && Network::GetInstance()->GetNbPlayersConnected() != 0 && play_in_loop->GetValue()) { PrepareForNewGame(); return false; } Network::GetInstance()->network_menu = NULL; } Network::Disconnect(); return true; error: play_error_sound(); return false; } void NetworkMenu::key_ok() { // return was pressed while chat texbox still had focus (player wants to send his msg) if (msg_box->TextHasFocus()) { msg_box->SendChatMsg(); return; } IndexServer::GetInstance()->Disconnect(); Menu::key_ok(); } bool NetworkMenu::signal_cancel() { Network::Disconnect(); return true; } void NetworkMenu::Draw(const Point2i& /*mousePosition*/) { if (Network::GetInstance()->IsConnected()) { //Refresh the number of connected players: int nbr = Network::GetInstance()->GetNbPlayersConnected() + 1; std::string pl = Format(ngettext("%i player connected", "%i players connected", nbr), nbr); if (connected_players->GetText() != pl) connected_players->SetText(pl); if (Network::GetInstance()->IsGameMaster()) { //Refresh the number of players ready (does not work on client): nbr = Network::GetInstance()->GetNbPlayersWithState(Player::STATE_INITIALIZED); if (Network::GetInstance()->GetState() == WNet::NETWORK_MENU_OK) nbr++; pl = Format(ngettext("%i player ready", "%i players ready", nbr), nbr); if (initialized_players->GetText() != pl) { initialized_players->SetText(pl); msg_box->NewMessage(pl, c_red); if (Network::GetInstance()->GetNbPlayersConnected() == Network::GetInstance()->GetNbPlayersWithState(Player::STATE_INITIALIZED)) { msg_box->NewMessage(_("The others are waiting for you! Wake up! :-)"), c_red); JukeBox::GetInstance()->Play("default", "menu/newcomer"); } else if (Network::GetInstance()->GetNbPlayersConnected() == 0) { msg_box->NewMessage(_("You are alone. :-/"), c_red); } } } } else { close_menu = true; } ActionHandler * action_handler = ActionHandler::GetInstance(); action_handler->ExecFrameLessActions(); } void NetworkMenu::DelTeamCallback(const std::string& team_id) { if( close_menu ) return; // Called from the action handler team_box->DelTeamCallback(team_id); } void NetworkMenu::AddTeamCallback(const std::string& team_id) { if ( close_menu ) return; team_box->AddTeamCallback(team_id); } void NetworkMenu::UpdateTeamCallback(const std::string& old_team_id, const std::string& team_id) { if ( close_menu ) return; team_box->UpdateTeamCallback(old_team_id, team_id); } void NetworkMenu::ChangeMapCallback() { if (close_menu) return; map_box->ChangeMapCallback(); } void NetworkMenu::SetGameMasterCallback() { // We are becoming game master, updating the menu... AppWarmux::GetInstance()->video->SetWindowCaption( std::string("Warmux ") + Constants::WARMUX_VERSION + " - " + _("Master mode")); mode_label->SetText(_("Master mode")); connected_players->SetVisible(true); initialized_players->SetVisible(true); map_box->AllowSelection(); b_ok->SetVisible(true); // make sure OK button is available if we had already clicked it waiting_for_server = false; msg_box->NewMessage(_("You are the new turn master!"), c_red); msg_box->NewMessage(_("Wait until some opponent(s) connect!"), c_red); } void NetworkMenu::ReceiveMsgCallback(const std::string& msg, const Color& color) { msg_box->NewMessage(msg, color); } Team * NetworkMenu::FindUnusedTeam(const std::string default_team_id) { return team_box->FindUnusedTeam(default_team_id); } bool NetworkMenu::HasOpenTeamSlot() { return team_box->HasOpenTeamSlot(); } // to be call from NetworkMenu::WaitingForGameMaster() void NetworkMenu::HandleEvent(const SDL_Event& evnt) { if (!waiting_for_server) { Menu::HandleEvent(evnt); return; } if (evnt.type == SDL_QUIT) { Menu::mouse_cancel(); } else if (evnt.type == SDL_KEYDOWN) { switch (evnt.key.keysym.sym) { case SDLK_ESCAPE: Menu::mouse_cancel(); break; case SDLK_RETURN: case SDLK_KP_ENTER: msg_box->SendChatMsg(); break; case SDLK_F10: AppWarmux::GetInstance()->video->ToggleFullscreen(); break; default: widgets.SendKey(evnt.key.keysym); break; } } else if (evnt.type == SDL_MOUSEBUTTONUP) { int x=0, y=0; SDL_GetMouseState( &x, &y ); Point2i mousePosition(x, y); if (b_cancel->Contains(mousePosition)) Menu::mouse_cancel(); } } void NetworkMenu::WaitingForGameMaster() { Network::GetInstance()->SetState(WNet::NETWORK_MENU_OK); // warn the server that we have validated the menu Network::GetInstance()->SendNetworkState(); waiting_for_server = true; b_ok->SetVisible(false); actions_buttons->NeedRedrawing(); msg_box->NewMessage(_("Waiting for the server. All you can do is cancel or chat!"), c_red); widgets.SetFocusOn(msg_box->GetTextBox()); do { HandleEvents(); int x=0, y=0; SDL_GetMouseState( &x, &y ); Point2i mousePosition(x, y); Display(mousePosition); Menu::Display(mousePosition); } while (Network::GetInstance()->IsConnected() && Network::GetInstance()->GetState() == WNet::NETWORK_MENU_OK); waiting_for_server = false; }
yeKcim/warmux
old/warmux-10.12/src/menu/network_menu.cpp
C++
gpl-2.0
15,942
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.swing; import java.awt.Graphics; import java.awt.Image; import java.awt.Insets; import java.awt.ItemSelectable; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.Serializable; import javax.accessibility.AccessibleAction; import javax.accessibility.AccessibleExtendedComponent; import javax.accessibility.AccessibleIcon; import javax.accessibility.AccessibleKeyBinding; import javax.accessibility.AccessibleRelationSet; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; import javax.accessibility.AccessibleText; import javax.accessibility.AccessibleValue; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ButtonUI; import javax.swing.plaf.InsetsUIResource; import javax.swing.plaf.UIResource; import javax.swing.text.AttributeSet; import org.apache.harmony.x.swing.ButtonCommons; import org.apache.harmony.x.swing.StringConstants; import org.apache.harmony.x.swing.Utilities; import org.apache.harmony.x.swing.internal.nls.Messages; /** * <p> * <i>AbstractButton</i> * </p> * <h3>Implementation Notes:</h3> * <ul> * <li>The <code>serialVersionUID</code> fields are explicitly declared as a performance * optimization, not as a guarantee of serialization compatibility.</li> * </ul> */ public abstract class AbstractButton extends JComponent implements ItemSelectable, SwingConstants { protected abstract class AccessibleAbstractButton extends AccessibleJComponent implements AccessibleAction, AccessibleValue, AccessibleText, AccessibleExtendedComponent, Serializable { @Override public AccessibleKeyBinding getAccessibleKeyBinding() { return null; } public int getAccessibleActionCount() { return 1; } @Override public String getToolTipText() { return AbstractButton.this.getToolTipText(); } @Override public AccessibleValue getAccessibleValue() { return this; } @Override public AccessibleText getAccessibleText() { return null; } @Override public String getAccessibleName() { return (super.getAccessibleName() != null) ? super.getAccessibleName() : getText(); } @Override public AccessibleRelationSet getAccessibleRelationSet() { return super.getAccessibleRelationSet(); } @Override public String getTitledBorderText() { return super.getTitledBorderText(); } @Override public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet set = super.getAccessibleStateSet(); if (isSelected()) { set.add(AccessibleState.CHECKED); } return set; } @Override public AccessibleIcon[] getAccessibleIcon() { if (icon != null && icon instanceof ImageIcon) { return new AccessibleIcon[] { (AccessibleIcon) ((ImageIcon) icon) .getAccessibleContext() }; } return null; } @Override public AccessibleAction getAccessibleAction() { return this; } public boolean doAccessibleAction(int index) { if (0 <= index && index < getAccessibleActionCount()) { return true; } return false; } public String getAccessibleActionDescription(int index) { if (0 <= index && index < getAccessibleActionCount()) { return "click"; } return null; } public Number getCurrentAccessibleValue() { return (AbstractButton.this.isSelected()) ? new Integer(1) : new Integer(0); } public Number getMaximumAccessibleValue() { return new Integer(1); } public Number getMinimumAccessibleValue() { return new Integer(0); } public boolean setCurrentAccessibleValue(Number value) { boolean valueSet = (value.intValue() == 0) ? false : true; if (valueSet != isSelected()) { setSelected(valueSet); if (valueSet) { firePropertyChange("AccessibleState", null, AccessibleState.SELECTED); firePropertyChange("AccessibleValue", new Integer(0), new Integer(1)); } else { firePropertyChange("AccessibleState", AccessibleState.SELECTED, null); firePropertyChange("AccessibleValue", new Integer(1), new Integer(0)); } } return true; } public int getCaretPosition() { return -1; } public int getCharCount() { String text = AbstractButton.this.getText(); return (text != null) ? text.length() : 0; } public int getSelectionEnd() { return -1; } public int getSelectionStart() { return -1; } public int getIndexAtPoint(Point point) { return -1; } public Rectangle getCharacterBounds(int arg0) { return null; } public String getSelectedText() { return null; } public String getAfterIndex(int part, int index) { return null; } public String getAtIndex(int part, int index) { return null; } public String getBeforeIndex(int part, int index) { return null; } public AttributeSet getCharacterAttribute(int index) { return null; } }; protected class ButtonChangeListener implements ChangeListener, Serializable { private static final long serialVersionUID = 1L; private ButtonChangeListener() { } public void stateChanged(ChangeEvent event) { int mn = model.getMnemonic(); updateMnemonic(mn, Utilities.keyCodeToKeyChar(mn)); fireStateChanged(); } }; private final class ActionAndModelListener implements ItemListener, ActionListener, PropertyChangeListener, Serializable { private static final long serialVersionUID = 1L; public void itemStateChanged(ItemEvent event) { fireItemStateChanged(event); } public void actionPerformed(ActionEvent event) { fireActionPerformed(event); } public void propertyChange(PropertyChangeEvent event) { configurePropertyFromAction((Action) event.getSource(), event.getPropertyName()); } }; public static final String MODEL_CHANGED_PROPERTY = "model"; public static final String TEXT_CHANGED_PROPERTY = "text"; public static final String MNEMONIC_CHANGED_PROPERTY = "mnemonic"; public static final String MARGIN_CHANGED_PROPERTY = "margin"; public static final String VERTICAL_ALIGNMENT_CHANGED_PROPERTY = "verticalAlignment"; public static final String HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY = "horizontalAlignment"; public static final String VERTICAL_TEXT_POSITION_CHANGED_PROPERTY = "verticalTextPosition"; public static final String HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY = "horizontalTextPosition"; public static final String BORDER_PAINTED_CHANGED_PROPERTY = "borderPainted"; public static final String FOCUS_PAINTED_CHANGED_PROPERTY = "focusPainted"; public static final String ROLLOVER_ENABLED_CHANGED_PROPERTY = "rolloverEnabled"; public static final String CONTENT_AREA_FILLED_CHANGED_PROPERTY = "contentAreaFilled"; public static final String ICON_CHANGED_PROPERTY = "icon"; public static final String PRESSED_ICON_CHANGED_PROPERTY = "pressedIcon"; public static final String SELECTED_ICON_CHANGED_PROPERTY = "selectedIcon"; public static final String ROLLOVER_ICON_CHANGED_PROPERTY = "rolloverIcon"; public static final String ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY = "rolloverSelectedIcon"; public static final String DISABLED_ICON_CHANGED_PROPERTY = "disabledIcon"; public static final String DISABLED_SELECTED_ICON_CHANGED_PROPERTY = "disabledSelectedIcon"; private static final Object ALL_ACTION_PROPERTIES = new Object() { // $NON-LOCK-1$ @Override public boolean equals(Object o) { return true; } }; private static final Action CLEAR_ACTION_PROPERTIES = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { } @Override public void putValue(String name, Object value) { } @Override public void setEnabled(boolean enabled) { } }; protected transient ChangeEvent changeEvent = new ChangeEvent(this); protected ButtonModel model; protected ChangeListener changeListener = createChangeListener(); protected ActionListener actionListener = createActionListener(); protected ItemListener itemListener = createItemListener(); private PropertyChangeListener actionPropertyChangeListener; private ActionAndModelListener handler; private String text = ""; private Insets margin; private Action action; private Icon icon; private Icon pressedIcon; private Icon disabledIcon; private Icon defaultDisabledIcon; private Icon selectedIcon; private Icon disabledSelectedIcon; private Icon defaultDisabledSelectedIcon; private Icon rolloverIcon; private Icon rolloverSelectedIcon; private boolean borderPainted = true; private boolean focusPainted = true; private boolean rolloverEnabled; private boolean contentAreaFilled = true; private int verticalAlignment = SwingConstants.CENTER; private int horizontalAlignment = SwingConstants.CENTER; private int verticalTextPosition = SwingConstants.CENTER; private int horizontalTextPosition = SwingConstants.TRAILING; private int iconTextGap = 4; private int mnemonic; private int mnemonicIndex = -1; private long multiClickThreshhold; private InsetsUIResource defaultMargin; protected void init(String text, Icon icon) { if (text != null) { setText(text); } if (icon != null) { setIcon(icon); } updateUI(); } protected PropertyChangeListener createActionPropertyChangeListener(Action action) { return (handler != null) ? handler : (handler = new ActionAndModelListener()); } public void setUI(ButtonUI ui) { super.setUI(ui); } public ButtonUI getUI() { return (ButtonUI) ui; } public void removeChangeListener(ChangeListener listener) { listenerList.remove(ChangeListener.class, listener); } public void addChangeListener(ChangeListener listener) { listenerList.add(ChangeListener.class, listener); } public ChangeListener[] getChangeListeners() { return listenerList.getListeners(ChangeListener.class); } protected ChangeListener createChangeListener() { return new ButtonChangeListener(); } public void setSelectedIcon(Icon selectedIcon) { Icon oldValue = this.selectedIcon; this.selectedIcon = selectedIcon; resetDefaultDisabledIcons(); firePropertyChange(SELECTED_ICON_CHANGED_PROPERTY, oldValue, selectedIcon); } public void setRolloverSelectedIcon(Icon rolloverSelectedIcon) { if (this.rolloverSelectedIcon != rolloverSelectedIcon) { Icon oldValue = this.rolloverSelectedIcon; this.rolloverSelectedIcon = rolloverSelectedIcon; firePropertyChange(ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY, oldValue, rolloverSelectedIcon); setRolloverEnabled(true); } } public void setRolloverIcon(Icon rolloverIcon) { if (this.rolloverIcon != rolloverIcon) { Icon oldValue = this.rolloverIcon; this.rolloverIcon = rolloverIcon; firePropertyChange(ROLLOVER_ICON_CHANGED_PROPERTY, oldValue, rolloverIcon); setRolloverEnabled(true); } } public void setPressedIcon(Icon pressedIcon) { Icon oldValue = this.pressedIcon; this.pressedIcon = pressedIcon; firePropertyChange(PRESSED_ICON_CHANGED_PROPERTY, oldValue, pressedIcon); } private void resetDefaultDisabledIcons() { defaultDisabledIcon = null; defaultDisabledSelectedIcon = null; } public void setIcon(Icon icon) { Icon oldValue = this.icon; this.icon = icon; resetDefaultDisabledIcons(); firePropertyChange(ICON_CHANGED_PROPERTY, oldValue, icon); } public void setDisabledSelectedIcon(Icon disabledSelectedIcon) { Icon oldValue = this.disabledSelectedIcon; this.disabledSelectedIcon = disabledSelectedIcon; resetDefaultDisabledIcons(); firePropertyChange(DISABLED_SELECTED_ICON_CHANGED_PROPERTY, oldValue, disabledSelectedIcon); } public void setDisabledIcon(Icon disabledIcon) { Icon oldValue = this.disabledIcon; this.disabledIcon = disabledIcon; resetDefaultDisabledIcons(); firePropertyChange(DISABLED_ICON_CHANGED_PROPERTY, oldValue, disabledIcon); } public Icon getSelectedIcon() { return selectedIcon; } public Icon getRolloverSelectedIcon() { return rolloverSelectedIcon; } public Icon getRolloverIcon() { return rolloverIcon; } public Icon getPressedIcon() { return pressedIcon; } public Icon getIcon() { return icon; } private Icon createDefaultDisabledSelectedIcon() { if (defaultDisabledSelectedIcon != null) { return defaultDisabledSelectedIcon; } if (selectedIcon instanceof ImageIcon) { defaultDisabledIcon = new ImageIcon(GrayFilter .createDisabledImage(((ImageIcon) selectedIcon).getImage())); } else if (disabledIcon instanceof ImageIcon) { defaultDisabledIcon = new ImageIcon(GrayFilter .createDisabledImage(((ImageIcon) disabledIcon).getImage())); } else if (icon instanceof ImageIcon) { defaultDisabledIcon = new ImageIcon(GrayFilter .createDisabledImage(((ImageIcon) icon).getImage())); } return defaultDisabledIcon; } public Icon getDisabledSelectedIcon() { return (disabledSelectedIcon != null) ? disabledSelectedIcon : createDefaultDisabledSelectedIcon(); } private Icon createDefaultDisabledIcon() { if (defaultDisabledIcon != null) { return defaultDisabledIcon; } if (icon instanceof ImageIcon) { defaultDisabledIcon = new ImageIcon(GrayFilter .createDisabledImage(((ImageIcon) icon).getImage())); } return defaultDisabledIcon; } public Icon getDisabledIcon() { return (disabledIcon != null) ? disabledIcon : createDefaultDisabledIcon(); } public void setModel(ButtonModel m) { if (model != m) { ButtonModel oldValue = model; if (model != null) { model.removeActionListener(actionListener); model.removeItemListener(itemListener); model.removeChangeListener(changeListener); } model = m; if (model != null) { model.addChangeListener(changeListener); model.addItemListener(itemListener); model.addActionListener(actionListener); int mn = model.getMnemonic(); updateMnemonic(mn, Utilities.keyCodeToKeyChar(mn)); } firePropertyChange(MODEL_CHANGED_PROPERTY, oldValue, model); } } public ButtonModel getModel() { return model; } public void setAction(Action action) { if (this.action == action && action != null) { return; } Action oldValue = this.action; if (oldValue != null) { if (hasListener(Action.class, oldValue)) { removeActionListener(oldValue); } if (actionPropertyChangeListener != null) { oldValue.removePropertyChangeListener(actionPropertyChangeListener); } } this.action = action; if (action != null) { if (!hasListener(ActionListener.class, action)) { listenerList.add(Action.class, action); addActionListener(action); } actionPropertyChangeListener = createActionPropertyChangeListener(action); action.addPropertyChangeListener(actionPropertyChangeListener); } firePropertyChange(StringConstants.ACTION_PROPERTY_CHANGED, oldValue, action); configurePropertiesFromAction(action); } void configurePropertyFromAction(Action action, Object propertyName) { if (propertyName == null) { return; } if (propertyName.equals(Action.MNEMONIC_KEY)) { Object actionMnemonic = action.getValue(Action.MNEMONIC_KEY); setMnemonic((actionMnemonic != null) ? ((Integer) actionMnemonic).intValue() : 0); } if (propertyName.equals(Action.SHORT_DESCRIPTION)) { setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION)); } if (propertyName.equals(Action.SMALL_ICON)) { setIcon((Icon) action.getValue(Action.SMALL_ICON)); } if (propertyName.equals(StringConstants.ENABLED_PROPERTY_CHANGED)) { setEnabled(action.isEnabled()); } if (propertyName.equals(Action.NAME)) { setText((String) action.getValue(Action.NAME)); } if (propertyName.equals(Action.ACTION_COMMAND_KEY)) { setActionCommand((String) action.getValue(Action.ACTION_COMMAND_KEY)); } } protected void configurePropertiesFromAction(Action action) { final Action a = (action != null) ? action : CLEAR_ACTION_PROPERTIES; configurePropertyFromAction(a, getActionPropertiesFilter()); } public Action getAction() { return action; } public void setText(String text) { if (text != this.text) { String oldValue = this.text; this.text = text; firePropertyChange(TEXT_CHANGED_PROPERTY, oldValue, text); updateDisplayedMnemonicsIndex(Utilities.keyCodeToKeyChar(mnemonic)); } } @Deprecated public void setLabel(String label) { setText(label); } public void setActionCommand(String command) { model.setActionCommand(command); } protected int checkVerticalKey(int key, String exceptionText) { return Utilities.checkVerticalKey(key, exceptionText); } protected int checkHorizontalKey(int key, String exceptionText) { return Utilities.checkHorizontalKey(key, exceptionText); } public String getText() { return text; } @Deprecated public String getLabel() { return getText(); } public String getActionCommand() { String command = model.getActionCommand(); return (command != null) ? command : getText(); } public Object[] getSelectedObjects() { return model.isSelected() ? new Object[] { getText() } : null; } public void removeItemListener(ItemListener listener) { listenerList.remove(ItemListener.class, listener); } public void addItemListener(ItemListener listener) { listenerList.add(ItemListener.class, listener); } public ItemListener[] getItemListeners() { return listenerList.getListeners(ItemListener.class); } protected ItemListener createItemListener() { return (handler != null) ? handler : (handler = new ActionAndModelListener()); } protected void fireItemStateChanged(ItemEvent event) { ItemListener[] listeners = getItemListeners(); if (listeners.length > 0) { ItemEvent itemEvent = new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED, this, event .getStateChange()); for (int i = 0; i < listeners.length; i++) { listeners[i].itemStateChanged(itemEvent); } } } public void removeActionListener(ActionListener listener) { listenerList.remove(ActionListener.class, listener); } public void addActionListener(ActionListener listener) { listenerList.add(ActionListener.class, listener); } public ActionListener[] getActionListeners() { return listenerList.getListeners(ActionListener.class); } protected ActionListener createActionListener() { return (handler != null) ? handler : (handler = new ActionAndModelListener()); } protected void fireActionPerformed(ActionEvent event) { ActionListener[] listeners = getActionListeners(); if (listeners.length > 0) { String command = (event.getActionCommand() != null) ? event.getActionCommand() : getText(); ActionEvent actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, command, event.getModifiers()); for (int i = 0; i < listeners.length; i++) { listeners[i].actionPerformed(actionEvent); } } } public void setMargin(Insets margin) { /* default values are obtained from UI (Harmony-4655) */ if (margin instanceof InsetsUIResource) { defaultMargin = (InsetsUIResource) margin; } else if (margin == null) { /* * According to spec if margin == null default value sets * (Harmony-4655) */ margin = defaultMargin; } Insets oldValue = this.margin; this.margin = margin; firePropertyChange(MARGIN_CHANGED_PROPERTY, oldValue, margin); } public Insets getMargin() { return margin; } @Override public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) { Icon curIcon = ButtonCommons.getCurrentIcon(this); if ((curIcon == null) || !(curIcon instanceof ImageIcon) || (((ImageIcon) curIcon).getImage() != img)) { return false; } return super.imageUpdate(img, infoflags, x, y, w, h); } @Override protected void paintBorder(Graphics g) { if (isBorderPainted()) { super.paintBorder(g); } } public void doClick(int pressTime) { final ButtonModel model = getModel(); model.setArmed(true); model.setPressed(true); if (pressTime > 0) { paintImmediately(0, 0, getWidth(), getHeight()); try { Thread.sleep(pressTime); } catch (InterruptedException e) { } } model.setPressed(false); model.setArmed(false); } /** * The click delay is based on 1.5 release behavior which can be revealed using the * following code: * * <pre> * AbstractButton ab = new AbstractButton() { * }; * long startTime = System.currentTimeMillis(); * ab.setModel(new DefaultButtonModel()); * for (int i = 0; i &lt; 100; i++) { * ab.doClick(); * } * long stopTime = System.currentTimeMillis(); * System.err.println(&quot;doClick takes &quot; + (stopTime - startTime) / 100); * </pre> */ public void doClick() { doClick(70); } public void setSelected(boolean selected) { model.setSelected(selected); } public void setRolloverEnabled(boolean rollover) { boolean oldValue = rolloverEnabled; rolloverEnabled = rollover; firePropertyChange(ROLLOVER_ENABLED_CHANGED_PROPERTY, oldValue, rolloverEnabled); } public void setFocusPainted(boolean painted) { boolean oldValue = focusPainted; focusPainted = painted; firePropertyChange(FOCUS_PAINTED_CHANGED_PROPERTY, oldValue, painted); } @Override public void setEnabled(boolean enabled) { model.setEnabled(enabled); super.setEnabled(enabled); } public void setContentAreaFilled(boolean filled) { boolean oldValue = contentAreaFilled; contentAreaFilled = filled; firePropertyChange(CONTENT_AREA_FILLED_CHANGED_PROPERTY, oldValue, contentAreaFilled); } public void setBorderPainted(boolean painted) { boolean oldValue = borderPainted; borderPainted = painted; firePropertyChange(BORDER_PAINTED_CHANGED_PROPERTY, oldValue, borderPainted); } public void setMultiClickThreshhold(long threshold) { if (threshold < 0) { throw new IllegalArgumentException(Messages.getString("swing.05")); //$NON-NLS-1$ } multiClickThreshhold = threshold; } public void setVerticalTextPosition(int pos) { int oldValue = verticalTextPosition; verticalTextPosition = checkVerticalKey(pos, VERTICAL_TEXT_POSITION_CHANGED_PROPERTY); firePropertyChange(VERTICAL_TEXT_POSITION_CHANGED_PROPERTY, oldValue, verticalTextPosition); } public void setVerticalAlignment(int alignment) { int oldValue = verticalAlignment; verticalAlignment = checkVerticalKey(alignment, VERTICAL_ALIGNMENT_CHANGED_PROPERTY); firePropertyChange(VERTICAL_ALIGNMENT_CHANGED_PROPERTY, oldValue, verticalAlignment); } public void setMnemonic(char keyChar) { setMnemonic(Utilities.keyCharToKeyCode(keyChar), keyChar); } public void setMnemonic(int mnemonicCode) { setMnemonic(mnemonicCode, Utilities.keyCodeToKeyChar(mnemonicCode)); } private void setMnemonic(int keyCode, char keyChar) { model.setMnemonic(keyCode); } private void updateMnemonic(int keyCode, char keyChar) { int oldKeyCode = mnemonic; if (oldKeyCode == keyCode) { return; } mnemonic = keyCode; firePropertyChange(MNEMONIC_CHANGED_PROPERTY, oldKeyCode, keyCode); updateDisplayedMnemonicsIndex(keyChar); } private void updateDisplayedMnemonicsIndex(char keyChar) { setDisplayedMnemonicIndex(Utilities.getDisplayedMnemonicIndex(text, keyChar)); } public int getMnemonic() { return mnemonic; } public void setDisplayedMnemonicIndex(int index) throws IllegalArgumentException { if (index < -1 || index >= 0 && (text == null || index >= text.length())) { throw new IllegalArgumentException(Messages.getString("swing.10",index)); //$NON-NLS-1$ } int oldValue = mnemonicIndex; mnemonicIndex = index; firePropertyChange(StringConstants.MNEMONIC_INDEX_PROPERTY_CHANGED, oldValue, index); } public int getDisplayedMnemonicIndex() { return mnemonicIndex; } public void setIconTextGap(int gap) { LookAndFeel.markPropertyNotInstallable(this, StringConstants.ICON_TEXT_GAP_PROPERTY_CHANGED); int oldValue = iconTextGap; iconTextGap = gap; firePropertyChange(StringConstants.ICON_TEXT_GAP_PROPERTY_CHANGED, oldValue, iconTextGap); } public void setHorizontalTextPosition(int pos) { int oldValue = horizontalTextPosition; horizontalTextPosition = checkHorizontalKey(pos, HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY); firePropertyChange(HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY, oldValue, horizontalTextPosition); } public void setHorizontalAlignment(int alignment) { int oldValue = horizontalAlignment; horizontalAlignment = checkHorizontalKey(alignment, HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY); firePropertyChange(HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY, oldValue, horizontalAlignment); } public boolean isSelected() { return model.isSelected(); } public boolean isRolloverEnabled() { return rolloverEnabled; } public boolean isFocusPainted() { return focusPainted; } public boolean isContentAreaFilled() { return contentAreaFilled; } public boolean isBorderPainted() { return borderPainted; } protected void fireStateChanged() { ChangeListener[] listeners = getChangeListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].stateChanged(changeEvent); } } public long getMultiClickThreshhold() { return multiClickThreshhold; } public int getVerticalTextPosition() { return verticalTextPosition; } public int getVerticalAlignment() { return verticalAlignment; } public int getIconTextGap() { return iconTextGap; } public int getHorizontalTextPosition() { return horizontalTextPosition; } public int getHorizontalAlignment() { return horizontalAlignment; } Object getActionPropertiesFilter() { return ALL_ACTION_PROPERTIES; } boolean processMnemonics(KeyEvent event) { final KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(event); if (keyStroke.isOnKeyRelease() || getMnemonic() == 0) { return false; } if (isMnemonicKeyStroke(keyStroke)) { Action action = getActionMap().get(StringConstants.MNEMONIC_ACTION); if (action != null) { SwingUtilities.notifyAction(action, keyStroke, event, this, event .getModifiersEx()); return true; } } return false; } boolean isMnemonicKeyStroke(KeyStroke keyStroke) { return keyStroke.getKeyCode() == getMnemonic() && (keyStroke.getModifiers() & InputEvent.ALT_DOWN_MASK) != 0; } }
shannah/cn1
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/swing/src/main/java/common/javax/swing/AbstractButton.java
Java
gpl-2.0
32,559
class StopSendingException(Exception): """ pre_send exception """
ilstreltsov/django-db-mailer
dbmail/exceptions.py
Python
gpl-2.0
78
/* * Agent.java October 2012 * * Copyright (C) 2002, Niall Gallagher <niallg@users.sf.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.simpleframework.transport.trace; import java.nio.channels.SocketChannel; /** * The <code>Agent</code> object represents a tracing agent used to * monitor events on a connection. Its primary responsibilities are to * create <code>Trace</code> objects that are attached to a specific * socket channel. When any event occurs on that channel the trace is * notified and can forward the details on to the agent for analysis. * <p> * An agent implementation must make sure that it does not affect * the performance of the server. If there are delays creating a trace * or within the trace itself it will have an impact on performance. * * @author Niall Gallagher * * @see org.simpleframework.transport.trace.Trace */ public interface Agent { /** * This method is used to attach a trace to the specified channel. * Attaching a trace basically means associating events from that * trace with the specified socket. It ensures that the events * from a specific channel can be observed in isolation. * * @param channel this is the channel to associate with the trace * * @return this returns a trace associated with the channel */ Trace attach(SocketChannel channel); /** * This is used to stop the agent and clear all trace information. * Stopping the agent is typically done when the server is stopped * and is used to free any resources associated with the agent. If * an agent does not hold information this method can be ignored. */ void stop(); }
ael-code/preston
src/org/simpleframework/transport/trace/Agent.java
Java
gpl-2.0
2,209
<?php /** * @version 3.1.7 October 16, 2013 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * derived from JoomlaRTCacheDriver with original copyright and license * @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access defined('ROKCOMMON') or die; /** * PHP class format handler for RokCommon_Registry * * @package JoomlaRTCacheDriver.Framework * @subpackage Registry */ class RokCommon_Registry_Format_PHP extends RokCommon_Registry_Format { /** * Converts an object into a php class string. * - NOTE: Only one depth level is supported. * * @param object Data Source Object * @param array Parameters used by the formatter * @return string Config class formatted string */ public function objectToString($object, $params = array()) { // Build the object variables string $vars = ''; foreach (get_object_vars($object) as $k => $v) { if (is_scalar($v)) { $vars .= "\tpublic $". $k . " = '" . addcslashes($v, '\\\'') . "';\n"; } else if (is_array($v)) { $vars .= "\tpublic $". $k . " = " . $this->_getArrayString($v) . ";\n"; } } $str = "<?php\nclass ".$params['class']." {\n"; $str .= $vars; $str .= "}"; // Use the closing tag if it not set to false in parameters. if (!isset($params['closingtag']) || $params['closingtag'] !== false) { $str .= "\n?>"; } return $str; } /** * Placeholder method * * @return boolean True */ function stringToObject($data, $namespace='') { return true; } protected function _getArrayString($a) { $s = 'array('; $i = 0; foreach ($a as $k => $v) { $s .= ($i) ? ', ' : ''; $s .= '"'.$k.'" => '; if (is_array($v)) { $s .= $this->_getArrayString($v); } else { $s .= '"'.addslashes($v).'"'; } $i++; } $s .= ')'; return $s; } }
dguardia/reliant
libraries/rokcommon/RokCommon/Registry/Format/PHP.php
PHP
gpl-2.0
2,049
<?php namespace TYPO3\CMS\Core\Tests\Unit\Tca; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Backend\Tests\Functional\Form\FormTestService; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Lang\LanguageService; class FileMetadataVisibleFieldsTest extends \TYPO3\TestingFramework\Core\Functional\FunctionalTestCase { protected static $fileMetadataFields = [ 'title', 'description', 'alternative', 'categories', ]; /** * @test */ public function fileMetadataFormContainsExpectedFields() { $this->setUpBackendUserFromFixture(1); $GLOBALS['LANG'] = GeneralUtility::makeInstance(LanguageService::class); $formEngineTestService = GeneralUtility::makeInstance(FormTestService::class); $formResult = $formEngineTestService->createNewRecordForm('sys_file_metadata'); foreach (static::$fileMetadataFields as $expectedField) { $this->assertNotFalse( $formEngineTestService->formHtmlContainsField($expectedField, $formResult['html']), 'The field ' . $expectedField . ' is not in the form HTML' ); } } }
ksjogo/TYPO3.CMS
typo3/sysext/core/Tests/Functional/Tca/FileMetadataVisibleFieldsTest.php
PHP
gpl-2.0
1,564
<?php namespace TYPO3\CMS\Rtehtmlarea; use TYPO3\CMS\Core\Utility\GeneralUtility; /** * Base extension class which generates the folder tree. * Used directly by the RTE. * * @author Kasper Skårhøj <kasperYYYY@typo3.com> */ class FolderTree extends \localFolderTree { /** * Wrapping the title in a link, if applicable. * * @param string $title Title, ready for output. * @param \TYPO3\CMS\Core\Resource\Folder $folderObject The "record" * @return string Wrapping title string. * @todo Define visibility */ public function wrapTitle($title, \TYPO3\CMS\Core\Resource\Folder $folderObject) { if ($this->ext_isLinkable($folderObject)) { $aOnClick = 'return jumpToUrl(\'' . $this->getThisScript() . 'act=' . $GLOBALS['SOBE']->browser->act . '&mode=' . $GLOBALS['SOBE']->browser->mode . '&editorNo=' . $GLOBALS['SOBE']->browser->editorNo . '&contentTypo3Language=' . $GLOBALS['SOBE']->browser->contentTypo3Language . '&contentTypo3Charset=' . $GLOBALS['SOBE']->browser->contentTypo3Charset . '&expandFolder=' . rawurlencode($folderObject->getCombinedIdentifier()) . '\');'; return '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . $title . '</a>'; } else { return '<span class="typo3-dimmed">' . $title . '</span>'; } } /** * Wrap the plus/minus icon in a link * * @param string $icon HTML string to wrap, probably an image tag. * @param string $cmd Command for 'PM' get var * @param boolean $isExpand If expanded * @return string Link-wrapped input string * @access private */ public function PMiconATagWrap($icon, $cmd, $isExpand = TRUE) { if (empty($this->scope)) { $this->scope = array( 'class' => get_class($this), 'script' => $this->thisScript, 'ext_noTempRecyclerDirs' => $this->ext_noTempRecyclerDirs, 'browser' => array( 'mode' => $GLOBALS['SOBE']->browser->mode, 'act' => $GLOBALS['SOBE']->browser->act, 'editorNo' => $GLOBALS['SOBE']->browser->editorNo ), ); } if ($this->thisScript) { // Activates dynamic AJAX based tree $scopeData = serialize($this->scope); $scopeHash = GeneralUtility::hmac($scopeData); $js = htmlspecialchars('Tree.load(' . GeneralUtility::quoteJSvalue($cmd) . ', ' . (int)$isExpand . ', this, ' . GeneralUtility::quoteJSvalue($scopeData) . ', ' . GeneralUtility::quoteJSvalue($scopeHash) . ');'); return '<a class="pm" onclick="' . $js . '">' . $icon . '</a>'; } else { return $icon; } } }
demonege/sutogo
typo3/sysext/rtehtmlarea/Classes/FolderTree.php
PHP
gpl-2.0
2,464
<article <?php hybrid_attr( 'post' ); ?>> <?php if ( is_singular( get_post_type() ) ) : // If viewing a single post. ?> <header class="entry-header"> <div class="entry-byline"> <time <?php hybrid_attr( 'entry-published' ); ?>><?php echo get_the_date(); ?></time> <?php hybrid_post_author( array( 'text' => __( 'By %s', 'ravel' ) ) ); ?> <?php comments_popup_link( __( '0 Comments', 'ravel' ), __( '1 Comment', 'ravel' ), __( '% Comments', 'ravel' ), 'comments-link', '' ); ?> <?php edit_post_link(); ?> </div><!-- .entry-byline --> <h1 <?php hybrid_attr( 'entry-title' ); ?>><?php single_post_title(); ?></h1> </header><!-- .entry-header --> <div <?php hybrid_attr( 'entry-content' ); ?>> <?php the_content(); ?> <?php wp_link_pages(); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <a class="entry-permalink" href="<?php the_permalink(); ?>" rel="bookmark" itemprop="url"><?php _e( 'Permalink', 'ravel' ); ?></a> <?php hybrid_post_terms( array( 'taxonomy' => 'category', 'sep' => ' ' ) ); ?> <?php hybrid_post_terms( array( 'taxonomy' => 'post_tag', 'sep' => ' ' ) ); ?> </footer><!-- .entry-footer --> <?php else : // If not viewing a single post. ?> <header class="entry-header"> <div class="entry-byline"> <time <?php hybrid_attr( 'entry-published' ); ?>><?php echo get_the_date(); ?></time> <?php hybrid_post_author( array( 'text' => __( 'By %s', 'ravel' ) ) ); ?> <?php comments_popup_link( __( '0 Comments', 'ravel' ), __( '1 Comment', 'ravel' ), __( '% Comments', 'ravel' ), 'comments-link', '' ); ?> <?php edit_post_link(); ?> </div><!-- .entry-byline --> <?php the_title( '<h2 ' . hybrid_get_attr( 'entry-title' ) . '><a href="' . get_permalink() . '" rel="bookmark" itemprop="url">', '</a></h2>' ); ?> <?php $count = hybrid_get_gallery_item_count(); ?> <?php get_the_image( array( 'size' => 'ravel-medium', 'before' => '<div class="featured-media">', 'after' => '<span class="gallery-items-count">' . sprintf( _n( '%s item', '%s items', $count, 'ravel' ), $count ) . '</span></div>' ) ); ?> </header><!-- .entry-header --> <div <?php hybrid_attr( 'entry-summary' ); ?>> <?php the_excerpt(); ?> </div><!-- .entry-summary --> <footer class="entry-footer"> <a class="entry-permalink" href="<?php the_permalink(); ?>" rel="bookmark" itemprop="url"><?php _e( 'Permalink', 'ravel' ); ?></a> <?php hybrid_post_terms( array( 'taxonomy' => 'category', 'sep' => ' ' ) ); ?> <?php hybrid_post_terms( array( 'taxonomy' => 'post_tag', 'sep' => ' ' ) ); ?> </footer><!-- .entry-footer --> <?php endif; // End single post check. ?> </article><!-- .entry -->
jdolan/jaydolan
wp-content/themes/ravel/content/gallery.php
PHP
gpl-2.0
2,757
<?php /** * @package Joomla.Site * @subpackage com_content * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; use Joomla\Registry\Registry; JLoader::register('ContentModelArticles', __DIR__ . '/articles.php'); /** * Frontpage Component Model * * @since 1.5 */ class ContentModelFeatured extends ContentModelArticles { /** * Model context string. * * @var string */ public $_context = 'com_content.frontpage'; /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @param string $ordering The field to order on. * @param string $direction The direction to order on. * * @return void * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { parent::populateState($ordering, $direction); $input = JFactory::getApplication()->input; $user = JFactory::getUser(); $app = JFactory::getApplication('site'); // List state information $limitstart = $input->getUInt('limitstart', 0); $this->setState('list.start', $limitstart); $params = $this->state->params; $menuParams = new Registry; if ($menu = $app->getMenu()->getActive()) { $menuParams->loadString($menu->params); } $mergedParams = clone $menuParams; $mergedParams->merge($params); $this->setState('params', $mergedParams); $limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links'); $this->setState('list.limit', $limit); $this->setState('list.links', $params->get('num_links')); $this->setState('filter.frontpage', true); if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content'))) { // Filter on published for those who do not have edit or edit.state rights. $this->setState('filter.published', 1); } else { $this->setState('filter.published', array(0, 1, 2)); } // Process show_noauth parameter if (!$params->get('show_noauth')) { $this->setState('filter.access', true); } else { $this->setState('filter.access', false); } // Check for category selection if ($params->get('featured_categories') && implode(',', $params->get('featured_categories')) == true) { $featuredCategories = $params->get('featured_categories'); $this->setState('filter.frontpage.categories', $featuredCategories); } $articleOrderby = $params->get('orderby_sec', 'rdate'); $articleOrderDate = $params->get('order_date'); $categoryOrderby = $params->def('orderby_pri', ''); $secondary = ContentHelperQuery::orderbySecondary($articleOrderby, $articleOrderDate); $primary = ContentHelperQuery::orderbyPrimary($categoryOrderby); $this->setState('list.ordering', $primary . $secondary . ', a.created DESC'); $this->setState('list.direction', ''); } /** * Method to get a list of articles. * * @return mixed An array of objects on success, false on failure. */ public function getItems() { $params = clone $this->getState('params'); $limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links'); if ($limit > 0) { $this->setState('list.limit', $limit); return parent::getItems(); } return array(); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= $this->getState('filter.frontpage'); return parent::getStoreId($id); } /** * Get the list of items. * * @return JDatabaseQuery */ protected function getListQuery() { // Create a new query object. $query = parent::getListQuery(); // Filter by categories $featuredCategories = $this->getState('filter.frontpage.categories'); if (is_array($featuredCategories) && !in_array('', $featuredCategories)) { $query->where('a.catid IN (' . implode(',', $featuredCategories) . ')'); } return $query; } public function getImportant() { $params = clone $this->getState('params'); $id_category = $params->get('important_category'); $query = 'SELECT title'. ' FROM #__categories'. ' WHERE id ='.(int) $id_category; $Arows = $this->_getList($query); //Agafem l'unic element $categoria = array_pop($Arows); $query = 'SELECT id, alias, title, introtext, created, modified, catid, language, cf.ordering'. ' FROM #__content c'. ' JOIN #__content_frontpage cf ON cf.content_id=c.id'. ' WHERE state = 1'. ' AND featured = 1'. ' AND catid ='. (int) $id_category . ' ORDER BY cf.ordering'; $articles = $this->_getList($query); return $articles; } }
IOC/joomla3
components/com_content/models/featured.php
PHP
gpl-2.0
5,221
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.drlvm.tests.regression.h4292; import junit.framework.*; public class Test extends TestCase { synchronized void _testSyncRec1() { _testSyncRec1(); } public void testSyncRec1() { try { _testSyncRec1(); } catch (StackOverflowError e) { System.out.println("PASSED!"); return; } fail("FAILED:No SOE was thrown!"); } }
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/drlvm/src/test/regression/H4292/Test.java
Java
gpl-2.0
1,287
<?php /* Template Name: Archives Page */ ?> <?php // calling the header.php get_header(); // action hook for placing content above #container thematic_abovecontainer(); ?> <div id="container"> <div id="content"> <?php the_post(); ?> <div id="post-<?php the_ID() ?>" class="<?php thematic_post_class() ?>"> <?php // creating the post header thematic_postheader(); ?> <div class="entry-content"> <?php the_content(); // action hook for the 404 content thematic_archives(); edit_post_link(__('Edit', 'thematic'),'<span class="edit-link">','</span>'); ?> </div> </div><!-- .post --> <?php if ( get_post_custom_values('comments') ) comments_template(); // Add a key/value of "comments" to enable comments on pages! ?> </div><!-- #content --> </div><!-- #container --> <?php // action hook for placing content below #container thematic_belowcontainer(); // calling the standard sidebar thematic_sidebar(); // calling footer.php get_footer(); ?>
mariocontext/beautytv3
wp-content/themes/thematic/archives.php
PHP
gpl-2.0
1,507
<?php /** * @package Advanced Module Manager * @version 4.17.0 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2014 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ /** * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; jimport('joomla.application.component.modeladmin'); /** * Module model. * * @package Joomla.Administrator * @subpackage com_advancedmodules * @since 1.6 */ class AdvancedModulesModelModule extends JModelAdmin { /** * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_MODULES'; /** * @var string The help screen key for the module. * @since 1.6 */ protected $helpKey = 'JHELP_EXTENSIONS_MODULE_MANAGER_EDIT'; /** * @var string The help screen base URL for the module. * @since 1.6 */ protected $helpURL; /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @return void * * @since 1.6 */ protected function populateState() { $app = JFactory::getApplication('administrator'); // Load the User state. $pk = $app->input->getInt('id'); if (!$pk) { if ($extensionId = (int) $app->getUserState('com_advancedmodules.add.module.extension_id')) { $this->setState('extension.id', $extensionId); } } $this->setState('module.id', $pk); // Load the parameters. $params = JComponentHelper::getParams('com_advancedmodules'); $this->setState('params', $params); $this->getConfig(); } /** * Method to perform batch operations on a set of modules. * * @param array $commands An array of commands to perform. * @param array $pks An array of item ids. * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. * * @since 1.7 */ public function batch($commands, $pks, $contexts) { // Sanitize user ids. $pks = array_unique($pks); JArrayHelper::toInteger($pks); // Remove any values of zero. if (array_search(0, $pks, true)) { unset($pks[array_search(0, $pks, true)]); } if (empty($pks)) { $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; if (!empty($commands['position_id'])) { $cmd = JArrayHelper::getValue($commands, 'move_copy', 'c'); if (!empty($commands['position_id'])) { if ($cmd == 'c') { $result = $this->batchCopy($commands['position_id'], $pks, $contexts); if (is_array($result)) { $pks = $result; } else { return false; } } elseif ($cmd == 'm' && !$this->batchMove($commands['position_id'], $pks, $contexts)) { return false; } $done = true; } } if (!empty($commands['assetgroup_id'])) { if (!$this->batchAccess($commands['assetgroup_id'], $pks, $contexts)) { return false; } $done = true; } if (!empty($commands['language_id'])) { if (!$this->batchLanguage($commands['language_id'], $pks, $contexts)) { return false; } $done = true; } if (!$done) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } // Clear the cache $this->cleanCache(); return true; } /** * Batch language changes for a group of rows. * * @param string $value The new value matching a language. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 11.3 */ protected function batchLanguage($value, $pks, $contexts) { // Set the variables $user = JFactory::getUser(); $db = $this->getDbo(); $table = $this->getTable(); $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); foreach ($pks as $pk) { if ($user->authorise('core.edit', $contexts[$pk])) { $table->reset(); $table->load($pk); $table->language = $value; if (!$table->store()) { $this->setError($table->getError()); return false; } if ($table->id && !$table_adv->load($table->id)) { $table_adv->moduleid = $table->id; $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if ($table_adv->load($pk, true)) { $table_adv->moduleid = $table->id; $registry = new JRegistry; $registry->loadString($table_adv->params); $params = $registry->toArray(); if ($value == '*') { $params['assignto_languages'] = 0; $params['assignto_languages_selection'] = array(); } else { $params['assignto_languages'] = 1; $params['assignto_languages_selection'] = array($value); } $registry = new JRegistry; $registry->loadArray($params); $table_adv->params = (string) $registry; if (!$table_adv->check() || !$table_adv->store()) { $this->setError($table_adv->getError()); return false; } } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Batch copy modules to a new position or current. * * @param integer $value The new value matching a module position. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 11.1 */ protected function batchCopy($value, $pks, $contexts) { // Set the variables $user = JFactory::getUser(); $db = $this->getDbo(); $query = $db->getQuery(true); $table = $this->getTable(); $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); $newIds = array(); $i = 0; foreach ($pks as $pk) { if ($user->authorise('core.create', 'com_advancedmodules')) { $table->reset(); $table->load($pk); // Set the new position if ($value == 'noposition') { $position = ''; } elseif ($value == 'nochange') { $position = $table->position; } else { $position = $value; } $table->position = $position; // Alter the title if necessary $data = $this->generateNewTitle(0, $table->title, $table->position); $table->title = $data['0']; // Reset the ID because we are making a copy $table->id = 0; // Unpublish the new module $table->published = 0; if (!$table->store()) { $this->setError($table->getError()); return false; } // Get the new item ID $newId = (int) $table->get('id'); // Add the new ID to the array $newIds[$i] = $newId; $i++; // Now we need to handle the module assignments $query->clear() ->select('m.menuid') ->from('#__modules_menu as m') ->where('m.moduleid = ' . (int) $pk); $db->setQuery($query); $menus = $db->loadColumn(); // Insert the new records into the table foreach ($menus as $menu) { $query->clear() ->insert('#__modules_menu') ->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid'))) ->values($newId . ', ' . $menu); $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { return JError::raiseWarning(500, $e->getMessage()); } } if ($table->id && !$table_adv->load($table->id)) { $table_adv->moduleid = $table->id; $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if ($table_adv->load($pk, true)) { $table_adv->moduleid = $table->id; $rules = JAccess::getAssetRules('com_advancedmodules.module.' . $pk); $table_adv->setRules($rules); if (!$table_adv->check() || !$table_adv->store()) { $this->setError($table_adv->getError()); return false; } } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE')); return false; } } // Clean the cache $this->cleanCache(); return $newIds; } /** * Batch move modules to a new position or current. * * @param integer $value The new value matching a module position. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 11.1 */ protected function batchMove($value, $pks, $contexts) { // Set the variables $user = JFactory::getUser(); $table = $this->getTable(); foreach ($pks as $pk) { if ($user->authorise('core.edit', 'com_advancedmodules')) { $table->reset(); $table->load($pk); // Set the new position if ($value == 'noposition') { $position = ''; } elseif ($value == 'nochange') { $position = $table->position; } else { $position = $value; } $table->position = $position; // Alter the title if necessary $data = $this->generateNewTitle(0, $table->title, $table->position); $table->title = $data['0']; // Unpublish the moved module $table->published = 0; if (!$table->store()) { $this->setError($table->getError()); return false; } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Method to delete rows. * * @param array &$pks An array of item ids. * * @return boolean Returns true on success, false on failure. * * @since 1.6 */ public function delete(&$pks) { $pks = (array) $pks; $user = JFactory::getUser(); $table = $this->getTable(); $db = $this->getDbo(); $query = $db->getQuery(true); // Iterate the items to delete each one. foreach ($pks as $i => $pk) { if ($table->load($pk)) { // Access checks. if (!$user->authorise('core.delete', 'com_advancedmodules.module.' . (int) $pk) || $table->published != -2) { JError::raiseWarning(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED')); return; } if (!$table->delete($pk)) { throw new Exception($table->getError()); } else { // Delete the menu assignments $query->clear() ->delete('#__modules_menu') ->where('moduleid=' . (int) $pk); $db->setQuery($query); $db->execute(); $query->clear() ->delete('#__advancedmodules') ->where('moduleid=' . (int) $pk); $db->setQuery($query); $db->execute(); // delete asset $query->clear() ->delete('#__assets') ->where('name = ' . $db->quote('com_advancedmodules.module.' . (int) $pk)); $db->setQuery($query); $db->execute(); } // Clear module cache parent::cleanCache($table->module, $table->client_id); } else { throw new Exception($table->getError()); } } // Clear modules cache $this->cleanCache(); return true; } /** * Method to duplicate modules. * * @param array &$pks An array of primary key IDs. * * @return boolean True if successful. * * @since 1.6 * @throws Exception */ public function duplicate(&$pks) { $user = JFactory::getUser(); // Access checks. if (!$user->authorise('core.create', 'com_advancedmodules')) { throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED')); } $db = $this->getDbo(); $query = $db->getQuery(true); $inserts = array(); $table = $this->getTable(); $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); foreach ($pks as $pk) { if ($table->load($pk, true)) { // Reset the id to create a new record. $table->id = 0; // Alter the title. $m = null; if (preg_match('#\((\d+)\)$#', $table->title, $m)) { $table->title = preg_replace('#\(\d+\)$#', '(' . ($m[1] + 1) . ')', $table->title); } else { $table->title .= ' (2)'; } // Unpublish duplicate module $table->published = 0; if (!$table->check() || !$table->store()) { throw new Exception($table->getError()); } $query->clear() ->select($db->quoteName('menuid')) ->from($db->quoteName('#__modules_menu')) ->where($db->quoteName('moduleid') . ' = ' . (int) $pk); $db->setQuery($query); $rows = $db->loadColumn(); foreach ($rows as $menuid) { $inserts[(int) $table->id . '-' . (int) $menuid] = (int) $table->id . ',' . (int) $menuid; } if ($table->id && !$table_adv->load($table->id)) { $table_adv->moduleid = $table->id; $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if ($table_adv->load($pk, true)) { $table_adv->moduleid = $table->id; $rules = JAccess::getAssetRules('com_advancedmodules.module.' . $pk); $table_adv->setRules($rules); if (!$table_adv->check() || !$table_adv->store()) { throw new Exception($table_adv->getError()); } } } else { throw new Exception($table->getError()); } } if (!empty($inserts)) { // Module-Menu Mapping: Do it in one query $query->clear() ->insert('#__modules_menu') ->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid'))); foreach($inserts as $insert) { $query->values($insert); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { return JError::raiseWarning(500, $e->getMessage()); } } // Clear modules cache $this->cleanCache(); return true; } /** * Method to set color of modules. * * @param array &$pks An array of primary key IDs. * @param string $color RGB color * * @return boolean True if successful. * * @since 1.6 * @throws Exception */ public function setcolor(&$pks, $color) { // Set the variables $db = $this->getDbo(); $user = JFactory::getUser(); $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); foreach ($pks as $pk) { if ($user->authorise('core.edit', 'com_advancedmodules')) { if (!$table_adv->load($pk)) { $table_adv->moduleid = $pk; $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if ($table_adv->load($pk, true)) { $registry = new JRegistry; $registry->loadString($table_adv->params); $params = $registry->toArray(); $params['color'] = $color; $registry = new JRegistry; $registry->loadArray($params); $table_adv->params = (string) $registry; if (!$table_adv->check() || !$table_adv->store()) { $this->setError($table_adv->getError()); return false; } } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Method to change the title. * * @param integer $category_id The id of the category. Not used here. * @param string $title The title. * @param string $position The position. * * @return array Contains the modified title. * * @since 2.5 */ protected function generateNewTitle($category_id, $title, $position) { // Alter the title & alias $table = $this->getTable(); while ($table->load(array('position' => $position, 'title' => $title))) { $title = JString::increment($title); } return array($title); } /** * Method to get the client object * * @return void * * @since 1.6 */ function &getClient() { return $this->_client; } /** * Method to get the record form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * * @return JForm A JForm object on success, false on failure * * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // The folder and element vars are passed when saving the form. if (empty($data)) { $item = $this->getItem(); $clientId = $item->client_id; $module = $item->module; } else { $clientId = JArrayHelper::getValue($data, 'client_id'); $module = JArrayHelper::getValue($data, 'module'); } // These variables are used to add data from the plugin XML files. $this->setState('item.client_id', $clientId); $this->setState('item.module', $module); // Get the form. $form = $this->loadForm('com_advancedmodules.module', 'module', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } $form->setFieldAttribute('position', 'client', $this->getState('item.client_id') == 0 ? 'site' : 'administrator'); // Modify the form based on access controls. if (!$this->canEditState((object) $data)) { // Disable fields for display. $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('published', 'disabled', 'true'); $form->setFieldAttribute('publish_up', 'disabled', 'true'); $form->setFieldAttribute('publish_down', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is a record you can edit. $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('published', 'filter', 'unset'); $form->setFieldAttribute('publish_up', 'filter', 'unset'); $form->setFieldAttribute('publish_down', 'filter', 'unset'); } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * * @since 1.6 */ protected function loadFormData() { $app = JFactory::getApplication(); // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_advancedmodules.edit.module.data', array()); if (empty($data)) { $data = $this->getItem(); // This allows us to inject parameter settings into a new module. $params = $app->getUserState('com_advancedmodules.add.module.params'); if (is_array($params)) { $data->set('params', $params); } } return $data; } /** * Method to get a single record. * * @param integer $pk The id of the primary key. * * @return mixed Object on success, false on failure. * * @since 1.6 */ public function getItem($pk = null) { $pk = (!empty($pk)) ? (int) $pk : (int) $this->getState('module.id'); $db = $this->getDbo(); $query = $db->getQuery(true); if (!isset($this->_cache[$pk])) { $false = false; // Get a row instance. $table = $this->getTable(); // Attempt to load the row. $return = $table->load($pk); // Check for a table object error. if ($return === false && $error = $table->getError()) { $this->setError($error); return $false; } // Check if we are creating a new extension. if (empty($pk)) { if ($extensionId = (int) $this->getState('extension.id')) { $query->clear() ->select('e.element, e.client_id') ->from('#__extensions as e') ->where('e.extension_id = ' . $extensionId) ->where('e.type = ' . $db->quote('module')); $db->setQuery($query); try { $extension = $db->loadObject(); } catch (RuntimeException $e) { $this->setError($e->getMessage); return false; } if (empty($extension)) { $this->setError('COM_MODULES_ERROR_CANNOT_FIND_MODULE'); return false; } // Extension found, prime some module values. $table->module = $extension->element; $table->client_id = $extension->client_id; } else { $app = JFactory::getApplication(); $app->redirect(JRoute::_('index.php?option=com_advancedmodules&view=modules', false)); return false; } } // Convert to the JObject before adding other data. $properties = $table->getProperties(1); $this->_cache[$pk] = JArrayHelper::toObject($properties, 'JObject'); // Convert the params field to an array. $registry = new JRegistry; $registry->loadString($table->params); $this->_cache[$pk]->params = $registry->toArray(); // Advanced parameters // Get a row instance. $table_adv = $this->getTable('AdvancedModules', 'AdvancedModulesTable'); // Attempt to load the row. $table_adv->load($pk); $this->_cache[$pk]->asset_id = $table_adv->asset_id; // Convert the params field to an array. $registry = new JRegistry; $registry->loadString($table_adv->params); $this->_cache[$pk]->advancedparams = $registry->toArray(); $this->_cache[$pk]->advancedparams = $this->initAssignments($pk, $this->_cache[$pk]); $assigned = array(); $assignment = 0; if (isset($this->_cache[$pk]->advancedparams['assignto_menuitems']) && isset($this->_cache[$pk]->advancedparams['assignto_menuitems_selection'])) { $assigned = $this->_cache[$pk]->advancedparams['assignto_menuitems_selection']; if ($this->_cache[$pk]->advancedparams['assignto_menuitems'] == 1 && empty($this->_cache[$pk]->advancedparams['assignto_menuitems_selection'])) { $assignment = '-'; } else if ($this->_cache[$pk]->advancedparams['assignto_menuitems'] == 1) { $assignment = '1'; } else if ($this->_cache[$pk]->advancedparams['assignto_menuitems'] == 2) { $assignment = '-1'; } } $this->_cache[$pk]->assigned = $assigned; $this->_cache[$pk]->assignment = $assignment; // Get the module XML. $client = JApplicationHelper::getClientInfo($table->client_id); $path = JPath::clean($client->path . '/modules/' . $table->module . '/' . $table->module . '.xml'); if (file_exists($path)) { $this->_cache[$pk]->xml = simplexml_load_file($path); } else { $this->_cache[$pk]->xml = null; } } return $this->_cache[$pk]; } /** * Get the necessary data to load an item help screen. * * @return object An object with key, url, and local properties for loading the item help screen. * * @since 1.6 */ public function getHelp() { return (object) array('key' => $this->helpKey, 'url' => $this->helpURL); } /** * Returns a reference to the a Table object, always creating it. * * @param string $type The table type to instantiate * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * * @return JTable A database object * * @since 1.6 */ public function getTable($type = 'Module', $prefix = 'JTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } /** * Prepare and sanitise the table prior to saving. * * @param JTable &$table The database object * * @return void * * @since 1.6 */ protected function prepareTable(&$table) { $table->title = htmlspecialchars_decode($table->title, ENT_QUOTES); } /** * Method to preprocess the form * * @param JForm $form A form object. * @param mixed $data The data expected for the form. * @param string $group The name of the plugin group to import (defaults to "content"). * * @return void * * @since 1.6 * @throws Exception if there is an error loading the form. */ protected function preprocessForm(JForm $form, $data, $group = 'content') { jimport('joomla.filesystem.path'); $lang = JFactory::getLanguage(); $clientId = $this->getState('item.client_id'); $module = $this->getState('item.module'); $client = JApplicationHelper::getClientInfo($clientId); $formFile = JPath::clean($client->path . '/modules/' . $module . '/' . $module . '.xml'); // Load the core and/or local language file(s). $lang->load($module, $client->path, null, false, false) || $lang->load($module, $client->path . '/modules/' . $module, null, false, false) || $lang->load($module, $client->path, $lang->getDefault(), false, false) || $lang->load($module, $client->path . '/modules/' . $module, $lang->getDefault(), false, false); if (file_exists($formFile)) { // Get the module form. if (!$form->loadFile($formFile, false, '//config')) { throw new Exception(JText::_('JERROR_LOADFILE_FAILED')); } // Attempt to load the xml file. if (!$xml = simplexml_load_file($formFile)) { throw new Exception(JText::_('JERROR_LOADFILE_FAILED')); } // Get the help data from the XML file if present. $help = $xml->xpath('/extension/help'); if (!empty($help)) { $helpKey = trim((string) $help[0]['key']); $helpURL = trim((string) $help[0]['url']); $this->helpKey = $helpKey ? $helpKey : $this->helpKey; $this->helpURL = $helpURL ? $helpURL : $this->helpURL; } } // Trigger the default form events. parent::preprocessForm($form, $data, $group); } /** * Loads ContentHelper for filters before validating data. * * @param object $form The form to validate against. * @param array $data The data to validate. * @param string $group The name of the group(defaults to null). * * @return mixed Array of filtered data if valid, false otherwise. * * @since 1.1 */ public function validate($form, $data, $group = null) { require_once JPATH_ADMINISTRATOR . '/components/com_content/helpers/content.php'; return parent::validate($form, $data, $group); } /** * Applies the text filters to arbitrary text as per settings for current user groups * * @param text $text The string to filter * * @return string The filtered string */ public static function filterText($text) { return JComponentHelper::filterText($text); } /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. * * @since 1.6 */ public function save($data) { $advancedparams = JFactory::getApplication()->input->get('advancedparams', array(), 'array'); $dispatcher = JDispatcher::getInstance(); $input = JFactory::getApplication()->input; $table = $this->getTable(); $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('module.id'); $isNew = true; // Include the content modules for the onSave events. JPluginHelper::importPlugin('extension'); // Load the row if saving an existing record. if ($pk > 0) { $table->load($pk); $isNew = false; } // Alter the title and published state for Save as Copy if ($input->get('task') == 'save2copy') { $orig_data = $input->post->get('jform', array(), 'array'); $orig_table = clone($this->getTable()); $orig_table->load((int) $orig_data['id']); if ($data['title'] == $orig_table->title) { $data['title'] .= ' ' . JText::_('JGLOBAL_COPY'); $data['published'] = 0; } } // correct the publish date details if (isset($advancedparams['assignto_date'])) { $publish_up = 0; $publish_down = 0; if ($advancedparams['assignto_date'] == 2) { $publish_up = $advancedparams['assignto_date_publish_down']; } else if ($advancedparams['assignto_date'] == 1) { $publish_up = $advancedparams['assignto_date_publish_up']; $publish_down = $advancedparams['assignto_date_publish_down']; } $data['publish_up'] = $publish_up; $data['publish_down'] = $publish_down; } $lang = '*'; if (isset($advancedparams['assignto_languages']) && $advancedparams['assignto_languages'] == 1 && count($advancedparams['assignto_languages_selection']) === 1 ) { $lang = (string) $advancedparams['assignto_languages_selection']['0']; } $data['language'] = $lang; // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } // Prepare the row for saving $this->prepareTable($table); // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Trigger the onExtensionBeforeSave event. $result = $dispatcher->trigger('onExtensionBeforeSave', array('com_advancedmodules.module', &$table, $isNew)); if (in_array(false, $result, true)) { $this->setError($table->getError()); return false; } // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); $table_adv->moduleid = $table->id; if ($table_adv->moduleid && !$table_adv->load($table_adv->moduleid)) { $db = $table_adv->getDbo(); $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if (isset($data['rules'])) { $table_adv->_title = $data['title']; $table_adv->setRules($data['rules']); } $registry = new JRegistry; $registry->loadArray($advancedparams); $table_adv->params = (string) $registry; // Check the row $table_adv->check(); // Store the row if (!$table_adv->store()) { $this->setError($table_adv->getError()); } // // Process the menu link mappings. // $data['assignment'] = '0'; $data['assigned'] = array(); if (isset($advancedparams['assignto_menuitems'])) { $empty = 0; if (isset($advancedparams['assignto_menuitems_selection'])) { $data['assigned'] = $advancedparams['assignto_menuitems_selection']; $empty = empty($advancedparams['assignto_menuitems_selection']); } else { $empty = 1; } if ($advancedparams['assignto_menuitems'] == 1 && $empty) { $data['assignment'] = '-'; } else if ($advancedparams['assignto_menuitems'] == 1) { $data['assignment'] = '1'; } else if ($advancedparams['assignto_menuitems'] == 2 && $empty) { $data['assignment'] = '0'; } else if ($advancedparams['assignto_menuitems'] == 2) { $data['assignment'] = '-1'; } } $assignment = $data['assignment']; $db = $this->getDbo(); $query = $db->getQuery(true) ->delete('#__modules_menu') ->where('moduleid = ' . (int) $table->id); $db->setQuery($query); $db->execute(); // If the assignment is numeric, then something is selected (otherwise it's none). if (is_numeric($assignment)) { // Variable is numeric, but could be a string. $assignment = (int) $assignment; // Logic check: if no module excluded then convert to display on all. if ($assignment == -1 && empty($data['assigned'])) { $assignment = 0; } // Check needed to stop a module being assigned to `All` // and other menu items resulting in a module being displayed twice. if ($assignment === 0) { // Assign new module to `all` menu item associations. $query->clear() ->insert('#__modules_menu') ->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid'))) ->values((int) $table->id . ', 0'); $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } } elseif (!empty($data['assigned'])) { // Get the sign of the number. $sign = $assignment < 0 ? -1 : 1; // Preprocess the assigned array. $inserts = array(); if (!is_array($data['assigned'])) { $data['assigned'] = explode(',', $data['assigned']); } foreach ($data['assigned'] as &$pk) { if(is_numeric($pk)) { $menuid = (int) $pk * $sign; $inserts[(int) $table->id . '-' . $menuid] = (int) $table->id . ',' . $menuid; } } $query->clear() ->insert('#__modules_menu') ->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid'))); foreach($inserts as $insert) { $query->values($insert); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } } } // Trigger the onExtensionAfterSave event. $dispatcher->trigger('onExtensionAfterSave', array('com_advancedmodules.module', &$table, $isNew)); // Compute the extension id of this module in case the controller wants it. $query->clear() ->select('extension_id') ->from('#__extensions AS e') ->join('LEFT', '#__modules AS m ON e.element = m.module') ->where('m.id = ' . (int) $table->id); $db->setQuery($query); try { $extensionId = $db->loadResult(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); return false; } $this->setState('module.extension_id', $extensionId); $this->setState('module.id', $table->id); // Clear modules cache $this->cleanCache(); // Clean module cache parent::cleanCache($table->module, $table->client_id); return true; } /** * Method to save the advanced parameters. * * @param array $data The form data. * * @return boolean True on success. * @since 1.6 */ public function saveAdvancedParams($data, $id = 0) { if (!$id) { $id = JFactory::getApplication()->input->getInt('id'); } if (!$id) { return true; } require_once JPATH_ADMINISTRATOR . '/components/com_advancedmodules/tables/advancedmodules.php'; $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); $table_adv->moduleid = $id; if ($id && !$table_adv->load($id)) { $db = $table_adv->getDbo(); $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if (isset($data['rules'])) { $table_adv->_title = $data['title']; $table_adv->setRules($data['rules']); } $registry = new JRegistry; $registry->loadArray($data); $table_adv->params = (string) $registry; // Check the row $table_adv->check(); try { // Store the data. $table_adv->store(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); return false; } return true; } /** * Method to get and save the module core menu assignments * * @param int $id The module id. * * @return boolean True on success. * @since 1.6 */ public function initAssignments($id, &$module) { if (!$id) { $id = JFactory::getApplication()->input->getInt('id'); } if (empty($id)) { $module->advancedparams = array( 'assignto_menuitems' => $this->config->default_menu_assignment, 'assignto_menuitems_selection' => array() ); } else { if (!isset($module->advancedparams['assignto_menuitems'])) { $db = $this->getDbo(); $query = $db->getQuery(true) ->select('m.menuid') ->from('#__modules_menu as m') ->where('m.moduleid = ' . (int) $id); $db->setQuery($query); $module->advancedparams['assignto_menuitems_selection'] = $db->loadColumn(); $module->advancedparams['assignto_menuitems'] = 0; if (!empty($module->advancedparams['assignto_menuitems_selection'])) { if ($module->advancedparams['assignto_menuitems_selection']['0'] == 0) { $module->advancedparams['assignto_menuitems'] = 0; $module->advancedparams['assignto_menuitems_selection'] = array(); } else if ($module->advancedparams['assignto_menuitems_selection']['0'] < 0) { $module->advancedparams['assignto_menuitems'] = 2; } else { $module->advancedparams['assignto_menuitems'] = 1; } foreach ($module->advancedparams['assignto_menuitems_selection'] as $i => $menuitem) { if ($menuitem < 0) { $module->advancedparams['assignto_menuitems_selection'][$i] = $menuitem * -1; } } } } else if( isset($module->advancedparams['assignto_menuitems_selection']['0']) && strpos($module->advancedparams['assignto_menuitems_selection']['0'], ',') !== false) { $module->advancedparams['assignto_menuitems_selection'] = explode(',', $module->advancedparams['assignto_menuitems_selection']['0']); } if (!isset($module->advancedparams['assignto_date']) || !$module->advancedparams['assignto_date']) { if ((isset($module->publish_up) && (int) $module->publish_up) || (isset($module->publish_down) && (int) $module->publish_down) ) { $module->advancedparams['assignto_date'] = 1; $module->advancedparams['assignto_date_publish_up'] = isset($module->publish_up) ? $module->publish_up : ''; $module->advancedparams['assignto_date_publish_down'] = isset($module->publish_down) ? $module->publish_down : ''; } } if (!isset($module->advancedparams['assignto_languages']) || !$module->advancedparams['assignto_languages']) { if (isset($module->language) && $module->language && $module->language != '*') { $module->advancedparams['assignto_languages'] = 1; $module->advancedparams['assignto_languages_selection'] = array($module->language); } } } AdvancedModulesModelModule::saveAdvancedParams($module->advancedparams, $id); return $module->advancedparams; } /** * A protected method to get a set of ordering conditions. * * @param object $table A record object. * * @return array An array of conditions to add to add to ordering queries. * * @since 1.6 */ protected function getReorderConditions($table) { $condition = array(); $condition[] = 'client_id = ' . (int) $table->client_id; $condition[] = 'position = ' . $this->_db->quote($table->position); return $condition; } /** * Custom clean cache method for different clients * * @param string $group The name of the plugin group to import (defaults to null). * @param integer $client_id The client ID. [optional] * * @return void * * @since 1.6 */ protected function cleanCache($group = null, $client_id = 0) { parent::cleanCache('com_advancedmodules', $this->getClient()); } /** * Method to test whether a record can be deleted. * * @param object $record A record object. * * @return boolean True if allowed to delete the record. Defaults to the permission set in the component. */ protected function canDelete($record) { if (!empty($record->id)) { if ($record->state != -2) { return; } $user = JFactory::getUser(); return $user->authorise('core.delete', 'com_advancedmodules.module.' . (int) $record->id); } } /** * Method to test whether a record can have its state edited. * * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. */ protected function canEditState($record) { $user = JFactory::getUser(); // Check for existing module. if (!empty($record->id)) { return $user->authorise('core.edit.state', 'com_advancedmodules.module.' . (int) $record->id); } // Default to component settings if neither article nor category known. else { return parent::canEditState('com_advancedmodules'); } } /** * Method override to check if you can edit an existing record. * * @param array $data An array of input data. * @param string $key The name of the key for the primary key. * * @return boolean */ protected function allowEdit($data = array(), $key = 'id') { // Initialise variables. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; $user = JFactory::getUser(); $userId = $user->get('id'); // Check general edit permission first. if ($user->authorise('core.edit', 'com_advancedmodules.module.' . $recordId)) { return true; } // Since there is no asset tracking, revert to the component permissions. return parent::allowEdit($data, $key); } /** * Function that gets the config settings * * @return Object */ protected function getConfig() { if (!isset($this->config)) { require_once JPATH_PLUGINS . '/system/nnframework/helpers/parameters.php'; $parameters = NNParameters::getInstance(); $this->config = $parameters->getComponentParams('advancedmodules'); } return $this->config; } }
adrian2020my/vichi
administrator/components/com_advancedmodules/models/module.php
PHP
gpl-2.0
40,561
diamondApp.service('scrollSvc', function () { this.scrollTo = function (eID) { // This scrolling function // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript var startY = currentYPosition(); var stopY = elmYPosition(eID); var distance = stopY > startY ? stopY - startY : startY - stopY; if (distance < 100) { scrollTo(0, stopY); return; } var speed = Math.round(distance / 10); if (speed >= 20) speed = 20; var step = Math.round(distance / 25); var leapY = stopY > startY ? startY + step : startY - step; var timer = 0; if (stopY > startY) { for (var i = startY; i < stopY; i += step) { setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed); leapY += step; if (leapY > stopY) leapY = stopY; timer++; } return; } for (var i = startY; i > stopY; i -= step) { setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed); leapY -= step; if (leapY < stopY) leapY = stopY; timer++; } function currentYPosition() { // Firefox, Chrome, Opera, Safari if (self.pageYOffset) return self.pageYOffset; // Internet Explorer 6 - standards mode if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6, 7 and 8 if (document.body.scrollTop) return document.body.scrollTop; return 0; } function elmYPosition(eID) { var elm = document.getElementById(eID); var y = elm.offsetTop; var node = elm; while (node.offsetParent && node.offsetParent != document.body) { node = node.offsetParent; y += node.offsetTop; } return y; } }; });
leadershipdiamond/leadershipdiamond
wp-content/themes/leadership-diamond-theme/js/app/services/scrollSvc.js
JavaScript
gpl-2.0
2,069
<?php /** * This file is part of TheCartPress. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with This program. If not, see <http://www.gnu.org/licenses/>. */ // Exit if accessed directly if ( !defined( 'ABSPATH' ) ) exit; if ( ! isset( $source ) ) return; if ( $source->see_address() ) : ?> <div class="row-fluid"> <dl id="tcp_order_id" class="dl-horizontal span12 well"> <dt class="tcp_order_id_row" scope="row" ><?php _e( 'Order ID', 'tcp' ); ?>:</dt> <dd class="tcp_order_id_value tcp_order_id"><?php echo $source->get_order_id(); ?></dd> <dt class="tcp_order_id_row" scope="row" ><?php _e( 'Created at', 'tcp' ); ?>:</dt> <dd class="tcp_order_id_value tcp_created_at"><?php echo $source->get_created_at(); ?></dd> </dl> <dl id="tcp_status" class="dl-horizontal span6"> <dt class="tcp_status_row" scope="row" ><?php _e( 'Payment method', 'tcp' ); ?>: </dt> <dd class="tcp_status_value tcp_payment_method" ><?php echo $source->get_payment_name(); ?></dd> <?php if ( $source->get_payment_notice() ) : ?> <dt class="tcp_status_row" scope="row" ><?php _e( 'Payment notice', 'tcp' ); ?>: </dt> <dd class="tcp_payment_notice"><?php echo $source->get_payment_notice(); ?></dd> <?php endif; ?> <dt class="tcp_status_row" scope="row" ><?php _e( 'Shipping method', 'tcp' ); ?>: </dt> <dd class="tcp_status_value tcp_shipping_method"><?php echo $source->get_shipping_method(); ?></dd> <?php if ( $source->get_shipping_notice() ) : ?> <dt class="tcp_status_row" scope="row" ><?php _e( 'Shipping notice', 'tcp' ); ?>: </dt> <dd class="tcp_shipping_notice"><?php echo $source->get_shipping_notice(); ?></dd> <?php endif; ?> <dt class="tcp_status_row" scope="row" ><?php _e( 'Status', 'tcp' ); ?>: </dt> <dd class="tcp_status_value tcp_status tcp_status_<?php echo $source->get_status(); ?>"><?php echo tcp_get_status_label( $source->get_status() ); ?></dd> </dl> </div> <?php if ( strlen( $source->get_shipping_firstname() ) > 0 && strlen( $source->get_shipping_lastname() ) > 0 ) : ?> <div id="shipping_billing_info" class="row-fluid tcpf"> <ul class="span4 unstyled"> <li class="shipping_info divider" ><h3><?php _e( 'Shipping address', 'tcp' ); ?></h3></li> <li class="shipping_info"> <?php echo $source->get_shipping_firstname(); ?> <?php echo $source->get_shipping_lastname(); ?> </li> <?php if ( strlen( $source->get_shipping_company() ) > 0 || strlen( $source->get_billing_company() ) > 0 ) : ?> <li class="shipping_info"> <?php if ( strlen( $source->get_shipping_company() ) > 0 ) : ?> <?php echo $source->get_shipping_company(); ?> <?php endif; ?>&nbsp; </li> <?php endif; ?> <?php if ( strlen( $source->get_billing_tax_id_number() ) > 0 ) : ?> <li class="shipping_info"> &nbsp; </li> <?php endif; ?> <li class="shipping_info"> <?php echo $source->get_shipping_street(); ?> </li> <li class="shipping_info"> <?php $out = array(); if ( strlen( $source->get_shipping_postcode() ) > 0 ) $out[] = $source->get_shipping_postcode(); if ( strlen( $source->get_shipping_city() ) > 0 ) $out[] = $source->get_shipping_city(); echo implode( ', ', $out ); ?> </li> <li class="shipping_info"> <?php $out = array(); if ( strlen( $source->get_shipping_region() ) > 0 ) $out[] = $source->get_shipping_region(); if ( strlen( $source->get_shipping_country() ) > 0 ) $out[] = $source->get_shipping_country(); echo implode( ', ', $out ); ?> </li> <li class="shipping_info"> <?php $telephone = $source->get_shipping_telephone_1(); if ( strlen( $source->get_shipping_telephone_2() ) > 0 ) $telephone .= ' - ' . $source->get_shipping_telephone_2(); ?> <?php if ( strlen( $telephone ) > 0 ) : _e( 'Telephones', 'tcp' ); ?>: <?php echo $telephone; ?><?php endif; ?> </li> <li class="shipping_info"> <?php if ( strlen( $source->get_shipping_fax() ) > 0 ) : _e( 'Fax', 'tcp' ); ?>: <?php echo $source->get_shipping_fax(); ?><?php endif; ?> </li> <li class="shipping_info"> <?php if ( strlen( $source->get_shipping_email() ) > 0 ) : echo $source->get_shipping_email(); ?><?php endif; ?> </li> </ul> <ul class="span7 unstyled"> <li class="billing_info divider" ><h3><?php _e( 'Billing address', 'tcp' ); ?></h3></li> <li class="billing_info"> <?php echo $source->get_billing_firstname(); ?> <?php echo $source->get_billing_lastname(); ?> </li> <?php if ( strlen( $source->get_shipping_company() ) > 0 && strlen( $source->get_billing_company() ) > 0 ) : ?> <li class="billing_info"> <?php if ( strlen( $source->get_billing_company() ) > 0 ) : ?> <?php echo $source->get_billing_company(); ?> <?php endif; ?>&nbsp; </li> <?php endif; ?> <?php if ( strlen( $source->get_billing_tax_id_number() ) > 0 ) : ?> <li class="billing_info"> <?php if ( strlen( $source->get_billing_tax_id_number() ) > 0 ) : ?> <?php echo $source->get_billing_tax_id_number(); ?> <?php endif; ?>&nbsp; </li> <?php endif; ?> <li class="billing_info"> <?php echo $source->get_billing_street(); ?> </li> <li class="billing_info"> <?php $out = array(); if ( strlen( $source->get_billing_postcode() ) > 0 ) $out[] = $source->get_billing_postcode(); if ( strlen( $source->get_billing_city() ) > 0 ) $out[] = $source->get_billing_city(); echo implode( ', ', $out ); ?> </li> <li class="billing_info"> <?php $out = array(); if ( strlen( $source->get_billing_region() ) > 0 ) $out[] = $source->get_billing_region(); if ( strlen( $source->get_billing_country() ) > 0 ) $out[] = $source->get_billing_country(); echo implode( ', ', $out ); ?> </li> <li class="billing_info"> <?php $telephone = $source->get_billing_telephone_1(); if ( strlen( $source->get_billing_telephone_2() ) > 0 ) $telephone .= ' - ' . $source->get_billing_telephone_2(); ?> <?php if ( strlen( $telephone ) > 0 ) : _e( 'Telephones', 'tcp' ); ?>: <?php echo $telephone; ?><br/><?php endif; ?> </li> <li class="billing_info"> <?php if ( strlen( $source->get_billing_fax() ) > 0 ) : _e( 'Fax', 'tcp' ); ?>: <?php echo $source->get_billing_fax(); ?><?php endif; ?> </li> <li class="billing_info"> <?php if ( strlen( $source->get_billing_email() ) > 0 ) : echo $source->get_billing_email(); ?><br/><?php endif; ?> </li> </ul> </div> <?php else : ?> <div id="shipping_billing_info" class="row-fluid"> <ul class="span6 unstyled"> <li class="billing_info divider" ><h3><?php _e( 'Shipping and Billing address', 'tcp' ); ?></h3></li> <li class="billing_info"> <?php echo $source->get_billing_firstname();?> <?php echo $source->get_billing_lastname(); ?> </li> <?php if ( strlen( $source->get_billing_company() ) > 0 ) : ?> <li class="billing_info"> <?php echo $source->get_billing_company(); ?> </li> <?php endif; ?> <?php if ( strlen( $source->get_billing_tax_id_number() ) > 0 ) : ?> <li class="billing_info"> <?php echo $source->get_billing_tax_id_number(); ?> </li> <?php endif; ?> <li class="billing_info"> <?php echo $source->get_billing_street(); ?> </li> <li class="billing_info"> <?php $out = array(); if ( strlen( $source->get_billing_postcode() ) > 0 ) $out[] = $source->get_billing_postcode(); if ( strlen( $source->get_billing_city() ) > 0 ) $out[] = $source->get_billing_city(); echo implode( ', ', $out ); ?> </li> <li class="billing_info"> <?php $out = array(); if ( strlen( $source->get_billing_region() ) > 0 ) $out[] = $source->get_billing_region(); if ( strlen( $source->get_billing_country() ) > 0 ) $out[] = $source->get_billing_country(); echo implode( ', ', $out ); ?> </li> <li class="billing_info"> <?php $telephone = $source->get_billing_telephone_1(); if ( strlen( $source->get_billing_telephone_2() ) > 0 ) $telephone .= ' - ' . $source->get_billing_telephone_2(); ?> <?php if ( strlen( $telephone ) > 0 ) : _e( 'Telephones', 'tcp' ); ?>: <?php echo $telephone; ?><br/><?php endif; ?> </li> <li class="billing_info"> <?php if ( strlen( $source->get_billing_fax() ) > 0 ) : _e( 'Fax', 'tcp' ); ?>: <?php echo $source->get_billing_fax(); ?><?php endif; ?> </li> <li class="billing_info"> <?php if ( strlen( $source->get_billing_email() ) > 0 ) : echo $source->get_billing_email(); ?><br/><?php endif; ?> </li> </ul> </div> <?php endif; ?> <?php endif; ?> <table id="tcp_shopping_cart_table" class="tcp_shopping_cart_table table" width="100%" cellpading="0" cellspacing="0"> <thead> <tr class="tcp_cart_title_row"> <?php if ( $source->see_thumbnail() ) : ?> <th class="tcp_cart_thumbnail">&nbsp;</th> <?php endif; ?> <th class="tcp_cart_name" ><?php _e( 'Name', 'tcp' ); ?></th> <th class="tcp_cart_price" ><?php _e( 'Price', 'tcp' ); ?></th> <th class="tcp_cart_units" ><?php _e( 'Units', 'tcp' ); ?></th> <?php if ( $source->see_sku() ) : ?><th class="tcp_cart_sku" ><?php _e( 'SKU', 'tcp' ); ?></th><?php endif; ?> <?php if ( $source->see_weight() ) : ?><th class="tcp_cart_weight" ><?php _e( 'Weight', 'tcp' ); ?></th><?php endif; ?> <?php if ( $source->see_tax() ) : ?><th class="tcp_cart_tax" ><?php _e( 'Tax', 'tcp' ); ?></th><?php endif; ?> <th class="tcp_cart_total" ><?php _e( 'Total', 'tcp' ); ?></th> </tr> </thead> <tbody> <?php $total_tax = 0; $total = 0; if ( $source->has_order_details() ) : $i = 0; foreach( $source->get_orders_details() as $order_detail ) : ?> <tr class="tcp_cart_product_row <?php if ( $i++ & 1 == 1 ) : ?> par<?php endif; ?>"> <?php if ( $source->see_thumbnail() ) : ?> <td class="tcp_cart_thumbnail"> <?php //$size = apply_filters( 'tcp_get_shopping_cart_image_size', array( 32, 32 ) ); echo tcp_get_the_thumbnail( $order_detail->get_post_id(), $order_detail->get_option_1_id(), $order_detail->get_option_2_id() ); //, $size ); ?> </td> <?php endif; ?> <td class="tcp_cart_name"> <?php $name = $order_detail->get_name(); $name = apply_filters( 'tcp_cart_table_title_item', $name, $order_detail ); if ( $source->see_product_link() ) { $name = '<a href="' . tcp_get_permalink( tcp_get_current_id( $order_detail->get_post_id(), get_post_type( $order_detail->get_post_id() ) ) ). '">' . $name . '</a>'; } ?> <?php echo apply_filters( 'tcp_cart_table_title_order_detail', $name, $order_detail->get_post_id() ); ?> </td> <td class="tcp_cart_price"><span class="tcp_cart_onlyprice"><?php echo tcp_format_the_price( $order_detail->get_price() ); ?></span> <?php if ( $order_detail->get_discount() > 0 ) : ?> <span class="tcp_cart_discount"><?php printf( __( '(-%s)', 'tcp' ), tcp_format_the_price( $order_detail->get_discount() / $order_detail->get_qty_ordered() ) ); ?></span> <?php endif; ?> </td> <td class="tcp_cart_units"> <?php if ( ! $source->is_editing_units() ) : ?> <?php echo tcp_number_format( $order_detail->get_qty_ordered(), 0 ); ?> <?php else : ?> <form method="post" action="<?php tcp_the_shopping_cart_url(); ?>" class="form-inline" role="form"> <input type="hidden" name="tcp_post_id" value="<?php echo $order_detail->get_post_id();?>" /> <input type="hidden" name="tcp_option_1_id" value="<?php echo $order_detail->get_option_1_id(); ?>" /> <input type="hidden" name="tcp_option_2_id" value="<?php echo $order_detail->get_option_2_id(); ?>" /> <?php do_action( 'tcp_get_shopping_cart_hidden_fields', $order_detail ); ?> <?php ob_start(); ?> <div class="form-group"> <label class="sr-only" for="tcp_count-<?php echo $order_detail->get_post_id();?>"><?php _e( 'Units', 'tcp' ); ?></label> <input type="number" name="tcp_count" id="tcp_count-<?php echo $order_detail->get_post_id();?>" value="<?php echo $order_detail->get_qty_ordered(); ?>" size="2" maxlength="4" class="tcp_count form-control input-sm" min="0" step="1"/> </div> <button type="submit" name="tcp_modify_item_shopping_cart" class="tcp_modify_item_shopping_cart tcp-btn tcp-btn-link tcp-btn-sm" title="<?php _e( 'Modify', 'tcp' ); ?>"><span class="glyphicon glyphicon-refresh"></span> <span class="sr-only"><?php _e( 'Modify', 'tcp' ); ?></span></button> <?php echo apply_filters( 'tcp_shopping_cart_page_units', ob_get_clean(), $order_detail ); ?> <button type="submit" name="tcp_delete_item_shopping_cart" class="tcp_delete_item_shopping_cart tcp-btn tcp-btn-link tcp-btn-sm" title="<?php _e( 'Delete', 'tcp' ); ?>"><span class="glyphicon glyphicon-trash"></span> <span class="sr-only"><?php _e( 'Delete', 'tcp' ); ?></span></button> <?php do_action( 'tcp_cart_units', $order_detail ); ?> </form> <?php endif; ?> </td> <?php if ( $source->see_sku() ) : ?> <td class="tcp_cart_sku"><?php echo $order_detail->get_sku(); ?></td> <?php endif; ?> <?php if ( $source->see_weight() ) : ?> <td class="tcp_cart_weight"><?php echo tcp_number_format( $order_detail->get_weight() ); ?>&nbsp;<?php echo tcp_get_the_unit_weight(); ?></td> <?php endif; ?> <?php $decimals = tcp_get_decimal_currency(); if ( ! $source->is_discount_applied() ) { $discount = round( $order_detail->get_discount() / $order_detail->get_qty_ordered(), $decimals ); } else { $discount = 0; } $price = $order_detail->get_price() - $discount; $price = round( $price, $decimals ); $tax = $price * $order_detail->get_tax() / 100; $tax = round( $tax, $decimals ); $total_tax += $tax * $order_detail->get_qty_ordered(); $price = round( $price * $order_detail->get_qty_ordered(), $decimals ); $price = apply_filters( 'tcp_shopping_cart_row_price', $price, $order_detail ); $total += $price; ?> <?php if ( $source->see_tax() ) : ?> <td class="tcp_cart_tax"><?php echo tcp_format_the_price( $tax ); ?></td> <?php endif; ?> <td class="tcp_cart_total"> <?php echo tcp_format_the_price( $price ); ?> </td> </tr> <?php endforeach; ?> <?php endif; ?> <tr class="tcp_cart_subtotal_row"> <?php $colspan = 3; if ( $source->see_weight() ) $colspan ++; if ( $source->see_sku() ) $colspan ++; if ( $source->see_tax() ) $colspan ++; if ( $source->see_thumbnail() ) $colspan ++; ?> <td colspan="<?php echo $colspan; ?>" class="tcp_cart_subtotal_title"><?php _e( 'Subtotal', 'tcp' ); ?></td> <td class="tcp_cart_subtotal"><?php echo tcp_format_the_price( $total ); ?></td> </tr> <?php $discount = $source->get_discount(); if ( $discount > 0 ) : ?> <tr class="tcp_cart_discount_row<?php if ( $i++ & 1 == 1 ) : ?> tcp_par<?php endif; ?>"> <td colspan="<?php echo $colspan; ?>" class="tcp_cart_discount_title"><?php _e( 'Discount', 'tcp' ); ?></td> <td class="tcp_cart_discount">-<?php echo tcp_format_the_price( $discount ); ?></td> </tr> <?php $total = $total - $discount; ?> <?php endif; if ( $source->see_other_costs() ) : if ( $source->has_orders_costs() ) : foreach( $source->get_orders_costs() as $order_cost ) : ?> <tr class="tcp_cart_other_costs_row"> <td colspan="<?php echo $colspan; ?>" class="tcp_cart_other_costs_title"><?php echo $order_cost->get_description(); ?></td> <td class="tcp_cart_other_costs"><?php echo tcp_format_the_price( $order_cost->get_cost() ); ?></td> <?php $tax = $order_cost->get_cost() * ( $order_cost->get_tax() / 100 ); $total_tax += $tax; $total += $order_cost->get_cost(); ?> </tr> <?php endforeach; endif; endif; if ( $source->see_tax_summary() && $total_tax > 0 ) : ?> <tr class="tcp_cart_tax_row"> <td colspan="<?php echo $colspan;?>" class="tcp_cart_tax_title"><?php _e( 'Taxes', 'tcp' ); ?></td> <td class="tcp_cart_tax"><?php echo tcp_format_the_price( $total_tax ); ?></td> </tr> <?php $total += $total_tax; ?> <?php endif; ?> <tr class="tcp_cart_total_row"> <td colspan="<?php echo $colspan; ?>" class="tcp_cart_total_title"><?php _e( 'Total', 'tcp' ); ?></td> <td class="tcp_cart_total"><?php echo tcp_format_the_price( $total ); ?></td> </tr> <tr class="tcp_shopping_cart_bottom"> <td colspan="<?php echo $colspan + 1; ?>" class="tcp_cart_total"> <?php tcp_do_template( 'tcp_shopping_cart_bottom' ); ?> </td> </tr> </tbody> </table> <?php if ( $source->see_comment() && strlen( $source->get_comment() ) > 0 ) : ?> <p class="tcp_comment"><?php echo $source->get_comment(); ?></p> <?php endif;
hassankbrian/LoveItLocal
wp-content/plugins/thecartpress/themes-templates/tcp_shopping_cart.php
PHP
gpl-2.0
17,053
import nose import sys import os import warnings import tempfile from contextlib import contextmanager import datetime import numpy as np import pandas import pandas as pd from pandas import (Series, DataFrame, Panel, MultiIndex, Categorical, bdate_range, date_range, Index, DatetimeIndex, isnull) from pandas.io.pytables import _tables try: _tables() except ImportError as e: raise nose.SkipTest(e) from pandas.io.pytables import (HDFStore, get_store, Term, read_hdf, IncompatibilityWarning, PerformanceWarning, AttributeConflictWarning, DuplicateWarning, PossibleDataLossError, ClosedFileError) from pandas.io import pytables as pytables import pandas.util.testing as tm from pandas.util.testing import (assert_panel4d_equal, assert_panel_equal, assert_frame_equal, assert_series_equal) from pandas import concat, Timestamp from pandas import compat from pandas.compat import range, lrange, u from pandas.util.testing import assert_produces_warning from numpy.testing.decorators import slow try: import tables except ImportError: raise nose.SkipTest('no pytables') from distutils.version import LooseVersion _default_compressor = LooseVersion(tables.__version__) >= '2.2' \ and 'blosc' or 'zlib' _multiprocess_can_split_ = False # contextmanager to ensure the file cleanup def safe_remove(path): if path is not None: try: os.remove(path) except: pass def safe_close(store): try: if store is not None: store.close() except: pass def create_tempfile(path): """ create an unopened named temporary file """ return os.path.join(tempfile.gettempdir(),path) @contextmanager def ensure_clean_store(path, mode='a', complevel=None, complib=None, fletcher32=False): try: # put in the temporary path if we don't have one already if not len(os.path.dirname(path)): path = create_tempfile(path) store = HDFStore(path, mode=mode, complevel=complevel, complib=complib, fletcher32=False) yield store finally: safe_close(store) if mode == 'w' or mode == 'a': safe_remove(path) @contextmanager def ensure_clean_path(path): """ return essentially a named temporary file that is not opened and deleted on existing; if path is a list, then create and return list of filenames """ try: if isinstance(path, list): filenames = [ create_tempfile(p) for p in path ] yield filenames else: filenames = [ create_tempfile(path) ] yield filenames[0] finally: for f in filenames: safe_remove(f) # set these parameters so we don't have file sharing tables.parameters.MAX_NUMEXPR_THREADS = 1 tables.parameters.MAX_BLOSC_THREADS = 1 tables.parameters.MAX_THREADS = 1 def _maybe_remove(store, key): """For tests using tables, try removing the table to be sure there is no content from previous tests using the same table name.""" try: store.remove(key) except: pass def compat_assert_produces_warning(w,f): """ don't produce a warning under PY3 """ if compat.PY3: f() else: with tm.assert_produces_warning(expected_warning=w): f() class TestHDFStore(tm.TestCase): @classmethod def setUpClass(cls): super(TestHDFStore, cls).setUpClass() # Pytables 3.0.0 deprecates lots of things tm.reset_testing_mode() @classmethod def tearDownClass(cls): super(TestHDFStore, cls).tearDownClass() # Pytables 3.0.0 deprecates lots of things tm.set_testing_mode() def setUp(self): warnings.filterwarnings(action='ignore', category=FutureWarning) self.path = 'tmp.__%s__.h5' % tm.rands(10) def tearDown(self): pass def test_factory_fun(self): try: with get_store(self.path) as tbl: raise ValueError('blah') except ValueError: pass finally: safe_remove(self.path) try: with get_store(self.path) as tbl: tbl['a'] = tm.makeDataFrame() with get_store(self.path) as tbl: self.assertEqual(len(tbl), 1) self.assertEqual(type(tbl['a']), DataFrame) finally: safe_remove(self.path) def test_context(self): try: with HDFStore(self.path) as tbl: raise ValueError('blah') except ValueError: pass finally: safe_remove(self.path) try: with HDFStore(self.path) as tbl: tbl['a'] = tm.makeDataFrame() with HDFStore(self.path) as tbl: self.assertEqual(len(tbl), 1) self.assertEqual(type(tbl['a']), DataFrame) finally: safe_remove(self.path) def test_conv_read_write(self): try: def roundtrip(key, obj,**kwargs): obj.to_hdf(self.path, key,**kwargs) return read_hdf(self.path, key) o = tm.makeTimeSeries() assert_series_equal(o, roundtrip('series',o)) o = tm.makeStringSeries() assert_series_equal(o, roundtrip('string_series',o)) o = tm.makeDataFrame() assert_frame_equal(o, roundtrip('frame',o)) o = tm.makePanel() assert_panel_equal(o, roundtrip('panel',o)) # table df = DataFrame(dict(A=lrange(5), B=lrange(5))) df.to_hdf(self.path,'table',append=True) result = read_hdf(self.path, 'table', where = ['index>2']) assert_frame_equal(df[df.index>2],result) finally: safe_remove(self.path) def test_long_strings(self): # GH6166 # unconversion of long strings was being chopped in earlier # versions of numpy < 1.7.2 df = DataFrame({'a': tm.rands_array(100, size=10)}, index=tm.rands_array(100, size=10)) with ensure_clean_store(self.path) as store: store.append('df', df, data_columns=['a']) result = store.select('df') assert_frame_equal(df, result) def test_api(self): # GH4584 # API issue when to_hdf doesn't acdept append AND format args with ensure_clean_path(self.path) as path: df = tm.makeDataFrame() df.iloc[:10].to_hdf(path,'df',append=True,format='table') df.iloc[10:].to_hdf(path,'df',append=True,format='table') assert_frame_equal(read_hdf(path,'df'),df) # append to False df.iloc[:10].to_hdf(path,'df',append=False,format='table') df.iloc[10:].to_hdf(path,'df',append=True,format='table') assert_frame_equal(read_hdf(path,'df'),df) with ensure_clean_path(self.path) as path: df = tm.makeDataFrame() df.iloc[:10].to_hdf(path,'df',append=True) df.iloc[10:].to_hdf(path,'df',append=True,format='table') assert_frame_equal(read_hdf(path,'df'),df) # append to False df.iloc[:10].to_hdf(path,'df',append=False,format='table') df.iloc[10:].to_hdf(path,'df',append=True) assert_frame_equal(read_hdf(path,'df'),df) with ensure_clean_path(self.path) as path: df = tm.makeDataFrame() df.to_hdf(path,'df',append=False,format='fixed') assert_frame_equal(read_hdf(path,'df'),df) df.to_hdf(path,'df',append=False,format='f') assert_frame_equal(read_hdf(path,'df'),df) df.to_hdf(path,'df',append=False) assert_frame_equal(read_hdf(path,'df'),df) df.to_hdf(path,'df') assert_frame_equal(read_hdf(path,'df'),df) with ensure_clean_store(self.path) as store: path = store._path df = tm.makeDataFrame() _maybe_remove(store,'df') store.append('df',df.iloc[:10],append=True,format='table') store.append('df',df.iloc[10:],append=True,format='table') assert_frame_equal(store.select('df'),df) # append to False _maybe_remove(store,'df') store.append('df',df.iloc[:10],append=False,format='table') store.append('df',df.iloc[10:],append=True,format='table') assert_frame_equal(store.select('df'),df) # formats _maybe_remove(store,'df') store.append('df',df.iloc[:10],append=False,format='table') store.append('df',df.iloc[10:],append=True,format='table') assert_frame_equal(store.select('df'),df) _maybe_remove(store,'df') store.append('df',df.iloc[:10],append=False,format='table') store.append('df',df.iloc[10:],append=True,format=None) assert_frame_equal(store.select('df'),df) with ensure_clean_path(self.path) as path: # invalid df = tm.makeDataFrame() self.assertRaises(ValueError, df.to_hdf, path,'df',append=True,format='f') self.assertRaises(ValueError, df.to_hdf, path,'df',append=True,format='fixed') self.assertRaises(TypeError, df.to_hdf, path,'df',append=True,format='foo') self.assertRaises(TypeError, df.to_hdf, path,'df',append=False,format='bar') #File path doesn't exist path = "" self.assertRaises(IOError, read_hdf, path, 'df') def test_api_default_format(self): # default_format option with ensure_clean_store(self.path) as store: df = tm.makeDataFrame() pandas.set_option('io.hdf.default_format','fixed') _maybe_remove(store,'df') store.put('df',df) self.assertFalse(store.get_storer('df').is_table) self.assertRaises(ValueError, store.append, 'df2',df) pandas.set_option('io.hdf.default_format','table') _maybe_remove(store,'df') store.put('df',df) self.assertTrue(store.get_storer('df').is_table) _maybe_remove(store,'df2') store.append('df2',df) self.assertTrue(store.get_storer('df').is_table) pandas.set_option('io.hdf.default_format',None) with ensure_clean_path(self.path) as path: df = tm.makeDataFrame() pandas.set_option('io.hdf.default_format','fixed') df.to_hdf(path,'df') with get_store(path) as store: self.assertFalse(store.get_storer('df').is_table) self.assertRaises(ValueError, df.to_hdf, path,'df2', append=True) pandas.set_option('io.hdf.default_format','table') df.to_hdf(path,'df3') with HDFStore(path) as store: self.assertTrue(store.get_storer('df3').is_table) df.to_hdf(path,'df4',append=True) with HDFStore(path) as store: self.assertTrue(store.get_storer('df4').is_table) pandas.set_option('io.hdf.default_format',None) def test_keys(self): with ensure_clean_store(self.path) as store: store['a'] = tm.makeTimeSeries() store['b'] = tm.makeStringSeries() store['c'] = tm.makeDataFrame() store['d'] = tm.makePanel() store['foo/bar'] = tm.makePanel() self.assertEqual(len(store), 5) self.assertTrue(set( store.keys()) == set(['/a', '/b', '/c', '/d', '/foo/bar'])) def test_repr(self): with ensure_clean_store(self.path) as store: repr(store) store['a'] = tm.makeTimeSeries() store['b'] = tm.makeStringSeries() store['c'] = tm.makeDataFrame() store['d'] = tm.makePanel() store['foo/bar'] = tm.makePanel() store.append('e', tm.makePanel()) df = tm.makeDataFrame() df['obj1'] = 'foo' df['obj2'] = 'bar' df['bool1'] = df['A'] > 0 df['bool2'] = df['B'] > 0 df['bool3'] = True df['int1'] = 1 df['int2'] = 2 df['timestamp1'] = Timestamp('20010102') df['timestamp2'] = Timestamp('20010103') df['datetime1'] = datetime.datetime(2001,1,2,0,0) df['datetime2'] = datetime.datetime(2001,1,3,0,0) df.ix[3:6,['obj1']] = np.nan df = df.consolidate().convert_objects() warnings.filterwarnings('ignore', category=PerformanceWarning) store['df'] = df warnings.filterwarnings('always', category=PerformanceWarning) # make a random group in hdf space store._handle.create_group(store._handle.root,'bah') repr(store) str(store) # storers with ensure_clean_store(self.path) as store: df = tm.makeDataFrame() store.append('df',df) s = store.get_storer('df') repr(s) str(s) def test_contains(self): with ensure_clean_store(self.path) as store: store['a'] = tm.makeTimeSeries() store['b'] = tm.makeDataFrame() store['foo/bar'] = tm.makeDataFrame() self.assertIn('a', store) self.assertIn('b', store) self.assertNotIn('c', store) self.assertIn('foo/bar', store) self.assertIn('/foo/bar', store) self.assertNotIn('/foo/b', store) self.assertNotIn('bar', store) # GH 2694 warnings.filterwarnings('ignore', category=tables.NaturalNameWarning) store['node())'] = tm.makeDataFrame() self.assertIn('node())', store) def test_versioning(self): with ensure_clean_store(self.path) as store: store['a'] = tm.makeTimeSeries() store['b'] = tm.makeDataFrame() df = tm.makeTimeDataFrame() _maybe_remove(store, 'df1') store.append('df1', df[:10]) store.append('df1', df[10:]) self.assertEqual(store.root.a._v_attrs.pandas_version, '0.15.2') self.assertEqual(store.root.b._v_attrs.pandas_version, '0.15.2') self.assertEqual(store.root.df1._v_attrs.pandas_version, '0.15.2') # write a file and wipe its versioning _maybe_remove(store, 'df2') store.append('df2', df) # this is an error because its table_type is appendable, but no version # info store.get_node('df2')._v_attrs.pandas_version = None self.assertRaises(Exception, store.select, 'df2') def test_mode(self): df = tm.makeTimeDataFrame() def check(mode): with ensure_clean_path(self.path) as path: # constructor if mode in ['r','r+']: self.assertRaises(IOError, HDFStore, path, mode=mode) else: store = HDFStore(path,mode=mode) self.assertEqual(store._handle.mode, mode) store.close() with ensure_clean_path(self.path) as path: # context if mode in ['r','r+']: def f(): with HDFStore(path,mode=mode) as store: pass self.assertRaises(IOError, f) else: with HDFStore(path,mode=mode) as store: self.assertEqual(store._handle.mode, mode) with ensure_clean_path(self.path) as path: # conv write if mode in ['r','r+']: self.assertRaises(IOError, df.to_hdf, path, 'df', mode=mode) df.to_hdf(path,'df',mode='w') else: df.to_hdf(path,'df',mode=mode) # conv read if mode in ['w']: self.assertRaises(KeyError, read_hdf, path, 'df', mode=mode) else: result = read_hdf(path,'df',mode=mode) assert_frame_equal(result,df) check('r') check('r+') check('a') check('w') def test_reopen_handle(self): with ensure_clean_path(self.path) as path: store = HDFStore(path,mode='a') store['a'] = tm.makeTimeSeries() # invalid mode change self.assertRaises(PossibleDataLossError, store.open, 'w') store.close() self.assertFalse(store.is_open) # truncation ok here store.open('w') self.assertTrue(store.is_open) self.assertEqual(len(store), 0) store.close() self.assertFalse(store.is_open) store = HDFStore(path,mode='a') store['a'] = tm.makeTimeSeries() # reopen as read store.open('r') self.assertTrue(store.is_open) self.assertEqual(len(store), 1) self.assertEqual(store._mode, 'r') store.close() self.assertFalse(store.is_open) # reopen as append store.open('a') self.assertTrue(store.is_open) self.assertEqual(len(store), 1) self.assertEqual(store._mode, 'a') store.close() self.assertFalse(store.is_open) # reopen as append (again) store.open('a') self.assertTrue(store.is_open) self.assertEqual(len(store), 1) self.assertEqual(store._mode, 'a') store.close() self.assertFalse(store.is_open) def test_open_args(self): with ensure_clean_path(self.path) as path: df = tm.makeDataFrame() # create an in memory store store = HDFStore(path,mode='a',driver='H5FD_CORE',driver_core_backing_store=0) store['df'] = df store.append('df2',df) tm.assert_frame_equal(store['df'],df) tm.assert_frame_equal(store['df2'],df) store.close() # the file should not have actually been written self.assertFalse(os.path.exists(path)) def test_flush(self): with ensure_clean_store(self.path) as store: store['a'] = tm.makeTimeSeries() store.flush() store.flush(fsync=True) def test_get(self): with ensure_clean_store(self.path) as store: store['a'] = tm.makeTimeSeries() left = store.get('a') right = store['a'] tm.assert_series_equal(left, right) left = store.get('/a') right = store['/a'] tm.assert_series_equal(left, right) self.assertRaises(KeyError, store.get, 'b') def test_getattr(self): with ensure_clean_store(self.path) as store: s = tm.makeTimeSeries() store['a'] = s # test attribute access result = store.a tm.assert_series_equal(result, s) result = getattr(store,'a') tm.assert_series_equal(result, s) df = tm.makeTimeDataFrame() store['df'] = df result = store.df tm.assert_frame_equal(result, df) # errors self.assertRaises(AttributeError, getattr, store, 'd') for x in ['mode','path','handle','complib']: self.assertRaises(AttributeError, getattr, store, x) # not stores for x in ['mode','path','handle','complib']: getattr(store,"_%s" % x) def test_put(self): with ensure_clean_store(self.path) as store: ts = tm.makeTimeSeries() df = tm.makeTimeDataFrame() store['a'] = ts store['b'] = df[:10] store['foo/bar/bah'] = df[:10] store['foo'] = df[:10] store['/foo'] = df[:10] store.put('c', df[:10], format='table') # not OK, not a table self.assertRaises( ValueError, store.put, 'b', df[10:], append=True) # node does not currently exist, test _is_table_type returns False in # this case # _maybe_remove(store, 'f') # self.assertRaises(ValueError, store.put, 'f', df[10:], append=True) # can't put to a table (use append instead) self.assertRaises(ValueError, store.put, 'c', df[10:], append=True) # overwrite table store.put('c', df[:10], format='table', append=False) tm.assert_frame_equal(df[:10], store['c']) def test_put_string_index(self): with ensure_clean_store(self.path) as store: index = Index( ["I am a very long string index: %s" % i for i in range(20)]) s = Series(np.arange(20), index=index) df = DataFrame({'A': s, 'B': s}) store['a'] = s tm.assert_series_equal(store['a'], s) store['b'] = df tm.assert_frame_equal(store['b'], df) # mixed length index = Index(['abcdefghijklmnopqrstuvwxyz1234567890'] + ["I am a very long string index: %s" % i for i in range(20)]) s = Series(np.arange(21), index=index) df = DataFrame({'A': s, 'B': s}) store['a'] = s tm.assert_series_equal(store['a'], s) store['b'] = df tm.assert_frame_equal(store['b'], df) def test_put_compression(self): with ensure_clean_store(self.path) as store: df = tm.makeTimeDataFrame() store.put('c', df, format='table', complib='zlib') tm.assert_frame_equal(store['c'], df) # can't compress if format='fixed' self.assertRaises(ValueError, store.put, 'b', df, format='fixed', complib='zlib') def test_put_compression_blosc(self): tm.skip_if_no_package('tables', '2.2', app='blosc support') df = tm.makeTimeDataFrame() with ensure_clean_store(self.path) as store: # can't compress if format='fixed' self.assertRaises(ValueError, store.put, 'b', df, format='fixed', complib='blosc') store.put('c', df, format='table', complib='blosc') tm.assert_frame_equal(store['c'], df) def test_put_integer(self): # non-date, non-string index df = DataFrame(np.random.randn(50, 100)) self._check_roundtrip(df, tm.assert_frame_equal) def test_put_mixed_type(self): df = tm.makeTimeDataFrame() df['obj1'] = 'foo' df['obj2'] = 'bar' df['bool1'] = df['A'] > 0 df['bool2'] = df['B'] > 0 df['bool3'] = True df['int1'] = 1 df['int2'] = 2 df['timestamp1'] = Timestamp('20010102') df['timestamp2'] = Timestamp('20010103') df['datetime1'] = datetime.datetime(2001, 1, 2, 0, 0) df['datetime2'] = datetime.datetime(2001, 1, 3, 0, 0) df.ix[3:6, ['obj1']] = np.nan df = df.consolidate().convert_objects() with ensure_clean_store(self.path) as store: _maybe_remove(store, 'df') # cannot use assert_produces_warning here for some reason # a PendingDeprecationWarning is also raised? warnings.filterwarnings('ignore', category=PerformanceWarning) store.put('df',df) warnings.filterwarnings('always', category=PerformanceWarning) expected = store.get('df') tm.assert_frame_equal(expected,df) def test_append(self): with ensure_clean_store(self.path) as store: df = tm.makeTimeDataFrame() _maybe_remove(store, 'df1') store.append('df1', df[:10]) store.append('df1', df[10:]) tm.assert_frame_equal(store['df1'], df) _maybe_remove(store, 'df2') store.put('df2', df[:10], format='table') store.append('df2', df[10:]) tm.assert_frame_equal(store['df2'], df) _maybe_remove(store, 'df3') store.append('/df3', df[:10]) store.append('/df3', df[10:]) tm.assert_frame_equal(store['df3'], df) # this is allowed by almost always don't want to do it with tm.assert_produces_warning(expected_warning=tables.NaturalNameWarning): _maybe_remove(store, '/df3 foo') store.append('/df3 foo', df[:10]) store.append('/df3 foo', df[10:]) tm.assert_frame_equal(store['df3 foo'], df) # panel wp = tm.makePanel() _maybe_remove(store, 'wp1') store.append('wp1', wp.ix[:, :10, :]) store.append('wp1', wp.ix[:, 10:, :]) assert_panel_equal(store['wp1'], wp) # ndim p4d = tm.makePanel4D() _maybe_remove(store, 'p4d') store.append('p4d', p4d.ix[:, :, :10, :]) store.append('p4d', p4d.ix[:, :, 10:, :]) assert_panel4d_equal(store['p4d'], p4d) # test using axis labels _maybe_remove(store, 'p4d') store.append('p4d', p4d.ix[:, :, :10, :], axes=[ 'items', 'major_axis', 'minor_axis']) store.append('p4d', p4d.ix[:, :, 10:, :], axes=[ 'items', 'major_axis', 'minor_axis']) assert_panel4d_equal(store['p4d'], p4d) # test using differnt number of items on each axis p4d2 = p4d.copy() p4d2['l4'] = p4d['l1'] p4d2['l5'] = p4d['l1'] _maybe_remove(store, 'p4d2') store.append( 'p4d2', p4d2, axes=['items', 'major_axis', 'minor_axis']) assert_panel4d_equal(store['p4d2'], p4d2) # test using differt order of items on the non-index axes _maybe_remove(store, 'wp1') wp_append1 = wp.ix[:, :10, :] store.append('wp1', wp_append1) wp_append2 = wp.ix[:, 10:, :].reindex(items=wp.items[::-1]) store.append('wp1', wp_append2) assert_panel_equal(store['wp1'], wp) # dtype issues - mizxed type in a single object column df = DataFrame(data=[[1, 2], [0, 1], [1, 2], [0, 0]]) df['mixed_column'] = 'testing' df.ix[2, 'mixed_column'] = np.nan _maybe_remove(store, 'df') store.append('df', df) tm.assert_frame_equal(store['df'], df) # uints - test storage of uints uint_data = DataFrame({'u08' : Series(np.random.random_integers(0, high=255, size=5), dtype=np.uint8), 'u16' : Series(np.random.random_integers(0, high=65535, size=5), dtype=np.uint16), 'u32' : Series(np.random.random_integers(0, high=2**30, size=5), dtype=np.uint32), 'u64' : Series([2**58, 2**59, 2**60, 2**61, 2**62], dtype=np.uint64)}, index=np.arange(5)) _maybe_remove(store, 'uints') store.append('uints', uint_data) tm.assert_frame_equal(store['uints'], uint_data) # uints - test storage of uints in indexable columns _maybe_remove(store, 'uints') store.append('uints', uint_data, data_columns=['u08','u16','u32']) # 64-bit indices not yet supported tm.assert_frame_equal(store['uints'], uint_data) def test_append_series(self): with ensure_clean_store(self.path) as store: # basic ss = tm.makeStringSeries() ts = tm.makeTimeSeries() ns = Series(np.arange(100)) store.append('ss', ss) result = store['ss'] tm.assert_series_equal(result, ss) self.assertIsNone(result.name) store.append('ts', ts) result = store['ts'] tm.assert_series_equal(result, ts) self.assertIsNone(result.name) ns.name = 'foo' store.append('ns', ns) result = store['ns'] tm.assert_series_equal(result, ns) self.assertEqual(result.name, ns.name) # select on the values expected = ns[ns>60] result = store.select('ns',Term('foo>60')) tm.assert_series_equal(result,expected) # select on the index and values expected = ns[(ns>70) & (ns.index<90)] result = store.select('ns',[Term('foo>70'), Term('index<90')]) tm.assert_series_equal(result,expected) # multi-index mi = DataFrame(np.random.randn(5,1),columns=['A']) mi['B'] = np.arange(len(mi)) mi['C'] = 'foo' mi.loc[3:5,'C'] = 'bar' mi.set_index(['C','B'],inplace=True) s = mi.stack() s.index = s.index.droplevel(2) store.append('mi', s) tm.assert_series_equal(store['mi'], s) def test_store_index_types(self): # GH5386 # test storing various index types with ensure_clean_store(self.path) as store: def check(format,index): df = DataFrame(np.random.randn(10,2),columns=list('AB')) df.index = index(len(df)) _maybe_remove(store, 'df') store.put('df',df,format=format) assert_frame_equal(df,store['df']) for index in [ tm.makeFloatIndex, tm.makeStringIndex, tm.makeIntIndex, tm.makeDateIndex ]: check('table',index) check('fixed',index) # period index currently broken for table # seee GH7796 FIXME check('fixed',tm.makePeriodIndex) #check('table',tm.makePeriodIndex) # unicode index = tm.makeUnicodeIndex if compat.PY3: check('table',index) check('fixed',index) else: # only support for fixed types (and they have a perf warning) self.assertRaises(TypeError, check, 'table', index) with tm.assert_produces_warning(expected_warning=PerformanceWarning): check('fixed',index) def test_encoding(self): if sys.byteorder != 'little': raise nose.SkipTest('system byteorder is not little') with ensure_clean_store(self.path) as store: df = DataFrame(dict(A='foo',B='bar'),index=range(5)) df.loc[2,'A'] = np.nan df.loc[3,'B'] = np.nan _maybe_remove(store, 'df') store.append('df', df, encoding='ascii') tm.assert_frame_equal(store['df'], df) expected = df.reindex(columns=['A']) result = store.select('df',Term('columns=A',encoding='ascii')) tm.assert_frame_equal(result,expected) def test_append_some_nans(self): with ensure_clean_store(self.path) as store: df = DataFrame({'A' : Series(np.random.randn(20)).astype('int32'), 'A1' : np.random.randn(20), 'A2' : np.random.randn(20), 'B' : 'foo', 'C' : 'bar', 'D' : Timestamp("20010101"), 'E' : datetime.datetime(2001,1,2,0,0) }, index=np.arange(20)) # some nans _maybe_remove(store, 'df1') df.ix[0:15,['A1','B','D','E']] = np.nan store.append('df1', df[:10]) store.append('df1', df[10:]) tm.assert_frame_equal(store['df1'], df) # first column df1 = df.copy() df1.ix[:,'A1'] = np.nan _maybe_remove(store, 'df1') store.append('df1', df1[:10]) store.append('df1', df1[10:]) tm.assert_frame_equal(store['df1'], df1) # 2nd column df2 = df.copy() df2.ix[:,'A2'] = np.nan _maybe_remove(store, 'df2') store.append('df2', df2[:10]) store.append('df2', df2[10:]) tm.assert_frame_equal(store['df2'], df2) # datetimes df3 = df.copy() df3.ix[:,'E'] = np.nan _maybe_remove(store, 'df3') store.append('df3', df3[:10]) store.append('df3', df3[10:]) tm.assert_frame_equal(store['df3'], df3) def test_append_all_nans(self): with ensure_clean_store(self.path) as store: df = DataFrame({'A1' : np.random.randn(20), 'A2' : np.random.randn(20)}, index=np.arange(20)) df.ix[0:15,:] = np.nan # nan some entire rows (dropna=True) _maybe_remove(store, 'df') store.append('df', df[:10], dropna=True) store.append('df', df[10:], dropna=True) tm.assert_frame_equal(store['df'], df[-4:]) # nan some entire rows (dropna=False) _maybe_remove(store, 'df2') store.append('df2', df[:10], dropna=False) store.append('df2', df[10:], dropna=False) tm.assert_frame_equal(store['df2'], df) # tests the option io.hdf.dropna_table pandas.set_option('io.hdf.dropna_table',False) _maybe_remove(store, 'df3') store.append('df3', df[:10]) store.append('df3', df[10:]) tm.assert_frame_equal(store['df3'], df) pandas.set_option('io.hdf.dropna_table',True) _maybe_remove(store, 'df4') store.append('df4', df[:10]) store.append('df4', df[10:]) tm.assert_frame_equal(store['df4'], df[-4:]) # nan some entire rows (string are still written!) df = DataFrame({'A1' : np.random.randn(20), 'A2' : np.random.randn(20), 'B' : 'foo', 'C' : 'bar'}, index=np.arange(20)) df.ix[0:15,:] = np.nan _maybe_remove(store, 'df') store.append('df', df[:10], dropna=True) store.append('df', df[10:], dropna=True) tm.assert_frame_equal(store['df'], df) _maybe_remove(store, 'df2') store.append('df2', df[:10], dropna=False) store.append('df2', df[10:], dropna=False) tm.assert_frame_equal(store['df2'], df) # nan some entire rows (but since we have dates they are still written!) df = DataFrame({'A1' : np.random.randn(20), 'A2' : np.random.randn(20), 'B' : 'foo', 'C' : 'bar', 'D' : Timestamp("20010101"), 'E' : datetime.datetime(2001,1,2,0,0) }, index=np.arange(20)) df.ix[0:15,:] = np.nan _maybe_remove(store, 'df') store.append('df', df[:10], dropna=True) store.append('df', df[10:], dropna=True) tm.assert_frame_equal(store['df'], df) _maybe_remove(store, 'df2') store.append('df2', df[:10], dropna=False) store.append('df2', df[10:], dropna=False) tm.assert_frame_equal(store['df2'], df) def test_append_frame_column_oriented(self): with ensure_clean_store(self.path) as store: # column oriented df = tm.makeTimeDataFrame() _maybe_remove(store, 'df1') store.append('df1', df.ix[:, :2], axes=['columns']) store.append('df1', df.ix[:, 2:]) tm.assert_frame_equal(store['df1'], df) result = store.select('df1', 'columns=A') expected = df.reindex(columns=['A']) tm.assert_frame_equal(expected, result) # selection on the non-indexable result = store.select( 'df1', ('columns=A', Term('index=df.index[0:4]'))) expected = df.reindex(columns=['A'], index=df.index[0:4]) tm.assert_frame_equal(expected, result) # this isn't supported self.assertRaises(TypeError, store.select, 'df1', ( 'columns=A', Term('index>df.index[4]'))) def test_append_with_different_block_ordering(self): #GH 4096; using same frames, but different block orderings with ensure_clean_store(self.path) as store: for i in range(10): df = DataFrame(np.random.randn(10,2),columns=list('AB')) df['index'] = range(10) df['index'] += i*10 df['int64'] = Series([1]*len(df),dtype='int64') df['int16'] = Series([1]*len(df),dtype='int16') if i % 2 == 0: del df['int64'] df['int64'] = Series([1]*len(df),dtype='int64') if i % 3 == 0: a = df.pop('A') df['A'] = a df.set_index('index',inplace=True) store.append('df',df) # test a different ordering but with more fields (like invalid combinate) with ensure_clean_store(self.path) as store: df = DataFrame(np.random.randn(10,2),columns=list('AB'), dtype='float64') df['int64'] = Series([1]*len(df),dtype='int64') df['int16'] = Series([1]*len(df),dtype='int16') store.append('df',df) # store additonal fields in different blocks df['int16_2'] = Series([1]*len(df),dtype='int16') self.assertRaises(ValueError, store.append, 'df', df) # store multile additonal fields in different blocks df['float_3'] = Series([1.]*len(df),dtype='float64') self.assertRaises(ValueError, store.append, 'df', df) def test_ndim_indexables(self): """ test using ndim tables in new ways""" with ensure_clean_store(self.path) as store: p4d = tm.makePanel4D() def check_indexers(key, indexers): for i, idx in enumerate(indexers): self.assertTrue(getattr(getattr( store.root, key).table.description, idx)._v_pos == i) # append then change (will take existing schema) indexers = ['items', 'major_axis', 'minor_axis'] _maybe_remove(store, 'p4d') store.append('p4d', p4d.ix[:, :, :10, :], axes=indexers) store.append('p4d', p4d.ix[:, :, 10:, :]) assert_panel4d_equal(store.select('p4d'), p4d) check_indexers('p4d', indexers) # same as above, but try to append with differnt axes _maybe_remove(store, 'p4d') store.append('p4d', p4d.ix[:, :, :10, :], axes=indexers) store.append('p4d', p4d.ix[:, :, 10:, :], axes=[ 'labels', 'items', 'major_axis']) assert_panel4d_equal(store.select('p4d'), p4d) check_indexers('p4d', indexers) # pass incorrect number of axes _maybe_remove(store, 'p4d') self.assertRaises(ValueError, store.append, 'p4d', p4d.ix[ :, :, :10, :], axes=['major_axis', 'minor_axis']) # different than default indexables #1 indexers = ['labels', 'major_axis', 'minor_axis'] _maybe_remove(store, 'p4d') store.append('p4d', p4d.ix[:, :, :10, :], axes=indexers) store.append('p4d', p4d.ix[:, :, 10:, :]) assert_panel4d_equal(store['p4d'], p4d) check_indexers('p4d', indexers) # different than default indexables #2 indexers = ['major_axis', 'labels', 'minor_axis'] _maybe_remove(store, 'p4d') store.append('p4d', p4d.ix[:, :, :10, :], axes=indexers) store.append('p4d', p4d.ix[:, :, 10:, :]) assert_panel4d_equal(store['p4d'], p4d) check_indexers('p4d', indexers) # partial selection result = store.select('p4d', ['labels=l1']) expected = p4d.reindex(labels=['l1']) assert_panel4d_equal(result, expected) # partial selection2 result = store.select('p4d', [Term( 'labels=l1'), Term('items=ItemA'), Term('minor_axis=B')]) expected = p4d.reindex( labels=['l1'], items=['ItemA'], minor_axis=['B']) assert_panel4d_equal(result, expected) # non-existant partial selection result = store.select('p4d', [Term( 'labels=l1'), Term('items=Item1'), Term('minor_axis=B')]) expected = p4d.reindex(labels=['l1'], items=[], minor_axis=['B']) assert_panel4d_equal(result, expected) def test_append_with_strings(self): with ensure_clean_store(self.path) as store: wp = tm.makePanel() wp2 = wp.rename_axis( dict([(x, "%s_extra" % x) for x in wp.minor_axis]), axis=2) def check_col(key,name,size): self.assertEqual(getattr(store.get_storer(key).table.description,name).itemsize, size) store.append('s1', wp, min_itemsize=20) store.append('s1', wp2) expected = concat([wp, wp2], axis=2) expected = expected.reindex(minor_axis=sorted(expected.minor_axis)) assert_panel_equal(store['s1'], expected) check_col('s1', 'minor_axis', 20) # test dict format store.append('s2', wp, min_itemsize={'minor_axis': 20}) store.append('s2', wp2) expected = concat([wp, wp2], axis=2) expected = expected.reindex(minor_axis=sorted(expected.minor_axis)) assert_panel_equal(store['s2'], expected) check_col('s2', 'minor_axis', 20) # apply the wrong field (similar to #1) store.append('s3', wp, min_itemsize={'major_axis': 20}) self.assertRaises(ValueError, store.append, 's3', wp2) # test truncation of bigger strings store.append('s4', wp) self.assertRaises(ValueError, store.append, 's4', wp2) # avoid truncation on elements df = DataFrame([[123, 'asdqwerty'], [345, 'dggnhebbsdfbdfb']]) store.append('df_big', df) tm.assert_frame_equal(store.select('df_big'), df) check_col('df_big', 'values_block_1', 15) # appending smaller string ok df2 = DataFrame([[124, 'asdqy'], [346, 'dggnhefbdfb']]) store.append('df_big', df2) expected = concat([df, df2]) tm.assert_frame_equal(store.select('df_big'), expected) check_col('df_big', 'values_block_1', 15) # avoid truncation on elements df = DataFrame([[123, 'asdqwerty'], [345, 'dggnhebbsdfbdfb']]) store.append('df_big2', df, min_itemsize={'values': 50}) tm.assert_frame_equal(store.select('df_big2'), df) check_col('df_big2', 'values_block_1', 50) # bigger string on next append store.append('df_new', df) df_new = DataFrame( [[124, 'abcdefqhij'], [346, 'abcdefghijklmnopqrtsuvwxyz']]) self.assertRaises(ValueError, store.append, 'df_new', df_new) # with nans _maybe_remove(store, 'df') df = tm.makeTimeDataFrame() df['string'] = 'foo' df.ix[1:4, 'string'] = np.nan df['string2'] = 'bar' df.ix[4:8, 'string2'] = np.nan df['string3'] = 'bah' df.ix[1:, 'string3'] = np.nan store.append('df', df) result = store.select('df') tm.assert_frame_equal(result, df) with ensure_clean_store(self.path) as store: def check_col(key,name,size): self.assertEqual(getattr(store.get_storer(key).table.description,name).itemsize, size) df = DataFrame(dict(A = 'foo', B = 'bar'),index=range(10)) # a min_itemsize that creates a data_column _maybe_remove(store, 'df') store.append('df', df, min_itemsize={'A' : 200 }) check_col('df', 'A', 200) self.assertEqual(store.get_storer('df').data_columns, ['A']) # a min_itemsize that creates a data_column2 _maybe_remove(store, 'df') store.append('df', df, data_columns = ['B'], min_itemsize={'A' : 200 }) check_col('df', 'A', 200) self.assertEqual(store.get_storer('df').data_columns, ['B','A']) # a min_itemsize that creates a data_column2 _maybe_remove(store, 'df') store.append('df', df, data_columns = ['B'], min_itemsize={'values' : 200 }) check_col('df', 'B', 200) check_col('df', 'values_block_0', 200) self.assertEqual(store.get_storer('df').data_columns, ['B']) # infer the .typ on subsequent appends _maybe_remove(store, 'df') store.append('df', df[:5], min_itemsize=200) store.append('df', df[5:], min_itemsize=200) tm.assert_frame_equal(store['df'], df) # invalid min_itemsize keys df = DataFrame(['foo','foo','foo','barh','barh','barh'],columns=['A']) _maybe_remove(store, 'df') self.assertRaises(ValueError, store.append, 'df', df, min_itemsize={'foo' : 20, 'foobar' : 20}) def test_append_with_data_columns(self): with ensure_clean_store(self.path) as store: df = tm.makeTimeDataFrame() df.loc[:,'B'].iloc[0] = 1. _maybe_remove(store, 'df') store.append('df', df[:2], data_columns=['B']) store.append('df', df[2:]) tm.assert_frame_equal(store['df'], df) # check that we have indicies created assert(store._handle.root.df.table.cols.index.is_indexed is True) assert(store._handle.root.df.table.cols.B.is_indexed is True) # data column searching result = store.select('df', [Term('B>0')]) expected = df[df.B > 0] tm.assert_frame_equal(result, expected) # data column searching (with an indexable and a data_columns) result = store.select( 'df', [Term('B>0'), Term('index>df.index[3]')]) df_new = df.reindex(index=df.index[4:]) expected = df_new[df_new.B > 0] tm.assert_frame_equal(result, expected) # data column selection with a string data_column df_new = df.copy() df_new['string'] = 'foo' df_new.loc[1:4,'string'] = np.nan df_new.loc[5:6,'string'] = 'bar' _maybe_remove(store, 'df') store.append('df', df_new, data_columns=['string']) result = store.select('df', [Term('string=foo')]) expected = df_new[df_new.string == 'foo'] tm.assert_frame_equal(result, expected) # using min_itemsize and a data column def check_col(key,name,size): self.assertEqual(getattr(store.get_storer(key).table.description,name).itemsize, size) with ensure_clean_store(self.path) as store: _maybe_remove(store, 'df') store.append('df', df_new, data_columns=['string'], min_itemsize={'string': 30}) check_col('df', 'string', 30) _maybe_remove(store, 'df') store.append( 'df', df_new, data_columns=['string'], min_itemsize=30) check_col('df', 'string', 30) _maybe_remove(store, 'df') store.append('df', df_new, data_columns=['string'], min_itemsize={'values': 30}) check_col('df', 'string', 30) with ensure_clean_store(self.path) as store: df_new['string2'] = 'foobarbah' df_new['string_block1'] = 'foobarbah1' df_new['string_block2'] = 'foobarbah2' _maybe_remove(store, 'df') store.append('df', df_new, data_columns=['string', 'string2'], min_itemsize={'string': 30, 'string2': 40, 'values': 50}) check_col('df', 'string', 30) check_col('df', 'string2', 40) check_col('df', 'values_block_1', 50) with ensure_clean_store(self.path) as store: # multiple data columns df_new = df.copy() df_new.ix[0,'A'] = 1. df_new.ix[0,'B'] = -1. df_new['string'] = 'foo' df_new.loc[1:4,'string'] = np.nan df_new.loc[5:6,'string'] = 'bar' df_new['string2'] = 'foo' df_new.loc[2:5,'string2'] = np.nan df_new.loc[7:8,'string2'] = 'bar' _maybe_remove(store, 'df') store.append( 'df', df_new, data_columns=['A', 'B', 'string', 'string2']) result = store.select('df', [Term('string=foo'), Term( 'string2=foo'), Term('A>0'), Term('B<0')]) expected = df_new[(df_new.string == 'foo') & ( df_new.string2 == 'foo') & (df_new.A > 0) & (df_new.B < 0)] tm.assert_frame_equal(result, expected, check_index_type=False) # yield an empty frame result = store.select('df', [Term('string=foo'), Term( 'string2=cool')]) expected = df_new[(df_new.string == 'foo') & ( df_new.string2 == 'cool')] tm.assert_frame_equal(result, expected, check_index_type=False) with ensure_clean_store(self.path) as store: # doc example df_dc = df.copy() df_dc['string'] = 'foo' df_dc.ix[4:6, 'string'] = np.nan df_dc.ix[7:9, 'string'] = 'bar' df_dc['string2'] = 'cool' df_dc['datetime'] = Timestamp('20010102') df_dc = df_dc.convert_objects() df_dc.ix[3:5, ['A', 'B', 'datetime']] = np.nan _maybe_remove(store, 'df_dc') store.append('df_dc', df_dc, data_columns=['B', 'C', 'string', 'string2', 'datetime']) result = store.select('df_dc', [Term('B>0')]) expected = df_dc[df_dc.B > 0] tm.assert_frame_equal(result, expected, check_index_type=False) result = store.select( 'df_dc', ['B > 0', 'C > 0', 'string == foo']) expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & ( df_dc.string == 'foo')] tm.assert_frame_equal(result, expected, check_index_type=False) with ensure_clean_store(self.path) as store: # doc example part 2 np.random.seed(1234) index = date_range('1/1/2000', periods=8) df_dc = DataFrame(np.random.randn(8, 3), index=index, columns=['A', 'B', 'C']) df_dc['string'] = 'foo' df_dc.ix[4:6,'string'] = np.nan df_dc.ix[7:9,'string'] = 'bar' df_dc.ix[:,['B','C']] = df_dc.ix[:,['B','C']].abs() df_dc['string2'] = 'cool' # on-disk operations store.append('df_dc', df_dc, data_columns = ['B', 'C', 'string', 'string2']) result = store.select('df_dc', [ Term('B>0') ]) expected = df_dc[df_dc.B>0] tm.assert_frame_equal(result,expected) result = store.select('df_dc', ['B > 0', 'C > 0', 'string == "foo"']) expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == 'foo')] tm.assert_frame_equal(result,expected) with ensure_clean_store(self.path) as store: # panel # GH5717 not handling data_columns np.random.seed(1234) p = tm.makePanel() store.append('p1',p) tm.assert_panel_equal(store.select('p1'),p) store.append('p2',p,data_columns=True) tm.assert_panel_equal(store.select('p2'),p) result = store.select('p2',where='ItemA>0') expected = p.to_frame() expected = expected[expected['ItemA']>0] tm.assert_frame_equal(result.to_frame(),expected) result = store.select('p2',where='ItemA>0 & minor_axis=["A","B"]') expected = p.to_frame() expected = expected[expected['ItemA']>0] expected = expected[expected.reset_index(level=['major']).index.isin(['A','B'])] tm.assert_frame_equal(result.to_frame(),expected) def test_create_table_index(self): with ensure_clean_store(self.path) as store: def col(t,column): return getattr(store.get_storer(t).table.cols,column) # index=False wp = tm.makePanel() store.append('p5', wp, index=False) store.create_table_index('p5', columns=['major_axis']) assert(col('p5', 'major_axis').is_indexed is True) assert(col('p5', 'minor_axis').is_indexed is False) # index=True store.append('p5i', wp, index=True) assert(col('p5i', 'major_axis').is_indexed is True) assert(col('p5i', 'minor_axis').is_indexed is True) # default optlevels store.get_storer('p5').create_index() assert(col('p5', 'major_axis').index.optlevel == 6) assert(col('p5', 'minor_axis').index.kind == 'medium') # let's change the indexing scheme store.create_table_index('p5') assert(col('p5', 'major_axis').index.optlevel == 6) assert(col('p5', 'minor_axis').index.kind == 'medium') store.create_table_index('p5', optlevel=9) assert(col('p5', 'major_axis').index.optlevel == 9) assert(col('p5', 'minor_axis').index.kind == 'medium') store.create_table_index('p5', kind='full') assert(col('p5', 'major_axis').index.optlevel == 9) assert(col('p5', 'minor_axis').index.kind == 'full') store.create_table_index('p5', optlevel=1, kind='light') assert(col('p5', 'major_axis').index.optlevel == 1) assert(col('p5', 'minor_axis').index.kind == 'light') # data columns df = tm.makeTimeDataFrame() df['string'] = 'foo' df['string2'] = 'bar' store.append('f', df, data_columns=['string', 'string2']) assert(col('f', 'index').is_indexed is True) assert(col('f', 'string').is_indexed is True) assert(col('f', 'string2').is_indexed is True) # specify index=columns store.append( 'f2', df, index=['string'], data_columns=['string', 'string2']) assert(col('f2', 'index').is_indexed is False) assert(col('f2', 'string').is_indexed is True) assert(col('f2', 'string2').is_indexed is False) # try to index a non-table _maybe_remove(store, 'f2') store.put('f2', df) self.assertRaises(TypeError, store.create_table_index, 'f2') def test_append_diff_item_order(self): wp = tm.makePanel() wp1 = wp.ix[:, :10, :] wp2 = wp.ix[['ItemC', 'ItemB', 'ItemA'], 10:, :] with ensure_clean_store(self.path) as store: store.put('panel', wp1, format='table') self.assertRaises(ValueError, store.put, 'panel', wp2, append=True) def test_append_hierarchical(self): index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two', 'three']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['foo', 'bar']) df = DataFrame(np.random.randn(10, 3), index=index, columns=['A', 'B', 'C']) with ensure_clean_store(self.path) as store: store.append('mi', df) result = store.select('mi') tm.assert_frame_equal(result, df) # GH 3748 result = store.select('mi',columns=['A','B']) expected = df.reindex(columns=['A','B']) tm.assert_frame_equal(result,expected) with ensure_clean_path('test.hdf') as path: df.to_hdf(path,'df',format='table') result = read_hdf(path,'df',columns=['A','B']) expected = df.reindex(columns=['A','B']) tm.assert_frame_equal(result,expected) def test_column_multiindex(self): # GH 4710 # recreate multi-indexes properly index = MultiIndex.from_tuples([('A','a'), ('A','b'), ('B','a'), ('B','b')], names=['first','second']) df = DataFrame(np.arange(12).reshape(3,4), columns=index) with ensure_clean_store(self.path) as store: store.put('df',df) tm.assert_frame_equal(store['df'],df,check_index_type=True,check_column_type=True) store.put('df1',df,format='table') tm.assert_frame_equal(store['df1'],df,check_index_type=True,check_column_type=True) self.assertRaises(ValueError, store.put, 'df2',df,format='table',data_columns=['A']) self.assertRaises(ValueError, store.put, 'df3',df,format='table',data_columns=True) # appending multi-column on existing table (see GH 6167) with ensure_clean_store(self.path) as store: store.append('df2', df) store.append('df2', df) tm.assert_frame_equal(store['df2'], concat((df,df))) # non_index_axes name df = DataFrame(np.arange(12).reshape(3,4), columns=Index(list('ABCD'),name='foo')) with ensure_clean_store(self.path) as store: store.put('df1',df,format='table') tm.assert_frame_equal(store['df1'],df,check_index_type=True,check_column_type=True) def test_store_multiindex(self): # validate multi-index names # GH 5527 with ensure_clean_store(self.path) as store: def make_index(names=None): return MultiIndex.from_tuples([( datetime.datetime(2013,12,d), s, t) for d in range(1,3) for s in range(2) for t in range(3)], names=names) # no names _maybe_remove(store, 'df') df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index()) store.append('df',df) tm.assert_frame_equal(store.select('df'),df) # partial names _maybe_remove(store, 'df') df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index(['date',None,None])) store.append('df',df) tm.assert_frame_equal(store.select('df'),df) # series _maybe_remove(store, 's') s = Series(np.zeros(12), index=make_index(['date',None,None])) store.append('s',s) tm.assert_series_equal(store.select('s'),s) # dup with column _maybe_remove(store, 'df') df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index(['date','a','t'])) self.assertRaises(ValueError, store.append, 'df',df) # dup within level _maybe_remove(store, 'df') df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index(['date','date','date'])) self.assertRaises(ValueError, store.append, 'df',df) # fully names _maybe_remove(store, 'df') df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index(['date','s','t'])) store.append('df',df) tm.assert_frame_equal(store.select('df'),df) def test_select_columns_in_where(self): # GH 6169 # recreate multi-indexes when columns is passed # in the `where` argument index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two', 'three']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['foo_name', 'bar_name']) # With a DataFrame df = DataFrame(np.random.randn(10, 3), index=index, columns=['A', 'B', 'C']) with ensure_clean_store(self.path) as store: store.put('df', df, format='table') expected = df[['A']] tm.assert_frame_equal(store.select('df', columns=['A']), expected) tm.assert_frame_equal(store.select('df', where="columns=['A']"), expected) # With a Series s = Series(np.random.randn(10), index=index, name='A') with ensure_clean_store(self.path) as store: store.put('s', s, format='table') tm.assert_series_equal(store.select('s', where="columns=['A']"),s) def test_pass_spec_to_storer(self): df = tm.makeDataFrame() with ensure_clean_store(self.path) as store: store.put('df',df) self.assertRaises(TypeError, store.select, 'df', columns=['A']) self.assertRaises(TypeError, store.select, 'df',where=[('columns=A')]) def test_append_misc(self): with ensure_clean_store(self.path) as store: # unsuported data types for non-tables p4d = tm.makePanel4D() self.assertRaises(TypeError, store.put,'p4d',p4d) # unsuported data types self.assertRaises(TypeError, store.put,'abc',None) self.assertRaises(TypeError, store.put,'abc','123') self.assertRaises(TypeError, store.put,'abc',123) self.assertRaises(TypeError, store.put,'abc',np.arange(5)) df = tm.makeDataFrame() store.append('df', df, chunksize=1) result = store.select('df') tm.assert_frame_equal(result, df) store.append('df1', df, expectedrows=10) result = store.select('df1') tm.assert_frame_equal(result, df) # more chunksize in append tests def check(obj, comparator): for c in [10, 200, 1000]: with ensure_clean_store(self.path,mode='w') as store: store.append('obj', obj, chunksize=c) result = store.select('obj') comparator(result,obj) df = tm.makeDataFrame() df['string'] = 'foo' df['float322'] = 1. df['float322'] = df['float322'].astype('float32') df['bool'] = df['float322'] > 0 df['time1'] = Timestamp('20130101') df['time2'] = Timestamp('20130102') check(df, tm.assert_frame_equal) p = tm.makePanel() check(p, assert_panel_equal) p4d = tm.makePanel4D() check(p4d, assert_panel4d_equal) # empty frame, GH4273 with ensure_clean_store(self.path) as store: # 0 len df_empty = DataFrame(columns=list('ABC')) store.append('df',df_empty) self.assertRaises(KeyError,store.select, 'df') # repeated append of 0/non-zero frames df = DataFrame(np.random.rand(10,3),columns=list('ABC')) store.append('df',df) assert_frame_equal(store.select('df'),df) store.append('df',df_empty) assert_frame_equal(store.select('df'),df) # store df = DataFrame(columns=list('ABC')) store.put('df2',df) assert_frame_equal(store.select('df2'),df) # 0 len p_empty = Panel(items=list('ABC')) store.append('p',p_empty) self.assertRaises(KeyError,store.select, 'p') # repeated append of 0/non-zero frames p = Panel(np.random.randn(3,4,5),items=list('ABC')) store.append('p',p) assert_panel_equal(store.select('p'),p) store.append('p',p_empty) assert_panel_equal(store.select('p'),p) # store store.put('p2',p_empty) assert_panel_equal(store.select('p2'),p_empty) def test_append_raise(self): with ensure_clean_store(self.path) as store: # test append with invalid input to get good error messages # list in column df = tm.makeDataFrame() df['invalid'] = [['a']] * len(df) self.assertEqual(df.dtypes['invalid'], np.object_) self.assertRaises(TypeError, store.append,'df',df) # multiple invalid columns df['invalid2'] = [['a']] * len(df) df['invalid3'] = [['a']] * len(df) self.assertRaises(TypeError, store.append,'df',df) # datetime with embedded nans as object df = tm.makeDataFrame() s = Series(datetime.datetime(2001,1,2),index=df.index) s = s.astype(object) s[0:5] = np.nan df['invalid'] = s self.assertEqual(df.dtypes['invalid'], np.object_) self.assertRaises(TypeError, store.append,'df', df) # directy ndarray self.assertRaises(TypeError, store.append,'df',np.arange(10)) # series directly self.assertRaises(TypeError, store.append,'df',Series(np.arange(10))) # appending an incompatbile table df = tm.makeDataFrame() store.append('df',df) df['foo'] = 'foo' self.assertRaises(ValueError, store.append,'df',df) def test_table_index_incompatible_dtypes(self): df1 = DataFrame({'a': [1, 2, 3]}) df2 = DataFrame({'a': [4, 5, 6]}, index=date_range('1/1/2000', periods=3)) with ensure_clean_store(self.path) as store: store.put('frame', df1, format='table') self.assertRaises(TypeError, store.put, 'frame', df2, format='table', append=True) def test_table_values_dtypes_roundtrip(self): with ensure_clean_store(self.path) as store: df1 = DataFrame({'a': [1, 2, 3]}, dtype='f8') store.append('df_f8', df1) assert_series_equal(df1.dtypes,store['df_f8'].dtypes) df2 = DataFrame({'a': [1, 2, 3]}, dtype='i8') store.append('df_i8', df2) assert_series_equal(df2.dtypes,store['df_i8'].dtypes) # incompatible dtype self.assertRaises(ValueError, store.append, 'df_i8', df1) # check creation/storage/retrieval of float32 (a bit hacky to actually create them thought) df1 = DataFrame(np.array([[1],[2],[3]],dtype='f4'),columns = ['A']) store.append('df_f4', df1) assert_series_equal(df1.dtypes,store['df_f4'].dtypes) assert df1.dtypes[0] == 'float32' # check with mixed dtypes df1 = DataFrame(dict([ (c,Series(np.random.randn(5),dtype=c)) for c in ['float32','float64','int32','int64','int16','int8'] ])) df1['string'] = 'foo' df1['float322'] = 1. df1['float322'] = df1['float322'].astype('float32') df1['bool'] = df1['float32'] > 0 df1['time1'] = Timestamp('20130101') df1['time2'] = Timestamp('20130102') store.append('df_mixed_dtypes1', df1) result = store.select('df_mixed_dtypes1').get_dtype_counts() expected = Series({ 'float32' : 2, 'float64' : 1,'int32' : 1, 'bool' : 1, 'int16' : 1, 'int8' : 1, 'int64' : 1, 'object' : 1, 'datetime64[ns]' : 2}) result.sort() expected.sort() tm.assert_series_equal(result,expected) def test_table_mixed_dtypes(self): # frame df = tm.makeDataFrame() df['obj1'] = 'foo' df['obj2'] = 'bar' df['bool1'] = df['A'] > 0 df['bool2'] = df['B'] > 0 df['bool3'] = True df['int1'] = 1 df['int2'] = 2 df['timestamp1'] = Timestamp('20010102') df['timestamp2'] = Timestamp('20010103') df['datetime1'] = datetime.datetime(2001, 1, 2, 0, 0) df['datetime2'] = datetime.datetime(2001, 1, 3, 0, 0) df.ix[3:6, ['obj1']] = np.nan df = df.consolidate().convert_objects() with ensure_clean_store(self.path) as store: store.append('df1_mixed', df) tm.assert_frame_equal(store.select('df1_mixed'), df) # panel wp = tm.makePanel() wp['obj1'] = 'foo' wp['obj2'] = 'bar' wp['bool1'] = wp['ItemA'] > 0 wp['bool2'] = wp['ItemB'] > 0 wp['int1'] = 1 wp['int2'] = 2 wp = wp.consolidate() with ensure_clean_store(self.path) as store: store.append('p1_mixed', wp) assert_panel_equal(store.select('p1_mixed'), wp) # ndim wp = tm.makePanel4D() wp['obj1'] = 'foo' wp['obj2'] = 'bar' wp['bool1'] = wp['l1'] > 0 wp['bool2'] = wp['l2'] > 0 wp['int1'] = 1 wp['int2'] = 2 wp = wp.consolidate() with ensure_clean_store(self.path) as store: store.append('p4d_mixed', wp) assert_panel4d_equal(store.select('p4d_mixed'), wp) def test_unimplemented_dtypes_table_columns(self): with ensure_clean_store(self.path) as store: l = [('date', datetime.date(2001, 1, 2))] # py3 ok for unicode if not compat.PY3: l.append(('unicode', u('\\u03c3'))) ### currently not supported dtypes #### for n, f in l: df = tm.makeDataFrame() df[n] = f self.assertRaises( TypeError, store.append, 'df1_%s' % n, df) # frame df = tm.makeDataFrame() df['obj1'] = 'foo' df['obj2'] = 'bar' df['datetime1'] = datetime.date(2001, 1, 2) df = df.consolidate().convert_objects() with ensure_clean_store(self.path) as store: # this fails because we have a date in the object block...... self.assertRaises(TypeError, store.append, 'df_unimplemented', df) def test_append_with_timezones_pytz(self): from datetime import timedelta def compare(a,b): tm.assert_frame_equal(a,b) # compare the zones on each element for c in a.columns: for i in a.index: a_e = a[c][i] b_e = b[c][i] if not (a_e == b_e and a_e.tz == b_e.tz): raise AssertionError("invalid tz comparsion [%s] [%s]" % (a_e,b_e)) # as columns with ensure_clean_store(self.path) as store: _maybe_remove(store, 'df_tz') df = DataFrame(dict(A = [ Timestamp('20130102 2:00:00',tz='US/Eastern') + timedelta(hours=1)*i for i in range(5) ])) store.append('df_tz',df,data_columns=['A']) result = store['df_tz'] compare(result,df) assert_frame_equal(result,df) # select with tz aware compare(store.select('df_tz',where=Term('A>=df.A[3]')),df[df.A>=df.A[3]]) _maybe_remove(store, 'df_tz') # ensure we include dates in DST and STD time here. df = DataFrame(dict(A = Timestamp('20130102',tz='US/Eastern'), B = Timestamp('20130603',tz='US/Eastern')),index=range(5)) store.append('df_tz',df) result = store['df_tz'] compare(result,df) assert_frame_equal(result,df) _maybe_remove(store, 'df_tz') df = DataFrame(dict(A = Timestamp('20130102',tz='US/Eastern'), B = Timestamp('20130102',tz='EET')),index=range(5)) self.assertRaises(TypeError, store.append, 'df_tz', df) # this is ok _maybe_remove(store, 'df_tz') store.append('df_tz',df,data_columns=['A','B']) result = store['df_tz'] compare(result,df) assert_frame_equal(result,df) # can't append with diff timezone df = DataFrame(dict(A = Timestamp('20130102',tz='US/Eastern'), B = Timestamp('20130102',tz='CET')),index=range(5)) self.assertRaises(ValueError, store.append, 'df_tz', df) # as index with ensure_clean_store(self.path) as store: # GH 4098 example df = DataFrame(dict(A = Series(lrange(3), index=date_range('2000-1-1',periods=3,freq='H', tz='US/Eastern')))) _maybe_remove(store, 'df') store.put('df',df) result = store.select('df') assert_frame_equal(result,df) _maybe_remove(store, 'df') store.append('df',df) result = store.select('df') assert_frame_equal(result,df) def test_calendar_roundtrip_issue(self): # 8591 # doc example from tseries holiday section weekmask_egypt = 'Sun Mon Tue Wed Thu' holidays = ['2012-05-01', datetime.datetime(2013, 5, 1), np.datetime64('2014-05-01')] bday_egypt = pandas.offsets.CustomBusinessDay(holidays=holidays, weekmask=weekmask_egypt) dt = datetime.datetime(2013, 4, 30) dts = date_range(dt, periods=5, freq=bday_egypt) s = (Series(dts.weekday, dts).map(Series('Mon Tue Wed Thu Fri Sat Sun'.split()))) with ensure_clean_store(self.path) as store: store.put('fixed',s) result = store.select('fixed') assert_series_equal(result, s) store.append('table',s) result = store.select('table') assert_series_equal(result, s) def test_append_with_timezones_dateutil(self): from datetime import timedelta tm._skip_if_no_dateutil() # use maybe_get_tz instead of dateutil.tz.gettz to handle the windows filename issues. from pandas.tslib import maybe_get_tz gettz = lambda x: maybe_get_tz('dateutil/' + x) def compare(a, b): tm.assert_frame_equal(a, b) # compare the zones on each element for c in a.columns: for i in a.index: a_e = a[c][i] b_e = b[c][i] if not (a_e == b_e and a_e.tz == b_e.tz): raise AssertionError("invalid tz comparsion [%s] [%s]" % (a_e, b_e)) # as columns with ensure_clean_store(self.path) as store: _maybe_remove(store, 'df_tz') df = DataFrame(dict(A=[ Timestamp('20130102 2:00:00', tz=gettz('US/Eastern')) + timedelta(hours=1) * i for i in range(5) ])) store.append('df_tz', df, data_columns=['A']) result = store['df_tz'] compare(result, df) assert_frame_equal(result, df) # select with tz aware compare(store.select('df_tz', where=Term('A>=df.A[3]')), df[df.A >= df.A[3]]) _maybe_remove(store, 'df_tz') # ensure we include dates in DST and STD time here. df = DataFrame(dict(A=Timestamp('20130102', tz=gettz('US/Eastern')), B=Timestamp('20130603', tz=gettz('US/Eastern'))), index=range(5)) store.append('df_tz', df) result = store['df_tz'] compare(result, df) assert_frame_equal(result, df) _maybe_remove(store, 'df_tz') df = DataFrame(dict(A=Timestamp('20130102', tz=gettz('US/Eastern')), B=Timestamp('20130102', tz=gettz('EET'))), index=range(5)) self.assertRaises(TypeError, store.append, 'df_tz', df) # this is ok _maybe_remove(store, 'df_tz') store.append('df_tz', df, data_columns=['A', 'B']) result = store['df_tz'] compare(result, df) assert_frame_equal(result, df) # can't append with diff timezone df = DataFrame(dict(A=Timestamp('20130102', tz=gettz('US/Eastern')), B=Timestamp('20130102', tz=gettz('CET'))), index=range(5)) self.assertRaises(ValueError, store.append, 'df_tz', df) # as index with ensure_clean_store(self.path) as store: # GH 4098 example df = DataFrame(dict(A=Series(lrange(3), index=date_range('2000-1-1', periods=3, freq='H', tz=gettz('US/Eastern'))))) _maybe_remove(store, 'df') store.put('df', df) result = store.select('df') assert_frame_equal(result, df) _maybe_remove(store, 'df') store.append('df', df) result = store.select('df') assert_frame_equal(result, df) def test_store_timezone(self): # GH2852 # issue storing datetime.date with a timezone as it resets when read back in a new timezone import platform if platform.system() == "Windows": raise nose.SkipTest("timezone setting not supported on windows") import datetime import time import os # original method with ensure_clean_store(self.path) as store: today = datetime.date(2013,9,10) df = DataFrame([1,2,3], index = [today, today, today]) store['obj1'] = df result = store['obj1'] assert_frame_equal(result, df) # with tz setting orig_tz = os.environ.get('TZ') def setTZ(tz): if tz is None: try: del os.environ['TZ'] except: pass else: os.environ['TZ']=tz time.tzset() try: with ensure_clean_store(self.path) as store: setTZ('EST5EDT') today = datetime.date(2013,9,10) df = DataFrame([1,2,3], index = [today, today, today]) store['obj1'] = df setTZ('CST6CDT') result = store['obj1'] assert_frame_equal(result, df) finally: setTZ(orig_tz) def test_append_with_timedelta(self): # GH 3577 # append timedelta from datetime import timedelta df = DataFrame(dict(A = Timestamp('20130101'), B = [ Timestamp('20130101') + timedelta(days=i,seconds=10) for i in range(10) ])) df['C'] = df['A']-df['B'] df.ix[3:5,'C'] = np.nan with ensure_clean_store(self.path) as store: # table _maybe_remove(store, 'df') store.append('df',df,data_columns=True) result = store.select('df') assert_frame_equal(result,df) result = store.select('df',Term("C<100000")) assert_frame_equal(result,df) result = store.select('df',Term("C","<",-3*86400)) assert_frame_equal(result,df.iloc[3:]) result = store.select('df',"C<'-3D'") assert_frame_equal(result,df.iloc[3:]) # a bit hacky here as we don't really deal with the NaT properly result = store.select('df',"C<'-500000s'") result = result.dropna(subset=['C']) assert_frame_equal(result,df.iloc[6:]) result = store.select('df',"C<'-3.5D'") result = result.iloc[1:] assert_frame_equal(result,df.iloc[4:]) # fixed _maybe_remove(store, 'df2') store.put('df2',df) result = store.select('df2') assert_frame_equal(result,df) def test_remove(self): with ensure_clean_store(self.path) as store: ts = tm.makeTimeSeries() df = tm.makeDataFrame() store['a'] = ts store['b'] = df _maybe_remove(store, 'a') self.assertEqual(len(store), 1) tm.assert_frame_equal(df, store['b']) _maybe_remove(store, 'b') self.assertEqual(len(store), 0) # nonexistence self.assertRaises(KeyError, store.remove, 'a_nonexistent_store') # pathing store['a'] = ts store['b/foo'] = df _maybe_remove(store, 'foo') _maybe_remove(store, 'b/foo') self.assertEqual(len(store), 1) store['a'] = ts store['b/foo'] = df _maybe_remove(store, 'b') self.assertEqual(len(store), 1) # __delitem__ store['a'] = ts store['b'] = df del store['a'] del store['b'] self.assertEqual(len(store), 0) def test_remove_where(self): with ensure_clean_store(self.path) as store: # non-existance crit1 = Term('index>foo') self.assertRaises(KeyError, store.remove, 'a', [crit1]) # try to remove non-table (with crit) # non-table ok (where = None) wp = tm.makePanel(30) store.put('wp', wp, format='table') store.remove('wp', ["minor_axis=['A', 'D']"]) rs = store.select('wp') expected = wp.reindex(minor_axis=['B', 'C']) assert_panel_equal(rs, expected) # empty where _maybe_remove(store, 'wp') store.put('wp', wp, format='table') # deleted number (entire table) n = store.remove('wp', []) self.assertTrue(n == 120) # non - empty where _maybe_remove(store, 'wp') store.put('wp', wp, format='table') self.assertRaises(ValueError, store.remove, 'wp', ['foo']) # selectin non-table with a where # store.put('wp2', wp, format='f') # self.assertRaises(ValueError, store.remove, # 'wp2', [('column', ['A', 'D'])]) def test_remove_startstop(self): # GH #4835 and #6177 with ensure_clean_store(self.path) as store: wp = tm.makePanel(30) # start _maybe_remove(store, 'wp1') store.put('wp1', wp, format='t') n = store.remove('wp1', start=32) self.assertTrue(n == 120-32) result = store.select('wp1') expected = wp.reindex(major_axis=wp.major_axis[:32//4]) assert_panel_equal(result, expected) _maybe_remove(store, 'wp2') store.put('wp2', wp, format='t') n = store.remove('wp2', start=-32) self.assertTrue(n == 32) result = store.select('wp2') expected = wp.reindex(major_axis=wp.major_axis[:-32//4]) assert_panel_equal(result, expected) # stop _maybe_remove(store, 'wp3') store.put('wp3', wp, format='t') n = store.remove('wp3', stop=32) self.assertTrue(n == 32) result = store.select('wp3') expected = wp.reindex(major_axis=wp.major_axis[32//4:]) assert_panel_equal(result, expected) _maybe_remove(store, 'wp4') store.put('wp4', wp, format='t') n = store.remove('wp4', stop=-32) self.assertTrue(n == 120-32) result = store.select('wp4') expected = wp.reindex(major_axis=wp.major_axis[-32//4:]) assert_panel_equal(result, expected) # start n stop _maybe_remove(store, 'wp5') store.put('wp5', wp, format='t') n = store.remove('wp5', start=16, stop=-16) self.assertTrue(n == 120-32) result = store.select('wp5') expected = wp.reindex(major_axis=wp.major_axis[:16//4].union(wp.major_axis[-16//4:])) assert_panel_equal(result, expected) _maybe_remove(store, 'wp6') store.put('wp6', wp, format='t') n = store.remove('wp6', start=16, stop=16) self.assertTrue(n == 0) result = store.select('wp6') expected = wp.reindex(major_axis=wp.major_axis) assert_panel_equal(result, expected) # with where _maybe_remove(store, 'wp7') date = wp.major_axis.take(np.arange(0,30,3)) crit = Term('major_axis=date') store.put('wp7', wp, format='t') n = store.remove('wp7', where=[crit], stop=80) self.assertTrue(n == 28) result = store.select('wp7') expected = wp.reindex(major_axis=wp.major_axis.difference(wp.major_axis[np.arange(0,20,3)])) assert_panel_equal(result, expected) def test_remove_crit(self): with ensure_clean_store(self.path) as store: wp = tm.makePanel(30) # group row removal _maybe_remove(store, 'wp3') date4 = wp.major_axis.take([0, 1, 2, 4, 5, 6, 8, 9, 10]) crit4 = Term('major_axis=date4') store.put('wp3', wp, format='t') n = store.remove('wp3', where=[crit4]) self.assertTrue(n == 36) result = store.select('wp3') expected = wp.reindex(major_axis=wp.major_axis.difference(date4)) assert_panel_equal(result, expected) # upper half _maybe_remove(store, 'wp') store.put('wp', wp, format='table') date = wp.major_axis[len(wp.major_axis) // 2] crit1 = Term('major_axis>date') crit2 = Term("minor_axis=['A', 'D']") n = store.remove('wp', where=[crit1]) self.assertTrue(n == 56) n = store.remove('wp', where=[crit2]) self.assertTrue(n == 32) result = store['wp'] expected = wp.truncate(after=date).reindex(minor=['B', 'C']) assert_panel_equal(result, expected) # individual row elements _maybe_remove(store, 'wp2') store.put('wp2', wp, format='table') date1 = wp.major_axis[1:3] crit1 = Term('major_axis=date1') store.remove('wp2', where=[crit1]) result = store.select('wp2') expected = wp.reindex(major_axis=wp.major_axis.difference(date1)) assert_panel_equal(result, expected) date2 = wp.major_axis[5] crit2 = Term('major_axis=date2') store.remove('wp2', where=[crit2]) result = store['wp2'] expected = wp.reindex( major_axis=wp.major_axis.difference(date1).difference(Index([date2]))) assert_panel_equal(result, expected) date3 = [wp.major_axis[7], wp.major_axis[9]] crit3 = Term('major_axis=date3') store.remove('wp2', where=[crit3]) result = store['wp2'] expected = wp.reindex( major_axis=wp.major_axis.difference(date1).difference(Index([date2])).difference(Index(date3))) assert_panel_equal(result, expected) # corners _maybe_remove(store, 'wp4') store.put('wp4', wp, format='table') n = store.remove( 'wp4', where=[Term('major_axis>wp.major_axis[-1]')]) result = store.select('wp4') assert_panel_equal(result, wp) def test_invalid_terms(self): with ensure_clean_store(self.path) as store: df = tm.makeTimeDataFrame() df['string'] = 'foo' df.ix[0:4,'string'] = 'bar' wp = tm.makePanel() p4d = tm.makePanel4D() store.put('df', df, format='table') store.put('wp', wp, format='table') store.put('p4d', p4d, format='table') # some invalid terms self.assertRaises(ValueError, store.select, 'wp', "minor=['A', 'B']") self.assertRaises(ValueError, store.select, 'wp', ["index=['20121114']"]) self.assertRaises(ValueError, store.select, 'wp', ["index=['20121114', '20121114']"]) self.assertRaises(TypeError, Term) # more invalid self.assertRaises(ValueError, store.select, 'df','df.index[3]') self.assertRaises(SyntaxError, store.select, 'df','index>') self.assertRaises(ValueError, store.select, 'wp', "major_axis<'20000108' & minor_axis['A', 'B']") # from the docs with ensure_clean_path(self.path) as path: dfq = DataFrame(np.random.randn(10,4),columns=list('ABCD'),index=date_range('20130101',periods=10)) dfq.to_hdf(path,'dfq',format='table',data_columns=True) # check ok read_hdf(path,'dfq',where="index>Timestamp('20130104') & columns=['A', 'B']") read_hdf(path,'dfq',where="A>0 or C>0") # catch the invalid reference with ensure_clean_path(self.path) as path: dfq = DataFrame(np.random.randn(10,4),columns=list('ABCD'),index=date_range('20130101',periods=10)) dfq.to_hdf(path,'dfq',format='table') self.assertRaises(ValueError, read_hdf, path,'dfq',where="A>0 or C>0") def test_terms(self): with ensure_clean_store(self.path) as store: wp = tm.makePanel() p4d = tm.makePanel4D() wpneg = Panel.fromDict({-1: tm.makeDataFrame(), 0: tm.makeDataFrame(), 1: tm.makeDataFrame()}) store.put('wp', wp, table=True) store.put('p4d', p4d, table=True) store.put('wpneg', wpneg, table=True) # panel result = store.select('wp', [Term( 'major_axis<"20000108"'), Term("minor_axis=['A', 'B']")]) expected = wp.truncate(after='20000108').reindex(minor=['A', 'B']) assert_panel_equal(result, expected) # with deprecation result = store.select('wp', [Term( 'major_axis','<',"20000108"), Term("minor_axis=['A', 'B']")]) expected = wp.truncate(after='20000108').reindex(minor=['A', 'B']) tm.assert_panel_equal(result, expected) # p4d result = store.select('p4d', [Term('major_axis<"20000108"'), Term("minor_axis=['A', 'B']"), Term("items=['ItemA', 'ItemB']")]) expected = p4d.truncate(after='20000108').reindex( minor=['A', 'B'], items=['ItemA', 'ItemB']) assert_panel4d_equal(result, expected) # back compat invalid terms terms = [ dict(field='major_axis', op='>', value='20121114'), [ dict(field='major_axis', op='>', value='20121114') ], [ "minor_axis=['A','B']", dict(field='major_axis', op='>', value='20121114') ] ] for t in terms: with tm.assert_produces_warning(expected_warning=DeprecationWarning): Term(t) # valid terms terms = [ ('major_axis=20121114'), ('major_axis>20121114'), (("major_axis=['20121114', '20121114']"),), ('major_axis=datetime.datetime(2012, 11, 14)'), 'major_axis> 20121114', 'major_axis >20121114', 'major_axis > 20121114', (("minor_axis=['A', 'B']"),), (("minor_axis=['A', 'B']"),), ((("minor_axis==['A', 'B']"),),), (("items=['ItemA', 'ItemB']"),), ('items=ItemA'), ] for t in terms: store.select('wp', t) store.select('p4d', t) # valid for p4d only terms = [ (("labels=['l1', 'l2']"),), Term("labels=['l1', 'l2']"), ] for t in terms: store.select('p4d', t) with tm.assertRaisesRegexp(TypeError, 'Only named functions are supported'): store.select('wp', Term('major_axis == (lambda x: x)("20130101")')) # check USub node parsing res = store.select('wpneg', Term('items == -1')) expected = Panel({-1: wpneg[-1]}) tm.assert_panel_equal(res, expected) with tm.assertRaisesRegexp(NotImplementedError, 'Unary addition not supported'): store.select('wpneg', Term('items == +1')) def test_term_compat(self): with ensure_clean_store(self.path) as store: wp = Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) store.append('wp',wp) result = store.select('wp', [Term('major_axis>20000102'), Term('minor_axis', '=', ['A','B']) ]) expected = wp.loc[:,wp.major_axis>Timestamp('20000102'),['A','B']] assert_panel_equal(result, expected) store.remove('wp', Term('major_axis>20000103')) result = store.select('wp') expected = wp.loc[:,wp.major_axis<=Timestamp('20000103'),:] assert_panel_equal(result, expected) with ensure_clean_store(self.path) as store: wp = Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) store.append('wp',wp) # stringified datetimes result = store.select('wp', [Term('major_axis','>',datetime.datetime(2000,1,2))]) expected = wp.loc[:,wp.major_axis>Timestamp('20000102')] assert_panel_equal(result, expected) result = store.select('wp', [Term('major_axis','>',datetime.datetime(2000,1,2,0,0))]) expected = wp.loc[:,wp.major_axis>Timestamp('20000102')] assert_panel_equal(result, expected) result = store.select('wp', [Term('major_axis','=',[datetime.datetime(2000,1,2,0,0),datetime.datetime(2000,1,3,0,0)])]) expected = wp.loc[:,[Timestamp('20000102'),Timestamp('20000103')]] assert_panel_equal(result, expected) result = store.select('wp', [Term('minor_axis','=',['A','B'])]) expected = wp.loc[:,:,['A','B']] assert_panel_equal(result, expected) def test_backwards_compat_without_term_object(self): with ensure_clean_store(self.path) as store: wp = Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) store.append('wp',wp) with tm.assert_produces_warning(expected_warning=DeprecationWarning): result = store.select('wp', [('major_axis>20000102'), ('minor_axis', '=', ['A','B']) ]) expected = wp.loc[:,wp.major_axis>Timestamp('20000102'),['A','B']] assert_panel_equal(result, expected) store.remove('wp', ('major_axis>20000103')) result = store.select('wp') expected = wp.loc[:,wp.major_axis<=Timestamp('20000103'),:] assert_panel_equal(result, expected) with ensure_clean_store(self.path) as store: wp = Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) store.append('wp',wp) # stringified datetimes with tm.assert_produces_warning(expected_warning=DeprecationWarning): result = store.select('wp', [('major_axis','>',datetime.datetime(2000,1,2))]) expected = wp.loc[:,wp.major_axis>Timestamp('20000102')] assert_panel_equal(result, expected) with tm.assert_produces_warning(expected_warning=DeprecationWarning): result = store.select('wp', [('major_axis','>',datetime.datetime(2000,1,2,0,0))]) expected = wp.loc[:,wp.major_axis>Timestamp('20000102')] assert_panel_equal(result, expected) with tm.assert_produces_warning(expected_warning=DeprecationWarning): result = store.select('wp', [('major_axis','=',[datetime.datetime(2000,1,2,0,0), datetime.datetime(2000,1,3,0,0)])]) expected = wp.loc[:,[Timestamp('20000102'),Timestamp('20000103')]] assert_panel_equal(result, expected) with tm.assert_produces_warning(expected_warning=DeprecationWarning): result = store.select('wp', [('minor_axis','=',['A','B'])]) expected = wp.loc[:,:,['A','B']] assert_panel_equal(result, expected) def test_same_name_scoping(self): with ensure_clean_store(self.path) as store: import pandas as pd df = DataFrame(np.random.randn(20, 2),index=pd.date_range('20130101',periods=20)) store.put('df', df, table=True) expected = df[df.index>pd.Timestamp('20130105')] import datetime result = store.select('df','index>datetime.datetime(2013,1,5)') assert_frame_equal(result,expected) from datetime import datetime # technically an error, but allow it result = store.select('df','index>datetime.datetime(2013,1,5)') assert_frame_equal(result,expected) result = store.select('df','index>datetime(2013,1,5)') assert_frame_equal(result,expected) def test_series(self): s = tm.makeStringSeries() self._check_roundtrip(s, tm.assert_series_equal) ts = tm.makeTimeSeries() self._check_roundtrip(ts, tm.assert_series_equal) ts2 = Series(ts.index, Index(ts.index, dtype=object)) self._check_roundtrip(ts2, tm.assert_series_equal) ts3 = Series(ts.values, Index(np.asarray(ts.index, dtype=object), dtype=object)) self._check_roundtrip(ts3, tm.assert_series_equal) def test_sparse_series(self): s = tm.makeStringSeries() s[3:5] = np.nan ss = s.to_sparse() self._check_roundtrip(ss, tm.assert_series_equal, check_series_type=True) ss2 = s.to_sparse(kind='integer') self._check_roundtrip(ss2, tm.assert_series_equal, check_series_type=True) ss3 = s.to_sparse(fill_value=0) self._check_roundtrip(ss3, tm.assert_series_equal, check_series_type=True) def test_sparse_frame(self): s = tm.makeDataFrame() s.ix[3:5, 1:3] = np.nan s.ix[8:10, -2] = np.nan ss = s.to_sparse() self._check_double_roundtrip(ss, tm.assert_frame_equal, check_frame_type=True) ss2 = s.to_sparse(kind='integer') self._check_double_roundtrip(ss2, tm.assert_frame_equal, check_frame_type=True) ss3 = s.to_sparse(fill_value=0) self._check_double_roundtrip(ss3, tm.assert_frame_equal, check_frame_type=True) def test_sparse_panel(self): items = ['x', 'y', 'z'] p = Panel(dict((i, tm.makeDataFrame().ix[:2, :2]) for i in items)) sp = p.to_sparse() self._check_double_roundtrip(sp, assert_panel_equal, check_panel_type=True) sp2 = p.to_sparse(kind='integer') self._check_double_roundtrip(sp2, assert_panel_equal, check_panel_type=True) sp3 = p.to_sparse(fill_value=0) self._check_double_roundtrip(sp3, assert_panel_equal, check_panel_type=True) def test_float_index(self): # GH #454 index = np.random.randn(10) s = Series(np.random.randn(10), index=index) self._check_roundtrip(s, tm.assert_series_equal) def test_tuple_index(self): # GH #492 col = np.arange(10) idx = [(0., 1.), (2., 3.), (4., 5.)] data = np.random.randn(30).reshape((3, 10)) DF = DataFrame(data, index=idx, columns=col) with tm.assert_produces_warning(expected_warning=PerformanceWarning): self._check_roundtrip(DF, tm.assert_frame_equal) def test_index_types(self): values = np.random.randn(2) func = lambda l, r: tm.assert_series_equal(l, r, check_dtype=True, check_index_type=True, check_series_type=True) with tm.assert_produces_warning(expected_warning=PerformanceWarning): ser = Series(values, [0, 'y']) self._check_roundtrip(ser, func) with tm.assert_produces_warning(expected_warning=PerformanceWarning): ser = Series(values, [datetime.datetime.today(), 0]) self._check_roundtrip(ser, func) with tm.assert_produces_warning(expected_warning=PerformanceWarning): ser = Series(values, ['y', 0]) self._check_roundtrip(ser, func) with tm.assert_produces_warning(expected_warning=PerformanceWarning): ser = Series(values, [datetime.date.today(), 'a']) self._check_roundtrip(ser, func) with tm.assert_produces_warning(expected_warning=PerformanceWarning): ser = Series(values, [1.23, 'b']) self._check_roundtrip(ser, func) ser = Series(values, [1, 1.53]) self._check_roundtrip(ser, func) ser = Series(values, [1, 5]) self._check_roundtrip(ser, func) ser = Series(values, [datetime.datetime( 2012, 1, 1), datetime.datetime(2012, 1, 2)]) self._check_roundtrip(ser, func) def test_timeseries_preepoch(self): if sys.version_info[0] == 2 and sys.version_info[1] < 7: raise nose.SkipTest("won't work on Python < 2.7") dr = bdate_range('1/1/1940', '1/1/1960') ts = Series(np.random.randn(len(dr)), index=dr) try: self._check_roundtrip(ts, tm.assert_series_equal) except OverflowError: raise nose.SkipTest('known failer on some windows platforms') def test_frame(self): df = tm.makeDataFrame() # put in some random NAs df.values[0, 0] = np.nan df.values[5, 3] = np.nan self._check_roundtrip_table(df, tm.assert_frame_equal) self._check_roundtrip(df, tm.assert_frame_equal) self._check_roundtrip_table(df, tm.assert_frame_equal, compression=True) self._check_roundtrip(df, tm.assert_frame_equal, compression=True) tdf = tm.makeTimeDataFrame() self._check_roundtrip(tdf, tm.assert_frame_equal) self._check_roundtrip(tdf, tm.assert_frame_equal, compression=True) with ensure_clean_store(self.path) as store: # not consolidated df['foo'] = np.random.randn(len(df)) store['df'] = df recons = store['df'] self.assertTrue(recons._data.is_consolidated()) # empty self._check_roundtrip(df[:0], tm.assert_frame_equal) def test_empty_series_frame(self): s0 = Series() s1 = Series(name='myseries') df0 = DataFrame() df1 = DataFrame(index=['a', 'b', 'c']) df2 = DataFrame(columns=['d', 'e', 'f']) self._check_roundtrip(s0, tm.assert_series_equal) self._check_roundtrip(s1, tm.assert_series_equal) self._check_roundtrip(df0, tm.assert_frame_equal) self._check_roundtrip(df1, tm.assert_frame_equal) self._check_roundtrip(df2, tm.assert_frame_equal) def test_empty_series(self): for dtype in [np.int64, np.float64, np.object, 'm8[ns]', 'M8[ns]']: s = Series(dtype=dtype) self._check_roundtrip(s, tm.assert_series_equal) def test_can_serialize_dates(self): rng = [x.date() for x in bdate_range('1/1/2000', '1/30/2000')] frame = DataFrame(np.random.randn(len(rng), 4), index=rng) self._check_roundtrip(frame, tm.assert_frame_equal) def test_timezones(self): rng = date_range('1/1/2000', '1/30/2000', tz='US/Eastern') frame = DataFrame(np.random.randn(len(rng), 4), index=rng) with ensure_clean_store(self.path) as store: store['frame'] = frame recons = store['frame'] self.assertTrue(recons.index.equals(rng)) self.assertEqual(rng.tz, recons.index.tz) def test_fixed_offset_tz(self): rng = date_range('1/1/2000 00:00:00-07:00', '1/30/2000 00:00:00-07:00') frame = DataFrame(np.random.randn(len(rng), 4), index=rng) with ensure_clean_store(self.path) as store: store['frame'] = frame recons = store['frame'] self.assertTrue(recons.index.equals(rng)) self.assertEqual(rng.tz, recons.index.tz) def test_store_hierarchical(self): index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two', 'three']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['foo', 'bar']) frame = DataFrame(np.random.randn(10, 3), index=index, columns=['A', 'B', 'C']) self._check_roundtrip(frame, tm.assert_frame_equal) self._check_roundtrip(frame.T, tm.assert_frame_equal) self._check_roundtrip(frame['A'], tm.assert_series_equal) # check that the names are stored with ensure_clean_store(self.path) as store: store['frame'] = frame recons = store['frame'] assert(recons.index.names == ('foo', 'bar')) def test_store_index_name(self): df = tm.makeDataFrame() df.index.name = 'foo' with ensure_clean_store(self.path) as store: store['frame'] = df recons = store['frame'] assert(recons.index.name == 'foo') def test_store_series_name(self): df = tm.makeDataFrame() series = df['A'] with ensure_clean_store(self.path) as store: store['series'] = series recons = store['series'] assert(recons.name == 'A') def test_store_mixed(self): def _make_one(): df = tm.makeDataFrame() df['obj1'] = 'foo' df['obj2'] = 'bar' df['bool1'] = df['A'] > 0 df['bool2'] = df['B'] > 0 df['int1'] = 1 df['int2'] = 2 return df.consolidate() df1 = _make_one() df2 = _make_one() self._check_roundtrip(df1, tm.assert_frame_equal) self._check_roundtrip(df2, tm.assert_frame_equal) with ensure_clean_store(self.path) as store: store['obj'] = df1 tm.assert_frame_equal(store['obj'], df1) store['obj'] = df2 tm.assert_frame_equal(store['obj'], df2) # check that can store Series of all of these types self._check_roundtrip(df1['obj1'], tm.assert_series_equal) self._check_roundtrip(df1['bool1'], tm.assert_series_equal) self._check_roundtrip(df1['int1'], tm.assert_series_equal) # try with compression self._check_roundtrip(df1['obj1'], tm.assert_series_equal, compression=True) self._check_roundtrip(df1['bool1'], tm.assert_series_equal, compression=True) self._check_roundtrip(df1['int1'], tm.assert_series_equal, compression=True) self._check_roundtrip(df1, tm.assert_frame_equal, compression=True) def test_wide(self): wp = tm.makePanel() self._check_roundtrip(wp, assert_panel_equal) def test_wide_table(self): wp = tm.makePanel() self._check_roundtrip_table(wp, assert_panel_equal) def test_select_with_dups(self): # single dtypes df = DataFrame(np.random.randn(10,4),columns=['A','A','B','B']) df.index = date_range('20130101 9:30',periods=10,freq='T') with ensure_clean_store(self.path) as store: store.append('df',df) result = store.select('df') expected = df assert_frame_equal(result,expected,by_blocks=True) result = store.select('df',columns=df.columns) expected = df assert_frame_equal(result,expected,by_blocks=True) result = store.select('df',columns=['A']) expected = df.loc[:,['A']] assert_frame_equal(result,expected) # dups accross dtypes df = concat([DataFrame(np.random.randn(10,4),columns=['A','A','B','B']), DataFrame(np.random.randint(0,10,size=20).reshape(10,2),columns=['A','C'])], axis=1) df.index = date_range('20130101 9:30',periods=10,freq='T') with ensure_clean_store(self.path) as store: store.append('df',df) result = store.select('df') expected = df assert_frame_equal(result,expected,by_blocks=True) result = store.select('df',columns=df.columns) expected = df assert_frame_equal(result,expected,by_blocks=True) expected = df.loc[:,['A']] result = store.select('df',columns=['A']) assert_frame_equal(result,expected,by_blocks=True) expected = df.loc[:,['B','A']] result = store.select('df',columns=['B','A']) assert_frame_equal(result,expected,by_blocks=True) # duplicates on both index and columns with ensure_clean_store(self.path) as store: store.append('df',df) store.append('df',df) expected = df.loc[:,['B','A']] expected = concat([expected, expected]) result = store.select('df',columns=['B','A']) assert_frame_equal(result,expected,by_blocks=True) def test_wide_table_dups(self): wp = tm.makePanel() with ensure_clean_store(self.path) as store: store.put('panel', wp, format='table') store.put('panel', wp, format='table', append=True) with tm.assert_produces_warning(expected_warning=DuplicateWarning): recons = store['panel'] assert_panel_equal(recons, wp) def test_long(self): def _check(left, right): assert_panel_equal(left.to_panel(), right.to_panel()) wp = tm.makePanel() self._check_roundtrip(wp.to_frame(), _check) # empty # self._check_roundtrip(wp.to_frame()[:0], _check) def test_longpanel(self): pass def test_overwrite_node(self): with ensure_clean_store(self.path) as store: store['a'] = tm.makeTimeDataFrame() ts = tm.makeTimeSeries() store['a'] = ts tm.assert_series_equal(store['a'], ts) def test_sparse_with_compression(self): # GH 2931 # make sparse dataframe df = DataFrame(np.random.binomial(n=1, p=.01, size=(1e3, 10))).to_sparse(fill_value=0) # case 1: store uncompressed self._check_double_roundtrip(df, tm.assert_frame_equal, compression = False, check_frame_type=True) # case 2: store compressed (works) self._check_double_roundtrip(df, tm.assert_frame_equal, compression = 'zlib', check_frame_type=True) # set one series to be completely sparse df[0] = np.zeros(1e3) # case 3: store df with completely sparse series uncompressed self._check_double_roundtrip(df, tm.assert_frame_equal, compression = False, check_frame_type=True) # case 4: try storing df with completely sparse series compressed (fails) self._check_double_roundtrip(df, tm.assert_frame_equal, compression = 'zlib', check_frame_type=True) def test_select(self): wp = tm.makePanel() with ensure_clean_store(self.path) as store: # put/select ok _maybe_remove(store, 'wp') store.put('wp', wp, format='table') store.select('wp') # non-table ok (where = None) _maybe_remove(store, 'wp') store.put('wp2', wp) store.select('wp2') # selection on the non-indexable with a large number of columns wp = Panel( np.random.randn(100, 100, 100), items=['Item%03d' % i for i in range(100)], major_axis=date_range('1/1/2000', periods=100), minor_axis=['E%03d' % i for i in range(100)]) _maybe_remove(store, 'wp') store.append('wp', wp) items = ['Item%03d' % i for i in range(80)] result = store.select('wp', Term('items=items')) expected = wp.reindex(items=items) assert_panel_equal(expected, result) # selectin non-table with a where # self.assertRaises(ValueError, store.select, # 'wp2', ('column', ['A', 'D'])) # select with columns= df = tm.makeTimeDataFrame() _maybe_remove(store, 'df') store.append('df', df) result = store.select('df', columns=['A', 'B']) expected = df.reindex(columns=['A', 'B']) tm.assert_frame_equal(expected, result) # equivalentsly result = store.select('df', [("columns=['A', 'B']")]) expected = df.reindex(columns=['A', 'B']) tm.assert_frame_equal(expected, result) # with a data column _maybe_remove(store, 'df') store.append('df', df, data_columns=['A']) result = store.select('df', ['A > 0'], columns=['A', 'B']) expected = df[df.A > 0].reindex(columns=['A', 'B']) tm.assert_frame_equal(expected, result) # all a data columns _maybe_remove(store, 'df') store.append('df', df, data_columns=True) result = store.select('df', ['A > 0'], columns=['A', 'B']) expected = df[df.A > 0].reindex(columns=['A', 'B']) tm.assert_frame_equal(expected, result) # with a data column, but different columns _maybe_remove(store, 'df') store.append('df', df, data_columns=['A']) result = store.select('df', ['A > 0'], columns=['C', 'D']) expected = df[df.A > 0].reindex(columns=['C', 'D']) tm.assert_frame_equal(expected, result) def test_select_dtypes(self): with ensure_clean_store(self.path) as store: # with a Timestamp data column (GH #2637) df = DataFrame(dict(ts=bdate_range('2012-01-01', periods=300), A=np.random.randn(300))) _maybe_remove(store, 'df') store.append('df', df, data_columns=['ts', 'A']) result = store.select('df', [Term("ts>=Timestamp('2012-02-01')")]) expected = df[df.ts >= Timestamp('2012-02-01')] tm.assert_frame_equal(expected, result) # bool columns (GH #2849) df = DataFrame(np.random.randn(5,2), columns =['A','B']) df['object'] = 'foo' df.ix[4:5,'object'] = 'bar' df['boolv'] = df['A'] > 0 _maybe_remove(store, 'df') store.append('df', df, data_columns = True) expected = df[df.boolv == True].reindex(columns=['A','boolv']) for v in [True,'true',1]: result = store.select('df', Term('boolv == %s' % str(v)), columns = ['A','boolv']) tm.assert_frame_equal(expected, result) expected = df[df.boolv == False ].reindex(columns=['A','boolv']) for v in [False,'false',0]: result = store.select('df', Term('boolv == %s' % str(v)), columns = ['A','boolv']) tm.assert_frame_equal(expected, result) # integer index df = DataFrame(dict(A=np.random.rand(20), B=np.random.rand(20))) _maybe_remove(store, 'df_int') store.append('df_int', df) result = store.select( 'df_int', [Term("index<10"), Term("columns=['A']")]) expected = df.reindex(index=list(df.index)[0:10],columns=['A']) tm.assert_frame_equal(expected, result) # float index df = DataFrame(dict(A=np.random.rand( 20), B=np.random.rand(20), index=np.arange(20, dtype='f8'))) _maybe_remove(store, 'df_float') store.append('df_float', df) result = store.select( 'df_float', [Term("index<10.0"), Term("columns=['A']")]) expected = df.reindex(index=list(df.index)[0:10],columns=['A']) tm.assert_frame_equal(expected, result) with ensure_clean_store(self.path) as store: # floats w/o NaN df = DataFrame(dict(cols = range(11), values = range(11)),dtype='float64') df['cols'] = (df['cols']+10).apply(str) store.append('df1',df,data_columns=True) result = store.select( 'df1', where='values>2.0') expected = df[df['values']>2.0] tm.assert_frame_equal(expected, result) # floats with NaN df.iloc[0] = np.nan expected = df[df['values']>2.0] store.append('df2',df,data_columns=True,index=False) result = store.select( 'df2', where='values>2.0') tm.assert_frame_equal(expected, result) # https://github.com/PyTables/PyTables/issues/282 # bug in selection when 0th row has a np.nan and an index #store.append('df3',df,data_columns=True) #result = store.select( # 'df3', where='values>2.0') #tm.assert_frame_equal(expected, result) # not in first position float with NaN ok too df = DataFrame(dict(cols = range(11), values = range(11)),dtype='float64') df['cols'] = (df['cols']+10).apply(str) df.iloc[1] = np.nan expected = df[df['values']>2.0] store.append('df4',df,data_columns=True) result = store.select( 'df4', where='values>2.0') tm.assert_frame_equal(expected, result) def test_select_with_many_inputs(self): with ensure_clean_store(self.path) as store: df = DataFrame(dict(ts=bdate_range('2012-01-01', periods=300), A=np.random.randn(300), B=range(300), users = ['a']*50 + ['b']*50 + ['c']*100 + ['a%03d' % i for i in range(100)])) _maybe_remove(store, 'df') store.append('df', df, data_columns=['ts', 'A', 'B', 'users']) # regular select result = store.select('df', [Term("ts>=Timestamp('2012-02-01')")]) expected = df[df.ts >= Timestamp('2012-02-01')] tm.assert_frame_equal(expected, result) # small selector result = store.select('df', [Term("ts>=Timestamp('2012-02-01') & users=['a','b','c']")]) expected = df[ (df.ts >= Timestamp('2012-02-01')) & df.users.isin(['a','b','c']) ] tm.assert_frame_equal(expected, result) # big selector along the columns selector = [ 'a','b','c' ] + [ 'a%03d' % i for i in range(60) ] result = store.select('df', [Term("ts>=Timestamp('2012-02-01')"),Term('users=selector')]) expected = df[ (df.ts >= Timestamp('2012-02-01')) & df.users.isin(selector) ] tm.assert_frame_equal(expected, result) selector = range(100,200) result = store.select('df', [Term('B=selector')]) expected = df[ df.B.isin(selector) ] tm.assert_frame_equal(expected, result) self.assertEqual(len(result), 100) # big selector along the index selector = Index(df.ts[0:100].values) result = store.select('df', [Term('ts=selector')]) expected = df[ df.ts.isin(selector.values) ] tm.assert_frame_equal(expected, result) self.assertEqual(len(result), 100) def test_select_iterator(self): # single table with ensure_clean_store(self.path) as store: df = tm.makeTimeDataFrame(500) _maybe_remove(store, 'df') store.append('df', df) expected = store.select('df') results = [ s for s in store.select('df',iterator=True) ] result = concat(results) tm.assert_frame_equal(expected, result) results = [ s for s in store.select('df',chunksize=100) ] self.assertEqual(len(results), 5) result = concat(results) tm.assert_frame_equal(expected, result) results = [ s for s in store.select('df',chunksize=150) ] result = concat(results) tm.assert_frame_equal(result, expected) with ensure_clean_path(self.path) as path: df = tm.makeTimeDataFrame(500) df.to_hdf(path,'df_non_table') self.assertRaises(TypeError, read_hdf, path,'df_non_table',chunksize=100) self.assertRaises(TypeError, read_hdf, path,'df_non_table',iterator=True) with ensure_clean_path(self.path) as path: df = tm.makeTimeDataFrame(500) df.to_hdf(path,'df',format='table') results = [ s for s in read_hdf(path,'df',chunksize=100) ] result = concat(results) self.assertEqual(len(results), 5) tm.assert_frame_equal(result, df) tm.assert_frame_equal(result, read_hdf(path,'df')) # multiple with ensure_clean_store(self.path) as store: df1 = tm.makeTimeDataFrame(500) store.append('df1',df1,data_columns=True) df2 = tm.makeTimeDataFrame(500).rename(columns=lambda x: "%s_2" % x) df2['foo'] = 'bar' store.append('df2',df2) df = concat([df1, df2], axis=1) # full selection expected = store.select_as_multiple( ['df1', 'df2'], selector='df1') results = [ s for s in store.select_as_multiple( ['df1', 'df2'], selector='df1', chunksize=150) ] result = concat(results) tm.assert_frame_equal(expected, result) # where selection #expected = store.select_as_multiple( # ['df1', 'df2'], where= Term('A>0'), selector='df1') #results = [] #for s in store.select_as_multiple( # ['df1', 'df2'], where= Term('A>0'), selector='df1', chunksize=25): # results.append(s) #result = concat(results) #tm.assert_frame_equal(expected, result) def test_select_iterator_complete_8014(self): # GH 8014 # using iterator and where clause chunksize=1e4 # no iterator with ensure_clean_store(self.path) as store: expected = tm.makeTimeDataFrame(100064, 'S') _maybe_remove(store, 'df') store.append('df',expected) beg_dt = expected.index[0] end_dt = expected.index[-1] # select w/o iteration and no where clause works result = store.select('df') tm.assert_frame_equal(expected, result) # select w/o iterator and where clause, single term, begin # of range, works where = "index >= '%s'" % beg_dt result = store.select('df',where=where) tm.assert_frame_equal(expected, result) # select w/o iterator and where clause, single term, end # of range, works where = "index <= '%s'" % end_dt result = store.select('df',where=where) tm.assert_frame_equal(expected, result) # select w/o iterator and where clause, inclusive range, # works where = "index >= '%s' & index <= '%s'" % (beg_dt, end_dt) result = store.select('df',where=where) tm.assert_frame_equal(expected, result) # with iterator, full range with ensure_clean_store(self.path) as store: expected = tm.makeTimeDataFrame(100064, 'S') _maybe_remove(store, 'df') store.append('df',expected) beg_dt = expected.index[0] end_dt = expected.index[-1] # select w/iterator and no where clause works results = [ s for s in store.select('df',chunksize=chunksize) ] result = concat(results) tm.assert_frame_equal(expected, result) # select w/iterator and where clause, single term, begin of range where = "index >= '%s'" % beg_dt results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] result = concat(results) tm.assert_frame_equal(expected, result) # select w/iterator and where clause, single term, end of range where = "index <= '%s'" % end_dt results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] result = concat(results) tm.assert_frame_equal(expected, result) # select w/iterator and where clause, inclusive range where = "index >= '%s' & index <= '%s'" % (beg_dt, end_dt) results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] result = concat(results) tm.assert_frame_equal(expected, result) def test_select_iterator_non_complete_8014(self): # GH 8014 # using iterator and where clause chunksize=1e4 # with iterator, non complete range with ensure_clean_store(self.path) as store: expected = tm.makeTimeDataFrame(100064, 'S') _maybe_remove(store, 'df') store.append('df',expected) beg_dt = expected.index[1] end_dt = expected.index[-2] # select w/iterator and where clause, single term, begin of range where = "index >= '%s'" % beg_dt results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] result = concat(results) rexpected = expected[expected.index >= beg_dt] tm.assert_frame_equal(rexpected, result) # select w/iterator and where clause, single term, end of range where = "index <= '%s'" % end_dt results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] result = concat(results) rexpected = expected[expected.index <= end_dt] tm.assert_frame_equal(rexpected, result) # select w/iterator and where clause, inclusive range where = "index >= '%s' & index <= '%s'" % (beg_dt, end_dt) results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] result = concat(results) rexpected = expected[(expected.index >= beg_dt) & (expected.index <= end_dt)] tm.assert_frame_equal(rexpected, result) # with iterator, empty where with ensure_clean_store(self.path) as store: expected = tm.makeTimeDataFrame(100064, 'S') _maybe_remove(store, 'df') store.append('df',expected) end_dt = expected.index[-1] # select w/iterator and where clause, single term, begin of range where = "index > '%s'" % end_dt results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] self.assertEqual(0, len(results)) def test_select_iterator_many_empty_frames(self): # GH 8014 # using iterator and where clause can return many empty # frames. chunksize=int(1e4) # with iterator, range limited to the first chunk with ensure_clean_store(self.path) as store: expected = tm.makeTimeDataFrame(100000, 'S') _maybe_remove(store, 'df') store.append('df',expected) beg_dt = expected.index[0] end_dt = expected.index[chunksize-1] # select w/iterator and where clause, single term, begin of range where = "index >= '%s'" % beg_dt results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] result = concat(results) rexpected = expected[expected.index >= beg_dt] tm.assert_frame_equal(rexpected, result) # select w/iterator and where clause, single term, end of range where = "index <= '%s'" % end_dt results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] tm.assert_equal(1, len(results)) result = concat(results) rexpected = expected[expected.index <= end_dt] tm.assert_frame_equal(rexpected, result) # select w/iterator and where clause, inclusive range where = "index >= '%s' & index <= '%s'" % (beg_dt, end_dt) results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] # should be 1, is 10 tm.assert_equal(1, len(results)) result = concat(results) rexpected = expected[(expected.index >= beg_dt) & (expected.index <= end_dt)] tm.assert_frame_equal(rexpected, result) # select w/iterator and where clause which selects # *nothing*. # # To be consistent with Python idiom I suggest this should # return [] e.g. `for e in []: print True` never prints # True. where = "index <= '%s' & index >= '%s'" % (beg_dt, end_dt) results = [ s for s in store.select('df',where=where,chunksize=chunksize) ] # should be [] tm.assert_equal(0, len(results)) def test_retain_index_attributes(self): # GH 3499, losing frequency info on index recreation df = DataFrame(dict(A = Series(lrange(3), index=date_range('2000-1-1',periods=3,freq='H')))) with ensure_clean_store(self.path) as store: _maybe_remove(store,'data') store.put('data', df, format='table') result = store.get('data') tm.assert_frame_equal(df,result) for attr in ['freq','tz','name']: for idx in ['index','columns']: self.assertEqual(getattr(getattr(df,idx),attr,None), getattr(getattr(result,idx),attr,None)) # try to append a table with a different frequency with tm.assert_produces_warning(expected_warning=AttributeConflictWarning): df2 = DataFrame(dict(A = Series(lrange(3), index=date_range('2002-1-1',periods=3,freq='D')))) store.append('data',df2) self.assertIsNone(store.get_storer('data').info['index']['freq']) # this is ok _maybe_remove(store,'df2') df2 = DataFrame(dict(A = Series(lrange(3), index=[Timestamp('20010101'),Timestamp('20010102'),Timestamp('20020101')]))) store.append('df2',df2) df3 = DataFrame(dict(A = Series(lrange(3),index=date_range('2002-1-1',periods=3,freq='D')))) store.append('df2',df3) def test_retain_index_attributes2(self): with ensure_clean_path(self.path) as path: with tm.assert_produces_warning(expected_warning=AttributeConflictWarning): df = DataFrame(dict(A = Series(lrange(3), index=date_range('2000-1-1',periods=3,freq='H')))) df.to_hdf(path,'data',mode='w',append=True) df2 = DataFrame(dict(A = Series(lrange(3), index=date_range('2002-1-1',periods=3,freq='D')))) df2.to_hdf(path,'data',append=True) idx = date_range('2000-1-1',periods=3,freq='H') idx.name = 'foo' df = DataFrame(dict(A = Series(lrange(3), index=idx))) df.to_hdf(path,'data',mode='w',append=True) self.assertEqual(read_hdf(path,'data').index.name, 'foo') with tm.assert_produces_warning(expected_warning=AttributeConflictWarning): idx2 = date_range('2001-1-1',periods=3,freq='H') idx2.name = 'bar' df2 = DataFrame(dict(A = Series(lrange(3), index=idx2))) df2.to_hdf(path,'data',append=True) self.assertIsNone(read_hdf(path,'data').index.name) def test_panel_select(self): wp = tm.makePanel() with ensure_clean_store(self.path) as store: store.put('wp', wp, format='table') date = wp.major_axis[len(wp.major_axis) // 2] crit1 = ('major_axis>=date') crit2 = ("minor_axis=['A', 'D']") result = store.select('wp', [crit1, crit2]) expected = wp.truncate(before=date).reindex(minor=['A', 'D']) assert_panel_equal(result, expected) result = store.select( 'wp', ['major_axis>="20000124"', ("minor_axis=['A', 'B']")]) expected = wp.truncate(before='20000124').reindex(minor=['A', 'B']) assert_panel_equal(result, expected) def test_frame_select(self): df = tm.makeTimeDataFrame() with ensure_clean_store(self.path) as store: store.put('frame', df,format='table') date = df.index[len(df) // 2] crit1 = Term('index>=date') self.assertEqual(crit1.env.scope['date'], date) crit2 = ("columns=['A', 'D']") crit3 = ('columns=A') result = store.select('frame', [crit1, crit2]) expected = df.ix[date:, ['A', 'D']] tm.assert_frame_equal(result, expected) result = store.select('frame', [crit3]) expected = df.ix[:, ['A']] tm.assert_frame_equal(result, expected) # invalid terms df = tm.makeTimeDataFrame() store.append('df_time', df) self.assertRaises( ValueError, store.select, 'df_time', [Term("index>0")]) # can't select if not written as table # store['frame'] = df # self.assertRaises(ValueError, store.select, # 'frame', [crit1, crit2]) def test_frame_select_complex(self): # select via complex criteria df = tm.makeTimeDataFrame() df['string'] = 'foo' df.loc[df.index[0:4],'string'] = 'bar' with ensure_clean_store(self.path) as store: store.put('df', df, table=True, data_columns=['string']) # empty result = store.select('df', 'index>df.index[3] & string="bar"') expected = df.loc[(df.index>df.index[3]) & (df.string=='bar')] tm.assert_frame_equal(result, expected) result = store.select('df', 'index>df.index[3] & string="foo"') expected = df.loc[(df.index>df.index[3]) & (df.string=='foo')] tm.assert_frame_equal(result, expected) # or result = store.select('df', 'index>df.index[3] | string="bar"') expected = df.loc[(df.index>df.index[3]) | (df.string=='bar')] tm.assert_frame_equal(result, expected) result = store.select('df', '(index>df.index[3] & index<=df.index[6]) | string="bar"') expected = df.loc[((df.index>df.index[3]) & (df.index<=df.index[6])) | (df.string=='bar')] tm.assert_frame_equal(result, expected) # invert result = store.select('df', 'string!="bar"') expected = df.loc[df.string!='bar'] tm.assert_frame_equal(result, expected) # invert not implemented in numexpr :( self.assertRaises(NotImplementedError, store.select, 'df', '~(string="bar")') # invert ok for filters result = store.select('df', "~(columns=['A','B'])") expected = df.loc[:,df.columns-['A','B']] tm.assert_frame_equal(result, expected) # in result = store.select('df', "index>df.index[3] & columns in ['A','B']") expected = df.loc[df.index>df.index[3]].reindex(columns=['A','B']) tm.assert_frame_equal(result, expected) def test_frame_select_complex2(self): with ensure_clean_path(['parms.hdf','hist.hdf']) as paths: pp, hh = paths # use non-trivial selection criteria parms = DataFrame({ 'A' : [1,1,2,2,3] }) parms.to_hdf(pp,'df',mode='w',format='table',data_columns=['A']) selection = read_hdf(pp,'df',where='A=[2,3]') hist = DataFrame(np.random.randn(25,1),columns=['data'], index=MultiIndex.from_tuples([ (i,j) for i in range(5) for j in range(5) ], names=['l1','l2'])) hist.to_hdf(hh,'df',mode='w',format='table') expected = read_hdf(hh,'df',where=Term('l1','=',[2,3,4])) # list like result = read_hdf(hh,'df',where=Term('l1','=',selection.index.tolist())) assert_frame_equal(result, expected) l = selection.index.tolist() # sccope with list like store = HDFStore(hh) result = store.select('df',where='l1=l') assert_frame_equal(result, expected) store.close() result = read_hdf(hh,'df',where='l1=l') assert_frame_equal(result, expected) # index index = selection.index result = read_hdf(hh,'df',where='l1=index') assert_frame_equal(result, expected) result = read_hdf(hh,'df',where='l1=selection.index') assert_frame_equal(result, expected) result = read_hdf(hh,'df',where='l1=selection.index.tolist()') assert_frame_equal(result, expected) result = read_hdf(hh,'df',where='l1=list(selection.index)') assert_frame_equal(result, expected) # sccope with index store = HDFStore(hh) result = store.select('df',where='l1=index') assert_frame_equal(result, expected) result = store.select('df',where='l1=selection.index') assert_frame_equal(result, expected) result = store.select('df',where='l1=selection.index.tolist()') assert_frame_equal(result, expected) result = store.select('df',where='l1=list(selection.index)') assert_frame_equal(result, expected) store.close() def test_invalid_filtering(self): # can't use more than one filter (atm) df = tm.makeTimeDataFrame() with ensure_clean_store(self.path) as store: store.put('df', df, table=True) # not implemented self.assertRaises(NotImplementedError, store.select, 'df', "columns=['A'] | columns=['B']") # in theory we could deal with this self.assertRaises(NotImplementedError, store.select, 'df', "columns=['A','B'] & columns=['C']") def test_string_select(self): # GH 2973 with ensure_clean_store(self.path) as store: df = tm.makeTimeDataFrame() # test string ==/!= df['x'] = 'none' df.ix[2:7,'x'] = '' store.append('df',df,data_columns=['x']) result = store.select('df',Term('x=none')) expected = df[df.x == 'none'] assert_frame_equal(result,expected) try: result = store.select('df',Term('x!=none')) expected = df[df.x != 'none'] assert_frame_equal(result,expected) except Exception as detail: com.pprint_thing("[{0}]".format(detail)) com.pprint_thing(store) com.pprint_thing(expected) df2 = df.copy() df2.loc[df2.x=='','x'] = np.nan store.append('df2',df2,data_columns=['x']) result = store.select('df2',Term('x!=none')) expected = df2[isnull(df2.x)] assert_frame_equal(result,expected) # int ==/!= df['int'] = 1 df.ix[2:7,'int'] = 2 store.append('df3',df,data_columns=['int']) result = store.select('df3',Term('int=2')) expected = df[df.int==2] assert_frame_equal(result,expected) result = store.select('df3',Term('int!=2')) expected = df[df.int!=2] assert_frame_equal(result,expected) def test_read_column(self): df = tm.makeTimeDataFrame() with ensure_clean_store(self.path) as store: _maybe_remove(store, 'df') store.append('df', df) # error self.assertRaises(KeyError, store.select_column, 'df', 'foo') def f(): store.select_column('df', 'index', where = ['index>5']) self.assertRaises(Exception, f) # valid result = store.select_column('df', 'index') tm.assert_almost_equal(result.values, Series(df.index).values) self.assertIsInstance(result,Series) # not a data indexable column self.assertRaises( ValueError, store.select_column, 'df', 'values_block_0') # a data column df2 = df.copy() df2['string'] = 'foo' store.append('df2', df2, data_columns=['string']) result = store.select_column('df2', 'string') tm.assert_almost_equal(result.values, df2['string'].values) # a data column with NaNs, result excludes the NaNs df3 = df.copy() df3['string'] = 'foo' df3.ix[4:6, 'string'] = np.nan store.append('df3', df3, data_columns=['string']) result = store.select_column('df3', 'string') tm.assert_almost_equal(result.values, df3['string'].values) # start/stop result = store.select_column('df3', 'string', start=2) tm.assert_almost_equal(result.values, df3['string'].values[2:]) result = store.select_column('df3', 'string', start=-2) tm.assert_almost_equal(result.values, df3['string'].values[-2:]) result = store.select_column('df3', 'string', stop=2) tm.assert_almost_equal(result.values, df3['string'].values[:2]) result = store.select_column('df3', 'string', stop=-2) tm.assert_almost_equal(result.values, df3['string'].values[:-2]) result = store.select_column('df3', 'string', start=2, stop=-2) tm.assert_almost_equal(result.values, df3['string'].values[2:-2]) result = store.select_column('df3', 'string', start=-2, stop=2) tm.assert_almost_equal(result.values, df3['string'].values[-2:2]) def test_coordinates(self): df = tm.makeTimeDataFrame() with ensure_clean_store(self.path) as store: _maybe_remove(store, 'df') store.append('df', df) # all c = store.select_as_coordinates('df') assert((c.values == np.arange(len(df.index))).all() == True) # get coordinates back & test vs frame _maybe_remove(store, 'df') df = DataFrame(dict(A=lrange(5), B=lrange(5))) store.append('df', df) c = store.select_as_coordinates('df', ['index<3']) assert((c.values == np.arange(3)).all() == True) result = store.select('df', where=c) expected = df.ix[0:2, :] tm.assert_frame_equal(result, expected) c = store.select_as_coordinates('df', ['index>=3', 'index<=4']) assert((c.values == np.arange(2) + 3).all() == True) result = store.select('df', where=c) expected = df.ix[3:4, :] tm.assert_frame_equal(result, expected) self.assertIsInstance(c, Index) # multiple tables _maybe_remove(store, 'df1') _maybe_remove(store, 'df2') df1 = tm.makeTimeDataFrame() df2 = tm.makeTimeDataFrame().rename(columns=lambda x: "%s_2" % x) store.append('df1', df1, data_columns=['A', 'B']) store.append('df2', df2) c = store.select_as_coordinates('df1', ['A>0', 'B>0']) df1_result = store.select('df1', c) df2_result = store.select('df2', c) result = concat([df1_result, df2_result], axis=1) expected = concat([df1, df2], axis=1) expected = expected[(expected.A > 0) & (expected.B > 0)] tm.assert_frame_equal(result, expected) # pass array/mask as the coordinates with ensure_clean_store(self.path) as store: df = DataFrame(np.random.randn(1000,2),index=date_range('20000101',periods=1000)) store.append('df',df) c = store.select_column('df','index') where = c[DatetimeIndex(c).month==5].index expected = df.iloc[where] # locations result = store.select('df',where=where) tm.assert_frame_equal(result,expected) # boolean result = store.select('df',where=where) tm.assert_frame_equal(result,expected) # invalid self.assertRaises(ValueError, store.select, 'df',where=np.arange(len(df),dtype='float64')) self.assertRaises(ValueError, store.select, 'df',where=np.arange(len(df)+1)) self.assertRaises(ValueError, store.select, 'df',where=np.arange(len(df)),start=5) self.assertRaises(ValueError, store.select, 'df',where=np.arange(len(df)),start=5,stop=10) # selection with filter selection = date_range('20000101',periods=500) result = store.select('df', where='index in selection') expected = df[df.index.isin(selection)] tm.assert_frame_equal(result,expected) # list df = DataFrame(np.random.randn(10,2)) store.append('df2',df) result = store.select('df2',where=[0,3,5]) expected = df.iloc[[0,3,5]] tm.assert_frame_equal(result,expected) # boolean where = [True] * 10 where[-2] = False result = store.select('df2',where=where) expected = df.loc[where] tm.assert_frame_equal(result,expected) # start/stop result = store.select('df2', start=5, stop=10) expected = df[5:10] tm.assert_frame_equal(result,expected) def test_append_to_multiple(self): df1 = tm.makeTimeDataFrame() df2 = tm.makeTimeDataFrame().rename(columns=lambda x: "%s_2" % x) df2['foo'] = 'bar' df = concat([df1, df2], axis=1) with ensure_clean_store(self.path) as store: # exceptions self.assertRaises(ValueError, store.append_to_multiple, {'df1': ['A', 'B'], 'df2': None}, df, selector='df3') self.assertRaises(ValueError, store.append_to_multiple, {'df1': None, 'df2': None}, df, selector='df3') self.assertRaises( ValueError, store.append_to_multiple, 'df1', df, 'df1') # regular operation store.append_to_multiple( {'df1': ['A', 'B'], 'df2': None}, df, selector='df1') result = store.select_as_multiple( ['df1', 'df2'], where=['A>0', 'B>0'], selector='df1') expected = df[(df.A > 0) & (df.B > 0)] tm.assert_frame_equal(result, expected) def test_append_to_multiple_dropna(self): df1 = tm.makeTimeDataFrame() df2 = tm.makeTimeDataFrame().rename(columns=lambda x: "%s_2" % x) df1.ix[1, ['A', 'B']] = np.nan df = concat([df1, df2], axis=1) with ensure_clean_store(self.path) as store: # dropna=True should guarantee rows are synchronized store.append_to_multiple( {'df1': ['A', 'B'], 'df2': None}, df, selector='df1', dropna=True) result = store.select_as_multiple(['df1', 'df2']) expected = df.dropna() tm.assert_frame_equal(result, expected) tm.assert_index_equal(store.select('df1').index, store.select('df2').index) # dropna=False shouldn't synchronize row indexes store.append_to_multiple( {'df1': ['A', 'B'], 'df2': None}, df, selector='df1', dropna=False) self.assertRaises( ValueError, store.select_as_multiple, ['df1', 'df2']) assert not store.select('df1').index.equals( store.select('df2').index) def test_select_as_multiple(self): df1 = tm.makeTimeDataFrame() df2 = tm.makeTimeDataFrame().rename(columns=lambda x: "%s_2" % x) df2['foo'] = 'bar' with ensure_clean_store(self.path) as store: # no tables stored self.assertRaises(Exception, store.select_as_multiple, None, where=['A>0', 'B>0'], selector='df1') store.append('df1', df1, data_columns=['A', 'B']) store.append('df2', df2) # exceptions self.assertRaises(Exception, store.select_as_multiple, None, where=['A>0', 'B>0'], selector='df1') self.assertRaises(Exception, store.select_as_multiple, [None], where=['A>0', 'B>0'], selector='df1') self.assertRaises(KeyError, store.select_as_multiple, ['df1','df3'], where=['A>0', 'B>0'], selector='df1') self.assertRaises(KeyError, store.select_as_multiple, ['df3'], where=['A>0', 'B>0'], selector='df1') self.assertRaises(KeyError, store.select_as_multiple, ['df1','df2'], where=['A>0', 'B>0'], selector='df4') # default select result = store.select('df1', ['A>0', 'B>0']) expected = store.select_as_multiple( ['df1'], where=['A>0', 'B>0'], selector='df1') tm.assert_frame_equal(result, expected) expected = store.select_as_multiple( 'df1', where=['A>0', 'B>0'], selector='df1') tm.assert_frame_equal(result, expected) # multiple result = store.select_as_multiple( ['df1', 'df2'], where=['A>0', 'B>0'], selector='df1') expected = concat([df1, df2], axis=1) expected = expected[(expected.A > 0) & (expected.B > 0)] tm.assert_frame_equal(result, expected) # multiple (diff selector) result = store.select_as_multiple(['df1', 'df2'], where=[Term( 'index>df2.index[4]')], selector='df2') expected = concat([df1, df2], axis=1) expected = expected[5:] tm.assert_frame_equal(result, expected) # test excpection for diff rows store.append('df3', tm.makeTimeDataFrame(nper=50)) self.assertRaises(ValueError, store.select_as_multiple, ['df1','df3'], where=['A>0', 'B>0'], selector='df1') def test_nan_selection_bug_4858(self): # GH 4858; nan selection bug, only works for pytables >= 3.1 if LooseVersion(tables.__version__) < '3.1.0': raise nose.SkipTest('tables version does not support fix for nan selection bug: GH 4858') with ensure_clean_store(self.path) as store: df = DataFrame(dict(cols = range(6), values = range(6)), dtype='float64') df['cols'] = (df['cols']+10).apply(str) df.iloc[0] = np.nan expected = DataFrame(dict(cols = ['13.0','14.0','15.0'], values = [3.,4.,5.]), index=[3,4,5]) # write w/o the index on that particular column store.append('df',df, data_columns=True,index=['cols']) result = store.select('df',where='values>2.0') assert_frame_equal(result,expected) def test_start_stop(self): with ensure_clean_store(self.path) as store: df = DataFrame(dict(A=np.random.rand(20), B=np.random.rand(20))) store.append('df', df) result = store.select( 'df', [Term("columns=['A']")], start=0, stop=5) expected = df.ix[0:4, ['A']] tm.assert_frame_equal(result, expected) # out of range result = store.select( 'df', [Term("columns=['A']")], start=30, stop=40) assert(len(result) == 0) assert(type(result) == DataFrame) def test_select_filter_corner(self): df = DataFrame(np.random.randn(50, 100)) df.index = ['%.3d' % c for c in df.index] df.columns = ['%.3d' % c for c in df.columns] with ensure_clean_store(self.path) as store: store.put('frame', df, format='table') crit = Term('columns=df.columns[:75]') result = store.select('frame', [crit]) tm.assert_frame_equal(result, df.ix[:, df.columns[:75]]) crit = Term('columns=df.columns[:75:2]') result = store.select('frame', [crit]) tm.assert_frame_equal(result, df.ix[:, df.columns[:75:2]]) def _check_roundtrip(self, obj, comparator, compression=False, **kwargs): options = {} if compression: options['complib'] = _default_compressor with ensure_clean_store(self.path, 'w', **options) as store: store['obj'] = obj retrieved = store['obj'] comparator(retrieved, obj, **kwargs) def _check_double_roundtrip(self, obj, comparator, compression=False, **kwargs): options = {} if compression: options['complib'] = compression or _default_compressor with ensure_clean_store(self.path, 'w', **options) as store: store['obj'] = obj retrieved = store['obj'] comparator(retrieved, obj, **kwargs) store['obj'] = retrieved again = store['obj'] comparator(again, obj, **kwargs) def _check_roundtrip_table(self, obj, comparator, compression=False): options = {} if compression: options['complib'] = _default_compressor with ensure_clean_store(self.path, 'w', **options) as store: store.put('obj', obj, format='table') retrieved = store['obj'] # sorted_obj = _test_sort(obj) comparator(retrieved, obj) def test_multiple_open_close(self): # GH 4409, open & close multiple times with ensure_clean_path(self.path) as path: df = tm.makeDataFrame() df.to_hdf(path,'df',mode='w',format='table') # single store = HDFStore(path) self.assertNotIn('CLOSED', str(store)) self.assertTrue(store.is_open) store.close() self.assertIn('CLOSED', str(store)) self.assertFalse(store.is_open) with ensure_clean_path(self.path) as path: if pytables._table_file_open_policy_is_strict: # multiples store1 = HDFStore(path) def f(): HDFStore(path) self.assertRaises(ValueError, f) store1.close() else: # multiples store1 = HDFStore(path) store2 = HDFStore(path) self.assertNotIn('CLOSED', str(store1)) self.assertNotIn('CLOSED', str(store2)) self.assertTrue(store1.is_open) self.assertTrue(store2.is_open) store1.close() self.assertIn('CLOSED', str(store1)) self.assertFalse(store1.is_open) self.assertNotIn('CLOSED', str(store2)) self.assertTrue(store2.is_open) store2.close() self.assertIn('CLOSED', str(store1)) self.assertIn('CLOSED', str(store2)) self.assertFalse(store1.is_open) self.assertFalse(store2.is_open) # nested close store = HDFStore(path,mode='w') store.append('df',df) store2 = HDFStore(path) store2.append('df2',df) store2.close() self.assertIn('CLOSED', str(store2)) self.assertFalse(store2.is_open) store.close() self.assertIn('CLOSED', str(store)) self.assertFalse(store.is_open) # double closing store = HDFStore(path,mode='w') store.append('df', df) store2 = HDFStore(path) store.close() self.assertIn('CLOSED', str(store)) self.assertFalse(store.is_open) store2.close() self.assertIn('CLOSED', str(store2)) self.assertFalse(store2.is_open) # ops on a closed store with ensure_clean_path(self.path) as path: df = tm.makeDataFrame() df.to_hdf(path,'df',mode='w',format='table') store = HDFStore(path) store.close() self.assertRaises(ClosedFileError, store.keys) self.assertRaises(ClosedFileError, lambda : 'df' in store) self.assertRaises(ClosedFileError, lambda : len(store)) self.assertRaises(ClosedFileError, lambda : store['df']) self.assertRaises(ClosedFileError, lambda : store.df) self.assertRaises(ClosedFileError, store.select, 'df') self.assertRaises(ClosedFileError, store.get, 'df') self.assertRaises(ClosedFileError, store.append, 'df2', df) self.assertRaises(ClosedFileError, store.put, 'df3', df) self.assertRaises(ClosedFileError, store.get_storer, 'df2') self.assertRaises(ClosedFileError, store.remove, 'df2') def f(): store.select('df') tm.assertRaisesRegexp(ClosedFileError, 'file is not open', f) def test_pytables_native_read(self): try: store = HDFStore(tm.get_data_path('legacy_hdf/pytables_native.h5'), 'r') d2 = store['detector/readout'] assert isinstance(d2, DataFrame) finally: safe_close(store) try: store = HDFStore(tm.get_data_path('legacy_hdf/pytables_native2.h5'), 'r') str(store) d1 = store['detector'] assert isinstance(d1, DataFrame) finally: safe_close(store) def test_legacy_read(self): try: store = HDFStore(tm.get_data_path('legacy_hdf/legacy.h5'), 'r') store['a'] store['b'] store['c'] store['d'] finally: safe_close(store) def test_legacy_table_read(self): # legacy table types try: store = HDFStore(tm.get_data_path('legacy_hdf/legacy_table.h5'), 'r') store.select('df1') store.select('df2') store.select('wp1') # force the frame store.select('df2', typ='legacy_frame') # old version warning with tm.assert_produces_warning(expected_warning=IncompatibilityWarning): self.assertRaises( Exception, store.select, 'wp1', Term('minor_axis=B')) df2 = store.select('df2') result = store.select('df2', Term('index>df2.index[2]')) expected = df2[df2.index > df2.index[2]] assert_frame_equal(expected, result) finally: safe_close(store) def test_legacy_0_10_read(self): # legacy from 0.10 try: store = HDFStore(tm.get_data_path('legacy_hdf/legacy_0.10.h5'), 'r') str(store) for k in store.keys(): store.select(k) finally: safe_close(store) def test_legacy_0_11_read(self): # legacy from 0.11 try: path = os.path.join('legacy_hdf', 'legacy_table_0.11.h5') store = HDFStore(tm.get_data_path(path), 'r') str(store) assert 'df' in store assert 'df1' in store assert 'mi' in store df = store.select('df') df1 = store.select('df1') mi = store.select('mi') assert isinstance(df, DataFrame) assert isinstance(df1, DataFrame) assert isinstance(mi, DataFrame) finally: safe_close(store) def test_copy(self): def do_copy(f = None, new_f = None, keys = None, propindexes = True, **kwargs): try: if f is None: f = tm.get_data_path(os.path.join('legacy_hdf', 'legacy_0.10.h5')) store = HDFStore(f, 'r') if new_f is None: import tempfile fd, new_f = tempfile.mkstemp() tstore = store.copy(new_f, keys = keys, propindexes = propindexes, **kwargs) # check keys if keys is None: keys = store.keys() self.assertEqual(set(keys), set(tstore.keys())) # check indicies & nrows for k in tstore.keys(): if tstore.get_storer(k).is_table: new_t = tstore.get_storer(k) orig_t = store.get_storer(k) self.assertEqual(orig_t.nrows, new_t.nrows) # check propindixes if propindexes: for a in orig_t.axes: if a.is_indexed: self.assertTrue(new_t[a.name].is_indexed) finally: safe_close(store) safe_close(tstore) try: os.close(fd) except: pass safe_remove(new_f) do_copy() do_copy(keys = ['/a','/b','/df1_mixed']) do_copy(propindexes = False) # new table df = tm.makeDataFrame() try: st = HDFStore(self.path) st.append('df', df, data_columns = ['A']) st.close() do_copy(f = self.path) do_copy(f = self.path, propindexes = False) finally: safe_remove(self.path) def test_legacy_table_write(self): raise nose.SkipTest("cannot write legacy tables") store = HDFStore(tm.get_data_path('legacy_hdf/legacy_table_%s.h5' % pandas.__version__), 'a') df = tm.makeDataFrame() wp = tm.makePanel() index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two', 'three']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['foo', 'bar']) df = DataFrame(np.random.randn(10, 3), index=index, columns=['A', 'B', 'C']) store.append('mi', df) df = DataFrame(dict(A = 'foo', B = 'bar'),index=lrange(10)) store.append('df', df, data_columns = ['B'], min_itemsize={'A' : 200 }) store.append('wp', wp) store.close() def test_store_datetime_fractional_secs(self): with ensure_clean_store(self.path) as store: dt = datetime.datetime(2012, 1, 2, 3, 4, 5, 123456) series = Series([0], [dt]) store['a'] = series self.assertEqual(store['a'].index[0], dt) def test_tseries_indices_series(self): with ensure_clean_store(self.path) as store: idx = tm.makeDateIndex(10) ser = Series(np.random.randn(len(idx)), idx) store['a'] = ser result = store['a'] assert_series_equal(result, ser) self.assertEqual(type(result.index), type(ser.index)) self.assertEqual(result.index.freq, ser.index.freq) idx = tm.makePeriodIndex(10) ser = Series(np.random.randn(len(idx)), idx) store['a'] = ser result = store['a'] assert_series_equal(result, ser) self.assertEqual(type(result.index), type(ser.index)) self.assertEqual(result.index.freq, ser.index.freq) def test_tseries_indices_frame(self): with ensure_clean_store(self.path) as store: idx = tm.makeDateIndex(10) df = DataFrame(np.random.randn(len(idx), 3), index=idx) store['a'] = df result = store['a'] assert_frame_equal(result, df) self.assertEqual(type(result.index), type(df.index)) self.assertEqual(result.index.freq, df.index.freq) idx = tm.makePeriodIndex(10) df = DataFrame(np.random.randn(len(idx), 3), idx) store['a'] = df result = store['a'] assert_frame_equal(result, df) self.assertEqual(type(result.index), type(df.index)) self.assertEqual(result.index.freq, df.index.freq) def test_tseries_select_index_column(self): # GH7777 # selecting a UTC datetimeindex column did # not preserve UTC tzinfo set before storing # check that no tz still works rng = date_range('1/1/2000', '1/30/2000') frame = DataFrame(np.random.randn(len(rng), 4), index=rng) with ensure_clean_store(self.path) as store: store.append('frame', frame) result = store.select_column('frame', 'index') self.assertEqual(rng.tz, DatetimeIndex(result.values).tz) # check utc rng = date_range('1/1/2000', '1/30/2000', tz='UTC') frame = DataFrame(np.random.randn(len(rng), 4), index=rng) with ensure_clean_store(self.path) as store: store.append('frame', frame) result = store.select_column('frame', 'index') self.assertEqual(rng.tz, DatetimeIndex(result.values).tz) # double check non-utc rng = date_range('1/1/2000', '1/30/2000', tz='US/Eastern') frame = DataFrame(np.random.randn(len(rng), 4), index=rng) with ensure_clean_store(self.path) as store: store.append('frame', frame) result = store.select_column('frame', 'index') self.assertEqual(rng.tz, DatetimeIndex(result.values).tz) def test_unicode_index(self): unicode_values = [u('\u03c3'), u('\u03c3\u03c3')] def f(): s = Series(np.random.randn(len(unicode_values)), unicode_values) self._check_roundtrip(s, tm.assert_series_equal) compat_assert_produces_warning(PerformanceWarning,f) def test_store_datetime_mixed(self): df = DataFrame( {'a': [1, 2, 3], 'b': [1., 2., 3.], 'c': ['a', 'b', 'c']}) ts = tm.makeTimeSeries() df['d'] = ts.index[:3] self._check_roundtrip(df, tm.assert_frame_equal) # def test_cant_write_multiindex_table(self): # # for now, #1848 # df = DataFrame(np.random.randn(10, 4), # index=[np.arange(5).repeat(2), # np.tile(np.arange(2), 5)]) # self.assertRaises(Exception, store.put, 'foo', df, format='table') def test_append_with_diff_col_name_types_raises_value_error(self): df = DataFrame(np.random.randn(10, 1)) df2 = DataFrame({'a': np.random.randn(10)}) df3 = DataFrame({(1, 2): np.random.randn(10)}) df4 = DataFrame({('1', 2): np.random.randn(10)}) df5 = DataFrame({('1', 2, object): np.random.randn(10)}) with ensure_clean_store(self.path) as store: name = 'df_%s' % tm.rands(10) store.append(name, df) for d in (df2, df3, df4, df5): with tm.assertRaises(ValueError): store.append(name, d) def test_query_with_nested_special_character(self): df = DataFrame({'a': ['a', 'a', 'c', 'b', 'test & test', 'c' , 'b', 'e'], 'b': [1, 2, 3, 4, 5, 6, 7, 8]}) expected = df[df.a == 'test & test'] with ensure_clean_store(self.path) as store: store.append('test', df, format='table', data_columns=True) result = store.select('test', 'a = "test & test"') tm.assert_frame_equal(expected, result) def test_categorical(self): with ensure_clean_store(self.path) as store: # basic s = Series(Categorical(['a', 'b', 'b', 'a', 'a', 'c'], categories=['a','b','c','d'], ordered=False)) store.append('s', s, format='table') result = store.select('s') tm.assert_series_equal(s, result) s = Series(Categorical(['a', 'b', 'b', 'a', 'a', 'c'], categories=['a','b','c','d'], ordered=True)) store.append('s_ordered', s, format='table') result = store.select('s_ordered') tm.assert_series_equal(s, result) df = DataFrame({"s":s, "vals":[1,2,3,4,5,6]}) store.append('df', df, format='table') result = store.select('df') tm.assert_frame_equal(result, df) # dtypes s = Series([1,1,2,2,3,4,5]).astype('category') store.append('si',s) result = store.select('si') tm.assert_series_equal(result, s) s = Series([1,1,np.nan,2,3,4,5]).astype('category') store.append('si2',s) result = store.select('si2') tm.assert_series_equal(result, s) # multiple df2 = df.copy() df2['s2'] = Series(list('abcdefg')).astype('category') store.append('df2',df2) result = store.select('df2') tm.assert_frame_equal(result, df2) # make sure the metadata is ok self.assertTrue('/df2 ' in str(store)) self.assertTrue('/df2/meta/values_block_0/meta' in str(store)) self.assertTrue('/df2/meta/values_block_1/meta' in str(store)) # unordered s = Series(Categorical(['a', 'b', 'b', 'a', 'a', 'c'], categories=['a','b','c','d'],ordered=False)) store.append('s2', s, format='table') result = store.select('s2') tm.assert_series_equal(result, s) # query store.append('df3', df, data_columns=['s']) expected = df[df.s.isin(['b','c'])] result = store.select('df3', where = ['s in ["b","c"]']) tm.assert_frame_equal(result, expected) expected = df[df.s.isin(['b','c'])] result = store.select('df3', where = ['s = ["b","c"]']) tm.assert_frame_equal(result, expected) expected = df[df.s.isin(['d'])] result = store.select('df3', where = ['s in ["d"]']) tm.assert_frame_equal(result, expected) expected = df[df.s.isin(['f'])] result = store.select('df3', where = ['s in ["f"]']) tm.assert_frame_equal(result, expected) # appending with same categories is ok store.append('df3', df) df = concat([df,df]) expected = df[df.s.isin(['b','c'])] result = store.select('df3', where = ['s in ["b","c"]']) tm.assert_frame_equal(result, expected) # appending must have the same categories df3 = df.copy() df3['s'].cat.remove_unused_categories(inplace=True) self.assertRaises(ValueError, lambda : store.append('df3', df3)) # remove # make sure meta data is removed (its a recursive removal so should be) result = store.select('df3/meta/s/meta') self.assertIsNotNone(result) store.remove('df3') self.assertRaises(KeyError, lambda : store.select('df3/meta/s/meta')) def test_duplicate_column_name(self): df = DataFrame(columns=["a", "a"], data=[[0, 0]]) with ensure_clean_path(self.path) as path: self.assertRaises(ValueError, df.to_hdf, path, 'df', format='fixed') df.to_hdf(path, 'df', format='table') other = read_hdf(path, 'df') tm.assert_frame_equal(df, other) def _test_sort(obj): if isinstance(obj, DataFrame): return obj.reindex(sorted(obj.index)) elif isinstance(obj, Panel): return obj.reindex(major=sorted(obj.major_axis)) else: raise ValueError('type not supported here') if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
webmasterraj/FogOrNot
flask/lib/python2.7/site-packages/pandas/io/tests/test_pytables.py
Python
gpl-2.0
175,872
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM 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 General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Class Foam::motionSmoother Description Given a displacement moves the mesh by scaling the displacement back until there are no more mesh errors. Holds displacement field (read upon construction since need boundary conditions) and scaling factor and optional patch number on which to scale back displacement. E.g. @verbatim // Construct iterative mesh mover. motionSmoother meshMover(mesh, labelList(1, patchI)); // Set desired displacement: meshMover.displacement() = .. for (label iter = 0; iter < maxIter; iter++) { if (meshMover.scaleMesh(true)) { Info<< "Successfully moved mesh" << endl; return true; } } @endverbatim Note - Shared points (parallel): a processor can have points which are part of pp on another processor but have no pp itself (i.e. it has points and/or edges but no faces of pp). Hence we have to be careful when e.g. synchronising displacements that the value from the processor which has faces of pp get priority. This is currently handled in setDisplacement by resetting the internal displacement to zero before doing anything else. The combine operator used will give preference to non-zero values. - Various routines take baffles. These are sets of boundary faces that are treated as a single internal face. This is a hack used to apply movement to internal faces. - Mesh constraints are looked up from the supplied dictionary. (uses recursive lookup) SourceFiles motionSmoother.C motionSmootherTemplates.C \*---------------------------------------------------------------------------*/ #ifndef motionSmoother_H #define motionSmoother_H #include "pointFields.H" #include "HashSet.H" #include "PackedBoolList.H" #include "indirectPrimitivePatch.H" #include "className.H" #include "twoDPointCorrector.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { class polyMeshGeometry; class faceSet; /*---------------------------------------------------------------------------*\ Class motionSmoother Declaration \*---------------------------------------------------------------------------*/ class motionSmoother { // Private class //- To synchronise displacements. We want max displacement since // this is what is specified on pp and internal mesh will have // zero displacement. class maxMagEqOp { public: void operator()(vector& x, const vector& y) const { for (direction i = 0; i < vector::nComponents; i++) { scalar magX = mag(x[i]); scalar magY = mag(y[i]); if (magX < magY) { x[i] = y[i]; } else if (magX == magY) { if (y[i] > x[i]) { x[i] = y[i]; } } } } }; // Private data //- Reference to polyMesh. Non-const since we move mesh. polyMesh& mesh_; //- Reference to pointMesh pointMesh& pMesh_; //- Reference to face subset of all adaptPatchIDs indirectPrimitivePatch& pp_; //- Indices of fixedValue patches that we're allowed to modify the // displacement on. const labelList adaptPatchIDs_; // Smoothing and checking parameters dictionary paramDict_; // Internal data //- Displacement field pointVectorField displacement_; //- Scale factor for displacement pointScalarField scale_; //- Starting mesh position pointField oldPoints_; //- Is mesh point on boundary or not PackedBoolList isInternalPoint_; //- Is edge master (always except if on coupled boundary and on // lower processor) PackedBoolList isMasterEdge_; //- 2-D motion corrector twoDPointCorrector twoDCorrector_; // Muli-patch constraints (from pointPatchInterpolation) labelList patchPatchPointConstraintPoints_; tensorField patchPatchPointConstraintTensors_; // Private Member Functions //- Average of connected points. template <class Type> tmp<GeometricField<Type, pointPatchField, pointMesh> > avg ( const GeometricField<Type, pointPatchField, pointMesh>& fld, const scalarField& edgeWeight, const bool separation ) const; //- Check constraints template<class Type> static void checkConstraints ( GeometricField<Type, pointPatchField, pointMesh>& ); //- Multi-patch constraints template<class Type> void applyCornerConstraints ( GeometricField<Type, pointPatchField, pointMesh>& ) const; //- Test synchronisation of pointField template<class Type, class CombineOp> void testSyncField ( const Field<Type>&, const CombineOp& cop, const Type& zero, const bool separation, const scalar maxMag ) const; //- Assemble tensors for multi-patch constraints void makePatchPatchAddressing(); static void checkFld(const pointScalarField&); //- Get points used by given faces labelHashSet getPoints(const labelHashSet&) const; //- explicit smoothing and min on all affected internal points void minSmooth ( const PackedBoolList& isAffectedPoint, const pointScalarField& fld, pointScalarField& newFld ) const; //- same but only on selected points (usually patch points) void minSmooth ( const PackedBoolList& isAffectedPoint, const labelList& meshPoints, const pointScalarField& fld, pointScalarField& newFld ) const; //- Scale certain (internal) points of a field void scaleField ( const labelHashSet& pointLabels, const scalar scale, pointScalarField& ) const; //- As above but points have to be in meshPoints as well // (usually to scale patch points) void scaleField ( const labelList& meshPoints, const labelHashSet& pointLabels, const scalar scale, pointScalarField& ) const; //- Helper function. Is point internal? bool isInternalPoint(const label pointI) const; //- Given a set of faces that cause smoothing and a number of // iterations determine the maximum set of points who are affected // and the accordingly affected faces. void getAffectedFacesAndPoints ( const label nPointIter, const faceSet& wrongFaces, labelList& affectedFaces, PackedBoolList& isAffectedPoint ) const; //- Disallow default bitwise copy construct motionSmoother(const motionSmoother&); //- Disallow default bitwise assignment void operator=(const motionSmoother&); public: ClassName("motionSmoother"); // Constructors //- Construct from mesh, patches to work on and smoothing parameters. // Reads displacement field (only boundary conditions used) motionSmoother ( polyMesh&, pointMesh&, indirectPrimitivePatch& pp, // 'outside' points const labelList& adaptPatchIDs, // patches forming 'outside' const dictionary& paramDict ); //- Construct from mesh, patches to work on and smoothing parameters // and displacement field (only boundary conditions used) motionSmoother ( polyMesh&, indirectPrimitivePatch& pp, // 'outside' points const labelList& adaptPatchIDs, // patches forming 'outside' const pointVectorField&, const dictionary& paramDict ); // Destructor ~motionSmoother(); // Member Functions // Access //- Reference to mesh const polyMesh& mesh() const; //- Reference to pointMesh const pointMesh& pMesh() const; //- Reference to patch const indirectPrimitivePatch& patch() const; //- Patch labels that are being adapted const labelList& adaptPatchIDs() const; const dictionary& paramDict() const; //- Reference to displacement field pointVectorField& displacement(); //- Reference to displacement field const pointVectorField& displacement() const; //- Reference to scale field const pointScalarField& scale() const; //- Starting mesh position const pointField& oldPoints() const; //- Return reference to 2D point motion correction twoDPointCorrector& twoDCorrector() { return twoDCorrector_; } // Edit //- Take over existing mesh position. void correct(); //- Set displacement field from displacement on patch points. // Modify provided displacement to be consistent with actual // boundary conditions on displacement. Note: resets the // displacement to be 0 on coupled patches beforehand // to make sure shared points // partially on pp (on some processors) and partially not // (on other processors) get the value from pp. void setDisplacement(pointField& patchDisp); //- Special correctBoundaryConditions which evaluates fixedValue // patches first so they get overwritten with any constraint // bc's. void correctBoundaryConditions(pointVectorField&) const; //- Move mesh. Does 2D correction (modifies passed pointField) and // polyMesh::movePoints. Returns swept volumes. tmp<scalarField> movePoints(pointField&); //- Set the errorReduction (by how much to scale the displacement // at error locations) parameter. Returns the old value. // Set to 0 (so revert to old mesh) grows out one cell layer // from error faces. scalar setErrorReduction(const scalar); //- Move mesh with given scale. Return true if mesh ok or has // less than nAllow errors, false // otherwise and locally update scale. Smoothmesh=false means only // patch points get moved. // Parallel ok (as long as displacement field is consistent // across patches) bool scaleMesh ( labelList& checkFaces, const bool smoothMesh = true, const label nAllow = 0 ); //- Move mesh (with baffles) with given scale. bool scaleMesh ( labelList& checkFaces, const List<labelPair>& baffles, const bool smoothMesh = true, const label nAllow = 0 ); //- Move mesh with externally provided mesh constraints bool scaleMesh ( labelList& checkFaces, const List<labelPair>& baffles, const dictionary& paramDict, const dictionary& meshQualityDict, const bool smoothMesh = true, const label nAllow = 0 ); //- Update topology void updateMesh(); //- Check mesh with mesh settings in dict. Collects incorrect faces // in set. Returns true if one or more faces in error. // Parallel ok. static bool checkMesh ( const bool report, const polyMesh& mesh, const dictionary& dict, labelHashSet& wrongFaces ); //- Check (subset of mesh) with mesh settings in dict. // Collects incorrect faces in set. Returns true if one // or more faces in error. Parallel ok. static bool checkMesh ( const bool report, const polyMesh& mesh, const dictionary& dict, const labelList& checkFaces, labelHashSet& wrongFaces ); //- Check (subset of mesh including baffles) with mesh settings // in dict. Collects incorrect faces in set. Returns true if one // or more faces in error. Parallel ok. static bool checkMesh ( const bool report, const polyMesh& mesh, const dictionary& dict, const labelList& checkFaces, const List<labelPair>& baffles, labelHashSet& wrongFaces ); //- Check part of mesh with mesh settings in dict. // Collects incorrect faces in set. Returns true if one or // more faces in error. Parallel ok. static bool checkMesh ( const bool report, const dictionary& dict, const polyMeshGeometry&, const labelList& checkFaces, labelHashSet& wrongFaces ); //- Check part of mesh including baffles with mesh settings in dict. // Collects incorrect faces in set. Returns true if one or // more faces in error. Parallel ok. static bool checkMesh ( const bool report, const dictionary& dict, const polyMeshGeometry&, const labelList& checkFaces, const List<labelPair>& baffles, labelHashSet& wrongFaces ); // Helper functions to manipulate displacement vector. //- Fully explicit smoothing of internal points with varying // diffusivity. template <class Type> void smooth ( const GeometricField<Type, pointPatchField, pointMesh>& fld, const scalarField& edgeWeight, const bool separation, GeometricField<Type, pointPatchField, pointMesh>& newFld ) const; }; template<> void motionSmoother::applyCornerConstraints<scalar> ( GeometricField<scalar, pointPatchField, pointMesh>& pf ) const; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "motionSmootherTemplates.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
CFDEMproject/OpenFOAM-1.6-ext
src/dynamicMesh/dynamicMesh/motionSmoother/motionSmoother.H
C++
gpl-2.0
16,715
<?php // MyDMS. Document Management System // Copyright (C) 2010 Matteo Lucarelli // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. include("../inc/inc.Settings.php"); include("../inc/inc.Language.php"); include("../inc/inc.Init.php"); include("../inc/inc.Extension.php"); include("../inc/inc.DBInit.php"); include("../inc/inc.ClassUI.php"); include("../inc/inc.Calendar.php"); include("../inc/inc.Authentication.php"); if (!isset($_GET["id"])){ UI::exitError(getMLText("event_details"),getMLText("error_occured")); } $event=getEvent(intval($_GET["id"])); if (is_bool($event)&&!$event){ UI::exitError(getMLText("event_details"),getMLText("error_occured")); } $tmp = explode('.', basename($_SERVER['SCRIPT_FILENAME'])); $view = UI::factory($theme, $tmp[1], array('dms'=>$dms, 'user'=>$user, 'event'=>$event)); if($view) { $view->show(); exit; } ?>
bedla/seeddms
out/out.ViewEvent.php
PHP
gpl-2.0
1,546
<?php /** * WordPress 内置嵌套评论专用 Ajax comments >> WordPress-jQuery-Ajax-Comments v1.3 by Willin Kan. * * 说明: 这个文件是由 WP 3.0 根目录的 wp-comment-post.php 修改的, 修改的地方有注解. 当 WP 升级, 请注意可能有所不同. */ if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) { header('Allow: POST'); header('HTTP/1.1 405 Method Not Allowed'); header('Content-Type: text/plain'); exit; } /** Sets up the WordPress Environment. */ require( dirname(__FILE__) . '/../../../wp-load.php' ); // 此 comments-ajax.php 位于主题数据夹,所以位置已不同 nocache_headers(); $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0; $post = get_post($comment_post_ID); if ( empty($post->comment_status) ) { do_action('comment_id_not_found', $comment_post_ID); err(__('Invalid comment status.')); // 将 exit 改为错误提示 } // get_post_status() will get the parent status for attachments. $status = get_post_status($post); $status_obj = get_post_status_object($status); if ( !comments_open($comment_post_ID) ) { do_action('comment_closed', $comment_post_ID); err(__('Sorry, comments are closed for this item.')); // 将 wp_die 改为错误提示 } elseif ( 'trash' == $status ) { do_action('comment_on_trash', $comment_post_ID); err(__('Invalid comment status.')); // 将 exit 改为错误提示 } elseif ( !$status_obj->public && !$status_obj->private ) { do_action('comment_on_draft', $comment_post_ID); err(__('Invalid comment status.')); // 将 exit 改为错误提示 } elseif ( post_password_required($comment_post_ID) ) { do_action('comment_on_password_protected', $comment_post_ID); err(__('Password Protected')); // 将 exit 改为错误提示 } else { do_action('pre_comment_on_post', $comment_post_ID); } $comment_author = ( isset($_POST['author']) ) ? trim(strip_tags($_POST['author'])) : null; $comment_author_email = ( isset($_POST['email']) ) ? trim($_POST['email']) : null; $comment_author_url = ( isset($_POST['url']) ) ? trim($_POST['url']) : null; $comment_content = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null; $edit_id = ( isset($_POST['edit_id']) ) ? $_POST['edit_id'] : null; // 提取 edit_id // If the user is logged in $user = wp_get_current_user(); if ( $user->ID ) { if ( empty( $user->display_name ) ) $user->display_name=$user->user_login; $comment_author = $wpdb->escape($user->display_name); $comment_author_email = $wpdb->escape($user->user_email); $comment_author_url = $wpdb->escape($user->user_url); if ( current_user_can('unfiltered_html') ) { if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) { kses_remove_filters(); // start with a clean slate kses_init_filters(); // set up the filters } } } else { if ( get_option('comment_registration') || 'private' == $status ) err(__('对不起,您必须登录后才能发表评论。')); // 将 wp_die 改为错误提示 } $comment_type = ''; if ( get_option('require_name_email') && !$user->ID ) { if ( 6 > strlen($comment_author_email) || '' == $comment_author ) err( __('提示:必须填写昵称及邮件。') ); // 将 wp_die 改为错误提示 elseif ( !is_email($comment_author_email)) err( __('提示:请输入一个有效的电子邮件地址。') );// 将 wp_die 改为错误提示 } if ( '' == $comment_content ) err( __('提示:请输入评论内容。') ); // 将 wp_die 改为错误提示 // 增加: 错误提示功能 function err($ErrMsg) { header('HTTP/1.1 405 Method Not Allowed'); echo $ErrMsg; exit; } // 检查重复评论功能 $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' "; if ( $comment_author_email ) $dupe .= "OR comment_author_email = '$comment_author_email' "; $dupe .= ") AND comment_content = '$comment_content' LIMIT 1"; if ( $wpdb->get_var($dupe) ) { err(__('Duplicate comment detected; it looks as though you&#8217;ve already said that!')); } // 检查评论太快功能 if ( $lasttime = $wpdb->get_var( $wpdb->prepare("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author) ) ) { $time_lastcomment = mysql2date('U', $lasttime, false); $time_newcomment = mysql2date('U', current_time('mysql', 1), false); $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment); if ( $flood_die ) { err(__('您发表评论也太快了')); } } $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0; $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID'); // 检查评论是否正被编辑, 更新或新建评论 if ( $edit_id ){ $comment_id = $commentdata['comment_ID'] = $edit_id; wp_update_comment( $commentdata ); } else { $comment_id = wp_new_comment( $commentdata ); } $comment = get_comment($comment_id); if ( !$user->ID ) { $comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000); setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); } //$location = empty($_POST['redirect_to']) ? get_comment_link($comment_id) : $_POST['redirect_to'] . '#comment-' . $comment_id; //取消原有的刷新重定向 //$location = apply_filters('comment_post_redirect', $location, $comment); //wp_redirect($location); $comment_depth = 1; //为评论的 class 属性准备的 $tmp_c = $comment; while($tmp_c->comment_parent != 0){ $comment_depth++; $tmp_c = get_comment($tmp_c->comment_parent); } //以下是评论式样, 不含 "回复". ?> <li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>"> <div id="comment-<?php comment_ID(); ?>"> <div class="comment-author"> <div id="avatar"><?php echo get_avatar( $comment, 48 ); ?></div> <?php printf( __( '<span class="says">%s:</span>'), get_comment_author_link() ); ?> </div> <div class="comment-meta commentmetadata"> <a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>"><?php printf( __( '%1$s at %2$s' ), get_comment_date(), get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)' ), ' ' ); ?> <?php if ( $comment->comment_approved == '0' ) : ?> <font color=Red>您的评论需要管理员审核...</font> <?php endif; ?> </div> <div class="comment-body"><?php comment_text(); ?></div> </div>
zhuyicun/zyc
wp-content/themes/ZruckMetro/ZruckMetro/comments-ajax.php
PHP
gpl-2.0
6,949
<?php /** * @package Joomla.Installation * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * * @since 3.0.x */ defined('_JEXEC') or die; jimport('joomla.updater.update'); /** * Language Installer model for the Joomla Core Installer. * * @package Joomla.Installation * @since 3.0 */ class InstallationModelLanguages extends JModelLegacy { /** * @var object Client object * @since 3.0 */ protected $client = null; /** * @var array Languages description * @since 3.0 */ protected $data = null; /** * @var string Language path * @since 3.0 */ protected $path = null; /** * @var integer Total number of languages installed * @since 3.0 */ protected $langlist = null; /** * Constructor * * Deletes the default installation config file and recreates it with the good config file. * * @since 3.0 */ public function __construct() { // Overrides application config and set the configuration.php file so tokens and database works JFactory::$config = null; JFactory::getConfig(JPATH_SITE . '/configuration.php'); JFactory::$session = null; parent::__construct(); } /** * Generate a list of language choices to install in the Joomla CMS * * @return boolean True if successful * * @since 3.0 */ public function getItems() { $updater = JUpdater::getInstance(); /* * The following function uses extension_id 600, that is the English language extension id. * In #__update_sites_extensions you should have 600 linked to the Accredited Translations Repo */ $updater->findUpdates(array(600), 0); $db = JFactory::getDbo(); $query = $db->getQuery(true); // Select the required fields from the updates table $query->select('update_id, name, version') ->from('#__updates') ->order('name'); $db->setQuery($query); $list = $db->loadObjectList(); if (!$list || $list instanceof Exception) { $list = array(); } return $list; } /** * Method that installs in Joomla! the selected languages in the Languages View of the installer * * @param array $lids list of the update_id value of the languages to install * * @return boolean True if successful */ public function install($lids) { $app = JFactory::getApplication(); $installer = JInstaller::getInstance(); // Loop through every selected language foreach ($lids as $id) { // Loads the update database object that represents the language $language = JTable::getInstance('update'); $language->load($id); // Get the url to the XML manifest file of the selected language $remote_manifest = $this->getLanguageManifest($id); if (!$remote_manifest) { // Could not find the url, the information in the update server may be corrupt $message = JText::sprintf('INSTL_DEFAULTLANGUAGE_COULD_NOT_INSTALL_LANGUAGE', $language->name); $message .= ' ' . JText::_('INSTL_DEFAULTLANGUAGE_TRY_LATER'); $app->enqueueMessage($message); continue; } // Based on the language XML manifest get the url of the package to download $package_url = $this->getPackageUrl($remote_manifest); if (!$package_url) { // Could not find the url , maybe the url is wrong in the update server, or there is not internet access $message = JText::sprintf('INSTL_DEFAULTLANGUAGE_COULD_NOT_INSTALL_LANGUAGE', $language->name); $message .= ' ' . JText::_('INSTL_DEFAULTLANGUAGE_TRY_LATER'); $app->enqueueMessage($message); continue; } // Download the package to the tmp folder $package = $this->downloadPackage($package_url); // Install the package if (!$installer->install($package['dir'])) { // There was an error installing the package $message = JText::sprintf('INSTL_DEFAULTLANGUAGE_COULD_NOT_INSTALL_LANGUAGE', $language->name); $message .= ' ' . JText::_('INSTL_DEFAULTLANGUAGE_TRY_LATER'); $app->enqueueMessage($message); continue; } // Cleanup the install files in tmp folder if (!is_file($package['packagefile'])) { $config = JFactory::getConfig(); $package['packagefile'] = $config->get('tmp_path') . '/' . $package['packagefile']; } JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']); // Delete the installed language from the list $language->delete($id); } return true; } /** * Gets the manifest file of a selected language from a the language list in a update server. * * @param integer $uid The id of the language in the #__updates table * * @return string * * @since 3.0 */ protected function getLanguageManifest($uid) { $instance = JTable::getInstance('update'); $instance->load($uid); $detailurl = trim($instance->detailsurl); return $detailurl; } /** * Finds the url of the package to download. * * @param string $remote_manifest url to the manifest XML file of the remote package * * @return string|bool * * @since 3.0 */ protected function getPackageUrl($remote_manifest) { $update = new JUpdate; $update->loadFromXML($remote_manifest); $package_url = trim($update->get('downloadurl', false)->_data); return $package_url; } /** * Download a language package from a URL and unpack it in the tmp folder. * * @param string $url url of the package * * @return array|bool Package details or false on failure * * @since 3.0 */ protected function downloadPackage($url) { // Download the package from the given URL $p_file = JInstallerHelper::downloadPackage($url); // Was the package downloaded? if (!$p_file) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_INVALID_URL')); return false; } $config = JFactory::getConfig(); $tmp_dest = $config->get('tmp_path'); // Unpack the downloaded package file $package = JInstallerHelper::unpack($tmp_dest . '/' . $p_file); return $package; } /** * Method to get Languages item data for the Administrator * * @return array * * @since 3.0 */ public function getInstalledlangsAdministrator() { return $this->getInstalledlangs('administrator'); } /** * Method to get Languages item data for the Frontend * * @return array * * @since 3.0 */ public function getInstalledlangsFrontend() { return $this->getInstalledlangs('site'); } /** * Method to get Languages item data * * @param string $cms_client name of the cms client * * @return array * * @since 3.0 */ protected function getInstalledlangs($cms_client = 'administrator') { // Get information $path = $this->getPath(); $client = $this->getClient($cms_client); $langlist = $this->getLanguageList($client->id); // Compute all the languages $data = array(); foreach ($langlist as $lang) { $file = $path . '/' . $lang . '/' . $lang . '.xml'; $info = JInstaller::parseXMLInstallFile($file); $row = new stdClass; $row->language = $lang; if (!is_array($info)) { continue; } foreach ($info as $key => $value) { $row->$key = $value; } // If current then set published $params = JComponentHelper::getParams('com_languages'); if ($params->get($client->name, 'en-GB') == $row->language) { $row->published = 1; } else { $row->published = 0; } $row->checked_out = 0; $data[] = $row; } usort($data, array($this, 'compareLanguages')); return $data; } /** * Method to get installed languages data. * * @param integer $client_id The client ID to retrieve data for * * @return object The language data * * @since 3.0 */ protected function getLanguageList($client_id = 1) { // Create a new db object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select field element from the extensions table. $query->select('a.element, a.name'); $query->from('#__extensions AS a'); $query->where('a.type = ' . $db->quote('language')); $query->where('state = 0'); $query->where('enabled = 1'); $query->where('client_id=' . (int) $client_id); $db->setQuery($query); $this->langlist = $db->loadColumn(); return $this->langlist; } /** * Method to compare two languages in order to sort them * * @param object $lang1 the first language * @param object $lang2 the second language * * @return integer * * @since 3.0 */ protected function compareLanguages($lang1, $lang2) { return strcmp($lang1->name, $lang2->name); } /** * Method to get the path * * @return string The path to the languages folders * * @since 3.0 */ protected function getPath() { if (is_null($this->path)) { $client = $this->getClient(); $this->path = JLanguage::getLanguagePath($client->path); } return $this->path; } /** * Method to get the client object of Administrator or FrontEnd * * @param string $client name of the client object * * @return object * * @since 3.0 */ protected function getClient($client = null) { if (null == $this->client) { $this->client = JApplicationHelper::getClientInfo('administrator', true); } if ($client) { $this->client = JApplicationHelper::getClientInfo($client, true); } return $this->client; } /** * Method to set the default language. * * @param integer $language_id The Id of the language to be set as default * @param string $cms_client The name of the CMS client * * @return boolean * * @since 3.0 */ public function setDefault($language_id = null, $cms_client = "administrator") { if (!$language_id) { return false; } $client = $this->getClient($cms_client); $params = JComponentHelper::getParams('com_languages'); $params->set($client->name, $language_id); $table = JTable::getInstance('extension'); $id = $table->find(array('element' => 'com_languages')); // Load if (!$table->load($id)) { $this->setError($table->getError()); return false; } $table->params = (string) $params; // Pre-save checks if (!$table->check()) { $this->setError($table->getError()); return false; } // Save the changes if (!$table->store()) { $this->setError($table->getError()); return false; } return true; } /** * Get the current setup options from the session. * * @return array * * @since 3.0 */ public function getOptions() { $session = JFactory::getSession(); $options = $session->get('setup.options', array()); return $options; } }
syahidhaqiqy/tugas1
installation/models/languages.php
PHP
gpl-2.0
10,662
package com.study.thread; /** * Created by guobing on 2016/8/2. */ public class GenerThread extends Thread { public void run() { System.out.println(Thread.currentThread().getName() + " - General thread"); } synchronized public void GServer() { System.out.println(Thread.currentThread().getName() + " - General Server"); } }
guobingwei/guobing
src/main/java/com/study/thread/GenerThread.java
Java
gpl-2.0
360
<?php /* Copyright [2011, 2012, 2013] da Universidade Federal de Juiz de Fora * Este arquivo é parte do programa Framework Maestro. * O Framework Maestro é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da Licença Pública Geral GNU como publicada * pela Fundação do Software Livre (FSF); na versão 2 da Licença. * Este programa é distribuído na esperança que possa ser útil, * mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer * MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/GPL * em português para maiores detalhes. * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título * "LICENCA.txt", junto com este programa, se não, acesse o Portal do Software * Público Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a * Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301, USA. */ namespace Maestro\Types; use Maestro\Manager; /** * Classe utilitária para trabalhar com valores monetários. * Métodos para formatar e validar strings representando valores monetários. * * @category Maestro * @package Core * @subpackage Types * @version 1.0 * @since 1.0 */ class MCurrency extends MType { private $value; public function __construct($value) { $this->setValue($value); } private function getValueFromString($value){ $l = localeConv(); $sign = (strpos($value,$l['negative_sign']) !== false) ? -1 : 1; $value = strtr($value,$l['positive_sign'].$l['negative_sign'].'()', ' '); $value = str_replace(' ', '', $value); $value = str_replace($l['currency_symbol'], '', $value); $value = str_replace($l['mon_thousands_sep'], '', $value); $value = str_replace($l['mon_decimal_point'], '.', $value); return (float) ($value * $sign); } public function getValue() { return $this->value ? : (float) 0.0; } public function setValue($value) { if ($value instanceof MCurrency){ $value = $value->getValue(); } $this->value = (is_numeric($value) ? round($value, 2,PHP_ROUND_HALF_DOWN) : (is_string($value) ? $this->getValueFromString($value) : 0.0)) ; } public function format() { $l = localeConv(); // Sign specifications: if ($this->value >= 0) { $sign = $l['positive_sign']; $sign_posn = $l['p_sign_posn']; $sep_by_space = $l['p_sep_by_space']; $cs_precedes = $l['p_cs_precedes']; } else { $sign = $l['negative_sign']; $sign_posn = $l['n_sign_posn']; $sep_by_space = $l['n_sep_by_space']; $cs_precedes = $l['n_cs_precedes']; } // Currency format: $m = number_format(abs($this->value), $l['frac_digits'], $l['mon_decimal_point'], $l['mon_thousands_sep']); if ($sep_by_space) { $space = ' '; } else { $space = ''; } if ($cs_precedes) { $m = $l['currency_symbol'] . $space . $m; } else { $m = $m . $space . $l['currency_symbol']; } switch ($sign_posn) { case 0: $m = "($m)"; break; case 1: $m = "$sign$m"; break; case 2: $m = "$m$sign"; break; case 3: $m = "$sign$m"; break; case 4: $m = "$m$sign"; break; default: $m = "$m [error sign_posn=$sign_posn&nbsp;!]"; } return $m; } public function formatValue() { $l = localeConv(); // Sign specifications: if ($this->value >= 0) { $sign = $l['positive_sign']; $sign_posn = $l['p_sign_posn']; } else { $sign = $l['negative_sign']; $sign_posn = $l['n_sign_posn']; } // Currency format: $m = number_format(abs($this->value), $l['frac_digits'], $l['mon_decimal_point'], $l['mon_thousands_sep']); switch ($sign_posn) { case 0: $m = "($m)"; break; case 1: $m = "$sign$m"; break; case 2: $m = "$m$sign"; break; case 3: $m = "$sign$m"; break; case 4: $m = "$m$sign"; break; default: $m = "$m [error sign_posn=$sign_posn&nbsp;!]"; } return $m; } public function getPlainValue(){ return $this->getValue(); } public function __toString() { return $this->format(); } } ?>
HexSource/maestro2
Maestro/Types/MCurrency.php
PHP
gpl-2.0
4,886
/*************************************************************************** qgslegenditem.cpp --------------------- begin : January 2007 copyright : (C) 2007 by Martin Dobias email : wonder.sk at gmail.com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgslegenditem.h" #include <QCoreApplication> #include "qgslegend.h" #include "qgslogger.h" QgsLegendItem::QgsLegendItem( QTreeWidgetItem * theItem, QString theName ) : QTreeWidgetItem( theItem ) { setText( 0, theName ); } QgsLegendItem::QgsLegendItem( QTreeWidget* theListView, QString theString ) : QTreeWidgetItem( theListView ) { setText( 0, theString ); } QgsLegendItem::QgsLegendItem(): QTreeWidgetItem() { } QgsLegendItem::~QgsLegendItem() { } void QgsLegendItem::print( QgsLegendItem * theItem ) { #if 0 //todo: adapt to qt4 Q3ListViewItemIterator myIterator( theItem ); while ( myIterator.current() ) { LEGEND_ITEM_TYPE curtype = qobject_cast<QgsLegendItem *>( myIterator.current() )->type(); QgsDebugMsg( QString( "%1 - %2" ).arg( myIterator.current()->text( 0 ) ).arg( curtype ) ); if ( myIterator.current()->childCount() > 0 ) { //print(qobject_cast<QgsLegendItem *>(myIterator.current())); } ++myIterator; } #else Q_UNUSED( theItem ); #endif } QgsLegendItem* QgsLegendItem::firstChild() { return dynamic_cast<QgsLegendItem *>( child( 0 ) ); } QgsLegendItem* QgsLegendItem::nextSibling() { return dynamic_cast<QgsLegendItem *>( dynamic_cast<QgsLegend*>( treeWidget() )->nextSibling( this ) ); } QgsLegendItem* QgsLegendItem::findYoungerSibling() { return dynamic_cast<QgsLegendItem *>( dynamic_cast<QgsLegend*>( treeWidget() )->previousSibling( this ) ); } void QgsLegendItem::moveItem( QgsLegendItem* after ) { qobject_cast<QgsLegend *>( treeWidget() )->moveItem( this, after ); } void QgsLegendItem::removeAllChildren() { while ( child( 0 ) ) { takeChild( 0 ); } } void QgsLegendItem::storeAppearanceSettings() { mExpanded = treeWidget()->isItemExpanded( this ); mHidden = treeWidget()->isItemHidden( this ); //call recursively for all subitems for ( int i = 0; i < childCount(); ++i ) { static_cast<QgsLegendItem*>( child( i ) )->storeAppearanceSettings(); } } void QgsLegendItem::restoreAppearanceSettings() { treeWidget()->setItemExpanded( this, mExpanded ); treeWidget()->setItemHidden( this, mHidden ); //call recursively for all subitems for ( int i = 0; i < childCount(); ++i ) { static_cast<QgsLegendItem*>( child( i ) )->restoreAppearanceSettings(); } } QgsLegend* QgsLegendItem::legend() const { QTreeWidget* treeWidgetPtr = treeWidget(); QgsLegend* legendPtr = qobject_cast<QgsLegend *>( treeWidgetPtr ); return legendPtr; } QTreeWidgetItem* QgsLegendItem::child( int i ) const { return QTreeWidgetItem::child( i ); } QTreeWidgetItem* QgsLegendItem::parent() const { return QTreeWidgetItem::parent(); } void QgsLegendItem::insertChild( int index, QTreeWidgetItem *child ) { QTreeWidgetItem::insertChild( index, child ); }
polymeris/qgis
src/app/legend/qgslegenditem.cpp
C++
gpl-2.0
3,673
//#include "stdafx.h" #include <pnl_dll.hpp> #include <boost/smart_ptr.hpp> #include <iostream> namespace { namespace local { // [ref] testGetFactorsMRF2() in ${PNL_ROOT}/c_pgmtk/tests/src/AGetParametersTest.cpp pnl::CMRF2 * create_simple_pairwise_mrf() { const int numNodes = 7; const int numNodeTypes = 2; const int numCliques = 6; #if 0 const int cliqueSizes[] = { 2, 2, 2, 2, 2, 2 }; const int clique0[] = { 0, 1 }; const int clique1[] = { 1, 2 }; const int clique2[] = { 1, 3 }; const int clique3[] = { 2, 4 }; const int clique4[] = { 2, 5 }; const int clique5[] = { 3, 6 }; const int *cliques[] = { clique0, clique1, clique2, clique3, clique4, clique5 }; pnl::CNodeType *nodeTypes = new pnl::CNodeType [numNodeTypes]; nodeTypes[0].SetType(true, 3); nodeTypes[1].SetType(true, 4); int *nodeAssociation = new int [numNodes]; for (int i = 0; i < numNodes; ++i) nodeAssociation[i] = i % 2; pnl::CMRF2 *mrf2 = pnl::CMRF2::Create(numNodes, numNodeTypes, nodeTypes, nodeAssociation, numCliques, cliqueSizes, cliques); #else pnl::intVecVector cliques; { const int clique0[] = { 0, 1 }; const int clique1[] = { 1, 2 }; const int clique2[] = { 1, 3 }; const int clique3[] = { 2, 4 }; const int clique4[] = { 2, 5 }; const int clique5[] = { 3, 6 }; cliques.push_back(pnl::intVector(clique0, clique0 + sizeof(clique0) / sizeof(clique0[0]))); cliques.push_back(pnl::intVector(clique1, clique1 + sizeof(clique1) / sizeof(clique1[0]))); cliques.push_back(pnl::intVector(clique2, clique2 + sizeof(clique2) / sizeof(clique2[0]))); cliques.push_back(pnl::intVector(clique3, clique3 + sizeof(clique3) / sizeof(clique3[0]))); cliques.push_back(pnl::intVector(clique4, clique4 + sizeof(clique4) / sizeof(clique4[0]))); cliques.push_back(pnl::intVector(clique5, clique5 + sizeof(clique5) / sizeof(clique5[0]))); } //pnl::nodeTypeVector nodeTypes; //nodeTypes.push_back(pnl::CNodeType(true, 3)); //nodeTypes.push_back(pnl::CNodeType(true, 4)); pnl::nodeTypeVector nodeTypes(numNodeTypes); nodeTypes[0].SetType(true, 3); nodeTypes[1].SetType(true, 4); pnl::intVector nodeAssociation(numNodes); for (int i = 0; i < numNodes; ++i) nodeAssociation[i] = i % 2; pnl::CMRF2 *mrf2 = pnl::CMRF2::Create(numNodes, nodeTypes, nodeAssociation, cliques); #endif mrf2->AllocFactors(); for (int i = 0; i < numCliques; ++i) mrf2->AllocFactor(i); // get content of Graph mrf2->GetGraph()->Dump(); // const int numQueries = 13; const int queryLength[] = { 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }; const int queries[13][2] = { { 0 }, { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }, { 0, 1 }, { 1, 3 }, { 1, 2 }, { 4, 2 }, { 2, 5 }, { 6, 3 } }; pnl::pFactorVector params; for (int i = 0; i < numQueries; ++i) { mrf2->GetFactors(queryLength[i], queries[i], &params); // TODO [add] >> params.clear(); } #if 0 delete [] nodeAssociation; delete [] nodeTypes; #endif return mrf2; } } // namespace local } // unnamed namespace namespace my_pnl { void mrf_example() { // simple pairwise MRF std::cout << "========== simple pairwise MRF" << std::endl; { const boost::scoped_ptr<pnl::CMRF2> mrf2(local::create_simple_pairwise_mrf()); if (!mrf2) { std::cout << "fail to create a probabilistic graphical model at " << __LINE__ << " in " << __FILE__ << std::endl; return; } } } } // namespace my_pnl
sangwook236/general-development-and-testing
sw_dev/cpp/rnd/test/probabilistic_graphical_model/pnl/pnl_mrf_example.cpp
C++
gpl-2.0
3,533
// // Author: Vladimir Migashko <migashko@faslib.com>, (C) 2007 // // Copyright: See COPYING file that comes with this distribution // #ifndef FAS_SYSTEM_SYSTEM_H #define FAS_SYSTEM_SYSTEM_H #include <fas/unp.h> #include <fas/system/types.hpp> #include <errno.h> #include <string> #include <cstdlib> #include <stdexcept> namespace fas{ namespace system { inline int error_code() { #ifdef WIN32 return ::GetLastError(); #else return errno; #endif } inline std::string strerror(int lasterror) { #ifdef WIN32 LPVOID lpMsgBuf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lasterror, 0, // Default language (LPSTR) &lpMsgBuf, 0, NULL ); char errbuf[256] = {0}; _snprintf(errbuf, 255, "%d - %s", lasterror, reinterpret_cast<char*>(lpMsgBuf)); LocalFree( lpMsgBuf ); return errbuf; /* std::string message; message = reinterpret_cast<char*>(lpMsgBuf); LocalFree( lpMsgBuf ); return message; */ #else return ::strerror(lasterror); #endif } struct system_error : public std::runtime_error { explicit system_error(const std::string& msg) : std::runtime_error(msg + strerror(error_code())) { } }; inline ssize_t read(const descriptor_t& d, char* buff, size_t s) { #ifndef WIN32 ssize_t ret = ::read(d, buff, s); #else ssize_t ret = ::_read(d, buff, static_cast<unsigned int>(s)); #endif if ( ret < 0 ) { #ifndef WIN32 int err = error_code(); if (err==EWOULDBLOCK || err==EAGAIN || err == EINTR ) return ret; else if (err==EBADF || err == EFAULT || err==EINVAL || err == ENOMEM || err == ENOTCONN || err == ENOTSOCK) throw system_error("fas::system::read/_read: "); else return 0; #endif throw system_error("fas::system::read/_read: "); } return ret; } inline ssize_t write(const descriptor_t& d, const char* buff, size_t s) { #ifndef WIN32 ssize_t ret = ::write(d, buff, s); #else ssize_t ret = ::_write(d, buff, static_cast<unsigned int>(s) ); #endif if ( ret < 0 ) { #ifndef WIN32 int err = error_code(); if ( err==EWOULDBLOCK || err==EAGAIN || err == EINTR )return ret; else if (err==EBADF || err == EFAULT || err==EINVAL || err == ENOMEM || err == ENOTCONN || err == ENOTSOCK) { throw system_error("fas::system::_write/write: "); } else return 0; #endif throw system_error("fas::system::write/_write: "); } return ret; } inline void close(const descriptor_t& d) { #ifdef WIN32 if ( -1 == ::_close(d)) #else if ( -1 == ::close(d)) #endif throw system_error("fas::system::close: ");; } inline void sleep(int ms) { #ifdef WIN32 ::Sleep(ms); #else timeval tv={ms/1000, (ms%1000)*1000}; ::select(0, 0, 0, 0, &tv); #endif } inline int dumpable() { #if HAVE_SYS_PRCTL_H rlimit core = { RLIM_INFINITY, RLIM_INFINITY }; return ::prctl(PR_SET_DUMPABLE, 1) || ::setrlimit(RLIMIT_CORE, &core) ? -1 : 0; #endif return -1; } inline void daemonize() { #ifdef WIN32 return ; #else int null = ::open("/dev/null", O_RDWR); if(-1 == null) { ::perror("/dev/null"); ::exit(EXIT_FAILURE); } switch(::fork()) { case 0: ::setsid(); ::umask(0); ::close(0); ::close(1); ::close(2); ::dup2(null, 0); ::dup2(null, 1); ::dup2(null, 2); break; case -1: ::perror("fork()"); ::exit(EXIT_FAILURE); default: ::exit(EXIT_SUCCESS); } #endif } }} #endif // FAS_SYSTEM_SYSTEM_H
mambaru/leveldb-daemon
fas/system/system.hpp
C++
gpl-2.0
3,550
/* * Copyright (C) 2009 Ronald Lamprecht * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "floors/SlopeFloor.hh" #include "errors.hh" #include "main.hh" #include "stones.hh" #include "world.hh" namespace enigma { SlopeFloor::SlopeFloor(int slope, std::string shape) : Floor("fl_slope", 4, 2) { state = slope; Floor::setAttr("shape", shape); } std::string SlopeFloor::getClass() const { return "fl_slope"; } void SlopeFloor::setAttr(const std::string& key, const Value &val) { if (key == "shape") { std::string shape = val.to_string(); if (shape == "" || shape == "pw" || shape == "ps" || shape == "pe" || shape == "pn" || shape == "inw" || shape == "isw" || shape == "ise" || shape == "ine" || shape == "onw" || shape == "osw" || shape == "ose" || shape == "one" || shape == "tw" || shape == "ts" || shape == "te" || shape == "tn" || shape == "twl" || shape == "tsl" || shape == "tel" || shape == "tnl" || shape == "twr" || shape == "tsr" || shape == "ter" || shape == "tnr") { Floor::setAttr("shape", shape); init_model(); } } else if (key == "slope") { int slope = val; if (slope >= -1 && slope <= 7) state = slope; } else if (key == "strength") { var_floorforce[0] = val; objFlags = (objFlags & ~OBJBIT_FORCE) | OBJBIT_STRENGTH; } else if (key == "force_x") { var_floorforce[0] = val; objFlags = (objFlags & ~OBJBIT_STRENGTH) | OBJBIT_FORCE; } else if (key == "force_y") { var_floorforce[1] = val; objFlags = (objFlags & ~OBJBIT_STRENGTH) | OBJBIT_FORCE; } else Floor::setAttr(key, val); } Value SlopeFloor::getAttr(const std::string &key) const { if (key == "slope") { return state; } else if (key == "strength") { return var_floorforce[0]; } return Floor::getAttr(key); } void SlopeFloor::setState(int extState) { // ignore any state change attempts } std::string SlopeFloor::getModelName() const { std::string shape = getAttr("shape").to_string(); if (shape == "") return "fl_slope"; else return std::string("fl_slope_") + shape; } void SlopeFloor::add_force(Actor *a, ecl::V2 &f) { static int xforce[8] = { -1, 0, 1, 0, -1, -1, 1, 1 }; static int yforce[8] = { 0, 1, 0, -1, -1, 1, 1, -1 }; if (objFlags & OBJBIT_FORCE) return Floor::add_force(a, f); else { ecl::V2 force(0,0); if (state != NODIR) { force = ecl::V2(xforce[state], yforce[state]); force.normalize(); } f += ((objFlags & OBJBIT_STRENGTH) ? var_floorforce[0] : server::SlopeForce) * force; } } BOOT_REGISTER_START BootRegister(new SlopeFloor(-1, ""), "fl_slope"); BootRegister(new SlopeFloor( 0, "pw"), "fl_slope_pw"); BootRegister(new SlopeFloor( 1, "ps"), "fl_slope_ps"); BootRegister(new SlopeFloor( 2, "pe"), "fl_slope_pe"); BootRegister(new SlopeFloor( 3, "pn"), "fl_slope_pn"); BootRegister(new SlopeFloor( 4, "inw"), "fl_slope_inw"); BootRegister(new SlopeFloor( 5, "isw"), "fl_slope_isw"); BootRegister(new SlopeFloor( 6, "ise"), "fl_slope_ise"); BootRegister(new SlopeFloor( 7, "ine"), "fl_slope_ine"); BootRegister(new SlopeFloor( 4, "onw"), "fl_slope_onw"); BootRegister(new SlopeFloor( 5, "osw"), "fl_slope_osw"); BootRegister(new SlopeFloor( 6, "ose"), "fl_slope_ose"); BootRegister(new SlopeFloor( 7, "one"), "fl_slope_one"); BootRegister(new SlopeFloor( 0, "tw"), "fl_slope_tw"); BootRegister(new SlopeFloor( 1, "ts"), "fl_slope_ts"); BootRegister(new SlopeFloor( 2, "te"), "fl_slope_te"); BootRegister(new SlopeFloor( 3, "tn"), "fl_slope_tn"); BootRegister(new SlopeFloor( 4, "twl"), "fl_slope_twl"); BootRegister(new SlopeFloor( 5, "tsl"), "fl_slope_tsl"); BootRegister(new SlopeFloor( 6, "tel"), "fl_slope_tel"); BootRegister(new SlopeFloor( 7, "tnl"), "fl_slope_tnl"); BootRegister(new SlopeFloor( 5, "twr"), "fl_slope_twr"); BootRegister(new SlopeFloor( 6, "tsr"), "fl_slope_tsr"); BootRegister(new SlopeFloor( 7, "ter"), "fl_slope_ter"); BootRegister(new SlopeFloor( 4, "tnr"), "fl_slope_tnr"); BOOT_REGISTER_END } // namespace enigma
raoulb/Enigma
src/floors/SlopeFloor.cc
C++
gpl-2.0
5,542
/****************************************************************************** * Wormux is a convivial mass murder game. * Copyright (C) 2001-2007 Wormux Team. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA ****************************************************************************** * Widget list : store all widgets displayed on one screen * It is a fake widget. *****************************************************************************/ #include <SDL_keyboard.h> #include "gui/widget_list.h" #include "gui/widget.h" #include <iostream> WidgetList::WidgetList() { last_clicked = NULL; mouse_selection = NULL; keyboard_selection = NULL; } WidgetList::WidgetList(const Rectanglei &rect) : Widget(rect) { last_clicked = NULL; mouse_selection = NULL; keyboard_selection = NULL; } WidgetList::~WidgetList() { for(std::list<Widget*>::iterator w=widget_list.begin(); w != widget_list.end(); w++) delete *w; widget_list.clear(); } void WidgetList::DelFirstWidget() { delete widget_list.front(); widget_list.pop_front(); } void WidgetList::AddWidget(Widget* w) { ASSERT(w!=NULL); widget_list.push_back(w); w->SetContainer(this); } void WidgetList::Update(const Point2i &mousePosition, Surface& surf) { if (mouse_selection != NULL && !mouse_selection->Contains(mousePosition)) { mouse_selection = NULL; } for (std::list<Widget*>::iterator w=widget_list.begin(); w != widget_list.end(); w++) { // Then redraw the widget (*w)->Update(mousePosition, lastMousePosition, surf); if (lastMousePosition != mousePosition && (*w)->Contains(mousePosition)) { mouse_selection = (*w); mouse_selection->SetHighlighted(true); } if ((*w) != mouse_selection && (*w) != keyboard_selection && !(*w)->Contains(mousePosition)) { (*w)->SetHighlighted(false); } } if (mouse_selection != NULL && keyboard_selection != NULL && lastMousePosition != mousePosition) { keyboard_selection->SetFocus(false); keyboard_selection = NULL; } lastMousePosition = mousePosition; } void WidgetList::SetKeyboardFocusOnNextWidget() { // No widget => exit if (widget_list.size() == 0) { keyboard_selection = NULL; return; } // Previous selection ? if (keyboard_selection != NULL) keyboard_selection->SetFocus(false); else if (mouse_selection != NULL) { keyboard_selection = mouse_selection; mouse_selection->SetFocus(false); } else { keyboard_selection = (*widget_list.begin()); keyboard_selection->SetFocus(true); return; } std::list<Widget*>::iterator w = widget_list.begin(); for (; w != widget_list.end(); w++) { if (keyboard_selection == (*w)) break; } w++; // The next widget is not the end ? if (w != widget_list.end()) { keyboard_selection = (*w); } else { keyboard_selection = (*widget_list.begin()); } keyboard_selection->SetFocus(true); } void WidgetList::SetKeyboardFocusOnPreviousWidget() { Widget * previous_one = NULL; // No widget => exit if (widget_list.size() == 0) { keyboard_selection = NULL; return; } // Previous selection ? if (keyboard_selection != NULL) keyboard_selection->SetFocus(false); else if (mouse_selection != NULL) { keyboard_selection = mouse_selection; mouse_selection->SetFocus(false); } else { keyboard_selection = (*widget_list.begin()); keyboard_selection->SetFocus(true); return; } std::list<Widget*>::iterator w = widget_list.begin(); for (; w != widget_list.end(); w++) { if (keyboard_selection == (*w)) break; previous_one = (*w); } // The next widget is not the end ? if (previous_one == NULL) { w = widget_list.end(); w--; keyboard_selection = (*w); } else { keyboard_selection = previous_one; } keyboard_selection->SetFocus(true); } bool WidgetList::SendKey(SDL_keysym key) { if (last_clicked != NULL) return last_clicked->SendKey(key); return false; } Widget* WidgetList::ClickUp(const Point2i &mousePosition, uint button) { for(std::list<Widget*>::iterator w=widget_list.begin(); w != widget_list.end(); w++) { if((*w)->Contains(mousePosition)) { Widget* child = (*w)->ClickUp(mousePosition,button); if(child != NULL) { SetMouseFocusOn(child); return child; } } } return NULL; } Widget* WidgetList::Click(const Point2i &mousePosition, uint button) { for(std::list<Widget*>::iterator w=widget_list.begin(); w != widget_list.end(); w++) { if((*w)->Contains(mousePosition)) { (*w)->Click(mousePosition,button); } } return NULL; } void WidgetList::NeedRedrawing() { need_redrawing = true; for(std::list<Widget*>::iterator w=widget_list.begin(); w != widget_list.end(); w++) { (*w)->NeedRedrawing(); } } void WidgetList::SetMouseFocusOn(Widget* w) { if(last_clicked != NULL) { last_clicked->SetFocus(false); } if (w != NULL) { last_clicked = w ; last_clicked->SetFocus(true); } }
yeKcim/warmux
old/wormux-0.8beta4/src/gui/widget_list.cpp
C++
gpl-2.0
5,767
import time import os import ContentDb from Debug import Debug from Config import config class ContentDbDict(dict): def __init__(self, site, *args, **kwargs): s = time.time() self.site = site self.cached_keys = [] self.log = self.site.log self.db = ContentDb.getContentDb() self.db_id = self.db.needSite(site) self.num_loaded = 0 super(ContentDbDict, self).__init__(self.db.loadDbDict(site)) # Load keys from database self.log.debug("ContentDb init: %.3fs, found files: %s, sites: %s" % (time.time() - s, len(self), len(self.db.site_ids))) def loadItem(self, key): try: self.num_loaded += 1 if self.num_loaded % 100 == 0: if config.verbose: self.log.debug("Loaded json: %s (latest: %s) called by: %s" % (self.num_loaded, key, Debug.formatStack())) else: self.log.debug("Loaded json: %s (latest: %s)" % (self.num_loaded, key)) content = self.site.storage.loadJson(key) dict.__setitem__(self, key, content) except IOError: if dict.get(self, key): self.__delitem__(key) # File not exists anymore raise KeyError(key) self.addCachedKey(key) self.checkLimit() return content def getItemSize(self, key): return self.site.storage.getSize(key) # Only keep last 10 accessed json in memory def checkLimit(self): if len(self.cached_keys) > 10: key_deleted = self.cached_keys.pop(0) dict.__setitem__(self, key_deleted, False) def addCachedKey(self, key): if key not in self.cached_keys and key != "content.json" and len(key) > 40: # Always keep keys smaller than 40 char self.cached_keys.append(key) def __getitem__(self, key): val = dict.get(self, key) if val: # Already loaded return val elif val is None: # Unknown key raise KeyError(key) elif val is False: # Loaded before, but purged from cache return self.loadItem(key) def __setitem__(self, key, val): self.addCachedKey(key) self.checkLimit() size = self.getItemSize(key) self.db.setContent(self.site, key, val, size) dict.__setitem__(self, key, val) def __delitem__(self, key): self.db.deleteContent(self.site, key) dict.__delitem__(self, key) try: self.cached_keys.remove(key) except ValueError: pass def iteritems(self): for key in dict.keys(self): try: val = self[key] except Exception as err: self.log.warning("Error loading %s: %s" % (key, err)) continue yield key, val def items(self): back = [] for key in dict.keys(self): try: val = self[key] except Exception as err: self.log.warning("Error loading %s: %s" % (key, err)) continue back.append((key, val)) return back def values(self): back = [] for key, val in dict.iteritems(self): if not val: try: val = self.loadItem(key) except Exception: continue back.append(val) return back def get(self, key, default=None): try: return self.__getitem__(key) except KeyError: return default except Exception as err: self.site.bad_files[key] = self.site.bad_files.get(key, 1) dict.__delitem__(self, key) self.log.warning("Error loading %s: %s" % (key, err)) return default def execute(self, query, params={}): params["site_id"] = self.db_id return self.db.execute(query, params) if __name__ == "__main__": import psutil process = psutil.Process(os.getpid()) s_mem = process.memory_info()[0] / float(2 ** 20) root = "data-live/1MaiL5gfBM1cyb4a8e3iiL8L5gXmoAJu27" contents = ContentDbDict("1MaiL5gfBM1cyb4a8e3iiL8L5gXmoAJu27", root) print "Init len", len(contents) s = time.time() for dir_name in os.listdir(root + "/data/users/")[0:8000]: contents["data/users/%s/content.json" % dir_name] print "Load: %.3fs" % (time.time() - s) s = time.time() found = 0 for key, val in contents.iteritems(): found += 1 assert key assert val print "Found:", found print "Iteritem: %.3fs" % (time.time() - s) s = time.time() found = 0 for key in contents.keys(): found += 1 assert key in contents print "In: %.3fs" % (time.time() - s) print "Len:", len(contents.values()), len(contents.keys()) print "Mem: +", process.memory_info()[0] / float(2 ** 20) - s_mem
OliverCole/ZeroNet
src/Content/ContentDbDict.py
Python
gpl-2.0
4,975
package com.vvdeng.portal.web.controller.admin; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.paipai.verticalframework.web.spring.BaseController; import com.vvdeng.portal.bizservice.SideMenuService; import com.vvdeng.portal.dataservice.SysMenuDataService; import com.vvdeng.portal.entity.SysMenu; import com.vvdeng.portal.model.MenuLevel; import com.vvdeng.portal.model.SysMenuType; import com.vvdeng.portal.util.EmptyUtil; import com.vvdeng.portal.web.form.SideForm; import com.vvdeng.portal.web.form.SysUserForm; @Controller public class AdminController extends BaseController { private SysMenuDataService sysMenuDataService; @RequestMapping("/admin/index.xhtml") public String index() { return "/admin/base"; } @RequestMapping(method = RequestMethod.GET, value = "/admin/login.jhtml") public String loginPage() { return "/admin/login"; } @RequestMapping(method = RequestMethod.POST, value = "/admin/login.jhtml") public String login(SysUserForm sysUserForm, HttpSession session,ModelMap model) { System.out.println("uName=" + sysUserForm.getName() + " uPwd=" + sysUserForm.getPwd()); if ("admin".equals(sysUserForm.getName()) && "admin".equals(sysUserForm.getPwd())) { System.out.println("SessionVefityCode:"+session.getAttribute("verifyCode")+" msg="+session.getAttribute("msg")); session.setAttribute("sysUser", sysUserForm); return "redirect:/admin/index.xhtml"; } else { model.put("errMsg", "用户名或密码不正确"); return "/admin/login"; } } @RequestMapping("/admin/needLogin.jhtml") public String needLogin() { return "/admin/need_login"; } @RequestMapping("/admin/logout.jhtml") public String logout(HttpSession session) { session.invalidate(); return "redirect:/admin/needLogin.jhtml"; } @RequestMapping("/admin/head.xhtml") public String head(ModelMap map) { List<SysMenu> topSysMenuList = sysMenuDataService .queryByLevel(MenuLevel.TOP.getId()); map.put("topSysMenuList", topSysMenuList); System.out.println("topSysMenuList size=" + topSysMenuList.size()); return "/admin/head"; } @RequestMapping("/admin/side.xhtml") public String side(SideForm sideForm, ModelMap map) { processSide(sideForm, map); map.put("sideForm", sideForm); return "/admin/side"; } @RequestMapping("/admin/main.xhtml") public String main() { return "/admin/main"; } @RequestMapping("/admin/welcome.xhtml") public String welcome() { return "/admin/welcome"; } public SysMenuDataService getSysMenuDataService() { return sysMenuDataService; } public void setSysMenuDataService(SysMenuDataService sysMenuDataService) { this.sysMenuDataService = sysMenuDataService; } private void processSide(SideForm sideForm, ModelMap map) { if (sideForm.getOperation() == null || sideForm.getOperation().isEmpty() || sideForm.getOperation().equals(SysMenu.DEFAULT_OPERATION)) { if (sideForm.getType() == null || sideForm.getType().equals(SysMenuType.LIST.getId())) { List<SysMenu> sysMenuList = sysMenuDataService .queryByParentId(sideForm.getId()); map.put("menuList", sysMenuList); map.put("defaultHref", EmptyUtil.isNull(sysMenuList) ? "" : sysMenuList.get(0).getHref()); } } else { SideMenuService sideMenuEditMenu = getBean("editMenu", SideMenuService.class); sideMenuEditMenu.tree(sideForm, map); } } }
vvdeng/vportal
src/com/vvdeng/portal/web/controller/admin/AdminController.java
Java
gpl-2.0
3,792
<?php /** * Easy Blog Multicategories lsit * @package News Show Pro GK5 * @Copyright (C) 2009-2013 Gavick.com * @ All rights reserved * @ Joomla! is Free Software * @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL * @version $Revision: GK5 1.3.3 $ **/ // access restriction defined('_JEXEC') or die('Restricted access'); jimport('joomla.html.html'); jimport('joomla.form.formfield');//import the necessary class definition for formfield class JFormFieldEasyblogMulticategories extends JFormFieldList { protected $type = 'EasyblogMulticategories'; //the form field type var $options = array(); protected function getInput() { // Initialize variables. $html = array(); $attr = ''; // Initialize some field attributes. $attr .= $this->element['class'] ? ' class="'.(string) $this->element['class'].'"' : ''; // To avoid user's confusion, readonly="true" should imply disabled="true". if ( (string) $this->element['readonly'] == 'true' || (string) $this->element['disabled'] == 'true') { $attr .= ' disabled="disabled"'; } $attr .= $this->element['size'] ? ' size="'.(int) $this->element['size'].'"' : ''; $attr .= $this->multiple ? ' multiple="multiple"' : ''; // Initialize JavaScript field attributes. $attr .= $this->element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : ''; // Get the field options. $this->getOptions(); // Create a read-only list (no name) with a hidden input to store the value. if ((string) $this->element['readonly'] == 'true') { $html[] = JHtml::_('select.genericlist', $this->options, '', trim($attr), 'value', 'text', $this->value, $this->id); $html[] = '<input type="hidden" name="'.$this->name.'" value="'.$this->value.'"/>'; } // Create a regular list. else { if(isset($this->options[0]) && $this->options[0] != ''){ $html[] = JHtml::_('select.genericlist', $this->options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); } else { return '<select id="jform_params_easyblog_categories" style="display:none"></select><strong style="line-height: 2.6em" class="gk-hidden-field">Easy Blog is not installed or any Easy Blog categories are available.</strong>'; } } return implode($html); } protected function getOptions() { // Initialize variables. $session = JFactory::getSession(); $attr = ''; // Initialize some field attributes. $attr .= $this->element['class'] ? ' class="'.(string) $this->element['class'].'"' : ''; // To avoid user's confusion, readonly="true" should imply disabled="true". if ( (string) $this->element['readonly'] == 'true' || (string) $this->element['disabled'] == 'true') { $attr .= ' disabled="disabled"'; } $attr .= $this->element['size'] ? ' size="'.(int) $this->element['size'].'"' : ''; $attr .= $this->multiple ? ' multiple="multiple"' : ''; // Initialize JavaScript field attributes. $attr .= $this->element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : ''; $db = JFactory::getDBO(); // generating query $tables = $db->getTableList(); $dbprefix = $db->getPrefix(); if(in_array($dbprefix . 'easyblog_category', $tables)) { $db->setQuery("SELECT c.title AS name, c.id AS id, c.parent_id AS parent FROM #__easyblog_category AS c WHERE published = 1 ORDER BY c.title, c.parent_id ASC"); $results = $db->loadObjectList(); } else { $results = array(); } if(count($results)){ // iterating $temp_options = array(); foreach ($results as $item) { array_push($temp_options, array($item->id, $item->name, $item->parent)); } foreach ($temp_options as $option) { if($option[2] == 0) { $this->options[] = JHtml::_('select.option', $option[0], $option[1]); $this->recursive_options($temp_options, 1, $option[0]); } } } } // bind function to save function bind( $array, $ignore = '' ) { if (key_exists( 'field-name', $array ) && is_array( $array['field-name'] )) { $array['field-name'] = implode( ',', $array['field-name'] ); } return parent::bind( $array, $ignore ); } function recursive_options($temp_options, $level, $parent){ foreach ($temp_options as $option) { if($option[2] == $parent) { $level_string = ''; for($i = 0; $i < $level; $i++) $level_string .= '- - '; $this->options[] = JHtml::_('select.option', $option[0], $level_string . $option[1]); $this->recursive_options($temp_options, $level+1, $option[0]); } } } } /* EOF */
adrian2020my/vichi
modules/mod_news_pro_gk5/admin/elements/easyblogmulticategories.php
PHP
gpl-2.0
4,809
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/ * Copyright : Copyright © Nequeo Pty Ltd 2012 http://www.nequeo.com.au/ * * File : * Purpose : * */ #region Nequeo Pty Ltd License /* 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. */ #endregion namespace Nequeo.Net.OAuth2.Consumer.Session.Authorization.Messages { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Nequeo.Net.Core.Messaging; using Nequeo.Net.Core.Messaging.Reflection; using Nequeo.Net.OAuth2.Framework; using Nequeo.Net.OAuth2.Framework.ChannelElements; using Nequeo.Net.OAuth2.Framework.Messages; using Nequeo.Net.OAuth2.Consumer.Session.Authorization.ChannelElements; /// <summary> /// A request from a Client to an Authorization Server to exchange the user's username and password for an access token. /// </summary> internal class AccessTokenResourceOwnerPasswordCredentialsRequest : ScopedAccessTokenRequest, IAuthorizationCarryingRequest, IAuthorizationDescription { /// <summary> /// Initializes a new instance of the <see cref="AccessTokenResourceOwnerPasswordCredentialsRequest"/> class. /// </summary> /// <param name="accessTokenEndpoint">The access token endpoint.</param> /// <param name="version">The protocol version.</param> internal AccessTokenResourceOwnerPasswordCredentialsRequest(Uri accessTokenEndpoint, Version version) : base(accessTokenEndpoint, version) { } /// <summary> /// Gets the authorization that the code or token describes. /// </summary> IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get { return this.CredentialsValidated ? this : null; } } /// <summary> /// Gets the date this authorization was established or the token was issued. /// </summary> /// <value>A date/time expressed in UTC.</value> DateTime IAuthorizationDescription.UtcIssued { get { return DateTime.UtcNow; } } /// <summary> /// Gets the name on the account whose data on the resource server is accessible using this authorization. /// </summary> string IAuthorizationDescription.UserDataAndNonce { get { return this.UserName; } } /// <summary> /// Gets the scope of operations the client is allowed to invoke. /// </summary> HashSet<string> IAuthorizationDescription.Scope { get { return this.Scope; } } /// <summary> /// Gets the type of the grant. /// </summary> /// <value>The type of the grant.</value> internal override GrantType GrantType { get { return Messages.GrantType.Password; } } /// <summary> /// Gets or sets the user's account username. /// </summary> /// <value>The username on the user's account.</value> [MessagePart(Protocol.username, IsRequired = true)] internal string UserName { get; set; } /// <summary> /// Gets or sets the user's password. /// </summary> /// <value>The password.</value> [MessagePart(Protocol.password, IsRequired = true)] internal string Password { get; set; } /// <summary> /// Gets or sets a value indicating whether the resource owner's credentials have been validated at the authorization server. /// </summary> internal bool CredentialsValidated { get; set; } } }
drazenzadravec/nequeo
Source/Components/Net/Nequeo.OAuth2/Consumer/Session/Authorization/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs
C#
gpl-2.0
4,456
// Copyright (C) 2007, 2008, 2009 EPITA Research and Development Laboratory (LRDE) // // This file is part of Olena. // // Olena is free software: you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free // Software Foundation, version 2 of the License. // // Olena 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Olena. If not, see <http://www.gnu.org/licenses/>. // // As a special exception, you may use this file as part of a free // software project without restriction. Specifically, if other files // instantiate templates or use macros or inline functions from this // file, or you compile this file and link it with other files to produce // an executable, this file does not by itself cause the resulting // executable to be covered by the GNU General Public License. This // exception does not however invalidate any other reasons why the // executable file might be covered by the GNU General Public License. #include <mln/util/lemmings.hh> #include <mln/core/image/image2d.hh> int main () { using namespace mln; typedef image2d<int> I; int vals[4][4] = {{2, 2, 6, 6}, {2, 2, 6, 6}, {3, 3, 4, 4}, {3, 3, 4, 4}}; I ima = make::image<int>(vals); point2d pt1(1, 0), pt2(0, 2), pt3(2, 3), pt4(3, 1), pt5(1, 1); int vl1 = ima(pt1), vl2 = ima(pt2), vl3 = ima(pt3), vl4 = ima(pt4), vl5 = ima(pt5); point2d ptl1 = util::lemmings(ima, pt1, right, vl1), ptl2 = util::lemmings(ima, pt2, down, vl2), ptl3 = util::lemmings(ima, pt3, left, vl3), ptl4 = util::lemmings(ima, pt4, up, vl4), ptl5 = util::lemmings(ima, pt5, up, vl5); mln_assertion(ptl1 == point2d(1, 2)); mln_assertion(ptl2 == point2d(2, 2)); mln_assertion(ptl3 == point2d(2, 1)); mln_assertion(ptl4 == point2d(1, 1)); mln_assertion(ptl5 == point2d(-1, 1)); }
codingforfun/Olena-Mirror
milena/tests/util/lemmings.cc
C++
gpl-2.0
2,176
/* * Copyright (c) [2017-2021] SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * This program 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 General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Devices/DmRaidImpl.h" #include "storage/Devicegraph.h" namespace storage { using namespace std; DmRaid* DmRaid::create(Devicegraph* devicegraph, const string& name) { DmRaid* ret = new DmRaid(new DmRaid::Impl(name)); ret->Device::create(devicegraph); return ret; } DmRaid* DmRaid::create(Devicegraph* devicegraph, const string& name, const Region& region) { DmRaid* ret = new DmRaid(new DmRaid::Impl(name, region)); ret->Device::create(devicegraph); return ret; } DmRaid* DmRaid::create(Devicegraph* devicegraph, const string& name, unsigned long long size) { DmRaid* ret = new DmRaid(new DmRaid::Impl(name, Region(0, size / 512, 512))); ret->Device::create(devicegraph); return ret; } DmRaid* DmRaid::load(Devicegraph* devicegraph, const xmlNode* node) { DmRaid* ret = new DmRaid(new DmRaid::Impl(node)); ret->Device::load(devicegraph); return ret; } DmRaid::DmRaid(Impl* impl) : Partitionable(impl) { } DmRaid* DmRaid::clone() const { return new DmRaid(get_impl().clone()); } DmRaid::Impl& DmRaid::get_impl() { return dynamic_cast<Impl&>(Device::get_impl()); } const DmRaid::Impl& DmRaid::get_impl() const { return dynamic_cast<const Impl&>(Device::get_impl()); } DmRaid* DmRaid::find_by_name(Devicegraph* devicegraph, const string& name) { return to_dm_raid(BlkDevice::find_by_name(devicegraph, name)); } const DmRaid* DmRaid::find_by_name(const Devicegraph* devicegraph, const string& name) { return to_dm_raid(BlkDevice::find_by_name(devicegraph, name)); } vector<BlkDevice*> DmRaid::get_blk_devices() { return get_impl().get_blk_devices(); } vector<const BlkDevice*> DmRaid::get_blk_devices() const { return get_impl().get_blk_devices(); } bool DmRaid::is_rotational() const { return get_impl().is_rotational(); } vector<DmRaid*> DmRaid::get_all(Devicegraph* devicegraph) { return devicegraph->get_impl().get_devices_of_type<DmRaid>(); } vector<const DmRaid*> DmRaid::get_all(const Devicegraph* devicegraph) { return devicegraph->get_impl().get_devices_of_type<const DmRaid>(); } bool is_dm_raid(const Device* device) { return is_device_of_type<const DmRaid>(device); } DmRaid* to_dm_raid(Device* device) { return to_device_of_type<DmRaid>(device); } const DmRaid* to_dm_raid(const Device* device) { return to_device_of_type<const DmRaid>(device); } }
aschnell/libstorage-ng
storage/Devices/DmRaid.cc
C++
gpl-2.0
3,410
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ module jdk.net { exports jdk.net; }
FauxFaux/jdk9-jdk
src/jdk.net/share/classes/module-info.java
Java
gpl-2.0
1,249
<?php /** * Outputs a property map onto the property template using a hook * This allows us to filter the hook and replace it with a different map * * @package EPL * @subpackage Hooks/Map * @copyright Copyright (c) 2020, Merv Barrett * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 1.0.0 */ // Exit if accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Pulls the address details so the map can be generated * * @since 1.0.0 */ function epl_property_map_default_callback() { global $property; $api_key = epl_get_option( 'epl_google_api_key' ); $show_warning = apply_filters( 'epl_show_map_key_warning', true ); if ( empty( $api_key ) ) { if ( $show_warning && is_user_logged_in() && current_user_can( 'administrator' ) ) { epl_map_api_key_warning(); } return; } // Only show map if address display is set to true. if ( 'yes' === $property->get_property_meta( 'property_address_display' ) ) { $address = epl_property_get_the_full_address(); $address = apply_filters( 'epl_map_address', $address ); // Use coordinates if they are already present. $coordinates = $property->get_property_meta( 'property_address_coordinates' ); echo do_shortcode( '[listing_map zoom=14 cord="' . $coordinates . '" q="' . $address . '"]' ); } else { $address = $property->get_property_meta( 'property_address_suburb' ) . ', '; $address .= $property->get_property_meta( 'property_address_state' ) . ', '; $address .= $property->get_property_meta( 'property_address_postal_code' ); $address = apply_filters( 'epl_map_address', $address ); echo do_shortcode( '[listing_map zoom=14 suburb_mode=1 q="' . $address . '"]' ); } } add_action( 'epl_property_map', 'epl_property_map_default_callback' ); /** * Missing map key warning message * * @since 3.3.0 */ function epl_map_api_key_warning() { ?> <div class="epl-danger epl-warning-map-key" > <p> <?php esc_html_e( 'Ensure you have set a Google Maps API Key from Dashboard > Easy Property Listings > Settings.', 'easy-property-listings' ); ?> <em> <?php esc_html_e( 'Note: This message is only displayed to logged in administrators.', 'easy-property-listings' ); ?></em></p> </div> <?php }
wpdevstudio/Easy-Property-Listings
lib/hooks/hook-property-map.php
PHP
gpl-2.0
2,259
// $XConsortium: UAS_LinkedObject.hh /main/2 1996/06/11 16:38:08 cde-hal $
sTeeLM/MINIME
toolkit/srpm/SOURCES/cde-2.2.4/programs/dtinfo/dtinfo/src/UAS/Base/UAS_LinkedObject.hh
C++
gpl-2.0
75
################################ # These variables are overwritten by Zenoss when the ZenPack is exported # or saved. Do not modify them directly here. # NB: PACKAGES is deprecated NAME = 'ZenPacks.community.DistributedCollectors' VERSION = '1.7' AUTHOR = 'Egor Puzanov' LICENSE = '' NAMESPACE_PACKAGES = ['ZenPacks', 'ZenPacks.community'] PACKAGES = ['ZenPacks', 'ZenPacks.community', 'ZenPacks.community.DistributedCollectors'] INSTALL_REQUIRES = [] COMPAT_ZENOSS_VERS = '>=2.5' PREV_ZENPACK_NAME = '' # STOP_REPLACEMENTS ################################ # Zenoss will not overwrite any changes you make below here. from setuptools import setup, find_packages setup( # This ZenPack metadata should usually be edited with the Zenoss # ZenPack edit page. Whenever the edit page is submitted it will # overwrite the values below (the ones it knows about) with new values. name = NAME, version = VERSION, author = AUTHOR, license = LICENSE, # This is the version spec which indicates what versions of Zenoss # this ZenPack is compatible with compatZenossVers = COMPAT_ZENOSS_VERS, # previousZenPackName is a facility for telling Zenoss that the name # of this ZenPack has changed. If no ZenPack with the current name is # installed then a zenpack of this name if installed will be upgraded. prevZenPackName = PREV_ZENPACK_NAME, # Indicate to setuptools which namespace packages the zenpack # participates in namespace_packages = NAMESPACE_PACKAGES, # Tell setuptools what packages this zenpack provides. packages = find_packages(), # Tell setuptools to figure out for itself which files to include # in the binary egg when it is built. include_package_data = True, # The MANIFEST.in file is the recommended way of including additional files # in your ZenPack. package_data is another. #package_data = {} # Indicate dependencies on other python modules or ZenPacks. This line # is modified by zenoss when the ZenPack edit page is submitted. Zenoss # tries to put add/delete the names it manages at the beginning of this # list, so any manual additions should be added to the end. Things will # go poorly if this line is broken into multiple lines or modified to # dramatically. install_requires = INSTALL_REQUIRES, # Every ZenPack egg must define exactly one zenoss.zenpacks entry point # of this form. entry_points = { 'zenoss.zenpacks': '%s = %s' % (NAME, NAME), }, # All ZenPack eggs must be installed in unzipped form. zip_safe = False, )
anksp21/Community-Zenpacks
ZenPacks.community.DistributedCollectors/setup.py
Python
gpl-2.0
2,617
// // linq.cs: support for query expressions // // Authors: Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2007-2008 Novell, Inc // Copyright 2011 Xamarin Inc // using System; using System.Collections.Generic; namespace Mono.CSharp.Linq { public class QueryExpression : AQueryClause { public QueryExpression (AQueryClause start) : base (null, null, start.Location) { this.next = start; } public override Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parentParameter) { return next.BuildQueryClause (ec, lSide, parentParameter); } protected override Expression DoResolve (ResolveContext ec) { int counter = QueryBlock.TransparentParameter.Counter; Expression e = BuildQueryClause (ec, null, null); if (e != null) e = e.Resolve (ec); // // Reset counter in probing mode to ensure that all transparent // identifier anonymous types are created only once // if (ec.IsInProbingMode) QueryBlock.TransparentParameter.Counter = counter; return e; } protected override string MethodName { get { throw new NotSupportedException (); } } } public abstract class AQueryClause : ShimExpression { protected class QueryExpressionAccess : MemberAccess { public QueryExpressionAccess (Expression expr, string methodName, Location loc) : base (expr, methodName, loc) { } public QueryExpressionAccess (Expression expr, string methodName, TypeArguments typeArguments, Location loc) : base (expr, methodName, typeArguments, loc) { } public override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name) { ec.Report.Error (1935, loc, "An implementation of `{0}' query expression pattern could not be found. " + "Are you missing `System.Linq' using directive or `System.Core.dll' assembly reference?", name); } } protected class QueryExpressionInvocation : Invocation, OverloadResolver.IErrorHandler { public QueryExpressionInvocation (QueryExpressionAccess expr, Arguments arguments) : base (expr, arguments) { } protected override MethodGroupExpr DoResolveOverload (ResolveContext ec) { MethodGroupExpr rmg = mg.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.None); return rmg; } protected override Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr) { ec.Report.Error (1979, loc, "Query expressions with a source or join sequence of type `dynamic' are not allowed"); return null; } #region IErrorHandler Members bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous) { ec.Report.SymbolRelatedToPreviousError (best); ec.Report.SymbolRelatedToPreviousError (ambiguous); ec.Report.Error (1940, loc, "Ambiguous implementation of the query pattern `{0}' for source type `{1}'", best.Name, mg.InstanceExpression.GetSignatureForError ()); return true; } bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index) { return false; } bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best) { return false; } bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best) { var ms = (MethodSpec) best; TypeSpec source_type = ms.Parameters.ExtensionMethodType; if (source_type != null) { Argument a = arguments[0]; if (TypeManager.IsGenericType (source_type) && InflatedTypeSpec.ContainsTypeParameter (source_type)) { TypeInferenceContext tic = new TypeInferenceContext (source_type.TypeArguments); tic.OutputTypeInference (rc, a.Expr, source_type); if (tic.FixAllTypes (rc)) { source_type = source_type.GetDefinition ().MakeGenericType (rc, tic.InferredTypeArguments); } } if (!Convert.ImplicitConversionExists (rc, a.Expr, source_type)) { rc.Report.Error (1936, loc, "An implementation of `{0}' query expression pattern for source type `{1}' could not be found", best.Name, a.Type.GetSignatureForError ()); return true; } } if (best.Name == "SelectMany") { rc.Report.Error (1943, loc, "An expression type is incorrect in a subsequent `from' clause in a query expression with source type `{0}'", arguments[0].GetSignatureForError ()); } else { rc.Report.Error (1942, loc, "An expression type in `{0}' clause is incorrect. Type inference failed in the call to `{1}'", best.Name.ToLowerInvariant (), best.Name); } return true; } #endregion } public AQueryClause next; public QueryBlock block; protected AQueryClause (QueryBlock block, Expression expr, Location loc) : base (expr) { this.block = block; this.loc = loc; } protected override void CloneTo (CloneContext clonectx, Expression target) { base.CloneTo (clonectx, target); AQueryClause t = (AQueryClause) target; if (block != null) t.block = (QueryBlock) clonectx.LookupBlock (block); if (next != null) t.next = (AQueryClause) next.Clone (clonectx); } protected override Expression DoResolve (ResolveContext ec) { return expr.Resolve (ec); } public virtual Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parameter) { Arguments args = null; CreateArguments (ec, parameter, ref args); lSide = CreateQueryExpression (lSide, args); if (next != null) { parameter = CreateChildrenParameters (parameter); Select s = next as Select; if (s == null || s.IsRequired (parameter)) return next.BuildQueryClause (ec, lSide, parameter); // Skip transparent select clause if any clause follows if (next.next != null) return next.next.BuildQueryClause (ec, lSide, parameter); } return lSide; } protected virtual Parameter CreateChildrenParameters (Parameter parameter) { // Have to clone the parameter for any children use, it carries block sensitive data return parameter.Clone (); } protected virtual void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args) { args = new Arguments (2); LambdaExpression selector = new LambdaExpression (loc); block.SetParameter (parameter); selector.Block = block; selector.Block.AddStatement (new ContextualReturn (expr)); args.Add (new Argument (selector)); } protected Invocation CreateQueryExpression (Expression lSide, Arguments arguments) { return new QueryExpressionInvocation ( new QueryExpressionAccess (lSide, MethodName, loc), arguments); } protected abstract string MethodName { get; } public AQueryClause Next { set { next = value; } } public AQueryClause Tail { get { return next == null ? this : next.Tail; } } } // // A query clause with an identifier (range variable) // public abstract class ARangeVariableQueryClause : AQueryClause { sealed class RangeAnonymousTypeParameter : AnonymousTypeParameter { public RangeAnonymousTypeParameter (Expression initializer, RangeVariable parameter) : base (initializer, parameter.Name, parameter.Location) { } protected override void Error_InvalidInitializer (ResolveContext ec, string initializer) { ec.Report.Error (1932, loc, "A range variable `{0}' cannot be initialized with `{1}'", Name, initializer); } } class RangeParameterReference : ParameterReference { Parameter parameter; public RangeParameterReference (Parameter p) : base (null, p.Location) { this.parameter = p; } protected override Expression DoResolve (ResolveContext ec) { pi = ec.CurrentBlock.ParametersBlock.GetParameterInfo (parameter); return base.DoResolve (ec); } } protected RangeVariable identifier; protected ARangeVariableQueryClause (QueryBlock block, RangeVariable identifier, Expression expr, Location loc) : base (block, expr, loc) { this.identifier = identifier; } public RangeVariable Identifier { get { return identifier; } } public FullNamedExpression IdentifierType { get; set; } protected Invocation CreateCastExpression (Expression lSide) { return new QueryExpressionInvocation ( new QueryExpressionAccess (lSide, "Cast", new TypeArguments (IdentifierType), loc), null); } protected override Parameter CreateChildrenParameters (Parameter parameter) { return new QueryBlock.TransparentParameter (parameter.Clone (), GetIntoVariable ()); } protected static Expression CreateRangeVariableType (ResolveContext rc, Parameter parameter, RangeVariable name, Expression init) { var args = new List<AnonymousTypeParameter> (2); // // The first argument is the reference to the parameter // args.Add (new AnonymousTypeParameter (new RangeParameterReference (parameter), parameter.Name, parameter.Location)); // // The second argument is the linq expression // args.Add (new RangeAnonymousTypeParameter (init, name)); // // Create unique anonymous type // return new NewAnonymousType (args, rc.MemberContext.CurrentMemberDefinition.Parent, name.Location); } protected virtual RangeVariable GetIntoVariable () { return identifier; } } public sealed class RangeVariable : INamedBlockVariable { Block block; public RangeVariable (string name, Location loc) { Name = name; Location = loc; } #region Properties public Block Block { get { return block; } set { block = value; } } public bool IsDeclared { get { return true; } } public bool IsParameter { get { return false; } } public Location Location { get; private set; } public string Name { get; private set; } #endregion public Expression CreateReferenceExpression (ResolveContext rc, Location loc) { // // We know the variable name is somewhere in the scope. This generates // an access expression from current block // var pb = rc.CurrentBlock.ParametersBlock; while (true) { if (pb is QueryBlock) { for (int i = pb.Parameters.Count - 1; i >= 0; --i) { var p = pb.Parameters[i]; if (p.Name == Name) return pb.GetParameterReference (i, loc); Expression expr = null; var tp = p as QueryBlock.TransparentParameter; while (tp != null) { if (expr == null) expr = pb.GetParameterReference (i, loc); else expr = new TransparentMemberAccess (expr, tp.Name); if (tp.Identifier == Name) return new TransparentMemberAccess (expr, Name); if (tp.Parent.Name == Name) return new TransparentMemberAccess (expr, Name); tp = tp.Parent as QueryBlock.TransparentParameter; } } } if (pb == block) return null; pb = pb.Parent.ParametersBlock; } } } public class QueryStartClause : ARangeVariableQueryClause { public QueryStartClause (QueryBlock block, Expression expr, RangeVariable identifier, Location loc) : base (block, identifier, expr, loc) { block.AddRangeVariable (identifier); } public override Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parameter) { if (IdentifierType != null) expr = CreateCastExpression (expr); if (parameter == null) lSide = expr; return next.BuildQueryClause (ec, lSide, new ImplicitLambdaParameter (identifier.Name, identifier.Location)); } protected override Expression DoResolve (ResolveContext ec) { Expression e = BuildQueryClause (ec, null, null); return e.Resolve (ec); } protected override string MethodName { get { throw new NotSupportedException (); } } } public class GroupBy : AQueryClause { Expression element_selector; QueryBlock element_block; public GroupBy (QueryBlock block, Expression elementSelector, QueryBlock elementBlock, Expression keySelector, Location loc) : base (block, keySelector, loc) { // // Optimizes clauses like `group A by A' // if (!elementSelector.Equals (keySelector)) { this.element_selector = elementSelector; this.element_block = elementBlock; } } public Expression SelectorExpression { get { return element_selector; } } protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args) { base.CreateArguments (ec, parameter, ref args); if (element_selector != null) { LambdaExpression lambda = new LambdaExpression (element_selector.Location); element_block.SetParameter (parameter.Clone ()); lambda.Block = element_block; lambda.Block.AddStatement (new ContextualReturn (element_selector)); args.Add (new Argument (lambda)); } } protected override void CloneTo (CloneContext clonectx, Expression target) { GroupBy t = (GroupBy) target; if (element_selector != null) { t.element_selector = element_selector.Clone (clonectx); t.element_block = (QueryBlock) element_block.Clone (clonectx); } base.CloneTo (clonectx, t); } protected override string MethodName { get { return "GroupBy"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class Join : SelectMany { QueryBlock inner_selector, outer_selector; public Join (QueryBlock block, RangeVariable lt, Expression inner, QueryBlock outerSelector, QueryBlock innerSelector, Location loc) : base (block, lt, inner, loc) { this.outer_selector = outerSelector; this.inner_selector = innerSelector; } public QueryBlock InnerSelector { get { return inner_selector; } } public QueryBlock OuterSelector { get { return outer_selector; } } protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args) { args = new Arguments (4); if (IdentifierType != null) expr = CreateCastExpression (expr); args.Add (new Argument (expr)); outer_selector.SetParameter (parameter.Clone ()); var lambda = new LambdaExpression (outer_selector.StartLocation); lambda.Block = outer_selector; args.Add (new Argument (lambda)); inner_selector.SetParameter (new ImplicitLambdaParameter (identifier.Name, identifier.Location)); lambda = new LambdaExpression (inner_selector.StartLocation); lambda.Block = inner_selector; args.Add (new Argument (lambda)); base.CreateArguments (ec, parameter, ref args); } protected override void CloneTo (CloneContext clonectx, Expression target) { Join t = (Join) target; t.inner_selector = (QueryBlock) inner_selector.Clone (clonectx); t.outer_selector = (QueryBlock) outer_selector.Clone (clonectx); base.CloneTo (clonectx, t); } protected override string MethodName { get { return "Join"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class GroupJoin : Join { readonly RangeVariable into; public GroupJoin (QueryBlock block, RangeVariable lt, Expression inner, QueryBlock outerSelector, QueryBlock innerSelector, RangeVariable into, Location loc) : base (block, lt, inner, outerSelector, innerSelector, loc) { this.into = into; } protected override RangeVariable GetIntoVariable () { return into; } protected override string MethodName { get { return "GroupJoin"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class Let : ARangeVariableQueryClause { public Let (QueryBlock block, RangeVariable identifier, Expression expr, Location loc) : base (block, identifier, expr, loc) { } protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args) { expr = CreateRangeVariableType (ec, parameter, identifier, expr); base.CreateArguments (ec, parameter, ref args); } protected override string MethodName { get { return "Select"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class Select : AQueryClause { public Select (QueryBlock block, Expression expr, Location loc) : base (block, expr, loc) { } // // For queries like `from a orderby a select a' // the projection is transparent and select clause can be safely removed // public bool IsRequired (Parameter parameter) { SimpleName sn = expr as SimpleName; if (sn == null) return true; return sn.Name != parameter.Name; } protected override string MethodName { get { return "Select"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class SelectMany : ARangeVariableQueryClause { public SelectMany (QueryBlock block, RangeVariable identifier, Expression expr, Location loc) : base (block, identifier, expr, loc) { } protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args) { if (args == null) { if (IdentifierType != null) expr = CreateCastExpression (expr); base.CreateArguments (ec, parameter.Clone (), ref args); } Expression result_selector_expr; QueryBlock result_block; var target = GetIntoVariable (); var target_param = new ImplicitLambdaParameter (target.Name, target.Location); // // When select follows use it as a result selector // if (next is Select) { result_selector_expr = next.Expr; result_block = next.block; result_block.SetParameters (parameter, target_param); next = next.next; } else { result_selector_expr = CreateRangeVariableType (ec, parameter, target, new SimpleName (target.Name, target.Location)); result_block = new QueryBlock (block.Parent, block.StartLocation); result_block.SetParameters (parameter, target_param); } LambdaExpression result_selector = new LambdaExpression (Location); result_selector.Block = result_block; result_selector.Block.AddStatement (new ContextualReturn (result_selector_expr)); args.Add (new Argument (result_selector)); } protected override string MethodName { get { return "SelectMany"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class Where : AQueryClause { public Where (QueryBlock block, Expression expr, Location loc) : base (block, expr, loc) { } protected override string MethodName { get { return "Where"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class OrderByAscending : AQueryClause { public OrderByAscending (QueryBlock block, Expression expr) : base (block, expr, expr.Location) { } protected override string MethodName { get { return "OrderBy"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class OrderByDescending : AQueryClause { public OrderByDescending (QueryBlock block, Expression expr) : base (block, expr, expr.Location) { } protected override string MethodName { get { return "OrderByDescending"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class ThenByAscending : OrderByAscending { public ThenByAscending (QueryBlock block, Expression expr) : base (block, expr) { } protected override string MethodName { get { return "ThenBy"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class ThenByDescending : OrderByDescending { public ThenByDescending (QueryBlock block, Expression expr) : base (block, expr) { } protected override string MethodName { get { return "ThenByDescending"; } } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } // // Implicit query block // public class QueryBlock : ParametersBlock { // // Transparent parameters are used to package up the intermediate results // and pass them onto next clause // public sealed class TransparentParameter : ImplicitLambdaParameter { public static int Counter; const string ParameterNamePrefix = "<>__TranspIdent"; public readonly Parameter Parent; public readonly string Identifier; public TransparentParameter (Parameter parent, RangeVariable identifier) : base (ParameterNamePrefix + Counter++, identifier.Location) { Parent = parent; Identifier = identifier.Name; } public static void Reset () { Counter = 0; } } public QueryBlock (Block parent, Location start) : base (parent, ParametersCompiled.EmptyReadOnlyParameters, start, Flags.CompilerGenerated) { } public void AddRangeVariable (RangeVariable variable) { variable.Block = this; TopBlock.AddLocalName (variable.Name, variable, true); } public override void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason) { TopBlock.Report.Error (1931, variable.Location, "A range variable `{0}' conflicts with a previous declaration of `{0}'", name); } public override void Error_AlreadyDeclared (string name, INamedBlockVariable variable) { TopBlock.Report.Error (1930, variable.Location, "A range variable `{0}' has already been declared in this scope", name); } public override void Error_AlreadyDeclaredTypeParameter (string name, Location loc) { TopBlock.Report.Error (1948, loc, "A range variable `{0}' conflicts with a method type parameter", name); } public void SetParameter (Parameter parameter) { base.parameters = new ParametersCompiled (parameter); base.parameter_info = new ParameterInfo[] { new ParameterInfo (this, 0) }; } public void SetParameters (Parameter first, Parameter second) { base.parameters = new ParametersCompiled (first, second); base.parameter_info = new ParameterInfo[] { new ParameterInfo (this, 0), new ParameterInfo (this, 1) }; } } sealed class TransparentMemberAccess : MemberAccess { public TransparentMemberAccess (Expression expr, string name) : base (expr, name) { } public override Expression DoResolveLValue (ResolveContext rc, Expression right_side) { rc.Report.Error (1947, loc, "A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value", Name); return null; } } }
hardvain/mono-compiler
mcs/linq.cs
C#
gpl-2.0
22,813
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.element.style; import org.odftoolkit.odfdom.pkg.OdfElement; import org.odftoolkit.odfdom.pkg.ElementVisitor; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.dom.DefaultElementVisitor; import org.odftoolkit.odfdom.dom.element.table.TableTableElement; import org.odftoolkit.odfdom.dom.element.text.TextAlphabeticalIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextAlphabeticalIndexAutoMarkFileElement; import org.odftoolkit.odfdom.dom.element.text.TextBibliographyElement; import org.odftoolkit.odfdom.dom.element.text.TextChangeElement; import org.odftoolkit.odfdom.dom.element.text.TextChangeEndElement; import org.odftoolkit.odfdom.dom.element.text.TextChangeStartElement; import org.odftoolkit.odfdom.dom.element.text.TextDdeConnectionDeclsElement; import org.odftoolkit.odfdom.dom.element.text.TextHElement; import org.odftoolkit.odfdom.dom.element.text.TextIllustrationIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextIndexTitleElement; import org.odftoolkit.odfdom.dom.element.text.TextListElement; import org.odftoolkit.odfdom.dom.element.text.TextObjectIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextPElement; import org.odftoolkit.odfdom.dom.element.text.TextSectionElement; import org.odftoolkit.odfdom.dom.element.text.TextSequenceDeclsElement; import org.odftoolkit.odfdom.dom.element.text.TextTableIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextTableOfContentElement; import org.odftoolkit.odfdom.dom.element.text.TextTrackedChangesElement; import org.odftoolkit.odfdom.dom.element.text.TextUserFieldDeclsElement; import org.odftoolkit.odfdom.dom.element.text.TextUserIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextVariableDeclsElement; import org.odftoolkit.odfdom.dom.attribute.style.StyleDisplayAttribute; /** * DOM implementation of OpenDocument element {@odf.element style:footer}. * */ public class StyleFooterElement extends OdfElement { public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.STYLE, "footer"); /** * Create the instance of <code>StyleFooterElement</code> * * @param ownerDoc The type is <code>OdfFileDom</code> */ public StyleFooterElement(OdfFileDom ownerDoc) { super(ownerDoc, ELEMENT_NAME); } /** * Get the element name * * @return return <code>OdfName</code> the name of element {@odf.element style:footer}. */ public OdfName getOdfName() { return ELEMENT_NAME; } /** * Receives the value of the ODFDOM attribute representation <code>StyleDisplayAttribute</code> , See {@odf.attribute style:display} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getStyleDisplayAttribute() { StyleDisplayAttribute attr = (StyleDisplayAttribute) getOdfAttribute(OdfDocumentNamespace.STYLE, "display"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(StyleDisplayAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>StyleDisplayAttribute</code> , See {@odf.attribute style:display} * * @param styleDisplayValue The type is <code>Boolean</code> */ public void setStyleDisplayAttribute(Boolean styleDisplayValue) { StyleDisplayAttribute attr = new StyleDisplayAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(styleDisplayValue.booleanValue()); } /** * Create child element {@odf.element style:region-center}. * * @return the element {@odf.element style:region-center} */ public StyleRegionCenterElement newStyleRegionCenterElement() { StyleRegionCenterElement styleRegionCenter = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleRegionCenterElement.class); this.appendChild(styleRegionCenter); return styleRegionCenter; } /** * Create child element {@odf.element style:region-left}. * * @return the element {@odf.element style:region-left} */ public StyleRegionLeftElement newStyleRegionLeftElement() { StyleRegionLeftElement styleRegionLeft = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleRegionLeftElement.class); this.appendChild(styleRegionLeft); return styleRegionLeft; } /** * Create child element {@odf.element style:region-right}. * * @return the element {@odf.element style:region-right} */ public StyleRegionRightElement newStyleRegionRightElement() { StyleRegionRightElement styleRegionRight = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleRegionRightElement.class); this.appendChild(styleRegionRight); return styleRegionRight; } /** * Create child element {@odf.element table:table}. * * @return the element {@odf.element table:table} */ public TableTableElement newTableTableElement() { TableTableElement tableTable = ((OdfFileDom) this.ownerDocument).newOdfElement(TableTableElement.class); this.appendChild(tableTable); return tableTable; } /** * Create child element {@odf.element text:alphabetical-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:alphabetical-index} */ public TextAlphabeticalIndexElement newTextAlphabeticalIndexElement(String textNameValue) { TextAlphabeticalIndexElement textAlphabeticalIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextAlphabeticalIndexElement.class); textAlphabeticalIndex.setTextNameAttribute(textNameValue); this.appendChild(textAlphabeticalIndex); return textAlphabeticalIndex; } /** * Create child element {@odf.element text:alphabetical-index-auto-mark-file}. * * @param xlinkHrefValue the <code>String</code> value of <code>XlinkHrefAttribute</code>, see {@odf.attribute xlink:href} at specification * @param xlinkTypeValue the <code>String</code> value of <code>XlinkTypeAttribute</code>, see {@odf.attribute xlink:type} at specification * @return the element {@odf.element text:alphabetical-index-auto-mark-file} */ public TextAlphabeticalIndexAutoMarkFileElement newTextAlphabeticalIndexAutoMarkFileElement(String xlinkHrefValue, String xlinkTypeValue) { TextAlphabeticalIndexAutoMarkFileElement textAlphabeticalIndexAutoMarkFile = ((OdfFileDom) this.ownerDocument).newOdfElement(TextAlphabeticalIndexAutoMarkFileElement.class); textAlphabeticalIndexAutoMarkFile.setXlinkHrefAttribute(xlinkHrefValue); textAlphabeticalIndexAutoMarkFile.setXlinkTypeAttribute(xlinkTypeValue); this.appendChild(textAlphabeticalIndexAutoMarkFile); return textAlphabeticalIndexAutoMarkFile; } /** * Create child element {@odf.element text:bibliography}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:bibliography} */ public TextBibliographyElement newTextBibliographyElement(String textNameValue) { TextBibliographyElement textBibliography = ((OdfFileDom) this.ownerDocument).newOdfElement(TextBibliographyElement.class); textBibliography.setTextNameAttribute(textNameValue); this.appendChild(textBibliography); return textBibliography; } /** * Create child element {@odf.element text:change}. * * @param textChangeIdValue the <code>String</code> value of <code>TextChangeIdAttribute</code>, see {@odf.attribute text:change-id} at specification * @return the element {@odf.element text:change} */ public TextChangeElement newTextChangeElement(String textChangeIdValue) { TextChangeElement textChange = ((OdfFileDom) this.ownerDocument).newOdfElement(TextChangeElement.class); textChange.setTextChangeIdAttribute(textChangeIdValue); this.appendChild(textChange); return textChange; } /** * Create child element {@odf.element text:change-end}. * * @param textChangeIdValue the <code>String</code> value of <code>TextChangeIdAttribute</code>, see {@odf.attribute text:change-id} at specification * @return the element {@odf.element text:change-end} */ public TextChangeEndElement newTextChangeEndElement(String textChangeIdValue) { TextChangeEndElement textChangeEnd = ((OdfFileDom) this.ownerDocument).newOdfElement(TextChangeEndElement.class); textChangeEnd.setTextChangeIdAttribute(textChangeIdValue); this.appendChild(textChangeEnd); return textChangeEnd; } /** * Create child element {@odf.element text:change-start}. * * @param textChangeIdValue the <code>String</code> value of <code>TextChangeIdAttribute</code>, see {@odf.attribute text:change-id} at specification * @return the element {@odf.element text:change-start} */ public TextChangeStartElement newTextChangeStartElement(String textChangeIdValue) { TextChangeStartElement textChangeStart = ((OdfFileDom) this.ownerDocument).newOdfElement(TextChangeStartElement.class); textChangeStart.setTextChangeIdAttribute(textChangeIdValue); this.appendChild(textChangeStart); return textChangeStart; } /** * Create child element {@odf.element text:dde-connection-decls}. * * @return the element {@odf.element text:dde-connection-decls} */ public TextDdeConnectionDeclsElement newTextDdeConnectionDeclsElement() { TextDdeConnectionDeclsElement textDdeConnectionDecls = ((OdfFileDom) this.ownerDocument).newOdfElement(TextDdeConnectionDeclsElement.class); this.appendChild(textDdeConnectionDecls); return textDdeConnectionDecls; } /** * Create child element {@odf.element text:h}. * * @param textOutlineLevelValue the <code>Integer</code> value of <code>TextOutlineLevelAttribute</code>, see {@odf.attribute text:outline-level} at specification * @return the element {@odf.element text:h} */ public TextHElement newTextHElement(int textOutlineLevelValue) { TextHElement textH = ((OdfFileDom) this.ownerDocument).newOdfElement(TextHElement.class); textH.setTextOutlineLevelAttribute(textOutlineLevelValue); this.appendChild(textH); return textH; } /** * Create child element {@odf.element text:illustration-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:illustration-index} */ public TextIllustrationIndexElement newTextIllustrationIndexElement(String textNameValue) { TextIllustrationIndexElement textIllustrationIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextIllustrationIndexElement.class); textIllustrationIndex.setTextNameAttribute(textNameValue); this.appendChild(textIllustrationIndex); return textIllustrationIndex; } /** * Create child element {@odf.element text:index-title}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:index-title} */ public TextIndexTitleElement newTextIndexTitleElement(String textNameValue) { TextIndexTitleElement textIndexTitle = ((OdfFileDom) this.ownerDocument).newOdfElement(TextIndexTitleElement.class); textIndexTitle.setTextNameAttribute(textNameValue); this.appendChild(textIndexTitle); return textIndexTitle; } /** * Create child element {@odf.element text:list}. * * @return the element {@odf.element text:list} */ public TextListElement newTextListElement() { TextListElement textList = ((OdfFileDom) this.ownerDocument).newOdfElement(TextListElement.class); this.appendChild(textList); return textList; } /** * Create child element {@odf.element text:object-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:object-index} */ public TextObjectIndexElement newTextObjectIndexElement(String textNameValue) { TextObjectIndexElement textObjectIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextObjectIndexElement.class); textObjectIndex.setTextNameAttribute(textNameValue); this.appendChild(textObjectIndex); return textObjectIndex; } /** * Create child element {@odf.element text:p}. * * @return the element {@odf.element text:p} */ public TextPElement newTextPElement() { TextPElement textP = ((OdfFileDom) this.ownerDocument).newOdfElement(TextPElement.class); this.appendChild(textP); return textP; } /** * Create child element {@odf.element text:section}. * * @param textDisplayValue the <code>String</code> value of <code>TextDisplayAttribute</code>, see {@odf.attribute text:display} at specification * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:section} */ public TextSectionElement newTextSectionElement(String textDisplayValue, String textNameValue) { TextSectionElement textSection = ((OdfFileDom) this.ownerDocument).newOdfElement(TextSectionElement.class); textSection.setTextDisplayAttribute(textDisplayValue); textSection.setTextNameAttribute(textNameValue); this.appendChild(textSection); return textSection; } /** * Create child element {@odf.element text:sequence-decls}. * * @return the element {@odf.element text:sequence-decls} */ public TextSequenceDeclsElement newTextSequenceDeclsElement() { TextSequenceDeclsElement textSequenceDecls = ((OdfFileDom) this.ownerDocument).newOdfElement(TextSequenceDeclsElement.class); this.appendChild(textSequenceDecls); return textSequenceDecls; } /** * Create child element {@odf.element text:table-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:table-index} */ public TextTableIndexElement newTextTableIndexElement(String textNameValue) { TextTableIndexElement textTableIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextTableIndexElement.class); textTableIndex.setTextNameAttribute(textNameValue); this.appendChild(textTableIndex); return textTableIndex; } /** * Create child element {@odf.element text:table-of-content}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:table-of-content} */ public TextTableOfContentElement newTextTableOfContentElement(String textNameValue) { TextTableOfContentElement textTableOfContent = ((OdfFileDom) this.ownerDocument).newOdfElement(TextTableOfContentElement.class); textTableOfContent.setTextNameAttribute(textNameValue); this.appendChild(textTableOfContent); return textTableOfContent; } /** * Create child element {@odf.element text:tracked-changes}. * * @return the element {@odf.element text:tracked-changes} */ public TextTrackedChangesElement newTextTrackedChangesElement() { TextTrackedChangesElement textTrackedChanges = ((OdfFileDom) this.ownerDocument).newOdfElement(TextTrackedChangesElement.class); this.appendChild(textTrackedChanges); return textTrackedChanges; } /** * Create child element {@odf.element text:user-field-decls}. * * @return the element {@odf.element text:user-field-decls} */ public TextUserFieldDeclsElement newTextUserFieldDeclsElement() { TextUserFieldDeclsElement textUserFieldDecls = ((OdfFileDom) this.ownerDocument).newOdfElement(TextUserFieldDeclsElement.class); this.appendChild(textUserFieldDecls); return textUserFieldDecls; } /** * Create child element {@odf.element text:user-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:user-index} */ public TextUserIndexElement newTextUserIndexElement(String textNameValue) { TextUserIndexElement textUserIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextUserIndexElement.class); textUserIndex.setTextNameAttribute(textNameValue); this.appendChild(textUserIndex); return textUserIndex; } /** * Create child element {@odf.element text:variable-decls}. * * @return the element {@odf.element text:variable-decls} */ public TextVariableDeclsElement newTextVariableDeclsElement() { TextVariableDeclsElement textVariableDecls = ((OdfFileDom) this.ownerDocument).newOdfElement(TextVariableDeclsElement.class); this.appendChild(textVariableDecls); return textVariableDecls; } @Override public void accept(ElementVisitor visitor) { if (visitor instanceof DefaultElementVisitor) { DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor; defaultVisitor.visit(this); } else { visitor.visit(this); } } }
jbjonesjr/geoproponis
external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/element/style/StyleFooterElement.java
Java
gpl-2.0
18,135
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2015 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef XCSOAR_FORM_DRAW_HPP #define XCSOAR_FORM_DRAW_HPP #include "Screen/PaintWindow.hpp" #include <functional> class ContainerWindow; /** * This class is used for creating custom drawn content. * It is based on the WindowControl class. */ class WndOwnerDrawFrame : public PaintWindow { public: typedef void (*OnPaintCallback_t)(Canvas &canvas, const PixelRect &rc); public: template<typename CB> void Create(ContainerWindow &parent, PixelRect rc, const WindowStyle style, CB &&_paint) { mOnPaintCallback = std::move(_paint); PaintWindow::Create(parent, rc, style); } protected: /** * The callback function for painting the content of the control * @see SetOnPaintNotify() */ std::function<void(Canvas &canvas, const PixelRect &rc)> mOnPaintCallback; /** from class PaintWindow */ virtual void OnPaint(Canvas &canvas) override; }; #endif
etnestad/xcsoar
src/Form/Draw.hpp
C++
gpl-2.0
1,812
<?php /* * User Role Editor Pro WordPress plugin options page * * @Author: Vladimir Garagulya * @URL: http://role-editor.com * @package UserRoleEditor * */ if (is_super_admin()) { ?> <tr> <td> <input type="checkbox" name="enable_simple_admin_for_multisite" id="enable_simple_admin_for_multisite" value="1" <?php echo ($enable_simple_admin_for_multisite==1) ? 'checked="checked"' : ''; ?> <?php echo defined('URE_ENABLE_SIMPLE_ADMIN_FOR_MULTISITE') ? 'disabled="disabled" title="Predefined by \'URE_ENABLE_SIMPLE_ADMIN_FOR_MULTISITE\' PHP constant"' : ''; ?> /> <label for="enable_simple_admin_for_multisite"> <?php esc_html_e('Allow single site administrator access to User Role Editor', 'user-role-editor'); ?> </label> </td> <td> </td> </tr> <tr> <td> <input type="checkbox" name="enable_help_links_for_simple_admin_ms" id="enable_help_links_for_simple_admin_ms" value="1" <?php echo ($enable_help_links_for_simple_admin_ms==1) ? 'checked="checked"' : ''; ?> /> <label for="enable_help_links_for_simple_admin_ms"> <?php esc_html_e('Show help links for single site administrator', 'user-role-editor'); ?> </label> </td> <td> </td> </tr> <?php } ?> <tr> <td> <input type="checkbox" name="enable_unfiltered_html_ms" id="enable_unfiltered_html_ms" value="1" <?php echo ($enable_unfiltered_html_ms==1) ? 'checked="checked"' : ''; ?> /> <label for="enable_unfiltered_html_ms" style="color: red;"> <?php esc_html_e('Enable "unfiltered_html" capability', 'user-role-editor'); ?> </label> </td> <td> <?php if ($enable_unfiltered_html_ms==1) { ?> <span style="color: red; font-weight: bold;">Warning!</span> This is a very dangerous to activate, if you have untrusted users on your site. Any user with <strong>unfiltered_html</strong> capability could add Javascript code to steal the login cookies of any visitor who runs a blog on the same site. The rogue user can then impersonate any of those users. <?php } ?> </td> </tr> <?php if (is_super_admin()) { ?> <tr> <td> <input type="checkbox" name="manage_themes_access" id="manage_themes_access" value="1" <?php echo ($manage_themes_access==1) ? 'checked="checked"' : ''; ?> <label for="manage_themes_access"> <?php esc_html_e('Activate access management for themes', 'user-role-editor'); ?> </label> </td> <td> </td> </tr> <tr> <td> <input type="checkbox" name="caps_access_restrict_for_simple_admin" id="caps_access_restrict_for_simple_admin" value="1" <?php echo ($caps_access_restrict_for_simple_admin==1) ? 'checked="checked"' : ''; ?> <label for="caps_access_restrict_for_simple_admin"> <?php esc_html_e('Activate access restrictions to User Role Editor for single site administrator', 'user-role-editor'); ?> </label> </td> <td> </td> </tr> <?php if ($caps_access_restrict_for_simple_admin) { ?> <tr> <td colspan="2"> <hr/> </td> </tr> <tr> <td colspan="2"> <h3>Restrict single site administrators access to User Role Editor</h3> </td> </tr> <tr> <td colspan="2"> <input type="checkbox" name="add_del_role_for_simple_admin" id="add_del_role_for_simple_admin" value="1" <?php echo ($add_del_role_for_simple_admin==1) ? 'checked="checked"' : ''; ?> <label for="add_del_role_for_simple_admin" title="<?php esc_html_e('Single site administrator can delete roles with allowed capabilities inside only', 'user-role-editor'); ?>"> <?php esc_html_e('Allow single site administrator Add/Delete roles', 'user-role-editor'); ?> </label> </td> </tr> <tr> <td colspan="2"> <table> <tr> <td> <span style="color: red;font-weight: bold;"><?php esc_html_e('Blocked capabilities:', 'user-role-editor'); ?></span><br/> Filter: <input type="text" id="box1Filter" /><button type="button" id="box1Clear">X</button><br /> <select id="box1View" multiple="multiple" style="height:400px;width:300px;"> <?php echo $html_caps_blocked_for_single_admin;?> </select><br/> <span id="box1Counter" class="countLabel"></span> <select id="box1Storage"> </select> </td> <td> <button id="to2" type="button" style="width: 50px;">&nbsp;>&nbsp;</button><br/><br/> <button id="to1" type="button" style="width: 50px;">&nbsp;<&nbsp;</button><br/><br/> <button id="allTo2" type="button" style="width: 50px;">&nbsp;>>&nbsp;</button><br/><br/> <button id="allTo1" type="button" style="width: 50px;">&nbsp;<<&nbsp;</button> </td> <td> <span style="color: green;font-weight: bold;"><?php esc_html_e('Allowed capabilities:', 'user-role-editor'); ?></span><br/> Filter: <input type="text" id="box2Filter" /><button type="button" id="box2Clear">X</button><br /> <select id="box2View" name="caps_allowed_for_single_admin[]" multiple="multiple" style="height:400px;width:300px;"> <?php echo $html_caps_allowed_for_single_admin;?> </select><br/> <span id="box2Counter" class="countLabel"></span> <select id="box2Storage"> </select> </td> </tr> </table> <script> jQuery(function() { jQuery.configureBoxes({ /*useSorting: false*/ }); }); </script> </td> </tr> <?php } // if ($caps_access_restrict_for_simple_admin) } // if (is_super_admin()) {
hungtran1202/merckquiz
wp-content/plugins/user-role-editor-pro/includes/pro/settings-template-ms.php
PHP
gpl-2.0
6,645
#include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include "resid-fp/sid.h" #include "sound_resid.h" typedef struct psid_t { /* resid sid implementation */ SIDFP *sid; int16_t last_sample; } psid_t; psid_t *psid; void *sid_init() { // psid_t *psid; int c; sampling_method method=SAMPLE_INTERPOLATE; float cycles_per_sec = 14318180.0 / 16.0; psid = new psid_t; // psid = (psid_t *)malloc(sizeof(sound_t)); psid->sid = new SIDFP; psid->sid->set_chip_model(MOS8580FP); psid->sid->set_voice_nonlinearity(1.0f); psid->sid->get_filter().set_distortion_properties(0.f, 0.f, 0.f); psid->sid->get_filter().set_type4_properties(6.55f, 20.0f); psid->sid->enable_filter(true); psid->sid->enable_external_filter(true); psid->sid->reset(); for (c=0;c<32;c++) psid->sid->write(c,0); if (!psid->sid->set_sampling_parameters((float)cycles_per_sec, method, (float)48000, 0.9*48000.0/2.0)) { // printf("reSID failed!\n"); } psid->sid->set_chip_model(MOS6581FP); psid->sid->set_voice_nonlinearity(0.96f); psid->sid->get_filter().set_distortion_properties(3.7e-3f, 2048.f, 1.2e-4f); psid->sid->input(0); psid->sid->get_filter().set_type3_properties(1.33e6f, 2.2e9f, 1.0056f, 7e3f); return (void *)psid; } void sid_close(void *p) { // psid_t *psid = (psid_t *)p; delete psid->sid; // free(psid); } void sid_reset(void *p) { // psid_t *psid = (psid_t *)p; int c; psid->sid->reset(); for (c = 0; c < 32; c++) psid->sid->write(c, 0); } uint8_t sid_read(uint16_t addr, void *p) { // psid_t *psid = (psid_t *)p; return psid->sid->read(addr & 0x1f); // return 0xFF; } void sid_write(uint16_t addr, uint8_t val, void *p) { // psid_t *psid = (psid_t *)p; psid->sid->write(addr & 0x1f,val); } #define CLOCK_DELTA(n) (int)(((14318180.0 * n) / 16.0) / 48000.0) static void fillbuf2(int& count, int16_t *buf, int len) { int c; c = psid->sid->clock(count, buf, len, 1); if (!c) *buf = psid->last_sample; psid->last_sample = *buf; } void sid_fillbuf(int16_t *buf, int len, void *p) { // psid_t *psid = (psid_t *)p; int x = CLOCK_DELTA(len); fillbuf2(x, buf, len); }
gatekeep/86Box
src/sound_resid.cc
C++
gpl-2.0
2,746
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.7 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2016 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM 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 Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ use Civi\Payment\System; /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2016 */ /** * Base class for building payment block for online contribution / event pages. */ class CRM_Core_Payment_ProcessorForm { /** * @param CRM_Contribute_Form_Contribution_Main|CRM_Event_Form_Registration_Register|CRM_Financial_Form_Payment $form * @param null $type * @param null $mode * * @throws Exception */ public static function preProcess(&$form, $type = NULL, $mode = NULL) { if ($type) { $form->_type = $type; } else { $form->_type = CRM_Utils_Request::retrieve('type', 'String', $form); } if ($form->_type) { $form->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($form->_type, $form->_mode); } if (empty($form->_paymentProcessor)) { // This would happen when hitting the back-button on a multi-page form with a $0 selection in play. return; } $form->set('paymentProcessor', $form->_paymentProcessor); $form->_paymentObject = System::singleton()->getByProcessor($form->_paymentProcessor); $form->assign('suppressSubmitButton', $form->_paymentObject->isSuppressSubmitButtons()); $form->assign('currency', CRM_Utils_Array::value('currency', $form->_values)); // also set cancel subscription url if (!empty($form->_paymentProcessor['is_recur']) && !empty($form->_values['is_recur'])) { $form->_values['cancelSubscriptionUrl'] = $form->_paymentObject->subscriptionURL(NULL, NULL, 'cancel'); } //checks after setting $form->_paymentProcessor // we do this outside of the above conditional to avoid // saving the country/state list in the session (which could be huge) CRM_Core_Payment_Form::setPaymentFieldsByProcessor( $form, $form->_paymentProcessor, CRM_Utils_Request::retrieve('billing_profile_id', 'String') ); $form->assign_by_ref('paymentProcessor', $form->_paymentProcessor); // check if this is a paypal auto return and redirect accordingly //@todo - determine if this is legacy and remove if (CRM_Core_Payment::paypalRedirect($form->_paymentProcessor)) { $url = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey={$form->controller->_key}" ); CRM_Utils_System::redirect($url); } // make sure we have a valid payment class, else abort if (!empty($form->_values['is_monetary']) && !$form->_paymentProcessor['class_name'] && empty($form->_values['is_pay_later']) ) { CRM_Core_Error::fatal(ts('Payment processor is not set for this page')); } if (!empty($form->_membershipBlock) && !empty($form->_membershipBlock['is_separate_payment']) && (!empty($form->_paymentProcessor['class_name']) && !$form->_paymentObject->supports('MultipleConcurrentPayments') ) ) { CRM_Core_Error::fatal(ts('This contribution page is configured to support separate contribution and membership payments. This %1 plugin does not currently support multiple simultaneous payments, or the option to "Execute real-time monetary transactions" is disabled. Please contact the site administrator and notify them of this error', array(1 => $form->_paymentProcessor['payment_processor_type']) ) ); } } /** * Build the payment processor form. * * @param CRM_Core_Form $form */ public static function buildQuickform(&$form) { //@todo document why this addHidden is here //CRM-15743 - we should not set/create hidden element for pay later // because payment processor is not selected $processorId = $form->getVar('_paymentProcessorID'); $billing_profile_id = CRM_Utils_Request::retrieve('billing_profile_id', 'String'); if (!empty($form->_values) && !empty($form->_values['is_billing_required'])) { $billing_profile_id = 'billing'; } if (!empty($processorId)) { $form->addElement('hidden', 'hidden_processor', 1); } CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, $billing_profile_id, FALSE); } }
USACYC/youth.coop
sites/all/modules/civicrm/CRM/Core/Payment/ProcessorForm.php
PHP
gpl-2.0
5,791
<?php if (erLhcoreClassUser::instance()->hasAccessTo('lhchat','take_screenshot')) : ?> <section> <p class="title" data-section-title><a href="#screenshot"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/screenshot','Screenshot')?></a></p> <div class="content" data-section-content> <div> <ul class="button-group radius"> <li><input type="button" value="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/screenshot','Take user screenshot')?>" class="button tiny" onclick="lhinst.addRemoteCommand('<?php echo $chat->id?>','lhc_screenshot')" /></li> <li><input type="button" value="<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/screenshot','Refresh')?>" class="button tiny" onclick="lhinst.updateScreenshot('<?php echo $chat->id?>')" /></li> </ul> <div id="user-screenshot-container"> <?php if ($chat->screenshot !== false) : ?> <h5><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/screenshot','Taken')?> <?php echo $chat->screenshot->date_front?></h5> <a href="#" class="screnshot-container"> <img id="screenshotImage" src="<?php echo erLhcoreClassDesign::baseurl('file/downloadfile')?>/<?php echo $chat->screenshot->id?>/<?php echo $chat->screenshot->security_hash?>" alt="" /> </a> <script> $(document).ready(function(){ $('.screnshot-container').zoom({callback: function(){ $(this).colorbox({'width':'95%','height':'95%',html: $('.screnshot-container').html()}); }}); }); </script> <?php else : ?> <?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/screenshot','Empty...')?> <?php endif;?> </div> </div> </div> </section> <?php endif;?>
euqip/glpi-smartcities
plugins/chat/front/design/defaulttheme/tpl/lhchat/chat_tabs/operator_screenshot.tpl.php
PHP
gpl-2.0
1,883
// Copyright 2015 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #include <cmath> #include "common/emu_window.h" #include "common/logging/log.h" #include "core/core_timing.h" #include "core/hle/kernel/event.h" #include "core/hle/kernel/shared_memory.h" #include "core/hle/service/hid/hid.h" #include "core/hle/service/hid/hid_spvr.h" #include "core/hle/service/hid/hid_user.h" #include "core/hle/service/service.h" #include "video_core/video_core.h" namespace Service { namespace HID { // Handle to shared memory region designated to HID_User service static Kernel::SharedPtr<Kernel::SharedMemory> shared_mem; // Event handles static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_1; static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_2; static Kernel::SharedPtr<Kernel::Event> event_accelerometer; static Kernel::SharedPtr<Kernel::Event> event_gyroscope; static Kernel::SharedPtr<Kernel::Event> event_debug_pad; static u32 next_pad_index; static u32 next_touch_index; static u32 next_accelerometer_index; static u32 next_gyroscope_index; static int enable_accelerometer_count = 0; // positive means enabled static int enable_gyroscope_count = 0; // positive means enabled static PadState GetCirclePadDirectionState(s16 circle_pad_x, s16 circle_pad_y) { // 30 degree and 60 degree are angular thresholds for directions constexpr float TAN30 = 0.577350269f; constexpr float TAN60 = 1 / TAN30; // a circle pad radius greater than 40 will trigger circle pad direction constexpr int CIRCLE_PAD_THRESHOLD_SQUARE = 40 * 40; PadState state; state.hex = 0; if (circle_pad_x * circle_pad_x + circle_pad_y * circle_pad_y > CIRCLE_PAD_THRESHOLD_SQUARE) { float t = std::abs(static_cast<float>(circle_pad_y) / circle_pad_x); if (circle_pad_x != 0 && t < TAN60) { if (circle_pad_x > 0) state.circle_right.Assign(1); else state.circle_left.Assign(1); } if (circle_pad_x == 0 || t > TAN30) { if (circle_pad_y > 0) state.circle_up.Assign(1); else state.circle_down.Assign(1); } } return state; } void Update() { SharedMem* mem = reinterpret_cast<SharedMem*>(shared_mem->GetPointer()); if (mem == nullptr) { LOG_DEBUG(Service_HID, "Cannot update HID prior to mapping shared memory!"); return; } PadState state = VideoCore::g_emu_window->GetPadState(); // Get current circle pad position and update circle pad direction s16 circle_pad_x, circle_pad_y; std::tie(circle_pad_x, circle_pad_y) = VideoCore::g_emu_window->GetCirclePadState(); state.hex |= GetCirclePadDirectionState(circle_pad_x, circle_pad_y).hex; mem->pad.current_state.hex = state.hex; mem->pad.index = next_pad_index; next_pad_index = (next_pad_index + 1) % mem->pad.entries.size(); // Get the previous Pad state u32 last_entry_index = (mem->pad.index - 1) % mem->pad.entries.size(); PadState old_state = mem->pad.entries[last_entry_index].current_state; // Compute bitmask with 1s for bits different from the old state PadState changed = {{(state.hex ^ old_state.hex)}}; // Get the current Pad entry PadDataEntry& pad_entry = mem->pad.entries[mem->pad.index]; // Update entry properties pad_entry.current_state.hex = state.hex; pad_entry.delta_additions.hex = changed.hex & state.hex; pad_entry.delta_removals.hex = changed.hex & old_state.hex; pad_entry.circle_pad_x = circle_pad_x; pad_entry.circle_pad_y = circle_pad_y; // If we just updated index 0, provide a new timestamp if (mem->pad.index == 0) { mem->pad.index_reset_ticks_previous = mem->pad.index_reset_ticks; mem->pad.index_reset_ticks = (s64)CoreTiming::GetTicks(); } mem->touch.index = next_touch_index; next_touch_index = (next_touch_index + 1) % mem->touch.entries.size(); // Get the current touch entry TouchDataEntry& touch_entry = mem->touch.entries[mem->touch.index]; bool pressed = false; std::tie(touch_entry.x, touch_entry.y, pressed) = VideoCore::g_emu_window->GetTouchState(); touch_entry.valid.Assign(pressed ? 1 : 0); // TODO(bunnei): We're not doing anything with offset 0xA8 + 0x18 of HID SharedMemory, which // supposedly is "Touch-screen entry, which contains the raw coordinate data prior to being // converted to pixel coordinates." (http://3dbrew.org/wiki/HID_Shared_Memory#Offset_0xA8). // If we just updated index 0, provide a new timestamp if (mem->touch.index == 0) { mem->touch.index_reset_ticks_previous = mem->touch.index_reset_ticks; mem->touch.index_reset_ticks = (s64)CoreTiming::GetTicks(); } // Signal both handles when there's an update to Pad or touch event_pad_or_touch_1->Signal(); event_pad_or_touch_2->Signal(); // Update accelerometer if (enable_accelerometer_count > 0) { mem->accelerometer.index = next_accelerometer_index; next_accelerometer_index = (next_accelerometer_index + 1) % mem->accelerometer.entries.size(); AccelerometerDataEntry& accelerometer_entry = mem->accelerometer.entries[mem->accelerometer.index]; std::tie(accelerometer_entry.x, accelerometer_entry.y, accelerometer_entry.z) = VideoCore::g_emu_window->GetAccelerometerState(); // Make up "raw" entry // TODO(wwylele): // From hardware testing, the raw_entry values are approximately, // but not exactly, as twice as corresponding entries (or with a minus sign). // It may caused by system calibration to the accelerometer. // Figure out how it works, or, if no game reads raw_entry, // the following three lines can be removed and leave raw_entry unimplemented. mem->accelerometer.raw_entry.x = -2 * accelerometer_entry.x; mem->accelerometer.raw_entry.z = 2 * accelerometer_entry.y; mem->accelerometer.raw_entry.y = -2 * accelerometer_entry.z; // If we just updated index 0, provide a new timestamp if (mem->accelerometer.index == 0) { mem->accelerometer.index_reset_ticks_previous = mem->accelerometer.index_reset_ticks; mem->accelerometer.index_reset_ticks = (s64)CoreTiming::GetTicks(); } event_accelerometer->Signal(); } // Update gyroscope if (enable_gyroscope_count > 0) { mem->gyroscope.index = next_gyroscope_index; next_gyroscope_index = (next_gyroscope_index + 1) % mem->gyroscope.entries.size(); GyroscopeDataEntry& gyroscope_entry = mem->gyroscope.entries[mem->gyroscope.index]; std::tie(gyroscope_entry.x, gyroscope_entry.y, gyroscope_entry.z) = VideoCore::g_emu_window->GetGyroscopeState(); // Make up "raw" entry mem->gyroscope.raw_entry.x = gyroscope_entry.x; mem->gyroscope.raw_entry.z = -gyroscope_entry.y; mem->gyroscope.raw_entry.y = gyroscope_entry.z; // If we just updated index 0, provide a new timestamp if (mem->gyroscope.index == 0) { mem->gyroscope.index_reset_ticks_previous = mem->gyroscope.index_reset_ticks; mem->gyroscope.index_reset_ticks = (s64)CoreTiming::GetTicks(); } event_gyroscope->Signal(); } } void GetIPCHandles(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); cmd_buff[1] = 0; // No error cmd_buff[2] = 0x14000000; // IPC Command Structure translate-header // TODO(yuriks): Return error from SendSyncRequest is this fails (part of IPC marshalling) cmd_buff[3] = Kernel::g_handle_table.Create(Service::HID::shared_mem).MoveFrom(); cmd_buff[4] = Kernel::g_handle_table.Create(Service::HID::event_pad_or_touch_1).MoveFrom(); cmd_buff[5] = Kernel::g_handle_table.Create(Service::HID::event_pad_or_touch_2).MoveFrom(); cmd_buff[6] = Kernel::g_handle_table.Create(Service::HID::event_accelerometer).MoveFrom(); cmd_buff[7] = Kernel::g_handle_table.Create(Service::HID::event_gyroscope).MoveFrom(); cmd_buff[8] = Kernel::g_handle_table.Create(Service::HID::event_debug_pad).MoveFrom(); } void EnableAccelerometer(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); ++enable_accelerometer_count; event_accelerometer->Signal(); cmd_buff[1] = RESULT_SUCCESS.raw; LOG_DEBUG(Service_HID, "called"); } void DisableAccelerometer(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); --enable_accelerometer_count; event_accelerometer->Signal(); cmd_buff[1] = RESULT_SUCCESS.raw; LOG_DEBUG(Service_HID, "called"); } void EnableGyroscopeLow(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); ++enable_gyroscope_count; event_gyroscope->Signal(); cmd_buff[1] = RESULT_SUCCESS.raw; LOG_DEBUG(Service_HID, "called"); } void DisableGyroscopeLow(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); --enable_gyroscope_count; event_gyroscope->Signal(); cmd_buff[1] = RESULT_SUCCESS.raw; LOG_DEBUG(Service_HID, "called"); } void GetGyroscopeLowRawToDpsCoefficient(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); cmd_buff[1] = RESULT_SUCCESS.raw; f32 coef = VideoCore::g_emu_window->GetGyroscopeRawToDpsCoefficient(); memcpy(&cmd_buff[2], &coef, 4); } void GetGyroscopeLowCalibrateParam(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); cmd_buff[1] = RESULT_SUCCESS.raw; const s16 param_unit = 6700; // an approximate value taken from hw GyroscopeCalibrateParam param = { {0, param_unit, -param_unit}, {0, param_unit, -param_unit}, {0, param_unit, -param_unit}, }; memcpy(&cmd_buff[2], &param, sizeof(param)); LOG_WARNING(Service_HID, "(STUBBED) called"); } void GetSoundVolume(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); const u8 volume = 0x3F; // TODO(purpasmart): Find out if this is the max value for the volume cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = volume; LOG_WARNING(Service_HID, "(STUBBED) called"); } void Init() { using namespace Kernel; AddService(new HID_U_Interface); AddService(new HID_SPVR_Interface); using Kernel::MemoryPermission; shared_mem = SharedMemory::Create(nullptr, 0x1000, MemoryPermission::ReadWrite, MemoryPermission::Read, 0, Kernel::MemoryRegion::BASE, "HID:SharedMemory"); next_pad_index = 0; next_touch_index = 0; // Create event handles event_pad_or_touch_1 = Event::Create(ResetType::OneShot, "HID:EventPadOrTouch1"); event_pad_or_touch_2 = Event::Create(ResetType::OneShot, "HID:EventPadOrTouch2"); event_accelerometer = Event::Create(ResetType::OneShot, "HID:EventAccelerometer"); event_gyroscope = Event::Create(ResetType::OneShot, "HID:EventGyroscope"); event_debug_pad = Event::Create(ResetType::OneShot, "HID:EventDebugPad"); } void Shutdown() { shared_mem = nullptr; event_pad_or_touch_1 = nullptr; event_pad_or_touch_2 = nullptr; event_accelerometer = nullptr; event_gyroscope = nullptr; event_debug_pad = nullptr; } } // namespace HID } // namespace Service
kratos121/citra
src/core/hle/service/hid/hid.cpp
C++
gpl-2.0
11,471
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.KeyNamePair; /** Generated Model for I_ElementValue * @author Adempiere (generated) * @version Release 3.6.0LTS - $Id$ */ public class X_I_ElementValue extends PO implements I_I_ElementValue, I_Persistent { /** * */ private static final long serialVersionUID = 20100614L; /** Standard Constructor */ public X_I_ElementValue (Properties ctx, int I_ElementValue_ID, String trxName) { super (ctx, I_ElementValue_ID, trxName); /** if (I_ElementValue_ID == 0) { setI_ElementValue_ID (0); setI_IsImported (false); } */ } /** Load Constructor */ public X_I_ElementValue (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_I_ElementValue[") .append(get_ID()).append("]"); return sb.toString(); } /** AccountSign AD_Reference_ID=118 */ public static final int ACCOUNTSIGN_AD_Reference_ID=118; /** Natural = N */ public static final String ACCOUNTSIGN_Natural = "N"; /** Debit = D */ public static final String ACCOUNTSIGN_Debit = "D"; /** Credit = C */ public static final String ACCOUNTSIGN_Credit = "C"; /** Set Account Sign. @param AccountSign Indicates the Natural Sign of the Account as a Debit or Credit */ public void setAccountSign (String AccountSign) { set_Value (COLUMNNAME_AccountSign, AccountSign); } /** Get Account Sign. @return Indicates the Natural Sign of the Account as a Debit or Credit */ public String getAccountSign () { return (String)get_Value(COLUMNNAME_AccountSign); } /** AccountType AD_Reference_ID=117 */ public static final int ACCOUNTTYPE_AD_Reference_ID=117; /** Asset = A */ public static final String ACCOUNTTYPE_Asset = "A"; /** Liability = L */ public static final String ACCOUNTTYPE_Liability = "L"; /** Revenue = R */ public static final String ACCOUNTTYPE_Revenue = "R"; /** Expense = E */ public static final String ACCOUNTTYPE_Expense = "E"; /** Owner's Equity = O */ public static final String ACCOUNTTYPE_OwnerSEquity = "O"; /** Memo = M */ public static final String ACCOUNTTYPE_Memo = "M"; /** Set Account Type. @param AccountType Indicates the type of account */ public void setAccountType (String AccountType) { set_Value (COLUMNNAME_AccountType, AccountType); } /** Get Account Type. @return Indicates the type of account */ public String getAccountType () { return (String)get_Value(COLUMNNAME_AccountType); } public I_AD_Column getAD_Column() throws RuntimeException { return (I_AD_Column)MTable.get(getCtx(), I_AD_Column.Table_Name) .getPO(getAD_Column_ID(), get_TrxName()); } /** Set Column. @param AD_Column_ID Column in the table */ public void setAD_Column_ID (int AD_Column_ID) { if (AD_Column_ID < 1) set_Value (COLUMNNAME_AD_Column_ID, null); else set_Value (COLUMNNAME_AD_Column_ID, Integer.valueOf(AD_Column_ID)); } /** Get Column. @return Column in the table */ public int getAD_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Column_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Element getC_Element() throws RuntimeException { return (I_C_Element)MTable.get(getCtx(), I_C_Element.Table_Name) .getPO(getC_Element_ID(), get_TrxName()); } /** Set Element. @param C_Element_ID Accounting Element */ public void setC_Element_ID (int C_Element_ID) { if (C_Element_ID < 1) set_Value (COLUMNNAME_C_Element_ID, null); else set_Value (COLUMNNAME_C_Element_ID, Integer.valueOf(C_Element_ID)); } /** Get Element. @return Accounting Element */ public int getC_Element_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Element_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ElementValue getC_ElementValue() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getC_ElementValue_ID(), get_TrxName()); } /** Set Account Element. @param C_ElementValue_ID Account Element */ public void setC_ElementValue_ID (int C_ElementValue_ID) { if (C_ElementValue_ID < 1) set_Value (COLUMNNAME_C_ElementValue_ID, null); else set_Value (COLUMNNAME_C_ElementValue_ID, Integer.valueOf(C_ElementValue_ID)); } /** Get Account Element. @return Account Element */ public int getC_ElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default Account. @param Default_Account Name of the Default Account Column */ public void setDefault_Account (String Default_Account) { set_Value (COLUMNNAME_Default_Account, Default_Account); } /** Get Default Account. @return Name of the Default Account Column */ public String getDefault_Account () { return (String)get_Value(COLUMNNAME_Default_Account); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Element Name. @param ElementName Name of the Element */ public void setElementName (String ElementName) { set_Value (COLUMNNAME_ElementName, ElementName); } /** Get Element Name. @return Name of the Element */ public String getElementName () { return (String)get_Value(COLUMNNAME_ElementName); } /** Set Import Account. @param I_ElementValue_ID Import Account Value */ public void setI_ElementValue_ID (int I_ElementValue_ID) { if (I_ElementValue_ID < 1) set_ValueNoCheck (COLUMNNAME_I_ElementValue_ID, null); else set_ValueNoCheck (COLUMNNAME_I_ElementValue_ID, Integer.valueOf(I_ElementValue_ID)); } /** Get Import Account. @return Import Account Value */ public int getI_ElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_I_ElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Import Error Message. @param I_ErrorMsg Messages generated from import process */ public void setI_ErrorMsg (String I_ErrorMsg) { set_Value (COLUMNNAME_I_ErrorMsg, I_ErrorMsg); } /** Get Import Error Message. @return Messages generated from import process */ public String getI_ErrorMsg () { return (String)get_Value(COLUMNNAME_I_ErrorMsg); } /** Set Imported. @param I_IsImported Has this import been processed */ public void setI_IsImported (boolean I_IsImported) { set_Value (COLUMNNAME_I_IsImported, Boolean.valueOf(I_IsImported)); } /** Get Imported. @return Has this import been processed */ public boolean isI_IsImported () { Object oo = get_Value(COLUMNNAME_I_IsImported); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Document Controlled. @param IsDocControlled Control account - If an account is controlled by a document, you cannot post manually to it */ public void setIsDocControlled (boolean IsDocControlled) { set_Value (COLUMNNAME_IsDocControlled, Boolean.valueOf(IsDocControlled)); } /** Get Document Controlled. @return Control account - If an account is controlled by a document, you cannot post manually to it */ public boolean isDocControlled () { Object oo = get_Value(COLUMNNAME_IsDocControlled); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Summary Level. @param IsSummary This is a summary entity */ public void setIsSummary (boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary)); } /** Get Summary Level. @return This is a summary entity */ public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } public I_C_ElementValue getParentElementValue() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getParentElementValue_ID(), get_TrxName()); } /** Set Parent Account. @param ParentElementValue_ID The parent (summary) account */ public void setParentElementValue_ID (int ParentElementValue_ID) { if (ParentElementValue_ID < 1) set_Value (COLUMNNAME_ParentElementValue_ID, null); else set_Value (COLUMNNAME_ParentElementValue_ID, Integer.valueOf(ParentElementValue_ID)); } /** Get Parent Account. @return The parent (summary) account */ public int getParentElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ParentElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Parent Key. @param ParentValue Key if the Parent */ public void setParentValue (String ParentValue) { set_Value (COLUMNNAME_ParentValue, ParentValue); } /** Get Parent Key. @return Key if the Parent */ public String getParentValue () { return (String)get_Value(COLUMNNAME_ParentValue); } /** Set Post Actual. @param PostActual Actual Values can be posted */ public void setPostActual (boolean PostActual) { set_Value (COLUMNNAME_PostActual, Boolean.valueOf(PostActual)); } /** Get Post Actual. @return Actual Values can be posted */ public boolean isPostActual () { Object oo = get_Value(COLUMNNAME_PostActual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Post Budget. @param PostBudget Budget values can be posted */ public void setPostBudget (boolean PostBudget) { set_Value (COLUMNNAME_PostBudget, Boolean.valueOf(PostBudget)); } /** Get Post Budget. @return Budget values can be posted */ public boolean isPostBudget () { Object oo = get_Value(COLUMNNAME_PostBudget); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Post Encumbrance. @param PostEncumbrance Post commitments to this account */ public void setPostEncumbrance (boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, Boolean.valueOf(PostEncumbrance)); } /** Get Post Encumbrance. @return Post commitments to this account */ public boolean isPostEncumbrance () { Object oo = get_Value(COLUMNNAME_PostEncumbrance); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Post Statistical. @param PostStatistical Post statistical quantities to this account? */ public void setPostStatistical (boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, Boolean.valueOf(PostStatistical)); } /** Get Post Statistical. @return Post statistical quantities to this account? */ public boolean isPostStatistical () { Object oo = get_Value(COLUMNNAME_PostStatistical); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getValue()); } }
arthurmelo88/palmetalADP
adempiere_360/base/src/org/compiere/model/X_I_ElementValue.java
Java
gpl-2.0
15,150
/* Copyright 2010 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.myblockchain.clusterj.openjpatest; public class TimestampAsUtilDateTest extends com.myblockchain.clusterj.jpatest.TimestampAsUtilDateTest { }
MrDunne/myblockchain
storage/ndb/clusterj/clusterj-openjpa/src/test/java/com/mysql/clusterj/openjpatest/TimestampAsUtilDateTest.java
Java
gpl-2.0
922
/* * RomRaider Open-Source Tuning, Logging and Reflashing * Copyright (C) 2006-2022 RomRaider.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.romraider.maps; import java.io.Serializable; import java.text.ParseException; import java.util.LinkedList; import java.util.StringTokenizer; import org.apache.log4j.Logger; import com.romraider.Settings; import com.romraider.Settings.Endian; import com.romraider.editor.ecu.ECUEditorManager; import com.romraider.util.ByteUtil; import com.romraider.util.JEPUtil; import com.romraider.util.NumberUtil; import com.romraider.util.SettingsManager; import com.romraider.xml.RomAttributeParser; public class DataCell implements Serializable { private static final long serialVersionUID = 1111479947434817639L; private static final Logger LOGGER = Logger.getLogger(DataCell.class); //View we need to keep up to date private DataCellView view = null; private Table table; //This sounds like a View property, but the manipulations //functions depend on this, so its better to put it here private boolean isSelected = false; private double binValue = 0.0; private double originalValue = 0.0; private double compareToValue = 0.0; private String liveValue = Settings.BLANK; private String staticText = null; private Rom rom; //Index within table private int index; public DataCell(Table table, Rom rom) { this.table = table; this.rom = rom; } public DataCell(Table table, String staticText, Rom rom) { this(table, rom); final StringTokenizer st = new StringTokenizer(staticText, DataCellView.ST_DELIMITER); if (st.hasMoreTokens()) { this.staticText = st.nextToken(); } } public DataCell(Table table, int index, Rom rom) { this(table, rom); this.index = index; updateBinValueFromMemory(); this.originalValue = this.binValue; registerDataCell(this); } public void setTable(Table t) { this.table = t; } public void setRom(Rom rom) { this.rom = rom; } public byte[] getBinary() { return rom.getBinary(); } private double getValueFromMemory(int index) { double dataValue = 0.0; byte[] input = getBinary(); int storageType = table.getStorageType(); Endian endian = table.getEndian(); int ramOffset = table.getRamOffset(); int storageAddress = table.getStorageAddress(); boolean signed = table.isSignedData(); // populate data cells if (storageType == Settings.STORAGE_TYPE_FLOAT) { //float storage type byte[] byteValue = new byte[4]; byteValue[0] = input[storageAddress + index * 4 - table.getRamOffset()]; byteValue[1] = input[storageAddress + index * 4 - table.getRamOffset() + 1]; byteValue[2] = input[storageAddress + index * 4 - table.getRamOffset() + 2]; byteValue[3] = input[storageAddress + index * 4 - table.getRamOffset() + 3]; dataValue = RomAttributeParser.byteToFloat(byteValue, table.getEndian(), table.getMemModelEndian()); } else if (storageType == Settings.STORAGE_TYPE_MOVI20 || storageType == Settings.STORAGE_TYPE_MOVI20S) { // when data is in MOVI20 instruction dataValue = RomAttributeParser.parseByteValue(input, endian, storageAddress + index * 3 - ramOffset, storageType, signed); } else { // integer storage type if(table.getBitMask() == 0) { dataValue = RomAttributeParser.parseByteValue(input, endian, storageAddress + index * storageType - ramOffset, storageType, signed); } else { dataValue = RomAttributeParser.parseByteValueMasked(input, endian, storageAddress + index * storageType - ramOffset, storageType, signed, table.getBitMask()); } } return dataValue; } private double getValueFromMemory() { if (table.getDataLayout() == Table.DataLayout.BOSCH_SUBTRACT) { //Bosch Motronic subtract method double dataValue = Math.pow(2, 8 * table.getStorageType()); for (int j = table.data.length - 1; j >= index; j--) { dataValue -= getValueFromMemory(j); } return dataValue; } else { return getValueFromMemory(index); } } public void saveBinValueInFile() { if (table.getName().contains("Checksum Fix")) return; byte[] binData = getBinary(); int userLevel = table.getUserLevel(); int storageType = table.getStorageType(); Endian endian = table.getEndian(); int ramOffset = table.getRamOffset(); int storageAddress = table.getStorageAddress(); boolean isBoschSubtract = table.getDataLayout() == Table.DataLayout.BOSCH_SUBTRACT; double crossedValue = 0; //Do reverse cross referencing in for Bosch Subtract Axis array if(isBoschSubtract) { for (int i = table.data.length - 1; i >=index ; i--) { if(i == index) crossedValue -= table.data[i].getBinValue(); else if(i == table.data.length - 1) crossedValue = Math.pow(2, 8 * storageType) - getValueFromMemory(i); else { crossedValue -= getValueFromMemory(i); } } } if (userLevel <= getSettings().getUserLevel() && (userLevel < 5 || getSettings().isSaveDebugTables()) ) { // determine output byte values byte[] output; int mask = table.getBitMask(); if (storageType != Settings.STORAGE_TYPE_FLOAT) { int finalValue = 0; // convert byte values if(table.isStaticDataTable() && storageType > 0) { LOGGER.warn("Static data table: " + table.toString() + ", storageType: "+storageType); try { finalValue = Integer.parseInt(getStaticText()); } catch (NumberFormatException ex) { LOGGER.error("Error parsing static data table value: " + getStaticText(), ex); LOGGER.error("Validate the table definition storageType and data value."); return; } } else if(table.isStaticDataTable() && storageType < 1) { // Do not save the value. //if (LOGGER.isDebugEnabled()) // LOGGER.debug("The static data table value will not be saved."); return; } else { finalValue = (int) (isBoschSubtract ? crossedValue : getBinValue()); } if(mask != 0) { // Shift left again finalValue = finalValue << ByteUtil.firstOneOfMask(mask); } output = RomAttributeParser.parseIntegerValue(finalValue, endian, storageType); int byteLength = storageType; if (storageType == Settings.STORAGE_TYPE_MOVI20 || storageType == Settings.STORAGE_TYPE_MOVI20S) { // when data is in MOVI20 instruction byteLength = 3; } //If mask enabled, only change bits within the mask if(mask != 0) { int tempBitMask = 0; for (int z = 0; z < byteLength; z++) { // insert into file tempBitMask = mask; //Trim mask depending on byte, from left to right tempBitMask = (tempBitMask & (0xFF << 8 * (byteLength - 1 - z))) >> 8*(byteLength - 1 - z); // Delete old bits binData[index * byteLength + z + storageAddress - ramOffset] &= ~tempBitMask; // Overwrite binData[index * byteLength + z + storageAddress - ramOffset] |= output[z]; } } //No Masking else { for (int z = 0; z < byteLength; z++) { // insert into file binData[index * byteLength + z + storageAddress - ramOffset] = output[z]; } } } else { // float // convert byte values output = RomAttributeParser.floatToByte((float) getBinValue(), endian, table.getMemModelEndian()); for (int z = 0; z < 4; z++) { // insert in to file binData[index * 4 + z + storageAddress - ramOffset] = output[z]; } } } //On the Bosch substract model, we need to update all previous cells, because they depend on our value if(isBoschSubtract && index > 0) table.data[index-1].saveBinValueInFile(); checkForDataUpdates(); } public void registerDataCell(DataCell cell) { int memoryIndex = getMemoryStartAddress(cell); if (rom.byteCellMapping.containsKey(memoryIndex)) { rom.byteCellMapping.get(memoryIndex).add(cell); } else { LinkedList<DataCell> l = new LinkedList<DataCell>(); l.add(cell); rom.byteCellMapping.put(memoryIndex, l); } } public void checkForDataUpdates() { int memoryIndex = getMemoryStartAddress(this); if (rom.byteCellMapping.containsKey(memoryIndex)){ for(DataCell c : rom.byteCellMapping.get(memoryIndex)) { c.updateBinValueFromMemory(); } } } public static int getMemoryStartAddress(DataCell cell) { Table t = cell.getTable(); return t.getStorageAddress() + cell.getIndexInTable() * t.getStorageType() - t.getRamOffset(); } public Settings getSettings() { return SettingsManager.getSettings(); } public void setSelected(boolean selected) { if(!table.isStaticDataTable() && this.isSelected != selected) { this.isSelected = selected; if(view!=null) { ECUEditorManager.getECUEditor().getTableToolBar().updateTableToolBar(table); view.drawCell(); } } } public boolean isSelected() { return isSelected; } public void updateBinValueFromMemory() { this.binValue = getValueFromMemory(); updateView(); } public void setDataView(DataCellView v) { view = v; } public int getIndexInTable() { return index; } private void updateView() { if(view != null) view.drawCell(); } public Table getTable() { return this.table; } public String getStaticText() { return staticText; } public String getLiveValue() { return this.liveValue; } public void setLiveDataTraceValue(String liveValue) { if(this.liveValue != liveValue) { this.liveValue = liveValue; updateView(); } } public double getBinValue() { return binValue; } public double getOriginalValue() { return originalValue; } public double getCompareToValue() { return compareToValue; } public double getRealValue() { if(table.getCurrentScale() == null) return binValue; return JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue); } public void setRealValue(String input) throws UserLevelException { // create parser input = input.replaceAll(DataCellView.REPLACE_TEXT, Settings.BLANK); try { double result = 0.0; if (!"x".equalsIgnoreCase(input)) { if(table.getCurrentScale().getByteExpression() == null) { result = table.getCurrentScale().approximateToByteFunction(NumberUtil.doubleValue(input), table.getStorageType(), table.isSignedData()); } else { result = JEPUtil.evaluate(table.getCurrentScale().getByteExpression(), NumberUtil.doubleValue(input)); } if (table.getStorageType() != Settings.STORAGE_TYPE_FLOAT) { result = (int) Math.round(result); } if(binValue != result) { this.setBinValue(result); } } } catch (ParseException e) { // Do nothing. input is null or not a valid number. } } public double getCompareValue() { return binValue - compareToValue; } public double getRealCompareValue() { return JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue) - JEPUtil.evaluate(table.getCurrentScale().getExpression(), compareToValue); } public double getRealCompareChangeValue() { double realBinValue = JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue); double realCompareValue = JEPUtil.evaluate(table.getCurrentScale().getExpression(), compareToValue); if(realCompareValue != 0.0) { // Compare change formula ((V2 - V1) / |V1|). return ((realBinValue - realCompareValue) / Math.abs(realCompareValue)); } else { // Use this to avoid divide by 0 or infinite increase. return realBinValue - realCompareValue; } } public void setBinValue(double newBinValue) throws UserLevelException { if(binValue == newBinValue || table.locked || table.getName().contains("Checksum Fix")) { return; } if (table.userLevel > getSettings().getUserLevel()) throw new UserLevelException(table.userLevel); double checkedValue = newBinValue; // make sure it's in range if(checkedValue < table.getMinAllowedBin()) { checkedValue = table.getMinAllowedBin(); } if(checkedValue > table.getMaxAllowedBin()) { checkedValue = table.getMaxAllowedBin(); } if(binValue == checkedValue) { return; } // set bin. binValue = checkedValue; saveBinValueInFile(); updateView(); } public void increment(double increment) throws UserLevelException { double oldValue = getRealValue(); if (table.getCurrentScale().getCoarseIncrement() < 0.0) { increment = 0.0 - increment; } double incResult = 0; if(table.getCurrentScale().getByteExpression() == null) { incResult = table.getCurrentScale().approximateToByteFunction(oldValue + increment, table.getStorageType(), table.isSignedData()); } else { incResult = JEPUtil.evaluate(table.getCurrentScale().getByteExpression(), (oldValue + increment)); } if (table.getStorageType() == Settings.STORAGE_TYPE_FLOAT) { if(binValue != incResult) { this.setBinValue(incResult); } } else { int roundResult = (int) Math.round(incResult); if(binValue != roundResult) { this.setBinValue(roundResult); } } // make sure table is incremented if change isn't great enough int maxValue = (int) Math.pow(8, table.getStorageType()); if (table.getStorageType() != Settings.STORAGE_TYPE_FLOAT && oldValue == getRealValue() && binValue > 0.0 && binValue < maxValue) { if (LOGGER.isDebugEnabled()) LOGGER.debug(maxValue + " " + binValue); increment(increment * 2); } } public void undo() throws UserLevelException { this.setBinValue(originalValue); } public void setRevertPoint() { this.setOriginalValue(binValue); updateView(); } public void setOriginalValue(double originalValue) { this.originalValue = originalValue; } public void setCompareValue(DataCell compareCell) { if(Settings.DataType.BIN == table.getCompareValueType()) { if(this.compareToValue == compareCell.binValue) { return; } this.compareToValue = compareCell.binValue; } else { if(this.compareToValue == compareCell.originalValue) { return; } this.compareToValue = compareCell.originalValue; } } public void multiply(double factor) throws UserLevelException { if(table.getCurrentScale().getCategory().equals("Raw Value")) setBinValue(binValue * factor); else { String newValue = (getRealValue() * factor) + ""; //We need to convert from dot to comma, in the case of EU Format. // This is because getRealValue to String has dot notation. if(NumberUtil.getSeperator() == ',') newValue = newValue.replace('.', ','); setRealValue(newValue); } } @Override public boolean equals(Object other) { if(other == null) { return false; } if(!(other instanceof DataCell)) { return false; } DataCell otherCell = (DataCell) other; if(this.table.isStaticDataTable() != otherCell.table.isStaticDataTable()) { return false; } return binValue == otherCell.binValue; } }
dschultzca/RomRaider
src/main/java/com/romraider/maps/DataCell.java
Java
gpl-2.0
18,799
<?php // $Id$ /*! * Dynamic display block module template: vsdupright60p - pager template * (c) Copyright Phelsa Information Technology, 2011. All rights reserved. * Version 1.2 (09-AUG-2011) * Licenced under GPL license * http://www.gnu.org/licenses/gpl.html */ /** * @file * Dynamic display block module template: vsdupright60p - pager template * - Scrollable pager with images * * Available variables: * - $views_slideshow_ddblock_pager_settings['delta']: Block number of the block. * - $views_slideshow_ddblock_pager_settings['pager']: Type of pager to add * - $views_slideshow_ddblock_pager_settings['pager2']: Add prev/next pager * - $views_slideshow_ddblock_pager_settings['pager_position']: position of the slider (top | bottom) * - $views_slideshow_ddblock_pager_items: array with pager_items * * notes: don't change the ID names, they are used by the jQuery script. */ $settings = $views_slideshow_ddblock_pager_settings; // add tools.scrollable-1.0.5.min.js file drupal_add_js(drupal_get_path('module', 'views_slideshow_ddblock') . '/js/tools.scrollable-1.0.5.min.js'); ?> <?php if ($settings['pager_position'] == 'bottom'): ?> <div class="spacer-horizontal"><b></b></div> <?php endif; ?> <!-- scrollable pager container --> <div id="views-slideshow-ddblock-scrollable-pager-<?php print $settings['delta'] ?>" class="scrollable-pager clear-block border"> <!-- prev/next page on slide --> <?php if ($settings['pager2'] == 1 && $settings['pager2_position']['slide'] === 'slide'): ?> <div class="views-slideshow-ddblock-prev-next-slide"> <div class="prev-container"> <a class="prev" href="#"><?php print $settings['pager2_slide_prev']?></a> </div> <div class="next-container"> <a class="next" href="#"><?php print $settings['pager2_slide_next'] ?></a> </div> </div> <?php endif; ?> <!-- custom "previous" links --> <!--<div class="prevPage"></div>--> <div class="prev"></div> <!-- scrollable part --> <div class="vsd-scrollable-pager clear-block border"> <div class="items <?php print $settings['pager'] ?>-inner clear-block border"> <?php if ($views_slideshow_ddblock_pager_items): ?> <?php $item_counter=1; ?> <?php foreach ($views_slideshow_ddblock_pager_items as $pager_item): ?> <div class="<?php print $settings['pager'] ?>-item <?php print $settings['pager'] ?>-item-<?php print $item_counter ?>"> <a href="#" title="navigate to topic" class="pager-link"><?php print $pager_item['pager_image'];?></a> </div> <!-- /custom-pager-item --> <?php $item_counter++; ?> <?php endforeach; ?> <?php endif; ?> </div> <!-- /pager-inner--> </div> <!-- /vsd-scrollable-pager --> <!-- custom "next" links --> <div class="next"></div> <!--<div class="nextPage"></div>--> <!-- navigator --> <div class="navi"></div> </div> <!-- /scrollable-pager--> <?php if ($settings['pager_position'] == 'top'): ?> <div class="spacer-horizontal"><b></b></div> <?php endif; ?>
54interndrupal/54intern
sites/all/themes/ffintern/custom/modules/views_slideshow_ddblock/views-slideshow-ddblock-pager-content--vsdupright60p.tpl.php
PHP
gpl-2.0
2,988
<?php /* * @package Joomla 1.5 * @copyright Copyright (C) 2005 Open Source Matters. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * * @component Phoca Component * @copyright Copyright (C) Jan Pavelka www.phoca.cz * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * */ class PhocaGalleryHelperComment { function closeTags($comment, $tag, $endTag) { if (substr_count(strtolower($comment), $tag) > substr_count(strtolower($comment), $endTag)) { $comment .= $endTag; $comment = PhocaGalleryHelperComment::closeTags($comment, $tag, $endTag); } return $comment; } function getSmileys() { $smileys = array(); $smileys[':)'] = 'icon-s-smile'; $smileys[':lol:'] = 'icon-s-lol'; $smileys[':('] = 'icon-s-sad'; $smileys[':?'] = 'icon-s-confused'; $smileys[':wink:'] = 'icon-s-wink'; return $smileys; } /* * @based based on Seb's BB-Code-Parser script by seb * @url http://www.traum-projekt.com/forum/54-traum-scripts/25292-sebs-bb-code-parser.html */ function bbCodeReplace($string, $currentString = '') { while($currentString != $string) { $currentString = $string; $string = preg_replace_callback('{\[(\w+)((=)(.+)|())\]((.|\n)*)\[/\1\]}U', array('PhocaGalleryHelperComment', 'bbCodeCallback'), $string); } return $string; } /* * @based based on Seb's BB-Code-Parser script by seb * @url http://www.traum-projekt.com/forum/54-traum-scripts/25292-sebs-bb-code-parser.html */ function bbCodeCallback($matches) { $tag = trim($matches[1]); $bodyString = $matches[6]; $argument = $matches[4]; switch($tag) { case 'b': case 'i': case 'u': $replacement = '<'.$tag.'>'.$bodyString.'</'.$tag.'>'; break; default: // unknown tag => reconstruct and return original expression $replacement = '[' . $tag . ']' . $bodyString . '[/' . $tag .']'; break; } return $replacement; } }
xonev/SUDWebsite
administrator/components/com_phocagallery/helpers/phocagallerycomment.php
PHP
gpl-2.0
2,016
void draw(){ TString histoFileName = "data0/histo.root"; TFile* histoFile = TFile::Open(histoFileName); TH3D* hDetEventTime = (TH3D*) histoFile->Get("hDetEventTime"); printf("Nentries:%i\n",hDetEventTime->GetEntries()); for (Int_t det=1;det<=6;det++){ TCanvas* c1 = new TCanvas(Form("c1_det%i",det),Form("c1_det%i",det),800,500); gPad->SetRightMargin(0.02); gPad->SetLeftMargin(0.12); gPad->SetLogy(); TH1D* hTime = hDetEventTime->ProjectionZ(Form("StsEvent%i",det),det,det,1,1000); hTime->SetStats(0); hTime->SetLineColor(kBlue); hTime->SetLineWidth(2); if (det==1) hTime->SetTitle("STS @ 30 cm; time, ns;Entries"); if (det==2) hTime->SetTitle("STS @ 100 cm; time, ns;Entries"); if (det==3) hTime->SetTitle("MuCh @ 130 cm; time, ns;Entries"); if (det==4) hTime->SetTitle("MuCh @ 315 cm; time, ns;Entries"); if (det==5) hTime->SetTitle("TOF @ 1000 cm; time, ns;Entries"); if (det==6) hTime->SetTitle("TRD @ 948 cm; time, ns;Entries"); hTime->Draw(); c1->Print(".png"); } TCanvas* c2 = new TCanvas("c2","Primary tracks distribution",800,500); gPad->SetRightMargin(0.04); // c2->Divide(2,1); // TH1D* hNPrimaryTracks = (TH1D*) histoFile->Get("hNPrimaryTracks"); TH1D* hNPrimaryTracksInAcceptance = (TH1D*) histoFile->Get("hNPrimaryTracksInAcceptance"); hNPrimaryTracksInAcceptance->SetLineColor(kBlue); // c2->cd(1); // hNPrimaryTracks->Draw(); // c2->cd(2); hNPrimaryTracksInAcceptance->SetTitle(";Number of primary tracks in CBM acceptance;Entries"); hNPrimaryTracksInAcceptance->Draw(); // gPad->Print(".png"); TCanvas* c3 = new TCanvas("c3","tau",800,500); gPad->SetRightMargin(0.04); gPad->SetRightMargin(0.12); TF1* f1 = new TF1("time","(1-exp(-x/[0]))",0,600); f1->SetParameter(0,100); f1->SetLineColor(kBlue); f1->Draw(); f1->SetTitle(";time, ns;Probability"); TH1D* hStsPointsZ = (TH1D*) histoFile->Get("hStsPointsZ"); TH1D* hTrdPointsZ = (TH1D*) histoFile->Get("hTrdPointsZ"); TH1D* hTofPointsZ = (TH1D*) histoFile->Get("hTofPointsZ"); TH1D* hMuchPointsZ = (TH1D*) histoFile->Get("hMuchPointsZ"); TCanvas* c4 = new TCanvas("c4","z position",1000,800); c4->Divide(2,2); c4->cd(1); hStsPointsZ->Draw(); c4->cd(2); hTrdPointsZ->Draw(); c4->cd(3); hTofPointsZ->Draw(); c4->cd(4); hMuchPointsZ->Draw(); }
desdemonda/cbmroot
macro/analysis/timing/draw.C
C++
gpl-2.0
2,433
<?php /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes for reading and writing Avro data to AvroIO objects. * * @package Avro * * @todo Implement JSON encoding, as is required by the Avro spec. */ /** * Exceptions arising from writing or reading Avro data. * * @package Avro */ class AvroIOTypeException extends AvroException { /** * @param AvroSchema $expected_schema * @param mixed $datum */ public function __construct($expected_schema, $datum) { parent::__construct(sprintf('The datum %s is not an example of schema %s', var_export($datum, true), $expected_schema)); } } /** * Exceptions arising from incompatibility between * reader and writer schemas. * * @package Avro */ class AvroIOSchemaMatchException extends AvroException { /** * @param AvroSchema $writers_schema * @param AvroSchema $readers_schema */ function __construct($writers_schema, $readers_schema) { parent::__construct( sprintf("Writer's schema %s and Reader's schema %s do not match.", $writers_schema, $readers_schema)); } } /** * Handles schema-specific writing of data to the encoder. * * Ensures that each datum written is consistent with the writer's schema. * * @package Avro */ class AvroIODatumWriter { /** * Schema used by this instance to write Avro data. * @var AvroSchema */ private $writers_schema; /** * @param AvroSchema $writers_schema */ function __construct($writers_schema=null) { $this->writers_schema = $writers_schema; } /** * @param AvroSchema $writers_schema * @param $datum * @param AvroIOBinaryEncoder $encoder * @return mixed * @throws AvroException * @throws AvroIOTypeException if $datum is invalid for $writers_schema * @throws AvroSchemaParseException */ function write_data($writers_schema, $datum, $encoder) { if (!AvroSchema::is_valid_datum($writers_schema, $datum)) throw new AvroIOTypeException($writers_schema, $datum); switch ($writers_schema->type()) { case AvroSchema::NULL_TYPE: return $encoder->write_null($datum); case AvroSchema::BOOLEAN_TYPE: return $encoder->write_boolean($datum); case AvroSchema::INT_TYPE: return $encoder->write_int($datum); case AvroSchema::LONG_TYPE: return $encoder->write_long($datum); case AvroSchema::FLOAT_TYPE: return $encoder->write_float($datum); case AvroSchema::DOUBLE_TYPE: return $encoder->write_double($datum); case AvroSchema::STRING_TYPE: return $encoder->write_string($datum); case AvroSchema::BYTES_TYPE: return $encoder->write_bytes($datum); case AvroSchema::ARRAY_SCHEMA: return $this->write_array($writers_schema, $datum, $encoder); case AvroSchema::MAP_SCHEMA: return $this->write_map($writers_schema, $datum, $encoder); case AvroSchema::FIXED_SCHEMA: return $this->write_fixed($writers_schema, $datum, $encoder); case AvroSchema::ENUM_SCHEMA: return $this->write_enum($writers_schema, $datum, $encoder); case AvroSchema::RECORD_SCHEMA: case AvroSchema::ERROR_SCHEMA: case AvroSchema::REQUEST_SCHEMA: return $this->write_record($writers_schema, $datum, $encoder); case AvroSchema::UNION_SCHEMA: return $this->write_union($writers_schema, $datum, $encoder); default: throw new AvroException(sprintf('Uknown type: %s', $writers_schema->type)); } } /** * @param $datum * @param AvroIOBinaryEncoder $encoder */ function write($datum, $encoder) { $this->write_data($this->writers_schema, $datum, $encoder); } /**#@+ * @param AvroSchema $writers_schema * @param null|boolean|int|float|string|array $datum item to be written * @param AvroIOBinaryEncoder $encoder */ private function write_array($writers_schema, $datum, $encoder) { $datum_count = count($datum); if (0 < $datum_count) { $encoder->write_long($datum_count); $items = $writers_schema->items(); foreach ($datum as $item) $this->write_data($items, $item, $encoder); } return $encoder->write_long(0); } /** * @param $writers_schema * @param $datum * @param $encoder * @throws AvroException * @throws AvroIOTypeException */ private function write_map($writers_schema, $datum, $encoder) { $datum_count = count($datum); if ($datum_count > 0) { $encoder->write_long($datum_count); foreach ($datum as $k => $v) { $encoder->write_string($k); $this->write_data($writers_schema->values(), $v, $encoder); } } $encoder->write_long(0); } /** * @param $writers_schema * @param $datum * @param $encoder * @throws AvroException * @throws AvroIOTypeException * @throws AvroSchemaParseException */ private function write_union($writers_schema, $datum, $encoder) { $datum_schema_index = -1; $datum_schema = null; foreach ($writers_schema->schemas() as $index => $schema) if (AvroSchema::is_valid_datum($schema, $datum)) { $datum_schema_index = $index; $datum_schema = $schema; break; } if (is_null($datum_schema)) throw new AvroIOTypeException($writers_schema, $datum); $encoder->write_long($datum_schema_index); $this->write_data($datum_schema, $datum, $encoder); } /** * @param $writers_schema * @param $datum * @param $encoder * @return mixed */ private function write_enum($writers_schema, $datum, $encoder) { $datum_index = $writers_schema->symbol_index($datum); return $encoder->write_int($datum_index); } /** * @param $writers_schema * @param $datum * @param $encoder * @return mixed */ private function write_fixed($writers_schema, $datum, $encoder) { /** * NOTE Unused $writers_schema parameter included for consistency * with other write_* methods. */ return $encoder->write($datum); } /** * @param $writers_schema * @param $datum * @param $encoder * @throws AvroException * @throws AvroIOTypeException */ private function write_record($writers_schema, $datum, $encoder) { foreach ($writers_schema->fields() as $field) $this->write_data($field->type(), $datum[$field->name()], $encoder); } /**#@-*/ } /** * Encodes and writes Avro data to an AvroIO object using * Avro binary encoding. * * @package Avro */ class AvroIOBinaryEncoder { /** * Performs encoding of the given float value to a binary string * * XXX: This is <b>not</b> endian-aware! The {@link Avro::check_platform()} * called in {@link AvroIOBinaryEncoder::__construct()} should ensure the * library is only used on little-endian platforms, which ensure the little-endian * encoding required by the Avro spec. * * @param float $float * @return string bytes * @see Avro::check_platform() */ static function float_to_int_bits($float) { return pack('f', (float) $float); } /** * Performs encoding of the given double value to a binary string * * XXX: This is <b>not</b> endian-aware! See comments in * {@link AvroIOBinaryEncoder::float_to_int_bits()} for details. * * @param double $double * @return string bytes */ static function double_to_long_bits($double) { return pack('d', (double) $double); } /** * @param int|string $n * @return string long $n encoded as bytes * @internal This relies on 64-bit PHP. */ static public function encode_long($n) { $n = (int) $n; $n = ($n << 1) ^ ($n >> 63); $str = ''; while (0 != ($n & ~0x7F)) { $str .= chr(($n & 0x7F) | 0x80); $n >>= 7; } $str .= chr($n); return $str; } /** * @var AvroIO */ private $io; /** * @param AvroIO $io object to which data is to be written. * */ function __construct($io) { Avro::check_platform(); $this->io = $io; } /** * @param null $datum actual value is ignored * @return null */ function write_null($datum) { return null; } /** * @param boolean $datum */ function write_boolean($datum) { $byte = $datum ? chr(1) : chr(0); $this->write($byte); } /** * @param int $datum */ function write_int($datum) { $this->write_long($datum); } /** * @param int $n */ function write_long($n) { if (Avro::uses_gmp()) $this->write(AvroGMP::encode_long($n)); else $this->write(self::encode_long($n)); } /** * @param float $datum * @uses self::float_to_int_bits() */ public function write_float($datum) { $this->write(self::float_to_int_bits($datum)); } /** * @param float $datum * @uses self::double_to_long_bits() */ public function write_double($datum) { $this->write(self::double_to_long_bits($datum)); } /** * @param string $str * @uses self::write_bytes() */ function write_string($str) { $this->write_bytes($str); } /** * @param string $bytes */ function write_bytes($bytes) { $this->write_long(strlen($bytes)); $this->write($bytes); } /** * @param string $datum */ function write($datum) { $this->io->write($datum); } } /** * Handles schema-specifc reading of data from the decoder. * * Also handles schema resolution between the reader and writer * schemas (if a writer's schema is provided). * * @package Avro */ class AvroIODatumReader { /** * * @param AvroSchema $writers_schema * @param AvroSchema $readers_schema * @return boolean true if the schemas are consistent with * each other and false otherwise. */ static function schemas_match($writers_schema, $readers_schema) { $writers_schema_type = $writers_schema->type; $readers_schema_type = $readers_schema->type; if (AvroSchema::UNION_SCHEMA == $writers_schema_type || AvroSchema::UNION_SCHEMA == $readers_schema_type) return true; if ($writers_schema_type == $readers_schema_type) { if (AvroSchema::is_primitive_type($writers_schema_type)) return true; switch ($readers_schema_type) { case AvroSchema::MAP_SCHEMA: return self::attributes_match($writers_schema->values(), $readers_schema->values(), array(AvroSchema::TYPE_ATTR)); case AvroSchema::ARRAY_SCHEMA: return self::attributes_match($writers_schema->items(), $readers_schema->items(), array(AvroSchema::TYPE_ATTR)); case AvroSchema::ENUM_SCHEMA: return self::attributes_match($writers_schema, $readers_schema, array(AvroSchema::FULLNAME_ATTR)); case AvroSchema::FIXED_SCHEMA: return self::attributes_match($writers_schema, $readers_schema, array(AvroSchema::FULLNAME_ATTR, AvroSchema::SIZE_ATTR)); case AvroSchema::RECORD_SCHEMA: case AvroSchema::ERROR_SCHEMA: return self::attributes_match($writers_schema, $readers_schema, array(AvroSchema::FULLNAME_ATTR)); case AvroSchema::REQUEST_SCHEMA: // XXX: This seems wrong return true; // XXX: no default } if (AvroSchema::INT_TYPE == $writers_schema_type && in_array($readers_schema_type, array(AvroSchema::LONG_TYPE, AvroSchema::FLOAT_TYPE, AvroSchema::DOUBLE_TYPE))) return true; if (AvroSchema::LONG_TYPE == $writers_schema_type && in_array($readers_schema_type, array(AvroSchema::FLOAT_TYPE, AvroSchema::DOUBLE_TYPE))) return true; if (AvroSchema::FLOAT_TYPE == $writers_schema_type && AvroSchema::DOUBLE_TYPE == $readers_schema_type) return true; return false; } } /** * Checks equivalence of the given attributes of the two given schemas. * * @param AvroSchema $schema_one * @param AvroSchema $schema_two * @param string[] $attribute_names array of string attribute names to compare * * @return boolean true if the attributes match and false otherwise. */ static function attributes_match($schema_one, $schema_two, $attribute_names) { foreach ($attribute_names as $attribute_name) if ($schema_one->attribute($attribute_name) != $schema_two->attribute($attribute_name)) return false; return true; } /** * @var AvroSchema */ private $writers_schema; /** * @var AvroSchema */ private $readers_schema; /** * @param AvroSchema $writers_schema * @param AvroSchema $readers_schema */ function __construct($writers_schema=null, $readers_schema=null) { $this->writers_schema = $writers_schema; $this->readers_schema = $readers_schema; } /** * @param AvroSchema $readers_schema */ public function set_writers_schema($readers_schema) { $this->writers_schema = $readers_schema; } /** * @param AvroIOBinaryDecoder $decoder * @return string */ public function read($decoder) { if (is_null($this->readers_schema)) $this->readers_schema = $this->writers_schema; return $this->read_data($this->writers_schema, $this->readers_schema, $decoder); } /**#@+ * @param AvroSchema $writers_schema * @param AvroSchema $readers_schema * @param AvroIOBinaryDecoder $decoder */ /** * @param $writers_schema * @param $readers_schema * @param $decoder * @return mixed * @throws AvroException * @throws AvroIOSchemaMatchException */ public function read_data($writers_schema, $readers_schema, $decoder) { if (!self::schemas_match($writers_schema, $readers_schema)) throw new AvroIOSchemaMatchException($writers_schema, $readers_schema); // Schema resolution: reader's schema is a union, writer's schema is not if (AvroSchema::UNION_SCHEMA == $readers_schema->type() && AvroSchema::UNION_SCHEMA != $writers_schema->type()) { foreach ($readers_schema->schemas() as $schema) if (self::schemas_match($writers_schema, $schema)) return $this->read_data($writers_schema, $schema, $decoder); throw new AvroIOSchemaMatchException($writers_schema, $readers_schema); } switch ($writers_schema->type()) { case AvroSchema::NULL_TYPE: return $decoder->read_null(); case AvroSchema::BOOLEAN_TYPE: return $decoder->read_boolean(); case AvroSchema::INT_TYPE: return $decoder->read_int(); case AvroSchema::LONG_TYPE: return $decoder->read_long(); case AvroSchema::FLOAT_TYPE: return $decoder->read_float(); case AvroSchema::DOUBLE_TYPE: return $decoder->read_double(); case AvroSchema::STRING_TYPE: return $decoder->read_string(); case AvroSchema::BYTES_TYPE: return $decoder->read_bytes(); case AvroSchema::ARRAY_SCHEMA: return $this->read_array($writers_schema, $readers_schema, $decoder); case AvroSchema::MAP_SCHEMA: return $this->read_map($writers_schema, $readers_schema, $decoder); case AvroSchema::UNION_SCHEMA: return $this->read_union($writers_schema, $readers_schema, $decoder); case AvroSchema::ENUM_SCHEMA: return $this->read_enum($writers_schema, $readers_schema, $decoder); case AvroSchema::FIXED_SCHEMA: return $this->read_fixed($writers_schema, $readers_schema, $decoder); case AvroSchema::RECORD_SCHEMA: case AvroSchema::ERROR_SCHEMA: case AvroSchema::REQUEST_SCHEMA: return $this->read_record($writers_schema, $readers_schema, $decoder); default: throw new AvroException(sprintf("Cannot read unknown schema type: %s", $writers_schema->type())); } } /** * @param $writers_schema * @param $readers_schema * @param $decoder * @return array * @throws AvroException * @throws AvroIOSchemaMatchException */ public function read_array($writers_schema, $readers_schema, $decoder) { $items = array(); $block_count = $decoder->read_long(); while (0 != $block_count) { if ($block_count < 0) { $block_count = -$block_count; $decoder->read_long(); // Read (and ignore) block size } for ($i = 0; $i < $block_count; $i++) $items []= $this->read_data($writers_schema->items(), $readers_schema->items(), $decoder); $block_count = $decoder->read_long(); } return $items; } /** * @param $writers_schema * @param $readers_schema * @param $decoder * @return array * @throws AvroException * @throws AvroIOSchemaMatchException */ public function read_map($writers_schema, $readers_schema, $decoder) { $items = array(); $pair_count = $decoder->read_long(); while (0 != $pair_count) { if ($pair_count < 0) { $pair_count = -$pair_count; // Note: Ingoring what we read here $decoder->read_long(); } for ($i = 0; $i < $pair_count; $i++) { $key = $decoder->read_string(); $items[$key] = $this->read_data($writers_schema->values(), $readers_schema->values(), $decoder); } $pair_count = $decoder->read_long(); } return $items; } /** * @param $writers_schema * @param $readers_schema * @param $decoder * @return mixed * @throws AvroException * @throws AvroIOSchemaMatchException */ public function read_union($writers_schema, $readers_schema, $decoder) { $schema_index = $decoder->read_long(); $selected_writers_schema = $writers_schema->schema_by_index($schema_index); return $this->read_data($selected_writers_schema, $readers_schema, $decoder); } /** * @param $writers_schema * @param $readers_schema * @param $decoder * @return string */ public function read_enum($writers_schema, $readers_schema, $decoder) { $symbol_index = $decoder->read_int(); $symbol = $writers_schema->symbol_by_index($symbol_index); if (!$readers_schema->has_symbol($symbol)) null; // FIXME: unset wrt schema resolution return $symbol; } /** * @param $writers_schema * @param $readers_schema * @param $decoder * @return string */ public function read_fixed($writers_schema, $readers_schema, $decoder) { return $decoder->read($writers_schema->size()); } /** * @param $writers_schema * @param $readers_schema * @param $decoder * @return array * @throws AvroException * @throws AvroIOSchemaMatchException */ public function read_record($writers_schema, $readers_schema, $decoder) { $readers_fields = $readers_schema->fields_hash(); $record = array(); foreach ($writers_schema->fields() as $writers_field) { $type = $writers_field->type(); if (isset($readers_fields[$writers_field->name()])) $record[$writers_field->name()] = $this->read_data($type, $readers_fields[$writers_field->name()]->type(), $decoder); else $this->skip_data($type, $decoder); } // Fill in default values if (count($readers_fields) > count($record)) { $writers_fields = $writers_schema->fields_hash(); foreach ($readers_fields as $field_name => $field) { if (!isset($writers_fields[$field_name])) { if ($field->has_default_value()) $record[$field->name()] = $this->read_default_value($field->type(), $field->default_value()); else null; // FIXME: unset } } } return $record; } /**#@-*/ /** * @param AvroSchema $field_schema * @param null|boolean|int|float|string|array $default_value * @return null|boolean|int|float|string|array * * @throws AvroException if $field_schema type is unknown. */ public function read_default_value($field_schema, $default_value) { switch($field_schema->type()) { case AvroSchema::NULL_TYPE: return null; case AvroSchema::BOOLEAN_TYPE: return $default_value; case AvroSchema::INT_TYPE: case AvroSchema::LONG_TYPE: return (int) $default_value; case AvroSchema::FLOAT_TYPE: case AvroSchema::DOUBLE_TYPE: return (float) $default_value; case AvroSchema::STRING_TYPE: case AvroSchema::BYTES_TYPE: return $default_value; case AvroSchema::ARRAY_SCHEMA: $array = array(); foreach ($default_value as $json_val) { $val = $this->read_default_value($field_schema->items(), $json_val); $array []= $val; } return $array; case AvroSchema::MAP_SCHEMA: $map = array(); foreach ($default_value as $key => $json_val) $map[$key] = $this->read_default_value($field_schema->values(), $json_val); return $map; case AvroSchema::UNION_SCHEMA: return $this->read_default_value($field_schema->schema_by_index(0), $default_value); case AvroSchema::ENUM_SCHEMA: case AvroSchema::FIXED_SCHEMA: return $default_value; case AvroSchema::RECORD_SCHEMA: $record = array(); foreach ($field_schema->fields() as $field) { $field_name = $field->name(); if (!$json_val = $default_value[$field_name]) $json_val = $field->default_value(); $record[$field_name] = $this->read_default_value($field->type(), $json_val); } return $record; default: throw new AvroException(sprintf('Unknown type: %s', $field_schema->type())); } } /** * @param AvroSchema $writers_schema * @param AvroIOBinaryDecoder $decoder * @return * @throws AvroException */ private function skip_data($writers_schema, $decoder) { switch ($writers_schema->type()) { case AvroSchema::NULL_TYPE: return $decoder->skip_null(); case AvroSchema::BOOLEAN_TYPE: return $decoder->skip_boolean(); case AvroSchema::INT_TYPE: return $decoder->skip_int(); case AvroSchema::LONG_TYPE: return $decoder->skip_long(); case AvroSchema::FLOAT_TYPE: return $decoder->skip_float(); case AvroSchema::DOUBLE_TYPE: return $decoder->skip_double(); case AvroSchema::STRING_TYPE: return $decoder->skip_string(); case AvroSchema::BYTES_TYPE: return $decoder->skip_bytes(); case AvroSchema::ARRAY_SCHEMA: return $decoder->skip_array($writers_schema, $decoder); case AvroSchema::MAP_SCHEMA: return $decoder->skip_map($writers_schema, $decoder); case AvroSchema::UNION_SCHEMA: return $decoder->skip_union($writers_schema, $decoder); case AvroSchema::ENUM_SCHEMA: return $decoder->skip_enum($writers_schema, $decoder); case AvroSchema::FIXED_SCHEMA: return $decoder->skip_fixed($writers_schema, $decoder); case AvroSchema::RECORD_SCHEMA: case AvroSchema::ERROR_SCHEMA: case AvroSchema::REQUEST_SCHEMA: return $decoder->skip_record($writers_schema, $decoder); default: throw new AvroException(sprintf('Uknown schema type: %s', $writers_schema->type())); } } } /** * Decodes and reads Avro data from an AvroIO object encoded using * Avro binary encoding. * * @package Avro */ class AvroIOBinaryDecoder { /** * @param int[] array of byte ascii values * @return int decoded value * @internal Requires 64-bit platform */ public static function decode_long_from_array($bytes) { $b = array_shift($bytes); $n = $b & 0x7f; $shift = 7; while (0 != ($b & 0x80)) { $b = array_shift($bytes); $n |= (($b & 0x7f) << $shift); $shift += 7; } return (($n >> 1) ^ -($n & 1)); } /** * Performs decoding of the binary string to a float value. * * XXX: This is <b>not</b> endian-aware! See comments in * {@link AvroIOBinaryEncoder::float_to_int_bits()} for details. * * @param string $bits * @return float */ static public function int_bits_to_float($bits) { $float = unpack('f', $bits); return (float) $float[1]; } /** * Performs decoding of the binary string to a double value. * * XXX: This is <b>not</b> endian-aware! See comments in * {@link AvroIOBinaryEncoder::float_to_int_bits()} for details. * * @param string $bits * @return float */ static public function long_bits_to_double($bits) { $double = unpack('d', $bits); return (double) $double[1]; } /** * @var AvroIO */ private $io; /** * @param AvroIO $io object from which to read. */ public function __construct($io) { Avro::check_platform(); $this->io = $io; } /** * @return string the next byte from $this->io. * @throws AvroException if the next byte cannot be read. */ private function next_byte() { return $this->read(1); } /** * @return null */ public function read_null() { return null; } /** * @return boolean */ public function read_boolean() { return (boolean) (1 == ord($this->next_byte())); } /** * @return int */ public function read_int() { return (int) $this->read_long(); } /** * @return int */ public function read_long() { $byte = ord($this->next_byte()); $bytes = array($byte); while (0 != ($byte & 0x80)) { $byte = ord($this->next_byte()); $bytes []= $byte; } if (Avro::uses_gmp()) return AvroGMP::decode_long_from_array($bytes); return self::decode_long_from_array($bytes); } /** * @return float */ public function read_float() { return self::int_bits_to_float($this->read(4)); } /** * @return double */ public function read_double() { return self::long_bits_to_double($this->read(8)); } /** * A string is encoded as a long followed by that many bytes * of UTF-8 encoded character data. * @return string */ public function read_string() { return $this->read_bytes(); } /** * @return string */ public function read_bytes() { return $this->read($this->read_long()); } /** * @param int $len count of bytes to read * @return string */ public function read($len) { return $this->io->read($len); } /** * @return null */ public function skip_null() { return null; } public function skip_boolean() { return $this->skip(1); } public function skip_int() { return $this->skip_long(); } protected function skip_long() { $b = ord($this->next_byte()); while (0 != ($b & 0x80)) $b = ord($this->next_byte()); } public function skip_float() { return $this->skip(4); } public function skip_double() { return $this->skip(8); } public function skip_bytes() { return $this->skip($this->read_long()); } public function skip_string() { return $this->skip_bytes(); } /** * @param int $len count of bytes to skip * @uses AvroIO::seek() */ public function skip($len) { $this->seek($len, AvroIO::SEEK_CUR); } /** * @return int position of pointer in AvroIO instance * @uses AvroIO::tell() */ private function tell() { return $this->io->tell(); } /** * @param int $offset * @param int $whence * @return boolean true upon success * @uses AvroIO::seek() */ private function seek($offset, $whence) { return $this->io->seek($offset, $whence); } }
pierres/archlinux-mediawiki
vendor/wikimedia/avro/lib/avro/datum.php
PHP
gpl-2.0
29,221
When /^I change the pseud "([^\"]*)" to "([^\"]*)"/ do |old_pseud, new_pseud| step %{I edit the pseud "#{old_pseud}"} fill_in("Name", with: new_pseud) click_button("Update") end When /^I edit the pseud "([^\"]*)"/ do |pseud| p = Pseud.where(name: pseud, user_id: User.current_user.id).first visit edit_user_pseud_path(User.current_user, p) end When /^I add the pseud "([^\"]*)"/ do |pseud| visit new_user_pseud_path(User.current_user) fill_in("Name", with: pseud) click_button("Create") end When(/^I delete the pseud "([^\"]*)"$/) do |pseud| visit user_pseuds_path(User.current_user) click_link("delete_#{pseud}") end
tuff/otwarchive
features/step_definitions/pseud_steps.rb
Ruby
gpl-2.0
643
// random -*- C++ -*- // Copyright (C) 2012-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, 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 General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. #define _GLIBCXX_USE_CXX11_ABI 1 #include <random> #ifdef _GLIBCXX_USE_C99_STDINT_TR1 #if defined __i386__ || defined __x86_64__ # include <cpuid.h> #endif #include <cstdio> #ifdef _GLIBCXX_HAVE_UNISTD_H # include <unistd.h> #endif namespace std _GLIBCXX_VISIBILITY(default) { namespace { static unsigned long _M_strtoul(const std::string& __str) { unsigned long __ret = 5489UL; if (__str != "mt19937") { const char* __nptr = __str.c_str(); char* __endptr; __ret = std::strtoul(__nptr, &__endptr, 0); if (*__nptr == '\0' || *__endptr != '\0') std::__throw_runtime_error(__N("random_device::_M_strtoul" "(const std::string&)")); } return __ret; } #if (defined __i386__ || defined __x86_64__) && defined _GLIBCXX_X86_RDRAND unsigned int __attribute__ ((target("rdrnd"))) __x86_rdrand(void) { unsigned int retries = 100; unsigned int val; while (__builtin_ia32_rdrand32_step(&val) == 0) if (--retries == 0) std::__throw_runtime_error(__N("random_device::__x86_rdrand(void)")); return val; } #endif } void random_device::_M_init(const std::string& token) { const char *fname = token.c_str(); if (token == "default") { #if (defined __i386__ || defined __x86_64__) && defined _GLIBCXX_X86_RDRAND unsigned int eax, ebx, ecx, edx; // Check availability of cpuid and, for now at least, also the // CPU signature for Intel's if (__get_cpuid_max(0, &ebx) > 0 && ebx == signature_INTEL_ebx) { __cpuid(1, eax, ebx, ecx, edx); if (ecx & bit_RDRND) { _M_file = nullptr; return; } } #endif fname = "/dev/urandom"; } else if (token != "/dev/urandom" && token != "/dev/random") fail: std::__throw_runtime_error(__N("random_device::" "random_device(const std::string&)")); _M_file = static_cast<void*>(std::fopen(fname, "rb")); if (!_M_file) goto fail; } void random_device::_M_init_pretr1(const std::string& token) { _M_mt.seed(_M_strtoul(token)); } void random_device::_M_fini() { if (_M_file) std::fclose(static_cast<FILE*>(_M_file)); } random_device::result_type random_device::_M_getval() { #if (defined __i386__ || defined __x86_64__) && defined _GLIBCXX_X86_RDRAND if (!_M_file) return __x86_rdrand(); #endif result_type __ret; #ifdef _GLIBCXX_HAVE_UNISTD_H auto e = read(fileno(static_cast<FILE*>(_M_file)), static_cast<void*>(&__ret), sizeof(result_type)); #else auto e = std::fread(static_cast<void*>(&__ret), sizeof(result_type), 1, static_cast<FILE*>(_M_file)); #endif if (e != sizeof(result_type)) __throw_runtime_error(__N("random_device could not read enough bytes")); return __ret; } random_device::result_type random_device::_M_getval_pretr1() { return _M_mt(); } template class mersenne_twister_engine< uint_fast32_t, 32, 624, 397, 31, 0x9908b0dfUL, 11, 0xffffffffUL, 7, 0x9d2c5680UL, 15, 0xefc60000UL, 18, 1812433253UL>; } #endif
schivei/gcc
libstdc++-v3/src/c++11/random.cc
C++
gpl-2.0
4,159
/* * Copyright (C) 2016,2017,2018,2020 by Jonathan Naylor G4KLX * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "NetworkInfo.h" #include "Nextion.h" #include "Log.h" #include <cstdio> #include <cassert> #include <cstring> #include <ctime> #include <clocale> const unsigned int DSTAR_RSSI_COUNT = 3U; // 3 * 420ms = 1260ms const unsigned int DSTAR_BER_COUNT = 63U; // 63 * 20ms = 1260ms const unsigned int DMR_RSSI_COUNT = 4U; // 4 * 360ms = 1440ms const unsigned int DMR_BER_COUNT = 24U; // 24 * 60ms = 1440ms const unsigned int YSF_RSSI_COUNT = 13U; // 13 * 100ms = 1300ms const unsigned int YSF_BER_COUNT = 13U; // 13 * 100ms = 1300ms const unsigned int P25_RSSI_COUNT = 7U; // 7 * 180ms = 1260ms const unsigned int P25_BER_COUNT = 7U; // 7 * 180ms = 1260ms const unsigned int NXDN_RSSI_COUNT = 28U; // 28 * 40ms = 1120ms const unsigned int NXDN_BER_COUNT = 28U; // 28 * 40ms = 1120ms const unsigned int M17_RSSI_COUNT = 28U; // 28 * 40ms = 1120ms const unsigned int M17_BER_COUNT = 28U; // 28 * 40ms = 1120ms #define LAYOUT_COMPAT_MASK (7 << 0) // compatibility for old setting #define LAYOUT_TA_ENABLE (1 << 4) // enable Talker Alias (TA) display #define LAYOUT_TA_COLOUR (1 << 5) // TA display with font colour change #define LAYOUT_TA_FONTSIZE (1 << 6) // TA display with font size change #define LAYOUT_DIY (1 << 7) // use ON7LDS-DIY layout // bit[3:2] is used in Display.cpp to set connection speed for LCD panel. // 00:low, others:high-speed. bit[2] is overlapped with LAYOUT_COMPAT_MASK. #define LAYOUT_HIGHSPEED (3 << 2) CNextion::CNextion(const std::string& callsign, unsigned int dmrid, ISerialPort* serial, unsigned int brightness, bool displayClock, bool utc, unsigned int idleBrightness, unsigned int screenLayout, unsigned int txFrequency, unsigned int rxFrequency, bool displayTempInF) : CDisplay(), m_callsign(callsign), m_ipaddress("(ip unknown)"), m_dmrid(dmrid), m_serial(serial), m_brightness(brightness), m_mode(MODE_IDLE), m_displayClock(displayClock), m_utc(utc), m_idleBrightness(idleBrightness), m_screenLayout(0), m_clockDisplayTimer(1000U, 0U, 400U), m_rssiAccum1(0U), m_rssiAccum2(0U), m_berAccum1(0.0F), m_berAccum2(0.0F), m_rssiCount1(0U), m_rssiCount2(0U), m_berCount1(0U), m_berCount2(0U), m_txFrequency(txFrequency), m_rxFrequency(rxFrequency), m_fl_txFrequency(0.0F), m_fl_rxFrequency(0.0F), m_displayTempInF(displayTempInF) { assert(serial != NULL); assert(brightness >= 0U && brightness <= 100U); static const unsigned int feature_set[] = { 0, // 0: G4KLX 0, // 1: (reserved, low speed) // 2: ON7LDS LAYOUT_TA_ENABLE | LAYOUT_TA_COLOUR | LAYOUT_TA_FONTSIZE, LAYOUT_TA_ENABLE | LAYOUT_DIY, // 3: ON7LDS-DIY LAYOUT_TA_ENABLE | LAYOUT_DIY, // 4: ON7LDS-DIY (high speed) 0, // 5: (reserved, high speed) 0, // 6: (reserved, high speed) 0, // 7: (reserved, high speed) }; if (screenLayout & ~LAYOUT_COMPAT_MASK) m_screenLayout = screenLayout & ~LAYOUT_COMPAT_MASK; else m_screenLayout = feature_set[screenLayout]; } CNextion::~CNextion() { } bool CNextion::open() { unsigned char info[100U]; CNetworkInfo* m_network; bool ret = m_serial->open(); if (!ret) { LogError("Cannot open the port for the Nextion display"); delete m_serial; return false; } info[0] = 0; m_network = new CNetworkInfo; m_network->getNetworkInterface(info); m_ipaddress = (char*)info; sendCommand("bkcmd=0"); sendCommandAction(0U); m_fl_txFrequency = double(m_txFrequency) / 1000000.0F; m_fl_rxFrequency = double(m_rxFrequency) / 1000000.0F; setIdle(); return true; } void CNextion::setIdleInt() { // a few bits borrowed from Lieven De Samblanx ON7LDS, NextionDriver char command[100U]; sendCommand("page MMDVM"); sendCommandAction(1U); if (m_brightness>0) { ::sprintf(command, "dim=%u", m_idleBrightness); sendCommand(command); } ::sprintf(command, "t0.txt=\"%s/%u\"", m_callsign.c_str(), m_dmrid); sendCommand(command); if (m_screenLayout & LAYOUT_DIY) { ::sprintf(command, "t4.txt=\"%s\"", m_callsign.c_str()); sendCommand(command); ::sprintf(command, "t5.txt=\"%u\"", m_dmrid); sendCommand(command); sendCommandAction(17U); ::sprintf(command, "t30.txt=\"%3.6f\"",m_fl_rxFrequency); // RX freq sendCommand(command); sendCommandAction(20U); ::sprintf(command, "t32.txt=\"%3.6f\"",m_fl_txFrequency); // TX freq sendCommand(command); sendCommandAction(21U); // CPU temperature FILE* fp = ::fopen("/sys/class/thermal/thermal_zone0/temp", "rt"); if (fp != NULL) { double val = 0.0; int n = ::fscanf(fp, "%lf", &val); ::fclose(fp); if (n == 1) { val /= 1000.0; if (m_displayTempInF) { val = (1.8 * val) + 32.0; ::sprintf(command, "t20.txt=\"%2.1f %cF\"", val, 176); } else { ::sprintf(command, "t20.txt=\"%2.1f %cC\"", val, 176); } sendCommand(command); sendCommandAction(22U); } } } else { sendCommandAction(17U); } sendCommand("t1.txt=\"MMDVM IDLE\""); sendCommandAction(11U); ::sprintf(command, "t3.txt=\"%s\"", m_ipaddress.c_str()); sendCommand(command); sendCommandAction(16U); m_clockDisplayTimer.start(); m_mode = MODE_IDLE; } void CNextion::setErrorInt(const char* text) { assert(text != NULL); sendCommand("page MMDVM"); sendCommandAction(1U); char command[20]; if (m_brightness>0) { ::sprintf(command, "dim=%u", m_brightness); sendCommand(command); } ::sprintf(command, "t0.txt=\"%s\"", text); sendCommandAction(13U); sendCommand(command); sendCommand("t1.txt=\"ERROR\""); sendCommandAction(14U); m_clockDisplayTimer.stop(); m_mode = MODE_ERROR; } void CNextion::setLockoutInt() { sendCommand("page MMDVM"); sendCommandAction(1U); char command[20]; if (m_brightness>0) { ::sprintf(command, "dim=%u", m_brightness); sendCommand(command); } sendCommand("t0.txt=\"LOCKOUT\""); sendCommandAction(15U); m_clockDisplayTimer.stop(); m_mode = MODE_LOCKOUT; } void CNextion::setQuitInt() { sendCommand("page MMDVM"); sendCommandAction(1U); char command[100]; if (m_brightness>0) { ::sprintf(command, "dim=%u", m_idleBrightness); sendCommand(command); } ::sprintf(command, "t3.txt=\"%s\"", m_ipaddress.c_str()); sendCommand(command); sendCommandAction(16U); sendCommand("t0.txt=\"MMDVM STOPPED\""); sendCommandAction(19U); m_clockDisplayTimer.stop(); m_mode = MODE_QUIT; } void CNextion::setFMInt() { sendCommand("page MMDVM"); sendCommandAction(1U); char command[20]; if (m_brightness > 0) { ::sprintf(command, "dim=%u", m_brightness); sendCommand(command); } sendCommand("t0.txt=\"FM\""); sendCommandAction(18U); m_clockDisplayTimer.stop(); m_mode = MODE_FM; } void CNextion::writeDStarInt(const char* my1, const char* my2, const char* your, const char* type, const char* reflector) { assert(my1 != NULL); assert(my2 != NULL); assert(your != NULL); assert(type != NULL); assert(reflector != NULL); if (m_mode != MODE_DSTAR) { sendCommand("page DStar"); sendCommandAction(2U); } char text[50U]; if (m_brightness>0) { ::sprintf(text, "dim=%u", m_brightness); sendCommand(text); } ::sprintf(text, "t0.txt=\"%s %.8s/%4.4s\"", type, my1, my2); sendCommand(text); sendCommandAction(42U); ::sprintf(text, "t1.txt=\"%.8s\"", your); sendCommand(text); sendCommandAction(45U); if (::strcmp(reflector, " ") != 0) { ::sprintf(text, "t2.txt=\"via %.8s\"", reflector); sendCommand(text); sendCommandAction(46U); } m_clockDisplayTimer.stop(); m_mode = MODE_DSTAR; m_rssiAccum1 = 0U; m_berAccum1 = 0.0F; m_rssiCount1 = 0U; m_berCount1 = 0U; } void CNextion::writeDStarRSSIInt(unsigned char rssi) { m_rssiAccum1 += rssi; m_rssiCount1++; if (m_rssiCount1 == DSTAR_RSSI_COUNT) { char text[25U]; ::sprintf(text, "t3.txt=\"-%udBm\"", m_rssiAccum1 / DSTAR_RSSI_COUNT); sendCommand(text); sendCommandAction(47U); m_rssiAccum1 = 0U; m_rssiCount1 = 0U; } } void CNextion::writeDStarBERInt(float ber) { m_berAccum1 += ber; m_berCount1++; if (m_berCount1 == DSTAR_BER_COUNT) { char text[25U]; ::sprintf(text, "t4.txt=\"%.1f%%\"", m_berAccum1 / float(DSTAR_BER_COUNT)); sendCommand(text); sendCommandAction(48U); m_berAccum1 = 0.0F; m_berCount1 = 0U; } } void CNextion::clearDStarInt() { sendCommand("t0.txt=\"Listening\""); sendCommandAction(41U); sendCommand("t1.txt=\"\""); sendCommand("t2.txt=\"\""); sendCommand("t3.txt=\"\""); sendCommand("t4.txt=\"\""); } void CNextion::writeDMRInt(unsigned int slotNo, const std::string& src, bool group, const std::string& dst, const char* type) { assert(type != NULL); if (m_mode != MODE_DMR) { sendCommand("page DMR"); sendCommandAction(3U); if (slotNo == 1U) { if (m_screenLayout & LAYOUT_TA_ENABLE) { if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t2.pco=0"); if (m_screenLayout & LAYOUT_TA_FONTSIZE) sendCommand("t2.font=4"); } sendCommand("t2.txt=\"2 Listening\""); sendCommandAction(69U); } else { if (m_screenLayout & LAYOUT_TA_ENABLE) { if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t0.pco=0"); if (m_screenLayout & LAYOUT_TA_FONTSIZE) sendCommand("t0.font=4"); } sendCommand("t0.txt=\"1 Listening\""); sendCommandAction(61U); } } char text[50U]; if (m_brightness>0) { ::sprintf(text, "dim=%u", m_brightness); sendCommand(text); } if (slotNo == 1U) { ::sprintf(text, "t0.txt=\"1 %s %s\"", type, src.c_str()); if (m_screenLayout & LAYOUT_TA_ENABLE) { if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t0.pco=0"); if (m_screenLayout & LAYOUT_TA_FONTSIZE) sendCommand("t0.font=4"); } sendCommand(text); sendCommandAction(62U); ::sprintf(text, "t1.txt=\"%s%s\"", group ? "TG" : "", dst.c_str()); sendCommand(text); sendCommandAction(65U); } else { ::sprintf(text, "t2.txt=\"2 %s %s\"", type, src.c_str()); if (m_screenLayout & LAYOUT_TA_ENABLE) { if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t2.pco=0"); if (m_screenLayout & LAYOUT_TA_FONTSIZE) sendCommand("t2.font=4"); } sendCommand(text); sendCommandAction(70U); ::sprintf(text, "t3.txt=\"%s%s\"", group ? "TG" : "", dst.c_str()); sendCommand(text); sendCommandAction(73U); } m_clockDisplayTimer.stop(); m_mode = MODE_DMR; m_rssiAccum1 = 0U; m_rssiAccum2 = 0U; m_berAccum1 = 0.0F; m_berAccum2 = 0.0F; m_rssiCount1 = 0U; m_rssiCount2 = 0U; m_berCount1 = 0U; m_berCount2 = 0U; } void CNextion::writeDMRRSSIInt(unsigned int slotNo, unsigned char rssi) { if (slotNo == 1U) { m_rssiAccum1 += rssi; m_rssiCount1++; if (m_rssiCount1 == DMR_RSSI_COUNT) { char text[25U]; ::sprintf(text, "t4.txt=\"-%udBm\"", m_rssiAccum1 / DMR_RSSI_COUNT); sendCommand(text); sendCommandAction(66U); m_rssiAccum1 = 0U; m_rssiCount1 = 0U; } } else { m_rssiAccum2 += rssi; m_rssiCount2++; if (m_rssiCount2 == DMR_RSSI_COUNT) { char text[25U]; ::sprintf(text, "t5.txt=\"-%udBm\"", m_rssiAccum2 / DMR_RSSI_COUNT); sendCommand(text); sendCommandAction(74U); m_rssiAccum2 = 0U; m_rssiCount2 = 0U; } } } void CNextion::writeDMRTAInt(unsigned int slotNo, unsigned char* talkerAlias, const char* type) { if (!(m_screenLayout & LAYOUT_TA_ENABLE)) return; if (type[0] == ' ') { if (slotNo == 1U) { if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t0.pco=33808"); sendCommandAction(64U); } else { if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t2.pco=33808"); sendCommandAction(72U); } return; } if (slotNo == 1U) { char text[50U]; ::sprintf(text, "t0.txt=\"1 %s %s\"", type, talkerAlias); if (m_screenLayout & LAYOUT_TA_FONTSIZE) { if (::strlen((char*)talkerAlias) > (16U-4U)) sendCommand("t0.font=3"); if (::strlen((char*)talkerAlias) > (20U-4U)) sendCommand("t0.font=2"); if (::strlen((char*)talkerAlias) > (24U-4U)) sendCommand("t0.font=1"); } if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t0.pco=1024"); sendCommand(text); sendCommandAction(63U); } else { char text[50U]; ::sprintf(text, "t2.txt=\"2 %s %s\"", type, talkerAlias); if (m_screenLayout & LAYOUT_TA_FONTSIZE) { if (::strlen((char*)talkerAlias) > (16U-4U)) sendCommand("t2.font=3"); if (::strlen((char*)talkerAlias) > (20U-4U)) sendCommand("t2.font=2"); if (::strlen((char*)talkerAlias) > (24U-4U)) sendCommand("t2.font=1"); } if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t2.pco=1024"); sendCommand(text); sendCommandAction(71U); } } void CNextion::writeDMRBERInt(unsigned int slotNo, float ber) { if (slotNo == 1U) { m_berAccum1 += ber; m_berCount1++; if (m_berCount1 == DMR_BER_COUNT) { char text[25U]; ::sprintf(text, "t6.txt=\"%.1f%%\"", m_berAccum1 / DMR_BER_COUNT); sendCommand(text); sendCommandAction(67U); m_berAccum1 = 0U; m_berCount1 = 0U; } } else { m_berAccum2 += ber; m_berCount2++; if (m_berCount2 == DMR_BER_COUNT) { char text[25U]; ::sprintf(text, "t7.txt=\"%.1f%%\"", m_berAccum2 / DMR_BER_COUNT); sendCommand(text); sendCommandAction(75U); m_berAccum2 = 0U; m_berCount2 = 0U; } } } void CNextion::clearDMRInt(unsigned int slotNo) { if (slotNo == 1U) { sendCommand("t0.txt=\"1 Listening\""); sendCommandAction(61U); if (m_screenLayout & LAYOUT_TA_ENABLE) { if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t0.pco=0"); if (m_screenLayout & LAYOUT_TA_FONTSIZE) sendCommand("t0.font=4"); } sendCommand("t1.txt=\"\""); sendCommand("t4.txt=\"\""); sendCommand("t6.txt=\"\""); } else { sendCommand("t2.txt=\"2 Listening\""); sendCommandAction(69U); if (m_screenLayout & LAYOUT_TA_ENABLE) { if (m_screenLayout & LAYOUT_TA_COLOUR) sendCommand("t2.pco=0"); if (m_screenLayout & LAYOUT_TA_FONTSIZE) sendCommand("t2.font=4"); } sendCommand("t3.txt=\"\""); sendCommand("t5.txt=\"\""); sendCommand("t7.txt=\"\""); } } void CNextion::writeFusionInt(const char* source, const char* dest, unsigned char dgid, const char* type, const char* origin) { assert(source != NULL); assert(dest != NULL); assert(type != NULL); assert(origin != NULL); if (m_mode != MODE_YSF) { sendCommand("page YSF"); sendCommandAction(4U); } char text[30U]; if (m_brightness>0) { ::sprintf(text, "dim=%u", m_brightness); sendCommand(text); } ::sprintf(text, "t0.txt=\"%s %.10s\"", type, source); sendCommand(text); sendCommandAction(82U); ::sprintf(text, "t1.txt=\"DG-ID %u\"", dgid); sendCommand(text); sendCommandAction(83U); if (::strcmp(origin, " ") != 0) { ::sprintf(text, "t2.txt=\"at %.10s\"", origin); sendCommand(text); sendCommandAction(84U); } m_clockDisplayTimer.stop(); m_mode = MODE_YSF; m_rssiAccum1 = 0U; m_berAccum1 = 0.0F; m_rssiCount1 = 0U; m_berCount1 = 0U; } void CNextion::writeFusionRSSIInt(unsigned char rssi) { m_rssiAccum1 += rssi; m_rssiCount1++; if (m_rssiCount1 == YSF_RSSI_COUNT) { char text[25U]; ::sprintf(text, "t3.txt=\"-%udBm\"", m_rssiAccum1 / YSF_RSSI_COUNT); sendCommand(text); sendCommandAction(85U); m_rssiAccum1 = 0U; m_rssiCount1 = 0U; } } void CNextion::writeFusionBERInt(float ber) { m_berAccum1 += ber; m_berCount1++; if (m_berCount1 == YSF_BER_COUNT) { char text[25U]; ::sprintf(text, "t4.txt=\"%.1f%%\"", m_berAccum1 / float(YSF_BER_COUNT)); sendCommand(text); sendCommandAction(86U); m_berAccum1 = 0.0F; m_berCount1 = 0U; } } void CNextion::clearFusionInt() { sendCommand("t0.txt=\"Listening\""); sendCommandAction(81U); sendCommand("t1.txt=\"\""); sendCommand("t2.txt=\"\""); sendCommand("t3.txt=\"\""); sendCommand("t4.txt=\"\""); } void CNextion::writeP25Int(const char* source, bool group, unsigned int dest, const char* type) { assert(source != NULL); assert(type != NULL); if (m_mode != MODE_P25) { sendCommand("page P25"); sendCommandAction(5U); } char text[30U]; if (m_brightness>0) { ::sprintf(text, "dim=%u", m_brightness); sendCommand(text); } ::sprintf(text, "t0.txt=\"%s %.10s\"", type, source); sendCommand(text); sendCommandAction(102U); ::sprintf(text, "t1.txt=\"%s%u\"", group ? "TG" : "", dest); sendCommand(text); sendCommandAction(103U); m_clockDisplayTimer.stop(); m_mode = MODE_P25; m_rssiAccum1 = 0U; m_berAccum1 = 0.0F; m_rssiCount1 = 0U; m_berCount1 = 0U; } void CNextion::writeP25RSSIInt(unsigned char rssi) { m_rssiAccum1 += rssi; m_rssiCount1++; if (m_rssiCount1 == P25_RSSI_COUNT) { char text[25U]; ::sprintf(text, "t2.txt=\"-%udBm\"", m_rssiAccum1 / P25_RSSI_COUNT); sendCommand(text); sendCommandAction(104U); m_rssiAccum1 = 0U; m_rssiCount1 = 0U; } } void CNextion::writeP25BERInt(float ber) { m_berAccum1 += ber; m_berCount1++; if (m_berCount1 == P25_BER_COUNT) { char text[25U]; ::sprintf(text, "t3.txt=\"%.1f%%\"", m_berAccum1 / float(P25_BER_COUNT)); sendCommand(text); sendCommandAction(105U); m_berAccum1 = 0.0F; m_berCount1 = 0U; } } void CNextion::clearP25Int() { sendCommand("t0.txt=\"Listening\""); sendCommandAction(101U); sendCommand("t1.txt=\"\""); sendCommand("t2.txt=\"\""); sendCommand("t3.txt=\"\""); } void CNextion::writeNXDNInt(const char* source, bool group, unsigned int dest, const char* type) { assert(source != NULL); assert(type != NULL); if (m_mode != MODE_NXDN) { sendCommand("page NXDN"); sendCommandAction(6U); } char text[30U]; if (m_brightness>0) { ::sprintf(text, "dim=%u", m_brightness); sendCommand(text); } ::sprintf(text, "t0.txt=\"%s %.10s\"", type, source); sendCommand(text); sendCommandAction(122U); ::sprintf(text, "t1.txt=\"%s%u\"", group ? "TG" : "", dest); sendCommand(text); sendCommandAction(123U); m_clockDisplayTimer.stop(); m_mode = MODE_NXDN; m_rssiAccum1 = 0U; m_berAccum1 = 0.0F; m_rssiCount1 = 0U; m_berCount1 = 0U; } void CNextion::writeNXDNRSSIInt(unsigned char rssi) { m_rssiAccum1 += rssi; m_rssiCount1++; if (m_rssiCount1 == NXDN_RSSI_COUNT) { char text[25U]; ::sprintf(text, "t2.txt=\"-%udBm\"", m_rssiAccum1 / NXDN_RSSI_COUNT); sendCommand(text); sendCommandAction(124U); m_rssiAccum1 = 0U; m_rssiCount1 = 0U; } } void CNextion::writeNXDNBERInt(float ber) { m_berAccum1 += ber; m_berCount1++; if (m_berCount1 == NXDN_BER_COUNT) { char text[25U]; ::sprintf(text, "t3.txt=\"%.1f%%\"", m_berAccum1 / float(NXDN_BER_COUNT)); sendCommand(text); sendCommandAction(125U); m_berAccum1 = 0.0F; m_berCount1 = 0U; } } void CNextion::clearNXDNInt() { sendCommand("t0.txt=\"Listening\""); sendCommandAction(121U); sendCommand("t1.txt=\"\""); sendCommand("t2.txt=\"\""); sendCommand("t3.txt=\"\""); } void CNextion::writeM17Int(const char* source, const char* dest, const char* type) { assert(source != NULL); assert(dest != NULL); assert(type != NULL); if (m_mode != MODE_M17) { sendCommand("page M17"); sendCommandAction(8U); } char text[30U]; if (m_brightness > 0) { ::sprintf(text, "dim=%u", m_brightness); sendCommand(text); } ::sprintf(text, "t0.txt=\"%s %.10s\"", type, source); sendCommand(text); sendCommandAction(142U); ::sprintf(text, "t1.txt=\"%s\"", dest); sendCommand(text); sendCommandAction(143U); m_clockDisplayTimer.stop(); m_mode = MODE_M17; m_rssiAccum1 = 0U; m_berAccum1 = 0.0F; m_rssiCount1 = 0U; m_berCount1 = 0U; } void CNextion::writeM17RSSIInt(unsigned char rssi) { m_rssiAccum1 += rssi; m_rssiCount1++; if (m_rssiCount1 == M17_RSSI_COUNT) { char text[25U]; ::sprintf(text, "t2.txt=\"-%udBm\"", m_rssiAccum1 / M17_RSSI_COUNT); sendCommand(text); sendCommandAction(144U); m_rssiAccum1 = 0U; m_rssiCount1 = 0U; } } void CNextion::writeM17BERInt(float ber) { m_berAccum1 += ber; m_berCount1++; if (m_berCount1 == M17_BER_COUNT) { char text[25U]; ::sprintf(text, "t3.txt=\"%.1f%%\"", m_berAccum1 / float(M17_BER_COUNT)); sendCommand(text); sendCommandAction(145U); m_berAccum1 = 0.0F; m_berCount1 = 0U; } } void CNextion::clearM17Int() { sendCommand("t0.txt=\"Listening\""); sendCommandAction(141U); sendCommand("t1.txt=\"\""); sendCommand("t2.txt=\"\""); sendCommand("t3.txt=\"\""); } void CNextion::writePOCSAGInt(uint32_t ric, const std::string& message) { if (m_mode != MODE_POCSAG) { sendCommand("page POCSAG"); sendCommandAction(7U); } char text[200U]; if (m_brightness>0) { ::sprintf(text, "dim=%u", m_brightness); sendCommand(text); } ::sprintf(text, "t0.txt=\"RIC: %u\"", ric); sendCommand(text); sendCommandAction(132U); ::sprintf(text, "t1.txt=\"%s\"", message.c_str()); sendCommand(text); sendCommandAction(133U); m_clockDisplayTimer.stop(); m_mode = MODE_POCSAG; } void CNextion::clearPOCSAGInt() { sendCommand("t0.txt=\"Waiting\""); sendCommandAction(134U); sendCommand("t1.txt=\"\""); } void CNextion::writeCWInt() { sendCommand("t1.txt=\"Sending CW Ident\""); sendCommandAction(12U); m_clockDisplayTimer.start(); m_mode = MODE_CW; } void CNextion::clearCWInt() { sendCommand("t1.txt=\"MMDVM IDLE\""); sendCommandAction(11U); } void CNextion::clockInt(unsigned int ms) { // Update the clock display in IDLE mode every 400ms m_clockDisplayTimer.clock(ms); if (m_displayClock && (m_mode == MODE_IDLE || m_mode == MODE_CW) && m_clockDisplayTimer.isRunning() && m_clockDisplayTimer.hasExpired()) { time_t currentTime; struct tm *Time; ::time(&currentTime); // Get the current time if (m_utc) Time = ::gmtime(&currentTime); else Time = ::localtime(&currentTime); setlocale(LC_TIME,""); char text[50U]; strftime(text, 50, "t2.txt=\"%x %X\"", Time); sendCommand(text); m_clockDisplayTimer.start(); // restart the clock display timer } } void CNextion::close() { m_serial->close(); delete m_serial; } void CNextion::sendCommandAction(unsigned int status) { if (!(m_screenLayout & LAYOUT_DIY)) return; char text[30U]; ::sprintf(text, "MMDVM.status.val=%d", status); sendCommand(text); sendCommand("click S0,1"); } void CNextion::sendCommand(const char* command) { assert(command != NULL); m_serial->write((unsigned char*)command, (unsigned int)::strlen(command)); m_serial->write((unsigned char*)"\xFF\xFF\xFF", 3U); // Since we just firing commands at the display, and not listening for the response, // we must add a bit of a delay to allow the display to process the commands, else some are getting mangled. // 10 ms is just a guess, but seems to be sufficient. CThread::sleep(10U); }
g4klx/MMDVMHost
Nextion.cpp
C++
gpl-2.0
23,254
<?php class BP_Registration_Options { function __construct() { // Define plugin constants $this->version = BP_REGISTRATION_OPTIONS_VERSION; $this->basename = plugin_basename( __FILE__ ); $this->directory_path = plugin_dir_path( __FILE__ ); //$this->directory_url = plugins_url( 'bp-registration-options/' ); register_activation_hook( __FILE__, array( &$this, 'activate' ) ); register_deactivation_hook( __FILE__, array( &$this, 'deactivate' ) ); require_once( $this->directory_path . 'includes/admin.php' ); require_once( $this->directory_path . 'includes/core.php' ); require_once( $this->directory_path . 'includes/compatibility.php' ); add_action( 'init', array( $this, 'load_textdomain' ) ); } /** * Activation hook for the plugin. */ function activate() { $this->includes(); //verify user is running WP 3.0 or newer if ( version_compare( get_bloginfo( 'version' ), '3.0', '<' ) ) { deactivate_plugins( plugin_basename( __FILE__ ) ); // Deactivate our plugin wp_die( __( 'This plugin requires WordPress version 3.0 or higher.', 'bp-registration-options' ) ); } flush_rewrite_rules(); } /** * Deactivation hook for the plugin. */ function deactivate() { flush_rewrite_rules(); } function load_textdomain() { load_plugin_textdomain( 'bp-registration-options', false, basename( dirname( __FILE__ ) ) . '/languages/' ); } }
futuhal-arifin/mommee
wp-content/plugins/bp-registration-options/bp-registration-options.php
PHP
gpl-2.0
1,410
/* Copyright (c) 2004-2006, The Dojo Foundation All Rights Reserved. Licensed under the Academic Free License version 2.1 or above OR the modified BSD license. For more information on Dojo licensing, see: http://dojotoolkit.org/community/licensing.shtml */ dojo.provide("dojo.logging.Logger"); dojo.provide("dojo.logging.LogFilter"); dojo.provide("dojo.logging.Record"); dojo.provide("dojo.log"); dojo.require("dojo.lang.common"); dojo.require("dojo.lang.declare"); /* This is the dojo logging facility, which is imported from nWidgets (written by Alex Russell, CLA on file), which is patterned on the Python logging module, which in turn has been heavily influenced by log4j (execpt with some more pythonic choices, which we adopt as well). While the dojo logging facilities do provide a set of familiar interfaces, many of the details are changed to reflect the constraints of the browser environment. Mainly, file and syslog-style logging facilites are not provided, with HTTP POST and GET requests being the only ways of getting data from the browser back to a server. Minimal support for this (and XML serialization of logs) is provided, but may not be of practical use in a deployment environment. The Dojo logging classes are agnostic of any environment, and while default loggers are provided for browser-based interpreter environments, this file and the classes it define are explicitly designed to be portable to command-line interpreters and other ECMA-262v3 envrionments. the logger needs to accomidate: log "levels" type identifiers file? message tic/toc? The logger should ALWAYS record: time/date logged message type level */ // TODO: define DTD for XML-formatted log messages // TODO: write XML Formatter class // TODO: write HTTP Handler which uses POST to send log lines/sections dojo.logging.Record = function(/*Integer*/logLevel, /*String||Array*/message){ // summary: // A simple data structure class that stores information for and about // a logged event. Objects of this type are created automatically when // an event is logged and are the internal format in which information // about log events is kept. // logLevel: // Integer mapped via the dojo.logging.log.levels object from a // string. This mapping also corresponds to an instance of // dojo.logging.Logger // message: // The contents of the message represented by this log record. this.level = logLevel; this.message = ""; this.msgArgs = []; this.time = new Date(); if(dojo.lang.isArray(message)){ if(message.length > 0 && dojo.lang.isString(message[0])){ this.message=message.shift(); } this.msgArgs = message; }else{ this.message = message; } // FIXME: what other information can we receive/discover here? } dojo.logging.LogFilter = function(loggerChain){ // summary: // An empty parent (abstract) class which concrete filters should // inherit from. Filters should have only a single method, filter(), // which processes a record and returns true or false to denote // whether or not it should be handled by the next step in a filter // chain. this.passChain = loggerChain || ""; this.filter = function(record){ // FIXME: need to figure out a way to enforce the loggerChain // restriction return true; // pass all records } } dojo.logging.Logger = function(){ this.cutOffLevel = 0; this.propagate = true; this.parent = null; // storage for dojo.logging.Record objects seen and accepted by this logger this.data = []; this.filters = []; this.handlers = []; } dojo.extend(dojo.logging.Logger,{ _argsToArr: function(args){ var ret = []; for(var x=0; x<args.length; x++){ ret.push(args[x]); } return ret; }, setLevel: function(/*Integer*/lvl){ // summary: // set the logging level for this logger. // lvl: // the logging level to set the cutoff for, as derived from the // dojo.logging.log.levels object. Any messages below the // specified level are dropped on the floor this.cutOffLevel = parseInt(lvl); }, isEnabledFor: function(/*Integer*/lvl){ // summary: // will a message at the specified level be emitted? return parseInt(lvl) >= this.cutOffLevel; // boolean }, getEffectiveLevel: function(){ // summary: // gets the effective cutoff level, including that of any // potential parent loggers in the chain. if((this.cutOffLevel==0)&&(this.parent)){ return this.parent.getEffectiveLevel(); // Integer } return this.cutOffLevel; // Integer }, addFilter: function(/*dojo.logging.LogFilter*/flt){ // summary: // registers a new LogFilter object. All records will be passed // through this filter from now on. this.filters.push(flt); return this.filters.length-1; // Integer }, removeFilterByIndex: function(/*Integer*/fltIndex){ // summary: // removes the filter at the specified index from the filter // chain. Returns whether or not removal was successful. if(this.filters[fltIndex]){ delete this.filters[fltIndex]; return true; // boolean } return false; // boolean }, removeFilter: function(/*dojo.logging.LogFilter*/fltRef){ // summary: // removes the passed LogFilter. Returns whether or not removal // was successful. for(var x=0; x<this.filters.length; x++){ if(this.filters[x]===fltRef){ delete this.filters[x]; return true; } } return false; }, removeAllFilters: function(){ // summary: clobbers all the registered filters. this.filters = []; // clobber all of them }, filter: function(/*dojo.logging.Record*/rec){ // summary: // runs the passed Record through the chain of registered filters. // Returns a boolean indicating whether or not the Record should // be emitted. for(var x=0; x<this.filters.length; x++){ if((this.filters[x]["filter"])&& (!this.filters[x].filter(rec))|| (rec.level<this.cutOffLevel)){ return false; // boolean } } return true; // boolean }, addHandler: function(/*dojo.logging.LogHandler*/hdlr){ // summary: adds as LogHandler to the chain this.handlers.push(hdlr); return this.handlers.length-1; }, handle: function(/*dojo.logging.Record*/rec){ // summary: // if the Record survives filtering, pass it down to the // registered handlers. Returns a boolean indicating whether or // not the record was successfully handled. If the message is // culled for some reason, returns false. if((!this.filter(rec))||(rec.level<this.cutOffLevel)){ return false; } // boolean for(var x=0; x<this.handlers.length; x++){ if(this.handlers[x]["handle"]){ this.handlers[x].handle(rec); } } // FIXME: not sure what to do about records to be propagated that may have // been modified by the handlers or the filters at this logger. Should // parents always have pristine copies? or is passing the modified record // OK? // if((this.propagate)&&(this.parent)){ this.parent.handle(rec); } return true; // boolean }, // the heart and soul of the logging system log: function(/*integer*/lvl, /*string*/msg){ // summary: // log a message at the specified log level if( (this.propagate)&&(this.parent)&& (this.parent.rec.level>=this.cutOffLevel)){ this.parent.log(lvl, msg); return false; } // FIXME: need to call logging providers here! this.handle(new dojo.logging.Record(lvl, msg)); return true; }, // logger helpers debug:function(/*string*/msg){ // summary: // log the msg and any other arguments at the "debug" logging // level. return this.logType("DEBUG", this._argsToArr(arguments)); }, info: function(msg){ // summary: // log the msg and any other arguments at the "info" logging // level. return this.logType("INFO", this._argsToArr(arguments)); }, warning: function(msg){ // summary: // log the msg and any other arguments at the "warning" logging // level. return this.logType("WARNING", this._argsToArr(arguments)); }, error: function(msg){ // summary: // log the msg and any other arguments at the "error" logging // level. return this.logType("ERROR", this._argsToArr(arguments)); }, critical: function(msg){ // summary: // log the msg and any other arguments at the "critical" logging // level. return this.logType("CRITICAL", this._argsToArr(arguments)); }, exception: function(/*string*/msg, /*Error*/e, /*boolean*/squelch){ // summary: // logs the error and the message at the "exception" logging // level. If squelch is true, also prevent bubbling of the // exception. // FIXME: this needs to be modified to put the exception in the msg // if we're on Moz, we can get the following from the exception object: // lineNumber // message // fileName // stack // name // on IE, we get: // name // message (from MDA?) // number // description (same as message!) if(e){ var eparts = [e.name, (e.description||e.message)]; if(e.fileName){ eparts.push(e.fileName); eparts.push("line "+e.lineNumber); // eparts.push(e.stack); } msg += " "+eparts.join(" : "); } this.logType("ERROR", msg); if(!squelch){ throw e; } }, logType: function(/*string*/type, /*array*/args){ // summary: // a more "user friendly" version of the log() function. Takes the // named log level instead of the corresponding integer. return this.log.apply(this, [dojo.logging.log.getLevel(type), args]); }, warn:function(){ // summary: shorthand for warning() this.warning.apply(this,arguments); }, err:function(){ // summary: shorthand for error() this.error.apply(this,arguments); }, crit:function(){ // summary: shorthand for critical() this.critical.apply(this,arguments); } }); // the Handler class dojo.logging.LogHandler = function(level){ this.cutOffLevel = (level) ? level : 0; this.formatter = null; // FIXME: default formatter? this.data = []; this.filters = []; } dojo.lang.extend(dojo.logging.LogHandler,{ setFormatter:function(formatter){ dojo.unimplemented("setFormatter"); }, flush:function(){ // summary: // Unimplemented. Should be implemented by subclasses to handle // finishing a transaction or otherwise comitting pending log // messages to whatevery underlying transport or storage system is // available. }, close:function(){ // summary: // Unimplemented. Should be implemented by subclasses to handle // shutting down the logger, including a call to flush() }, handleError:function(){ // summary: // Unimplemented. Should be implemented by subclasses. dojo.deprecated("dojo.logging.LogHandler.handleError", "use handle()", "0.6"); }, handle:function(/*dojo.logging.Record*/record){ // summary: // Emits the record object passed in should the record meet the // current logging level cuttof, as specified in cutOffLevel. if((this.filter(record))&&(record.level>=this.cutOffLevel)){ this.emit(record); } }, emit:function(/*dojo.logging.Record*/record){ // summary: // Unimplemented. Should be implemented by subclasses to handle // an individual record. Subclasses may batch records and send // them to their "substrate" only when flush() is called, but this // is generally not a good idea as losing logging messages may // make debugging significantly more difficult. Tuning the volume // of logging messages written to storage should be accomplished // with log levels instead. dojo.unimplemented("emit"); } }); // set aliases since we don't want to inherit from dojo.logging.Logger void(function(){ // begin globals protection closure var names = [ "setLevel", "addFilter", "removeFilterByIndex", "removeFilter", "removeAllFilters", "filter" ]; var tgt = dojo.logging.LogHandler.prototype; var src = dojo.logging.Logger.prototype; for(var x=0; x<names.length; x++){ tgt[names[x]] = src[names[x]]; } })(); // end globals protection closure dojo.logging.log = new dojo.logging.Logger(); // an associative array of logger objects. This object inherits from // a list of level names with their associated numeric levels dojo.logging.log.levels = [ {"name": "DEBUG", "level": 1}, {"name": "INFO", "level": 2}, {"name": "WARNING", "level": 3}, {"name": "ERROR", "level": 4}, {"name": "CRITICAL", "level": 5} ]; dojo.logging.log.loggers = {}; dojo.logging.log.getLogger = function(/*string*/name){ // summary: // returns a named dojo.logging.Logger instance. If one is not already // available with that name in the global map, one is created and // returne. if(!this.loggers[name]){ this.loggers[name] = new dojo.logging.Logger(); this.loggers[name].parent = this; } return this.loggers[name]; // dojo.logging.Logger } dojo.logging.log.getLevelName = function(/*integer*/lvl){ // summary: turns integer logging level into a human-friendly name for(var x=0; x<this.levels.length; x++){ if(this.levels[x].level == lvl){ return this.levels[x].name; // string } } return null; } dojo.logging.log.getLevel = function(/*string*/name){ // summary: name->integer conversion for log levels for(var x=0; x<this.levels.length; x++){ if(this.levels[x].name.toUpperCase() == name.toUpperCase()){ return this.levels[x].level; // integer } } return null; } // a default handler class, it simply saves all of the handle()'d records in // memory. Useful for attaching to with dojo.event.connect() dojo.declare("dojo.logging.MemoryLogHandler", dojo.logging.LogHandler, { initializer: function(level, recordsToKeep, postType, postInterval){ // mixin style inheritance dojo.logging.LogHandler.call(this, level); // default is unlimited this.numRecords = (typeof djConfig['loggingNumRecords'] != 'undefined') ? djConfig['loggingNumRecords'] : ((recordsToKeep) ? recordsToKeep : -1); // 0=count, 1=time, -1=don't post TODO: move this to a better location for prefs this.postType = (typeof djConfig['loggingPostType'] != 'undefined') ? djConfig['loggingPostType'] : ( postType || -1); // milliseconds for time, interger for number of records, -1 for non-posting, this.postInterval = (typeof djConfig['loggingPostInterval'] != 'undefined') ? djConfig['loggingPostInterval'] : ( postType || -1); }, emit: function(record){ if(!djConfig.isDebug){ return; } var logStr = String(dojo.log.getLevelName(record.level)+": " +record.time.toLocaleTimeString())+": "+record.message; if(!dj_undef("println", dojo.hostenv)){ dojo.hostenv.println(logStr, record.msgArgs); } this.data.push(record); if(this.numRecords != -1){ while(this.data.length>this.numRecords){ this.data.shift(); } } } } ); dojo.logging.logQueueHandler = new dojo.logging.MemoryLogHandler(0,50,0,10000); dojo.logging.log.addHandler(dojo.logging.logQueueHandler); dojo.log = dojo.logging.log;
smee/elateXam
taskmodel/taskmodel-core-view/src/main/webapp/dojo/src/logging/Logger.js
JavaScript
gpl-3.0
15,366
/* Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org> This file is part of OpenPnP. OpenPnP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenPnP 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 General Public License for more details. You should have received a copy of the GNU General Public License along with OpenPnP. If not, see <http://www.gnu.org/licenses/>. For more information about OpenPnP visit http://openpnp.org * * Change Log: * 03/10/2012 Ami: Add four points best fit algorithm. * - Takes the two angles of the two opposing corners (the diagonals) from the placements and compare it to the indicated values. * - These are the starting point for the binary search, to find the lowest error. * - Each iteration the mid-point angle is also taken, and all three are evaluated. * - Offset is re-calculated after rotation and averaged */ package org.openpnp.gui.processes; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.openpnp.gui.JobPanel; import org.openpnp.gui.MainFrame; import org.openpnp.gui.support.MessageBoxes; import org.openpnp.model.Board.Side; import org.openpnp.model.Configuration; import org.openpnp.model.Location; import org.openpnp.model.Placement; import org.openpnp.model.Point; import org.openpnp.spi.Camera; import org.openpnp.spi.Head; import org.openpnp.util.MovableUtils; import org.openpnp.util.Utils2D; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Guides the user through the two point board location operation using * step by step instructions. * * TODO: Select the right camera on startup and then disable the CameraPanel while active. * TODO: Disable the BoardLocation table while active. */ public class FourPlacementBoardLocationProcess { private static final Logger logger = LoggerFactory.getLogger(FourPlacementBoardLocationProcess.class); private final MainFrame mainFrame; private final JobPanel jobPanel; private int step = -1; private String[] instructions = new String[] { "<html><body>Pick an easily identifiable placement near the TOP-LEFT corner of the board. Select it in the table below and move the camera's crosshairs to it's center location. Click Next to continue.</body></html>", "<html><body>Next, pick another placement on the BOTTOM-RIGHT corner of the board, select it in the table below and move the camera's crosshairs to it's center location. Click Next to continue.</body></html>", "<html><body>And now, pick another placement on the TOP-RIGHT corner of the board, select it in the table below and move the camera's crosshairs to it's center location. Click Next to continue.</body></html>", "<html><body>Last, pick another placement on the BOTTOM-LEFT corner of the board, select it in the table below and move the camera's crosshairs to it's center location. Click Next to continue.</body></html>", "<html><body>The board's location and rotation has been set. Click Finish to position the camera at the board's origin, or Cancel to quit.</body></html>", }; private Placement placementA, placementB, placementC, placementD; private Location placementLocationA, placementLocationB, placementLocationC, placementLocationD; public FourPlacementBoardLocationProcess(MainFrame mainFrame, JobPanel jobPanel) { this.mainFrame = mainFrame; this.jobPanel = jobPanel; advance(); } private void advance() { boolean stepResult = true; if (step == 0) { stepResult = step1(); } else if (step == 1) { stepResult = step2(); } else if (step == 2) { stepResult = step3(); } else if (step == 3) { stepResult = step4(); } else if (step == 4) { stepResult = step5(); } if (!stepResult) { return; } step++; if (step == 5) { mainFrame.hideInstructions(); } else { String title = String.format("Set Board Location (%d / 5)", step + 1); mainFrame.showInstructions( title, instructions[step], true, true, step == 4 ? "Finish" : "Next", cancelActionListener, proceedActionListener); } } private boolean step1() { placementLocationA = MainFrame.cameraPanel.getSelectedCameraLocation(); if (placementLocationA == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please position the camera."); return false; } placementA = jobPanel.getSelectedPlacement(); if (placementA == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please select a placement."); return false; } return true; } private boolean step2() { placementLocationB = MainFrame.cameraPanel.getSelectedCameraLocation(); if (placementLocationB == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please position the camera."); return false; } placementB = jobPanel.getSelectedPlacement(); if (placementB == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please select a placement."); return false; } return true; } private boolean step3() { placementLocationC = MainFrame.cameraPanel.getSelectedCameraLocation(); if (placementLocationC == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please position the camera."); return false; } placementC = jobPanel.getSelectedPlacement(); if (placementC == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please select a placement."); return false; } return true; } private boolean step4() { placementLocationD = MainFrame.cameraPanel.getSelectedCameraLocation(); if (placementLocationD == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please position the camera."); return false; } placementD = jobPanel.getSelectedPlacement(); if (placementD == null || placementD == placementC) { MessageBoxes.errorBox(mainFrame, "Error", "Please select a second placement."); return false; } if ((placementA.getSide() != placementB.getSide()) || (placementC.getSide() != placementD.getSide())){ MessageBoxes.errorBox(mainFrame, "Error", "Both placements must be on the same side of the board."); return false; } // Get the Locations we'll be using and convert to system units. Location boardLocationA = placementLocationA.convertToUnits(Configuration.get().getSystemUnits()); Location placementLocationA = placementA.getLocation().convertToUnits(Configuration.get().getSystemUnits()); Location boardLocationB = placementLocationB.convertToUnits(Configuration.get().getSystemUnits()); Location placementLocationB = placementB.getLocation().convertToUnits(Configuration.get().getSystemUnits()); Location boardLocationC = placementLocationC.convertToUnits(Configuration.get().getSystemUnits()); Location placementLocationC = placementC.getLocation().convertToUnits(Configuration.get().getSystemUnits()); Location boardLocationD = placementLocationD.convertToUnits(Configuration.get().getSystemUnits()); Location placementLocationD = placementD.getLocation().convertToUnits(Configuration.get().getSystemUnits()); // If the placements are on the Bottom of the board we need to invert X if (placementA.getSide() == Side.Bottom) { // boardLocationA = boardLocationA.invert(true, false, false, false); placementLocationA = placementLocationA.invert(true, false, false, false); // boardLocationB = boardLocationB.invert(true, false, false, false); placementLocationB = placementLocationB.invert(true, false, false, false); } if (placementC.getSide() == Side.Bottom) { // boardLocationA = boardLocationA.invert(true, false, false, false); placementLocationC = placementLocationC.invert(true, false, false, false); // boardLocationB = boardLocationB.invert(true, false, false, false); placementLocationD = placementLocationD.invert(true, false, false, false); } logger.debug(String.format("locate")); logger.debug(String.format("%s - %s", boardLocationA, placementLocationA)); logger.debug(String.format("%s - %s", boardLocationB, placementLocationB)); logger.debug(String.format("%s - %s", boardLocationC, placementLocationC)); logger.debug(String.format("%s - %s", boardLocationD, placementLocationD)); double x1 = placementLocationA.getX(); double y1 = placementLocationA.getY(); double x2 = placementLocationB.getX(); double y2 = placementLocationB.getY(); // Center of the placement points used for rotation double centerX = (x1+x2)/2; double centerY = (y1+y2)/2; // Calculate the expected angle between the two coordinates, based // on their locations in the placement. double expectedAngle = Math.atan2(y1 - y2, x1 - x2); expectedAngle = Math.toDegrees(expectedAngle); logger.debug("expectedAngle A-B " + expectedAngle); // Then calculate the actual angle between the two coordinates, // based on the captured values. x1 = boardLocationA.getX(); y1 = boardLocationA.getY(); x2 = boardLocationB.getX(); y2 = boardLocationB.getY(); double indicatedAngle = Math.atan2(y1 - y2, x1 - x2); indicatedAngle = Math.toDegrees(indicatedAngle); logger.debug("indicatedAngle A-B " + indicatedAngle); // Subtract the difference and we have the angle that the board // is rotated by. double angleAB = indicatedAngle - expectedAngle ; // this is the rotation angle to be done logger.debug("angle A-B " + angleAB); // Now do the same for C-D x1 = placementLocationC.getX(); y1 = placementLocationC.getY(); x2 = placementLocationD.getX(); y2 = placementLocationD.getY(); centerX += (x1+x2)/2; centerY += (y1+y2)/2; // Calculate the expected angle between the two coordinates, based // on their locations in the placement. expectedAngle = Math.atan2(y1 - y2, x1 - x2); expectedAngle = Math.toDegrees(expectedAngle); logger.debug("expectedAngle C-D " + expectedAngle); // Then calculate the actual angle between the two coordinates, // based on the captured values. x1 = boardLocationC.getX(); y1 = boardLocationC.getY(); x2 = boardLocationD.getX(); y2 = boardLocationD.getY(); indicatedAngle = Math.atan2(y1 - y2, x1 - x2); indicatedAngle = Math.toDegrees(indicatedAngle); logger.debug("indicatedAngle C-D " + indicatedAngle); // Subtract the difference and we have the angle that the board // is rotated by. double angleCD = indicatedAngle - expectedAngle ; // this is the rotation angle to be done logger.debug("angle C-D " + angleCD); Point center = new Point(centerX/2,centerY/2); // This is the center point of the four board used for rotation double dxAB = 0, dxCD = 0, dxMP = 0; double dyAB = 0, dyCD = 0, dyMP = 0; // Now we do binary search n-times between AngleAB and AngleCD to find lowest error // This is up to as good as we want, I prefer for-loop than while-loop. for(int i = 0; i< 50;++i) { // use angleAB to calculate the displacement necessary to get placementLocation to boardLocation. // Each point will have slightly different value. // Then we can tell the error resulted from using this angleAB. Point A = new Point(placementLocationA.getX(),placementLocationA.getY()); A = Utils2D.rotateTranslateCenterPoint(A, angleAB,0,0,center); Point B = new Point(placementLocationB.getX(),placementLocationB.getY()); B = Utils2D.rotateTranslateCenterPoint(B, angleAB,0,0,center); Point C = new Point(placementLocationC.getX(),placementLocationC.getY()); C = Utils2D.rotateTranslateCenterPoint(C, angleAB,0,0,center); Point D = new Point(placementLocationD.getX(),placementLocationD.getY()); D = Utils2D.rotateTranslateCenterPoint(D, angleAB,0,0,center); double dA = (boardLocationA.getX() - A.getX()); double dB = (boardLocationB.getX() - B.getX()); double dC = (boardLocationC.getX() - C.getX()); double dD = (boardLocationD.getX() - D.getX()); // Take the average of the four dxAB = (dA + dB + dC + dD)/4; double errorAB = Math.abs(dxAB- dA) + Math.abs(dxAB- dB) + Math.abs(dxAB- dC) + Math.abs(dxAB- dD); dA = (boardLocationA.getY() - A.getY()); dB = (boardLocationB.getY() - B.getY()); dC = (boardLocationC.getY() - C.getY()); dD = (boardLocationD.getY() - D.getY()); // Take the average of the four dyAB = (dA + dB + dC + dD)/4; errorAB += Math.abs(dyAB- dA) + Math.abs(dyAB- dB) + Math.abs(dyAB- dC) + Math.abs(dyAB- dD); // Accumulate the error // Now do the same using angleCD, find the error caused by angleCD A = new Point(placementLocationA.getX(),placementLocationA.getY()); A = Utils2D.rotateTranslateCenterPoint(A, angleCD,0,0,center); B = new Point(placementLocationB.getX(),placementLocationB.getY()); B = Utils2D.rotateTranslateCenterPoint(B, angleCD,0,0,center); C = new Point(placementLocationC.getX(),placementLocationC.getY()); C = Utils2D.rotateTranslateCenterPoint(C, angleCD,0,0,center); D = new Point(placementLocationD.getX(),placementLocationD.getY()); D = Utils2D.rotateTranslateCenterPoint(D, angleCD,0,0,center); dA = (boardLocationA.getX() - A.getX()); dB = (boardLocationB.getX() - B.getX()); dC = (boardLocationC.getX() - C.getX()); dD = (boardLocationD.getX() - D.getX()); // Take the average of the four dxCD = (dA + dB + dC + dD)/4; double errorCD = Math.abs(dxCD- dA) + Math.abs(dxCD- dB) + Math.abs(dxCD- dC) + Math.abs(dxCD- dD); dA = (boardLocationA.getY() - A.getY()); dB = (boardLocationB.getY() - B.getY()); dC = (boardLocationC.getY() - C.getY()); dD = (boardLocationD.getY() - D.getY()); // Take the average of the four dyCD = (dA + dB + dC + dD)/4; errorCD += Math.abs(dyCD- dA) + Math.abs(dyCD- dB) + Math.abs(dyCD- dC) + Math.abs(dyCD- dD); // Accumulate the error // Now take the mid-point between the two angles, // and do the same math double angleMP = (angleAB + angleCD)/2; // MP = mid-point angle between angleAB and angleCD double deltaAngle = Math.abs(angleAB - angleCD); A = new Point(placementLocationA.getX(),placementLocationA.getY()); A = Utils2D.rotateTranslateCenterPoint(A, angleMP,0,0,center); B = new Point(placementLocationB.getX(),placementLocationB.getY()); B = Utils2D.rotateTranslateCenterPoint(B, angleMP,0,0,center); C = new Point(placementLocationC.getX(),placementLocationC.getY()); C = Utils2D.rotateTranslateCenterPoint(C, angleMP,0,0,center); D = new Point(placementLocationD.getX(),placementLocationD.getY()); D = Utils2D.rotateTranslateCenterPoint(D, angleMP,0,0,center); dA = (boardLocationA.getX() - A.getX()); dB = (boardLocationB.getX() - B.getX()); dC = (boardLocationC.getX() - C.getX()); dD = (boardLocationD.getX() - D.getX()); // Take the average of the four dxMP = (dA + dB + dC + dD)/4; double errorMP = Math.abs(dxMP- dA) + Math.abs(dxMP- dB) + Math.abs(dxMP- dC) + Math.abs(dxMP- dD); dA = (boardLocationA.getY() - A.getY()); dB = (boardLocationB.getY() - B.getY()); dC = (boardLocationC.getY() - C.getY()); dD = (boardLocationD.getY() - D.getY()); // Take the average of the four dyMP = (dA + dB + dC + dD)/4; errorMP += Math.abs(dyMP- dA) + Math.abs(dyMP- dB) + Math.abs(dyMP- dC) + Math.abs(dyMP- dD); // Accumulate the error // This is gradient descend searching for local minima (hopefully) between angleAB and angle CD logger.debug(String.format("Error AB=%g vs MP=%g vs CD=%g ", errorAB, errorMP, errorCD)); if(errorAB < errorCD) { if(errorMP > errorAB) // ok, so no local minima between AB and CD, let's search beyond AB { angleMP = angleAB; // use as temporary, this is MP of the previous cycle // Beyond means both ways if(angleAB > angleCD) angleAB += deltaAngle; else angleAB -= deltaAngle; angleCD = angleMP; } else { // Local minima is for sure between AB and CD, // best bet it's between MP and AB // otherwise next step it will look on the other side (angleCD + deltaAngle) angleCD = angleMP; } } else { if(errorMP > errorCD) // ok so no local minima between AB and CD, let's search beyond CD { angleMP = angleCD; // use as temporary, this is MP of the previous cycle // Beyond means both ways if(angleCD > angleAB) angleCD += deltaAngle; else angleCD -= deltaAngle; angleAB = angleCD; } else { // local minima is between AB and CD, // best bet it's between MP and CD, so set AB to the mid point (MP) // otherwise next step it will look on the other side (angleCD + deltaAngle) angleAB = angleMP; } } } double angle = (angleAB + angleCD)/2; // take the average logger.debug("angle final " + angle); // Take the average of the four //double dx = (dxAB + dxCD)/2; //double dy = (dyAB + dyCD)/2; double dx = dxMP; double dy = dyMP; logger.debug(String.format("dx %f, dy %f", dx, dy)); Location boardLocation = new Location(Configuration.get() .getSystemUnits(), dx, dy, 0, angle ); Location oldBoardLocation = jobPanel.getSelectedBoardLocation().getLocation(); oldBoardLocation = oldBoardLocation.convertToUnits(boardLocation.getUnits()); boardLocation = boardLocation.derive(null, null, oldBoardLocation.getZ(), null); jobPanel.getSelectedBoardLocation().setLocation(boardLocation); // TODO: Set Board center point when center points are finished. // jobPanel.getSelectedBoardLocation().setCenter(center); jobPanel.refreshSelectedBoardRow(); return true; } private boolean step5() { MainFrame.machineControlsPanel.submitMachineTask(new Runnable() { public void run() { Head head = Configuration.get().getMachine().getHeads().get(0); try { Camera camera = MainFrame.cameraPanel .getSelectedCamera(); Location location = jobPanel.getSelectedBoardLocation() .getLocation(); MovableUtils.moveToLocationAtSafeZ(camera, location, 1.0); } catch (Exception e) { MessageBoxes.errorBox(mainFrame, "Move Error", e); } } }); return true; } private void cancel() { mainFrame.hideInstructions(); } private final ActionListener proceedActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { advance(); } }; private final ActionListener cancelActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancel(); } }; }
EricB02/openpnp
src/main/java/org/openpnp/gui/processes/FourPlacementBoardLocationProcess.java
Java
gpl-3.0
18,974
/** * @class Ext.sparkline.Shape * @private */ Ext.define('Ext.sparkline.Shape', { constructor: function (target, id, type, args) { this.target = target; this.id = id; this.type = type; this.args = args; }, append: function () { this.target.appendShape(this); return this; } });
tlaitinen/sms
frontend/ext/src/sparkline/Shape.js
JavaScript
gpl-3.0
346
/** * @package omeka * @subpackage neatline * @copyright 2014 Rector and Board of Visitors, University of Virginia * @license http://www.apache.org/licenses/LICENSE-2.0.html */ Neatline.module('Editor.Exhibit.Records', function(Records) { Records.Controller = Neatline.Shared.Controller.extend({ slug: 'EDITOR:EXHIBIT:RECORDS', commands: [ 'display', 'load', 'ingest', 'navToList' ], requests: [ 'getModel' ], /** * Create the router, collection, and view. */ init: function() { this.router = new Records.Router(); this.view = new Records.View({ slug: this.slug }); }, /** * Append the list to the editor container. * * @param {Object} container: The container element. */ display: function(container) { this.view.showIn(container); }, /** * Query for new records. * * @param {Object} params: The query parameters. */ load: function(params) { this.view.load(params); }, /** * Render a records collection in the list. * * @param {Object} records: The collection of records. */ ingest: function(records) { this.view.ingest(records); }, /** * Navigate to the record list. */ navToList: function() { this.router.navigate('records', true); }, /** * Get a record model from the collection. * * @param {Number} id: The record id. * @param {Function} cb: A callback, called with the model. */ getModel: function(id, cb) { this.view.records.getOrFetch(id, cb); } }); });
elotroalex/devlib
plugins/Neatline/views/shared/javascripts/src/editor/exhibit/records/records.controller.js
JavaScript
gpl-3.0
1,675
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program 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 General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $layout_defs['ForContacts'] = array( 'top_buttons' => array( array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'Contacts'), ), ); ?>
Yuutakasan/SugarCRM-5.5.1-CE-JA-Dev
modules/Emails/subpanels/ForContacts.php
PHP
gpl-3.0
2,202
// Torc - Copyright 2011-2013 University of Southern California. All Rights Reserved. // $HeadURL$ // $Id$ // This program is free software: you can redistribute it and/or modify it under the terms of the // GNU General Public License as published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program. If // not, see <http://www.gnu.org/licenses/>. /// \file /// \brief Source for a PhysicalDiff command line utility. /// \details Opens up two designs with the XDLImporter and then compares them with PhysicalDiff. #include <fstream> #include "ArchitectureBrowser.hpp" #include "torc/common/DirectoryTree.hpp" /// \brief Main entry point for the architecture browser tool. int main(int argc, char *argv[]) { typedef std::string string; torc::common::DirectoryTree directoryTree(argv[0]); if (argc != 2) { std::cout << "Usage: " << argv[0] << " <device>" << std::endl; return 1; } string device_arg = argv[1]; torc::common::DeviceDesignator device(device_arg); torc::architecture::DDB db(device); torc::ArchitectureBrowser ab(db); ab.browse(); return 0; }
torc-isi/torc
src/torc/utils/BrowserMain.cpp
C++
gpl-3.0
1,487
/***************************************************************************** * * PROJECT: Open Faction * LICENSE: See LICENSE in the top level directory * FILE: shared/CStaticGeometry.cpp * PURPOSE: Loading of static geometry in levels * DEVELOPERS: Rafal Harabien * *****************************************************************************/ #include "CStaticGeometry.h" #include "CLevel.h" #include "CLevelProperties.h" #include "CConsole.h" #include "formats/rfl_format.h" #include "CGame.h" #include "CEventsHandler.h" #ifdef OF_CLIENT # include "CTextureMgr.h" # include "CLightmaps.h" # include "irr/CReadFile.h" # include "irr/CMeshSkyboxSceneNode.h" # include "irr/CVbmAnimator.h" #endif // OF_CLIENT #include <util/utils.h> #include <cmath> #include <cassert> using namespace std; #ifdef OF_CLIENT using namespace irr; #endif // OF_CLIENT struct SIndexDesc { unsigned idx; float u, v; float lm_u, lm_v; }; struct SFace { btVector3 vNormal; unsigned iTexture; unsigned iLightmapUnk; unsigned uFlags; unsigned iRoom; unsigned uPortalUnk; vector<SIndexDesc> Indices; }; #ifdef OF_CLIENT struct SIrrRoom { SIrrRoom(): pIrrMesh(NULL) {} scene::SMesh *pIrrMesh; vector<scene::ISceneNodeAnimator*> Animators; }; #endif CRoom::CRoom(CLevel *pLevel, unsigned nId, float fLife, bool bDetail): CKillableObject(OFET_LEVEL, pLevel, nId), m_pMesh(NULL), m_pShape(NULL), m_bDetail(bDetail) { m_iColGroup = COL_LEVEL; m_iColMask = COL_ENTITY; SetLife(fLife); } CRoom::~CRoom() { if(m_pShape) { assert(m_pColObj); m_pColObj->setCollisionShape(NULL); delete m_pShape; m_pShape = NULL; } if(m_pMesh) delete m_pMesh; m_pMesh = NULL; } void CRoom::Kill(SDamageInfo &DmgInfo) { if(!IsAlive()) return; // already dead m_fLife = 0.0f; m_pLevel->GetGame()->GetEventsHandler()->OnGlassKill(this, DmgInfo); RemoveFromWorld(); } void CStaticGeometry::Load(CLevel *pLevel, CInputBinaryStream &Stream, unsigned nVersion) { /* Unload old geometry first */ Unload(); Stream.ignore(nVersion == 0xB4 ? 6 : 10); // unknown unsigned cTextures = Stream.ReadUInt32(); assert(m_Materials.empty()); std::vector<CString> MaterialNames; for(unsigned i = 0; i < cTextures; ++i) { CString strFilename = Stream.ReadString2(); MaterialNames.push_back(strFilename); #ifdef OF_CLIENT CMultiTexture *pMaterial = pLevel->GetGame()->GetTextureMgr()->Load(strFilename); m_Materials.push_back(pMaterial); #endif // OF_CLIENT } unsigned cScrollAnim = Stream.ReadUInt32(); Stream.ignore(cScrollAnim * 12); unsigned cRooms = Stream.ReadUInt32(); m_Rooms.reserve(cRooms); #ifdef OF_CLIENT std::vector<SIrrRoom> IrrRooms(cRooms); #endif // OF_CLIENT unsigned iGlass = 0; for(unsigned i = 0; i < cRooms; ++i) { unsigned nId = Stream.ReadUInt32(); btVector3 vAabb1 = Stream.ReadVector(); btVector3 vAabb2 = Stream.ReadVector(); assert(vAabb1.x() < vAabb2.x() && vAabb1.y() < vAabb2.y() && vAabb1.z() < vAabb2.z()); bool bSkyRoom = Stream.ReadUInt8() ? true : false; Stream.ignore(3); // is_cold, is_outside, is_airlock bool bLiquidRoom = Stream.ReadUInt8() ? true : false; bool bAmbientLight = Stream.ReadUInt8() ? true : false; bool bDetail = Stream.ReadUInt8() ? true : false; unsigned Unknown = Stream.ReadUInt8(); assert(Unknown <= 1); float fLife = Stream.ReadFloat(); assert(fLife >= -1.0f && fLife <= 10000.f); Stream.ReadString2(); // eax_effect if(bLiquidRoom) { Stream.ignore(8); // liquid_depth, liquid_color Stream.ReadString2(); // liquid_surface_texture Stream.ignore(12 + 13 + 12); // liquid_visibility, liquid_type, liquid_alpha, liquid_unknown, // liquid_waveform, liquid_surface_texture_scroll_u, liquid_surface_texture_scroll_b } if(bAmbientLight) Stream.ignore(4); // ambient_color CRoom *pRoom = new CRoom(pLevel, nId, fLife, bDetail); pRoom->m_GlassIndex = pRoom->IsGlass() ? (iGlass++) : 0; pRoom->m_bSkyRoom = bSkyRoom; pRoom->m_vCenter = btVector3((vAabb1.x() + vAabb2.x())/2.0f, (vAabb1.y() + vAabb2.y())/2.0f, (vAabb1.z() + vAabb2.z())/2.0f); m_Rooms.push_back(pRoom); } unsigned cUnknown = Stream.ReadUInt32(); if(cRooms != cUnknown) pLevel->GetGame()->GetConsole()->DbgPrint("Warning! cRooms(%u) != cUnknown(%u)\n", cRooms, cUnknown); for(unsigned i = 0; i < cUnknown; ++i) { Stream.ignore(4); // index unsigned cUnknown2 = Stream.ReadUInt32(); // links_count Stream.ignore(cUnknown2 * 4); // links } unsigned cUnknown2 = Stream.ReadUInt32(); Stream.ignore(cUnknown2 * 32); // unknown3 unsigned cVertices = Stream.ReadUInt32(); std::vector<btVector3> Vertices(cVertices); for(unsigned i = 0; i < cVertices; ++i) Vertices[i] = Stream.ReadVector(); unsigned cFaces = Stream.ReadUInt32(); std::vector<SFace> Faces(cFaces); //CGame::GetInst().GetSceneMgr()->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); for(unsigned i = 0; i < cFaces; ++i) { unsigned nPos = (unsigned)Stream.tellg(); SFace &Face = Faces[i]; // Use normal from unknown plane Face.vNormal = Stream.ReadVector(); float fLen2 = Face.vNormal.length2(); assert(fLen2 > 0.99f && fLen2 < 1.01f); float fDist = Stream.ReadFloat(); //assert(fDist >= 0.0f); Face.iTexture = Stream.ReadUInt32(); if(Face.iTexture != 0xFFFFFFFF) assert(Face.iTexture < cTextures); Face.iLightmapUnk = Stream.ReadUInt32(); // its used later (lightmap?) assert(Face.iLightmapUnk == 0xFFFFFFFF || Face.iLightmapUnk < cFaces); unsigned Unknown3 = Stream.ReadUInt32(); //assert(Unknown3 == i); unsigned Unknown4 = Stream.ReadUInt32(); assert(Unknown4 == 0xFFFFFFFF); unsigned Unknown4_2 = Stream.ReadUInt32(); assert(Unknown4_2 == 0xFFFFFFFF); Face.uPortalUnk = Stream.ReadUInt32(); // its used later (it's not 0 for portals) Face.uFlags = Stream.ReadUInt8(); if((Face.uFlags & ~(RFL_FF_MASK))) pLevel->GetGame()->GetConsole()->DbgPrint("Unknown face flags 0x%x\n", Face.uFlags & ~(RFL_FF_MASK)); uint8_t uLightmapRes = Stream.ReadUInt8(); if(uLightmapRes >= 0x22) pLevel->GetGame()->GetConsole()->DbgPrint("Unknown lightmap resolution 0x%x\n", uLightmapRes); uint16_t Unk6 = Stream.ReadUInt16(); uint32_t Unk6_2 = Stream.ReadUInt32(); assert(Unk6 == 0); Face.iRoom = Stream.ReadUInt32(); assert(Face.iRoom < cRooms); unsigned cFaceVertices = Stream.ReadUInt32(); assert(cFaceVertices >= 3); //pLevel->GetGame()->GetConsole()->DbgPrint("Face %u vertices: %u, texture: %x (pos: 0x%x)\n", i, cFaceVertices, iTexture, nPos); if(cFaceVertices > 100) pLevel->GetGame()->GetConsole()->DbgPrint("Warning! Face %u has %u vertices (level can be corrupted) (pos: 0x%x)\n", i, cFaceVertices, nPos); Face.Indices.reserve(cFaceVertices); for(unsigned j = 0; j < cFaceVertices; ++j) { SIndexDesc Idx; Idx.idx = Stream.ReadUInt32(); assert(Idx.idx < cVertices); Idx.u = Stream.ReadFloat(); Idx.v = Stream.ReadFloat(); if(Face.iLightmapUnk != 0xFFFFFFFF) { Idx.lm_u = Stream.ReadFloat(); Idx.lm_v = Stream.ReadFloat(); assert(Idx.lm_u >= 0.0f && Idx.lm_u <= 1.0f); assert(Idx.lm_v >= 0.0f && Idx.lm_v <= 1.0f); } Face.Indices.push_back(Idx); } } unsigned cLightmapVertices = Stream.ReadUInt32(); #ifdef OF_CLIENT std::vector<unsigned> LightmapVertices(cLightmapVertices); #endif // OF_CLIENT for(unsigned i = 0; i < cLightmapVertices; ++i) { unsigned iLightmap = Stream.ReadUInt32(); #ifdef OF_CLIENT assert(iLightmap < pLevel->GetLightmaps()->GetCount()); LightmapVertices[i] = iLightmap; #endif // OF_CLIENT Stream.ignore(92); // unknown4 } if(nVersion == 0xB4) Stream.ignore(4); // unknown5 for(unsigned i = 0; i < cFaces; ++i) { SFace &Face = Faces[i]; CRoom *pRoom = m_Rooms[Face.iRoom]; CMultiTexture *pMaterial = (Face.iTexture != 0xFFFFFFFF) ? m_Materials[Face.iTexture] : NULL; const CString &MaterialName = (Face.iTexture != 0xFFFFFFFF) ? MaterialNames[Face.iTexture] : ""; bool bIsTransparent = (Face.uPortalUnk != 0) || (Face.uFlags & RFL_FF_SHOW_SKY) || IsInvisibleLevelTexture(MaterialName); #ifdef OF_CLIENT video::ITexture *pTexture = NULL, *pLightmapTexture = NULL; scene::SMeshBufferLightMap *pIrrBuf; unsigned iBuf, nFirstSubmeshIndex; if(!bIsTransparent) { // Get texture pointer if(pMaterial) pTexture = pMaterial->GetFrame(0); if(Face.iLightmapUnk != 0xFFFFFFFF) { unsigned iLightmap = LightmapVertices[Face.iLightmapUnk]; pLightmapTexture = pLevel->GetLightmaps()->Get(iLightmap); } if(!IrrRooms[Face.iRoom].pIrrMesh) { IrrRooms[Face.iRoom].pIrrMesh = new scene::SMesh; assert(IrrRooms[Face.iRoom].pIrrMesh->getMeshBufferCount() == 0); } // Find buffer for specified texture for(iBuf = 0; iBuf < IrrRooms[Face.iRoom].pIrrMesh->getMeshBufferCount(); ++iBuf) { pIrrBuf = (scene::SMeshBufferLightMap*)IrrRooms[Face.iRoom].pIrrMesh->getMeshBuffer(iBuf); if(pIrrBuf->Material.getTexture(0) == pTexture && pIrrBuf->Material.getTexture(1) == pLightmapTexture) { break; } } if(iBuf == IrrRooms[Face.iRoom].pIrrMesh->getMeshBufferCount()) { // Create new buffer and prepare it pIrrBuf = new scene::SMeshBufferLightMap; pIrrBuf->setHardwareMappingHint(scene::EHM_STATIC); // Setup material flags pIrrBuf->Material.setFlag(video::EMF_FOG_ENABLE, pLevel->GetProperties()->IsFogEnabled()); pIrrBuf->Material.setFlag(video::EMF_LIGHTING, false); // Setup textures pIrrBuf->Material.setTexture(0, pTexture); pIrrBuf->Material.setTexture(1, pLightmapTexture); if(pRoom->IsDetail() && pMaterial && pMaterial->HasAlpha()) pIrrBuf->Material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; else if(pLightmapTexture && !pRoom->m_bSkyRoom) pIrrBuf->Material.MaterialType = video::EMT_LIGHTMAP_M2; if(pMaterial && pMaterial->IsAnimated()) { scene::ISceneNodeAnimator *pAnim = pMaterial->CreateAnimator(iBuf); if(pAnim) IrrRooms[Face.iRoom].Animators.push_back(pAnim); } // Add buffer to the mesh IrrRooms[Face.iRoom].pIrrMesh->addMeshBuffer(pIrrBuf); pIrrBuf->drop(); } // Reallocate buffers to speed up things pIrrBuf->Vertices.reallocate(pIrrBuf->Vertices.size() + Face.Indices.size()); pIrrBuf->Indices.reallocate(pIrrBuf->Indices.size() + (Face.Indices.size() - 3 + 1) * 3); // First index points to first vertex nFirstSubmeshIndex = pIrrBuf->Vertices.size(); } #endif // OF_CLIENT unsigned nFirstIndex, nPrevIndex; for(unsigned j = 0; j < Face.Indices.size(); ++j) { SIndexDesc &Idx = Face.Indices[j]; if(!bIsTransparent) { if(!pRoom->m_bSkyRoom) { if(j == 0) nFirstIndex = Idx.idx; else if(j >= 2) { if(!pRoom->m_pMesh) { pRoom->m_pMesh = new btTriangleMesh(); pRoom->m_pMesh->preallocateVertices(Face.Indices.size()); pRoom->m_pMesh->preallocateIndices((Face.Indices.size() - 3 + 1) * 3); } pRoom->m_pMesh->addTriangle(Vertices[nFirstIndex] - pRoom->m_vCenter, Vertices[nPrevIndex] - pRoom->m_vCenter, Vertices[Idx.idx] - pRoom->m_vCenter); } } #ifdef OF_CLIENT btVector3 vPos = Vertices[Idx.idx] - pRoom->m_vCenter; video::S3DVertex2TCoords Vertex; Vertex.Pos.X = vPos.x(); Vertex.Pos.Y = vPos.y(); Vertex.Pos.Z = vPos.z(); Vertex.Normal.X = Face.vNormal.x(); Vertex.Normal.Y = Face.vNormal.y(); Vertex.Normal.Z = Face.vNormal.z(); Vertex.TCoords.X = Idx.u; Vertex.TCoords.Y = Idx.v; Vertex.TCoords2.X = Idx.lm_u; Vertex.TCoords2.Y = Idx.lm_v; Vertex.Color = video::SColor(255, 255, 255, 255); pIrrBuf->Vertices.push_back(Vertex); if(j >= 2) { pIrrBuf->Indices.push_back(nFirstSubmeshIndex); pIrrBuf->Indices.push_back(pIrrBuf->Vertices.size() - 2); pIrrBuf->Indices.push_back(pIrrBuf->Vertices.size() - 1); } #endif // OF_CLIENT } nPrevIndex = Idx.idx; } } for(unsigned i = 0; i < m_Rooms.size(); ++i) { CRoom *pRoom = m_Rooms[i]; if(pRoom->m_pMesh) { pRoom->m_pShape = new btBvhTriangleMeshShape(pRoom->m_pMesh, true); btRigidBody::btRigidBodyConstructionInfo ConstructionInfo(0.0f, &pRoom->m_MotionState, pRoom->m_pShape); ConstructionInfo.m_friction = 10.0f; ConstructionInfo.m_restitution = 1.0f; pRoom->m_pColObj = new btRigidBody(ConstructionInfo); pRoom->m_pColObj->setUserPointer(pRoom); pRoom->m_pColObj->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT); pRoom->m_pColObj->getWorldTransform().setOrigin(pRoom->m_vCenter); pRoom->AddToWorld(); } #ifdef OF_CLIENT if(IrrRooms[i].pIrrMesh) { // Update bounding boxes for(unsigned iBuf = 0; iBuf < IrrRooms[i].pIrrMesh->getMeshBufferCount(); ++iBuf) IrrRooms[i].pIrrMesh->getMeshBuffer(iBuf)->recalculateBoundingBox(); IrrRooms[i].pIrrMesh->recalculateBoundingBox(); // Create scene node if(pRoom->m_bSkyRoom) { scene::ISceneManager *pSM = pLevel->GetGame()->GetSceneMgr(); pRoom->m_pSceneNode = new scene::CMeshSkyboxSceneNode(IrrRooms[i].pIrrMesh, pSM->getRootSceneNode(), pSM, -1); pRoom->m_pSceneNode->drop(); // drop it because smgr owns it now } else { pRoom->m_pSceneNode = pLevel->GetGame()->GetSceneMgr()->addOctreeSceneNode(IrrRooms[i].pIrrMesh); pRoom->m_pSceneNode->setPosition(core::vector3df(pRoom->m_vCenter.x(), pRoom->m_vCenter.y(), pRoom->m_vCenter.z())); } // Setup animators for(unsigned iAnim = 0; iAnim < IrrRooms[i].Animators.size(); ++iAnim) { pRoom->m_pSceneNode->addAnimator(IrrRooms[i].Animators[iAnim]); IrrRooms[i].Animators[iAnim]->drop(); // Scene node owns animators } IrrRooms[i].Animators.clear(); } else assert(IrrRooms[i].Animators.empty()); #endif // OF_CLIENT } pLevel->GetGame()->GetConsole()->DbgPrint("Loaded geometry: %u textures, %u rooms, %u vertices, %u faces\n", cTextures, cRooms, cVertices, cFaces); } void CStaticGeometry::Unload() { // Cleanup rooms - they are deleted by CLevel m_Rooms.clear(); #ifdef OF_CLIENT // Cleanup materials for(unsigned i = 0; i < m_Materials.size(); ++i) m_Materials[i]->Release(); m_Materials.clear(); #endif // OF_CLIENT }
Sebbyastian/openfaction
shared/CStaticGeometry.cpp
C++
gpl-3.0
17,432
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LeagueSharp; using LeagueSharp.Common; using Marksman.Common; using EloBuddy; using LeagueSharp.Common; namespace Marksman.Champions.Common { internal static class PlayerSpells { public static void CastSpellWithHitchance(this Spell spell, AIHeroClient t) { var nPrediction = spell.GetPrediction(t); var nHitPosition = nPrediction.CastPosition.Extend(ObjectManager.Player.Position, -140); if (nPrediction.Hitchance >= spell.GetHitchance()) { spell.Cast(nHitPosition); } } } }
saophaisau/port
Core/AIO Ports/Marksman II/Champions/Common/PlayerSpells.cs
C#
gpl-3.0
713
/** * OpenEyes * * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011 * (C) OpenEyes Foundation, 2011-2013 * This file is part of OpenEyes. * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * OpenEyes 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 General Public License for more details. * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package OpenEyes * @link http://www.openeyes.org.uk * @author OpenEyes <info@openeyes.org.uk> * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust * @copyright Copyright (c) 2011-2013, OpenEyes Foundation * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ /** * Cutter Peripheral iridectomy * * @class CutterPI * @property {String} className Name of doodle subclass * @param {Drawing} _drawing * @param {Object} _parameterJSON */ ED.CutterPI = function(_drawing, _parameterJSON) { // Set classname this.className = "CutterPI"; // Saved parameters this.savedParameterArray = ['rotation']; // Call superclass constructor ED.Doodle.call(this, _drawing, _parameterJSON); } /** * Sets superclass and constructor */ ED.CutterPI.prototype = new ED.Doodle; ED.CutterPI.prototype.constructor = ED.CutterPI; ED.CutterPI.superclass = ED.Doodle.prototype; /** * Sets default properties */ ED.CutterPI.prototype.setPropertyDefaults = function() { this.isScaleable = false; this.isMoveable = false; } /** * Sets default parameters */ ED.CutterPI.prototype.setParameterDefaults = function() { this.setRotationWithDisplacements(160, 40); } /** * Draws doodle or performs a hit test if a Point parameter is passed * * @param {Point} _point Optional point in canvas plane, passed if performing hit test */ ED.CutterPI.prototype.draw = function(_point) { // Get context var ctx = this.drawing.context; // Call draw method in superclass ED.CutterPI.superclass.draw.call(this, _point); // Boundary path ctx.beginPath(); // Draw base ctx.arc(0, -324, 40, 0, 2 * Math.PI, true); // Colour of fill ctx.fillStyle = "rgba(255,255,255,1)"; // Set line attributes ctx.lineWidth = 4; // Colour of outer line is dark gray ctx.strokeStyle = "rgba(120,120,120,0.75)";; // Draw boundary path (also hit testing) this.drawBoundary(_point); // Return value indicating successful hittest return this.isClicked; } /** * Returns a string containing a text description of the doodle * * @returns {String} Description of doodle */ ED.CutterPI.prototype.groupDescription = function() { return "Cutter iridectomy/s"; }
openeyesarchive/eyedraw
src/ED/Doodles/Oph/CutterPI.js
JavaScript
gpl-3.0
3,009
#include "ExampleOne.h" ExampleOneWrite::ExampleOneWrite(std::string name): SamClass(name) { } void ExampleOneWrite::SamInit(void) { myint=0; newPort(&myfirst2, "W2"); // add new port newPort(&myfirst, "W1"); StartModule(); puts("started writer"); } void ExampleOneWrite::SamIter(void) { Bottle& B = myfirst.prepare(); // prepare the bottle/port B.clear(); B.addInt(myint++); myfirst.write(); // add stuff then send Bottle& C = myfirst2.prepare(); C.clear(); C.addInt(myint+5); myfirst2.write(); puts("running writer"); } //////////////////////////////////////////////////////////////////////////////// ExampleTwoRead::ExampleTwoRead(std::string name): SamClass(name) { } void ExampleTwoRead::SamInit(void) { myint=0; newPort(&myfirst, "R1"); StartModule(); puts("started reader"); } void ExampleTwoRead::SamIter(void) { puts("running reader"); Bottle *input = myfirst.read(false); // get in the input from the port, if // you want it to wait use true, else use false if(input!=NULL) // check theres data { puts("got a msg"); puts(input->toString()); } else puts("didn't get a msg"); } //////////////////////////////////////////////////////////////////////////////// ExampleThreeSendClass::ExampleThreeSendClass(std::string name): SamClass(name) { } void ExampleThreeSendClass::SamInit(void) { //name = "/SClass"; myint=0; newPort(&myfirst, "Out"); StartModule(); } void ExampleThreeSendClass::SamIter(void) { myint++; BinPortable<DataForm> &MyData = myfirst.prepare(); // prepare data/port MyData.content().x=myint; MyData.content().y=myint+5; MyData.content().p=myint+10; myfirst.write(); // add stuff and write } //////////////////////////////////////////////////////////////////////////////// // a Interupt port, when data hits this port it'll do whatever is onread, be // carefull, fast firing interupts can cause big problems as in normal code void DataPort ::onRead(BinPortable<DataForm>& b) { printf("X %i Y %i P %i \n",b.content().x,b.content().y,b.content().p); } ExampleFourReciveClassInterupt::ExampleFourReciveClassInterupt(std::string name): SamClass(name) { } void ExampleFourReciveClassInterupt::SamInit(void) { myint=0; //name="/RClass"; newPort(&myfirst, "In"); myfirst.useCallback(); // this tells it to use the onread method StartModule(); } void ExampleFourReciveClassInterupt::SamIter(void) { }
nurv/lirec
libs/SAMGAR/trunk/Modules/Examples/ExampleOne.cpp
C++
gpl-3.0
2,618
function loadText() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "K\u00E4lla"; txtLang[1].innerHTML = "Alternativ text"; txtLang[2].innerHTML = "Mellanrum"; txtLang[3].innerHTML = "Placering"; txtLang[4].innerHTML = "\u00D6verst"; txtLang[5].innerHTML = "Bildram"; txtLang[6].innerHTML = "Nederst"; txtLang[7].innerHTML = "Bredd"; txtLang[8].innerHTML = "V\u00E4nster"; txtLang[9].innerHTML = "H\u00F6jd"; txtLang[10].innerHTML = "H\u00F6ger"; var optLang = document.getElementsByName("optLang"); optLang[0].text = "Abs. nederst"; optLang[1].text = "Abs. mitten"; optLang[2].text = "Baslinje"; optLang[3].text = "Nederst"; optLang[4].text = "V\u00E4nster"; optLang[5].text = "Mitten"; optLang[6].text = "H\u00F6ger"; optLang[7].text = "Text-topp"; optLang[8].text = "\u00D6verst"; document.getElementById("btnBorder").value = " Kantlinje "; document.getElementById("btnReset").value = "\u00C5terst\u00E4ll"; document.getElementById("btnCancel").value = "Avbryt"; document.getElementById("btnInsert").value = "Infoga"; document.getElementById("btnApply").value = "Verkst\u00E4ll"; document.getElementById("btnOk").value = " OK "; } function writeTitle() { document.write("<title>Bild</title>") }
Alex-Bond/Core-package
tests/editors/iseditor2/scripts/language/finnish/image.js
JavaScript
gpl-3.0
1,371
#include "particleProperties_py.h" #include "stlContainers_py.h" namespace bp = boost::python; namespace { struct particlePropertiesWrapper : public rpwa::particleProperties, bp::wrapper<rpwa::particleProperties> { particlePropertiesWrapper() : rpwa::particleProperties(), bp::wrapper<rpwa::particleProperties>() { } particlePropertiesWrapper(const particleProperties& partProp) : rpwa::particleProperties(partProp), bp::wrapper<rpwa::particleProperties>() { } particlePropertiesWrapper(const std::string& partName, const int isospin, const int G, const int J, const int P, const int C) : rpwa::particleProperties(partName, isospin, G, J, P, C), bp::wrapper<rpwa::particleProperties>() { } std::string qnSummary() const { if(bp::override qnSummary = this->get_override("qnSummary")) { return qnSummary(); } return rpwa::particleProperties::qnSummary(); } std::string default_qnSummary() const { return rpwa::particleProperties::qnSummary(); } }; bool particleProperties_equal(const rpwa::particleProperties& self, const bp::object& rhsObj) { bp::extract<rpwa::particleProperties> get_partProp(rhsObj); if(get_partProp.check()) { return (self == get_partProp()); } std::pair<rpwa::particleProperties, std::string> rhsPair; if(not rpwa::py::convertBPObjectToPair<rpwa::particleProperties, std::string>(rhsObj, rhsPair)) { PyErr_SetString(PyExc_TypeError, "Got invalid input when executing rpwa::particleProperties::operator==()"); bp::throw_error_already_set(); } return (self == rhsPair); } bool particleProperties_nequal(const rpwa::particleProperties& self, const bp::object& rhsObj) { return not (self == rhsObj); } bool particleProperties_hasDecay(const rpwa::particleProperties& self, bp::object& pyDaughters) { std::multiset<std::string> daughters; if(not rpwa::py::convertBPObjectToMultiSet<std::string>(pyDaughters, daughters)) { PyErr_SetString(PyExc_TypeError, "Got invalid input for daughters when executing rpwa::particleProperties::hasDecay()"); bp::throw_error_already_set(); } return self.hasDecay(daughters); } void particleProperties_addDecayMode(rpwa::particleProperties& self, bp::object& pyDaughters) { std::multiset<std::string> daughters; if(not rpwa::py::convertBPObjectToMultiSet<std::string>(pyDaughters, daughters)) { PyErr_SetString(PyExc_TypeError, "Got invalid input for daughters when executing rpwa::particleProperties::addDecayMode()"); bp::throw_error_already_set(); } self.addDecayMode(daughters); } bool particleProperties_read(rpwa::particleProperties& self, bp::object& pyLine) { std::string strLine = bp::extract<std::string>(pyLine); std::istringstream sstrLine(strLine, std::istringstream::in); return self.read(sstrLine); } bp::tuple particleProperties_chargeFromName(const std::string& name) { int charge; std::string newName = rpwa::particleProperties::chargeFromName(name, charge); return bp::make_tuple(newName, charge); } } void rpwa::py::exportParticleProperties() { bp::class_< particlePropertiesWrapper >( "particleProperties" ) .def(bp::init<const rpwa::particleProperties&>()) .def(bp::init<std::string, int, int, int, int, int>()) .def("__eq__", &particleProperties_equal) .def("__neq__", &particleProperties_nequal) .def(bp::self_ns::str(bp::self)) .add_property("name", &rpwa::particleProperties::name, &rpwa::particleProperties::setName) .add_property("bareName", &rpwa::particleProperties::bareName) .add_property("antiPartName", &rpwa::particleProperties::antiPartName, &rpwa::particleProperties::setAntiPartName) .add_property("antiPartBareName", &rpwa::particleProperties::antiPartBareName) .add_property("charge", &rpwa::particleProperties::charge, &rpwa::particleProperties::setCharge) .add_property("mass", &rpwa::particleProperties::mass, &rpwa::particleProperties::setMass) .add_property("mass2", &rpwa::particleProperties::mass2) .add_property("width", &rpwa::particleProperties::width, &rpwa::particleProperties::setWidth) .add_property("baryonNmb", &rpwa::particleProperties::baryonNmb, &rpwa::particleProperties::setBaryonNmb) .add_property("isospin", &rpwa::particleProperties::isospin, &rpwa::particleProperties::setIsospin) .add_property("isospinProj", &rpwa::particleProperties::isospinProj, &rpwa::particleProperties::setIsospinProj) .add_property("strangeness", &rpwa::particleProperties::strangeness, &rpwa::particleProperties::setStrangeness) .add_property("charm", &rpwa::particleProperties::charm, &rpwa::particleProperties::setCharm) .add_property("beauty", &rpwa::particleProperties::beauty, &rpwa::particleProperties::setBeauty) .add_property("G", &rpwa::particleProperties::G, &rpwa::particleProperties::setG) .add_property("J", &rpwa::particleProperties::J, &rpwa::particleProperties::setJ) .add_property("P", &rpwa::particleProperties::P, &rpwa::particleProperties::setP) .add_property("C", &rpwa::particleProperties::C, &rpwa::particleProperties::setC) .add_property("isXParticle", &rpwa::particleProperties::isXParticle) .add_property("isMeson", &rpwa::particleProperties::isMeson) .add_property("isBaryon", &rpwa::particleProperties::isBaryon) .add_property("isLepton", &rpwa::particleProperties::isLepton) .add_property("isPhoton", &rpwa::particleProperties::isPhoton) .add_property("isItsOwnAntiPart", &rpwa::particleProperties::isItsOwnAntiPart) .add_property("isSpinExotic", &rpwa::particleProperties::isSpinExotic) .def( "fillFromDataTable" , &rpwa::particleProperties::fillFromDataTable , (bp::arg("name"), bp::arg("warnIfNotExistent")=(bool const)(true)) ) .add_property("nmbDecays", &rpwa::particleProperties::nmbDecays) .def("hasDecay", &particleProperties_hasDecay) .def("addDecayMode", &particleProperties_addDecayMode) .add_property("isStable", &rpwa::particleProperties::isStable) .def("setSCB", &rpwa::particleProperties::setSCB) .def("setIGJPC", &rpwa::particleProperties::setIGJPC) .add_property("antiPartProperties", &rpwa::particleProperties::antiPartProperties) .def("qnSummary", &particlePropertiesWrapper::qnSummary, &particlePropertiesWrapper::default_qnSummary) .def("qnSummary", &rpwa::particleProperties::qnSummary) .add_property("bareNameLaTeX", &rpwa::particleProperties::bareNameLaTeX) .def("read", &particleProperties_read) .def("nameWithCharge", &rpwa::particleProperties::nameWithCharge) .staticmethod("nameWithCharge") .def("chargeFromName", &particleProperties_chargeFromName) .staticmethod("chargeFromName") .def("stripChargeFromName", &rpwa::particleProperties::stripChargeFromName) .staticmethod("stripChargeFromName") .add_static_property("debugParticleProperties", &rpwa::particleProperties::debug, &rpwa::particleProperties::setDebug); }
odrotleff/ROOTPWA
pyInterface/particleData/particleProperties_py.cc
C++
gpl-3.0
7,031
<?php # -*- coding: utf-8 -*- $strings = 'tinyMCE.addI18n( "' . _WP_Editors::$mce_locale . '.strings", { classtitle: "' . esc_js( __( 'Class', 'pressbooks' ) ) . '", textboxes: "' . esc_js( __( 'Textboxes', 'pressbooks' ) ) . '", customtextbox: "' . esc_js( __( 'Custom Textbox', 'pressbooks' ) ) . '", standard: "' . esc_js( __( 'Standard', 'pressbooks' ) ) . '", standardsidebar: "' . esc_js( __( 'Standard (Sidebar)', 'pressbooks' ) ) . '", standardplaceholder: "' . esc_js( __( 'Type your textbox content here.', 'pressbooks' ) ) . '", shaded: "' . esc_js( __( 'Shaded', 'pressbooks' ) ) . '", shadedsidebar: "' . esc_js( __( 'Shaded (Sidebar)', 'pressbooks' ) ) . '", learningobjectives: "' . esc_js( __( 'Learning Objectives', 'pressbooks' ) ) . '", learningobjectivessidebar: "' . esc_js( __( 'Learning Objectives (Sidebar)', 'pressbooks' ) ) . '", learningobjectivesplaceholder: "' . esc_js( __( 'Type your learning objectives here.', 'pressbooks' ) ) . '", keytakeaways: "' . esc_js( __( 'Key Takeaways', 'pressbooks' ) ) . '", keytakeawayssidebar: "' . esc_js( __( 'Key Takeaways (Sidebar)', 'pressbooks' ) ) . '", keytakeawaysplaceholder: "' . esc_js( __( 'Type your key takeaways here.', 'pressbooks' ) ) . '", exercises: "' . esc_js( __( 'Exercises', 'pressbooks' ) ) . '", exercisessidebar: "' . esc_js( __( 'Exercises (Sidebar)', 'pressbooks' ) ) . '", exercisesplaceholder: "' . esc_js( __( 'Type your exercises here.', 'pressbooks' ) ) . '", examples: "' . esc_js( __( 'Examples', 'pressbooks' ) ) . '", examplessidebar: "' . esc_js( __( 'Examples (Sidebar)', 'pressbooks' ) ) . '", examplesplaceholder: "' . esc_js( __( 'Type your examples here.', 'pressbooks' ) ) . '", customellipses: "' . esc_js( __( 'Custom...', 'pressbooks' ) ) . '", first: "' . esc_js( __( 'First', 'pressbooks' ) ) . '", second: "' . esc_js( __( 'Second', 'pressbooks' ) ) . '", applyclass: "' . esc_js( __( 'Apply Class', 'pressbooks' ) ) . '" } )';
bdolor/pressbooks
languages/tinymce.php
PHP
gpl-3.0
2,039
#include "cinder/app/AppNative.h" #include "cinder/gl/Texture.h" #include "cinder/Capture.h" #include "cinder/params/Params.h" #include "CinderOpenCV.h" using namespace ci; using namespace ci::app; using namespace std; class ocvOpticalFlowApp : public AppNative { public: void setup(); void update(); void draw(); void keyDown( KeyEvent event ); void chooseFeatures( cv::Mat currentFrame ); void trackFeatures( cv::Mat currentFrame ); gl::Texture mTexture; Capture mCapture; cv::Mat mPrevFrame; vector<cv::Point2f> mPrevFeatures, mFeatures; vector<uint8_t> mFeatureStatuses; bool mDrawPoints; static const int MAX_FEATURES = 300; }; void ocvOpticalFlowApp::setup() { mDrawPoints = true; mCapture = Capture( 640, 480 ); mCapture.start(); } void ocvOpticalFlowApp::keyDown( KeyEvent event ) { if( event.getChar() == 'p' ) { mDrawPoints = ! mDrawPoints; } else if( event.getChar() == 'u' ) { chooseFeatures( mPrevFrame ); } } void ocvOpticalFlowApp::chooseFeatures( cv::Mat currentFrame ) { cv::goodFeaturesToTrack( currentFrame, mFeatures, MAX_FEATURES, 0.005, 3.0 ); } void ocvOpticalFlowApp::trackFeatures( cv::Mat currentFrame ) { vector<float> errors; mPrevFeatures = mFeatures; if( ! mFeatures.empty() ) cv::calcOpticalFlowPyrLK( mPrevFrame, currentFrame, mPrevFeatures, mFeatures, mFeatureStatuses, errors ); } void ocvOpticalFlowApp::update() { if( mCapture.checkNewFrame() ) { Surface surface( mCapture.getSurface() ); mTexture = gl::Texture( surface ); cv::Mat currentFrame( toOcv( Channel( surface ) ) ); if( mPrevFrame.data ) { if( mFeatures.empty() || getElapsedFrames() % 30 == 0 ) // pick new features once every 30 frames, or the first frame chooseFeatures( mPrevFrame ); trackFeatures( currentFrame ); } mPrevFrame = currentFrame; } } void ocvOpticalFlowApp::draw() { if( ( ! mTexture ) || mPrevFeatures.empty() ) return; gl::clear(); gl::enableAlphaBlending(); gl::setMatricesWindow( getWindowSize() ); gl::color( 1, 1, 1 ); gl::draw( mTexture ); glDisable( GL_TEXTURE_2D ); glColor4f( 1, 1, 0, 0.5f ); if( mDrawPoints ) { // draw all the old points for( vector<cv::Point2f>::const_iterator featureIt = mPrevFeatures.begin(); featureIt != mPrevFeatures.end(); ++featureIt ) gl::drawStrokedCircle( fromOcv( *featureIt ), 4 ); // draw all the new points for( vector<cv::Point2f>::const_iterator featureIt = mFeatures.begin(); featureIt != mFeatures.end(); ++featureIt ) gl::drawSolidCircle( fromOcv( *featureIt ), 4 ); } // draw the lines connecting them #if ! defined( CINDER_COCOA_TOUCH ) glColor4f( 0, 1, 0, 0.5f ); glBegin( GL_LINES ); for( size_t idx = 0; idx < mFeatures.size(); ++idx ) { if( mFeatureStatuses[idx] ) { gl::vertex( fromOcv( mFeatures[idx] ) ); gl::vertex( fromOcv( mPrevFeatures[idx] ) ); } } glEnd(); #endif } CINDER_APP_NATIVE( ocvOpticalFlowApp, RendererGl )
brittybaby/3DModelfitting
dependencies/include/cinder/blocks/OpenCV/samples/ocvOpticalFlow/src/ocvOpticalFlowApp.cpp
C++
gpl-3.0
2,941
<?php /** * Mahara: Electronic portfolio, weblog, resume builder and social networking * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see: * http://wiki.mahara.org/Contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package mahara * @subpackage core * @author Catalyst IT Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU GPL * @copyright (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz * */ define('INTERNAL', 1); define('MENUITEM', 'settings/preferences'); require(dirname(dirname(__FILE__)) . '/init.php'); define('TITLE', get_string('deleteaccount', 'account')); require_once('pieforms/pieform.php'); if (!$USER->can_delete_self()) { throw new AccessDeniedException(get_string('accessdenied', 'error')); } $deleteform = pieform(array( 'name' => 'account_delete', 'plugintype' => 'core', 'pluginname' => 'account', 'elements' => array( 'submit' => array( 'type' => 'submit', 'value' => get_string('deleteaccount', 'mahara', display_username($USER), full_name($USER)), ), ), )); function account_delete_submit(Pieform $form, $values) { global $SESSION, $USER; $userid = $USER->get('id'); $USER->logout(); delete_user($userid); $SESSION->add_ok_msg(get_string('accountdeleted', 'account')); redirect('/'); } $smarty = smarty(); $smarty->assign('form', $deleteform); $smarty->display('account/delete.tpl');
universityofglasgow/mahara
htdocs/account/delete.php
PHP
gpl-3.0
2,082