code
stringlengths
4
1.01M
language
stringclasses
2 values
<h2 class="page-header"><a href="<?= $Page->Url ?>"><?= $Page->Title ?></a></h2> <?= $Page->Content ?>
Java
<div align="center"><a href="/onestop/metadata-manager">Metadata Manager Documentation Home</a></div> <hr> **Estimated Reading Time: 15 minutes** # Upstream Connecting via Kafka ## Table of Contents * [Integrating upstream application to the underlying Kafka system](#integrating-upstream-application-to-the-underlying-kafka-system) * [Features](#features) * [Apache NiFi](#apache-nifi) * [Nifi as a Producer](#nifi-as-a-producer) * [Nifi as bidirectional Data Flows](#nifi-as-bidirectional-data-flows) * [kafka producer](#kafka-producer) * [Kafka connects](#kafka-connects) ## Integrating upstream application to the underlying Kafka system Metadata can be published into the OneStop system in two different ways, using Registry application [REST API](onestop-metadata-loading) or directly integrating upstream applications to the underline OneStop kafka cluster. This guide will take a look at some approaches for integrating upstream applications and Kafka, and look at some examples regarding the tools Kafka supports. Before we dive in, it's worth mentioning the single common data format, Apache Avro, which OneStop application is using for ensuring all data sources and integration points comply to it. Apache Avro is an [open source data serialization format](http://avro.apache.org/docs/1.9.1/). It relies on schema that define fields and their type. Avro also supports schema evolution. See [Avro schema project](https://github.com/cedardevs/schemas/tree/master/schemas-core) for details. ## Features - [Using Apache NiFi](#apache-niFi) - [Using kafka producer](#kafka-producer) - [Using Kafka connects](#kafka-connects) ### Apache NiFi NiFi is a highly scalable and user friendly UI based system that provides support for data collection and processing. In this case, Nifi can act as a source and sink to bring data to and from Kafka, which helps in automating the flow of data between systems in a Reliable, efficient, and manageable way. NiFi is able to support multiple versions of the Kafka client in a single NiFi instance. The Apache NiFi 1.10.0 release contains the following Kafka processors: - ConsumeKafka & PublishKafka using the 0.9 client - ConsumeKafka_1_0 & PublishKafka_1_0 using the 1.0 client - ConsumeKafka_2_0 & PublishKafka_2_0 using the 2.0 client Kafka does not necessarily provide backward compatibility between versions, so use kafka processors that is compatible with the OneStop kafka broker version. See [Apache NiFi website](https://nifi.apache.org/) page for details. #### Nifi as a Producer A simple use case of NiFi is to act as a Kafka producer, which can bring data from sources directly to a NiFi instance, which can then deliver data to the appropriate Kafka topic. Each instance of PublishKafka could have concurrent tasks executing and each of this tasks publishes messages independently. Here is the NiFi template with two processors and controller services configuration: ![sample kafka publishing flow](sampleCode/nifiKafkaFlow.png) The above example uses GenerateFlowFile processor to create FlowFiles of random data and PublishKafkaRecord processor with the Confluent Schema Registry to publish records to kafka. Sample Nifi template [download the sample nifi template](sampleCode/nifi-kafkaPublishing-template.xml). #### Nifi as bidirectional Data Flows Additional and more complex use case is combining tools such as Kafka, and kafka stream processing platform with Nifi to create a self-adjusting data flow. Kafka Stream is a lightweight library for creating stream processing applications. In this case, NiFi brings data to Kafka which makes it available to a stream processing platform with the results being written back to a different Kafka topic for downstream consumers. ### kafka producer kafka producer uses a Kafka producer API to write a producer that can be used to published record directly to kafka broker. see [kafka producer Confluent docs](https://docs.confluent.io/current/clients/producer.html) page for details. Let's look at a simple Kafka producer implementation using java. To create a Kafka producer, you need to pass a list of bootstrap servers/Kafka brokers and also specify a client.id that uniquely identifies this Producer client. you will need to specify a Key_serializer and a value_serializer, which Kafka will use to encode the message id as a Kafka record key, and the message body as the Kafka record value. Import the Kafka packages and define a constant for the producer to connect to the Kafka broker. ```java import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig; import io.confluent.kafka.serializers.KafkaAvroSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; public class KafkaProducerTest { private final static String TOPIC = "test-topic"; private final static String BOOTSTRAP_SERVERS = "localhost:9092"; private final static String SCHEMA_REGISTRY_URL = "localhost:8081"; private final static String CLIENT_ID = "test-client"; private final static String COMPRESSION_TYPE = "zstd"; private static Producer<Long, String> createProducer() { props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS); props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, SCHEMA_REGISTRY_URL); props.put(ProducerConfig.CLIENT_ID_CONFIG, CLIENT_ID); props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, COMPRESSION_TYPE); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.name); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.name); return new KafkaProducer<>(props); } } ``` The constant BOOTSTRAP_SERVERS_CONFIG is set to `http://localhost:9092` as default which also can be a comma separated list that the Producer uses to establish an initial connection to the Kafka cluster. The CLIENT_ID_CONFIG value is an id to pass to the server when making requests so the server can track the source of requests. The KEY_SERIALIZER_CLASS_CONFIG value is a Kafka Serializer class for Kafka record keys that implements the Kafka Serializer interface. Notice that we set this to StringSerializer as the message ids type. The VALUE_SERIALIZER_CLASS_CONFIG value is a Kafka Serializer class for Kafka record values that implements the Kafka Serializer interface. Notice that we set this to AbstractKafkaAvroSerDeConfig as the message body in OneStop is in Avro format. Import an Avro schema packages and changing an incoming message to Avro format. ```java import org.cedar.schemas.avro.psi.Input; import org.cedar.schemas.avro.psi.Method; import org.cedar.schemas.avro.psi.OperationType; import org.cedar.schemas.avro.psi.RecordType; public class KafkaProducerTest { ... private static Input buildInputTopicMessage(Map info) { Input.Builder builder = Input.newBuilder(); builder.setType(RecordType.collection); builder.setMethod(Method.PUT); builder.setContent(String.valueOf(info)); builder.setContentType(CONTENT_TYPE); builder.setSource(SOURCE); builder.setOperation(OperationType.NO_OP); return builder.build(); } } ``` The builder is setting the require fields which is define here in the [Input avro schema definition](https://github.com/cedardevs/schemas/blob/master/schemas-core/src/main/resources/avro/psi/input.avsc). see [sample kafka producer java code](sampleCode/kafkaSampleTest.java) file for detail. ### Kafka connects Kafka connect, which includes source and sink, can also be used to published data from upstream source into kafka broker. see [kafka connect Confluent page](https://docs.confluent.io/current/connect/index.html) for more details. <hr> <div align="center"><a href="#">Top of Page</a></div>
Java
<? session_start(); session_destroy(); header("Location: ../index.html"); ?>
Java
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace XORCISMModel { using System; using System.Collections.Generic; public partial class LIBRARYREFERENCE { public int LibraryReferenceID { get; set; } } }
Java
<link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/jquery.jscrollpane.custom.css" /> <link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/bookblock.css" /> <link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/custom.css" /> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/modernizr.custom.79639.js"></script> <div id="container" class="container"> <div class="menu-panel"> <h3>Table of Contents</h3> <ul id="menu-toc" class="menu-toc"> <?php print $menu_items; ?> </ul> </div> <div class="bb-custom-wrapper"> <div id="bb-bookblock" class="bb-bookblock"> <?php print $item_content; ?> </div> <nav> <span id="bb-nav-prev">&larr;</span> <span id="bb-nav-next">&rarr;</span> </nav> <span id="tblcontents" class="menu-button">Table of Contents</span> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.mousewheel.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.jscrollpane.min.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquerypp.custom.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.bookblock.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/page.js"></script> <script> $(function() { Page.init(); }); </script>
Java
require 'rails_helper' def topics_controller_show_gen_perm_tests(expected, ctx) expected.each do |sym, status| params = "topic_id: #{sym}.id, slug: #{sym}.slug" if sym == :nonexist params = "topic_id: nonexist_topic_id" end ctx.instance_eval(" it 'returns #{status} for #{sym}' do begin xhr :get, :show, #{params} expect(response.status).to eq(#{status}) rescue Discourse::NotLoggedIn expect(302).to eq(#{status}) end end") end end describe TopicsController do context 'wordpress' do let!(:user) { log_in(:moderator) } let(:p1) { Fabricate(:post, user: user) } let(:topic) { p1.topic } let!(:p2) { Fabricate(:post, topic: topic, user:user )} it "returns the JSON in the format our wordpress plugin needs" do SiteSetting.external_system_avatars_enabled = false xhr :get, :wordpress, topic_id: topic.id, best: 3 expect(response).to be_success json = ::JSON.parse(response.body) expect(json).to be_present # The JSON has the data the wordpress plugin needs expect(json['id']).to eq(topic.id) expect(json['posts_count']).to eq(2) expect(json['filtered_posts_count']).to eq(2) # Posts expect(json['posts'].size).to eq(1) post = json['posts'][0] expect(post['id']).to eq(p2.id) expect(post['username']).to eq(user.username) expect(post['avatar_template']).to eq("#{Discourse.base_url_no_prefix}#{user.avatar_template}") expect(post['name']).to eq(user.name) expect(post['created_at']).to be_present expect(post['cooked']).to eq(p2.cooked) # Participants expect(json['participants'].size).to eq(1) participant = json['participants'][0] expect(participant['id']).to eq(user.id) expect(participant['username']).to eq(user.username) expect(participant['avatar_template']).to eq("#{Discourse.base_url_no_prefix}#{user.avatar_template}") end end context 'move_posts' do it 'needs you to be logged in' do expect { xhr :post, :move_posts, topic_id: 111, title: 'blah', post_ids: [1,2,3] }.to raise_error(Discourse::NotLoggedIn) end describe 'moving to a new topic' do let!(:user) { log_in(:moderator) } let(:p1) { Fabricate(:post, user: user) } let(:topic) { p1.topic } it "raises an error without postIds" do expect { xhr :post, :move_posts, topic_id: topic.id, title: 'blah' }.to raise_error(ActionController::ParameterMissing) end it "raises an error when the user doesn't have permission to move the posts" do Guardian.any_instance.expects(:can_move_posts?).returns(false) xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [1,2,3] expect(response).to be_forbidden end context 'success' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p2.id], title: 'blah', category_id: 123).returns(topic) xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p2.id], category_id: 123 end it "returns success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(true) expect(result['url']).to be_present end end context 'failure' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p2.id], title: 'blah').returns(nil) xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p2.id] end it "returns JSON with a false success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(false) expect(result['url']).to be_blank end end end describe "moving replied posts" do let!(:user) { log_in(:moderator) } let!(:p1) { Fabricate(:post, user: user) } let!(:topic) { p1.topic } let!(:p2) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: p1.post_number ) } context 'success' do before do PostReply.create(post_id: p1.id, reply_id: p2.id) end it "moves the child posts too" do Topic.any_instance.expects(:move_posts).with(user, [p1.id, p2.id], title: 'blah').returns(topic) xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p1.id], reply_post_ids: [p1.id] end end end describe 'moving to an existing topic' do let!(:user) { log_in(:moderator) } let(:p1) { Fabricate(:post, user: user) } let(:topic) { p1.topic } let(:dest_topic) { Fabricate(:topic) } context 'success' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p2.id], destination_topic_id: dest_topic.id).returns(topic) xhr :post, :move_posts, topic_id: topic.id, post_ids: [p2.id], destination_topic_id: dest_topic.id end it "returns success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(true) expect(result['url']).to be_present end end context 'failure' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p2.id], destination_topic_id: dest_topic.id).returns(nil) xhr :post, :move_posts, topic_id: topic.id, destination_topic_id: dest_topic.id, post_ids: [p2.id] end it "returns JSON with a false success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(false) expect(result['url']).to be_blank end end end end context "merge_topic" do it 'needs you to be logged in' do expect { xhr :post, :merge_topic, topic_id: 111, destination_topic_id: 345 }.to raise_error(Discourse::NotLoggedIn) end describe 'moving to a new topic' do let!(:user) { log_in(:moderator) } let(:p1) { Fabricate(:post, user: user) } let(:topic) { p1.topic } it "raises an error without destination_topic_id" do expect { xhr :post, :merge_topic, topic_id: topic.id }.to raise_error(ActionController::ParameterMissing) end it "raises an error when the user doesn't have permission to merge" do Guardian.any_instance.expects(:can_move_posts?).returns(false) xhr :post, :merge_topic, topic_id: 111, destination_topic_id: 345 expect(response).to be_forbidden end let(:dest_topic) { Fabricate(:topic) } context 'moves all the posts to the destination topic' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p1.id], destination_topic_id: dest_topic.id).returns(topic) xhr :post, :merge_topic, topic_id: topic.id, destination_topic_id: dest_topic.id end it "returns success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(true) expect(result['url']).to be_present end end end end context 'change_post_owners' do it 'needs you to be logged in' do expect { xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3] }.to raise_error(Discourse::NotLoggedIn) end describe 'forbidden to moderators' do let!(:moderator) { log_in(:moderator) } it 'correctly denies' do xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3] expect(response).to be_forbidden end end describe 'forbidden to trust_level_4s' do let!(:trust_level_4) { log_in(:trust_level_4) } it 'correctly denies' do xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3] expect(response).to be_forbidden end end describe 'changing ownership' do let!(:editor) { log_in(:admin) } let(:topic) { Fabricate(:topic) } let(:user_a) { Fabricate(:user) } let(:p1) { Fabricate(:post, topic_id: topic.id) } let(:p2) { Fabricate(:post, topic_id: topic.id) } it "raises an error with a parameter missing" do expect { xhr :post, :change_post_owners, topic_id: 111, post_ids: [1,2,3] }.to raise_error(ActionController::ParameterMissing) expect { xhr :post, :change_post_owners, topic_id: 111, username: 'user_a' }.to raise_error(ActionController::ParameterMissing) end it "calls PostOwnerChanger" do PostOwnerChanger.any_instance.expects(:change_owner!).returns(true) xhr :post, :change_post_owners, topic_id: topic.id, username: user_a.username_lower, post_ids: [p1.id] expect(response).to be_success end it "changes multiple posts" do # an integration test xhr :post, :change_post_owners, topic_id: topic.id, username: user_a.username_lower, post_ids: [p1.id, p2.id] p1.reload; p2.reload expect(p1.user).not_to eq(nil) expect(p1.user).to eq(p2.user) end it "works with deleted users" do deleted_user = Fabricate(:user) t2 = Fabricate(:topic, user: deleted_user) p3 = Fabricate(:post, topic_id: t2.id, user: deleted_user) deleted_user.save t2.save p3.save UserDestroyer.new(editor).destroy(deleted_user, { delete_posts: true, context: 'test', delete_as_spammer: true }) xhr :post, :change_post_owners, topic_id: t2.id, username: user_a.username_lower, post_ids: [p3.id] expect(response).to be_success t2.reload p3.reload expect(t2.deleted_at).to be_nil expect(p3.user).to eq(user_a) end end end context 'change_timestamps' do let(:params) { { topic_id: 1, timestamp: Time.zone.now } } it 'needs you to be logged in' do expect { xhr :put, :change_timestamps, params }.to raise_error(Discourse::NotLoggedIn) end [:moderator, :trust_level_4].each do |user| describe "forbidden to #{user}" do let!(user) { log_in(user) } it 'correctly denies' do xhr :put, :change_timestamps, params expect(response).to be_forbidden end end end describe 'changing timestamps' do let!(:admin) { log_in(:admin) } let(:old_timestamp) { Time.zone.now } let(:new_timestamp) { old_timestamp - 1.day } let!(:topic) { Fabricate(:topic, created_at: old_timestamp) } let!(:p1) { Fabricate(:post, topic_id: topic.id, created_at: old_timestamp) } let!(:p2) { Fabricate(:post, topic_id: topic.id, created_at: old_timestamp + 1.day) } it 'raises an error with a missing parameter' do expect { xhr :put, :change_timestamps, topic_id: 1 }.to raise_error(ActionController::ParameterMissing) end it 'should update the timestamps of selected posts' do xhr :put, :change_timestamps, topic_id: topic.id, timestamp: new_timestamp.to_f expect(topic.reload.created_at).to be_within_one_second_of(new_timestamp) expect(p1.reload.created_at).to be_within_one_second_of(new_timestamp) expect(p2.reload.created_at).to be_within_one_second_of(old_timestamp) end end end context 'clear_pin' do it 'needs you to be logged in' do expect { xhr :put, :clear_pin, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn) end context 'when logged in' do let(:topic) { Fabricate(:topic) } let!(:user) { log_in } it "fails when the user can't see the topic" do Guardian.any_instance.expects(:can_see?).with(topic).returns(false) xhr :put, :clear_pin, topic_id: topic.id expect(response).not_to be_success end describe 'when the user can see the topic' do it "calls clear_pin_for if the user can see the topic" do Topic.any_instance.expects(:clear_pin_for).with(user).once xhr :put, :clear_pin, topic_id: topic.id end it "succeeds" do xhr :put, :clear_pin, topic_id: topic.id expect(response).to be_success end end end end context 'status' do it 'needs you to be logged in' do expect { xhr :put, :status, topic_id: 1, status: 'visible', enabled: true }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do before do @user = log_in(:moderator) @topic = Fabricate(:topic, user: @user) end it "raises an exception if you can't change it" do Guardian.any_instance.expects(:can_moderate?).with(@topic).returns(false) xhr :put, :status, topic_id: @topic.id, status: 'visible', enabled: 'true' expect(response).to be_forbidden end it 'requires the status parameter' do expect { xhr :put, :status, topic_id: @topic.id, enabled: true }.to raise_error(ActionController::ParameterMissing) end it 'requires the enabled parameter' do expect { xhr :put, :status, topic_id: @topic.id, status: 'visible' }.to raise_error(ActionController::ParameterMissing) end it 'raises an error with a status not in the whitelist' do expect { xhr :put, :status, topic_id: @topic.id, status: 'title', enabled: 'true' }.to raise_error(Discourse::InvalidParameters) end it 'calls update_status on the forum topic with false' do Topic.any_instance.expects(:update_status).with('closed', false, @user, until: nil) xhr :put, :status, topic_id: @topic.id, status: 'closed', enabled: 'false' end it 'calls update_status on the forum topic with true' do Topic.any_instance.expects(:update_status).with('closed', true, @user, until: nil) xhr :put, :status, topic_id: @topic.id, status: 'closed', enabled: 'true' end end end context 'delete_timings' do it 'needs you to be logged in' do expect { xhr :delete, :destroy_timings, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn) end context 'when logged in' do before do @user = log_in @topic = Fabricate(:topic, user: @user) @topic_user = TopicUser.get(@topic, @topic.user) end it 'deletes the forum topic user record' do PostTiming.expects(:destroy_for).with(@user.id, [@topic.id]) xhr :delete, :destroy_timings, topic_id: @topic.id end end end describe 'mute/unmute' do it 'needs you to be logged in' do expect { xhr :put, :mute, topic_id: 99}.to raise_error(Discourse::NotLoggedIn) end it 'needs you to be logged in' do expect { xhr :put, :unmute, topic_id: 99}.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do before do @topic = Fabricate(:topic, user: log_in) end end end describe 'recover' do it "won't allow us to recover a topic when we're not logged in" do expect { xhr :put, :recover, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do let(:topic) { Fabricate(:topic, user: log_in, deleted_at: Time.now, deleted_by: log_in) } describe 'without access' do it "raises an exception when the user doesn't have permission to delete the topic" do Guardian.any_instance.expects(:can_recover_topic?).with(topic).returns(false) xhr :put, :recover, topic_id: topic.id expect(response).to be_forbidden end end context 'with permission' do before do Guardian.any_instance.expects(:can_recover_topic?).with(topic).returns(true) end it 'succeeds' do PostDestroyer.any_instance.expects(:recover) xhr :put, :recover, topic_id: topic.id expect(response).to be_success end end end end describe 'delete' do it "won't allow us to delete a topic when we're not logged in" do expect { xhr :delete, :destroy, id: 1 }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do let(:topic) { Fabricate(:topic, user: log_in) } describe 'without access' do it "raises an exception when the user doesn't have permission to delete the topic" do Guardian.any_instance.expects(:can_delete?).with(topic).returns(false) xhr :delete, :destroy, id: topic.id expect(response).to be_forbidden end end describe 'with permission' do before do Guardian.any_instance.expects(:can_delete?).with(topic).returns(true) end it 'succeeds' do PostDestroyer.any_instance.expects(:destroy) xhr :delete, :destroy, id: topic.id expect(response).to be_success end end end end describe 'id_for_slug' do let(:topic) { Fabricate(:post).topic } it "returns JSON for the slug" do xhr :get, :id_for_slug, slug: topic.slug expect(response).to be_success json = ::JSON.parse(response.body) expect(json).to be_present expect(json['topic_id']).to eq(topic.id) expect(json['url']).to eq(topic.url) expect(json['slug']).to eq(topic.slug) end it "returns invalid access if the user can't see the topic" do Guardian.any_instance.expects(:can_see?).with(topic).returns(false) xhr :get, :id_for_slug, slug: topic.slug expect(response).not_to be_success end end describe 'show full render' do render_views it 'correctly renders canoicals' do topic = Fabricate(:post).topic get :show, topic_id: topic.id, slug: topic.slug expect(response).to be_success expect(css_select("link[rel=canonical]").length).to eq(1) end end describe 'show' do let(:topic) { Fabricate(:post).topic } let!(:p1) { Fabricate(:post, user: topic.user) } let!(:p2) { Fabricate(:post, user: topic.user) } it 'shows a topic correctly' do xhr :get, :show, topic_id: topic.id, slug: topic.slug expect(response).to be_success end it 'return 404 for an invalid page' do xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 2 expect(response.code).to eq("404") end it 'can find a topic given a slug in the id param' do xhr :get, :show, id: topic.slug expect(response).to redirect_to(topic.relative_url) end it 'keeps the post_number parameter around when redirecting' do xhr :get, :show, id: topic.slug, post_number: 42 expect(response).to redirect_to(topic.relative_url + "/42") end it 'keeps the page around when redirecting' do xhr :get, :show, id: topic.slug, post_number: 42, page: 123 expect(response).to redirect_to(topic.relative_url + "/42?page=123") end it 'does not accept page params as an array' do xhr :get, :show, id: topic.slug, post_number: 42, page: [2] expect(response).to redirect_to("#{topic.relative_url}/42?page=1") end it 'returns 404 when an invalid slug is given and no id' do xhr :get, :show, id: 'nope-nope' expect(response.status).to eq(404) end it 'returns a 404 when slug and topic id do not match a topic' do xhr :get, :show, topic_id: 123123, slug: 'topic-that-is-made-up' expect(response.status).to eq(404) end context 'a topic with nil slug exists' do before do @nil_slug_topic = Fabricate(:topic) Topic.connection.execute("update topics set slug=null where id = #{@nil_slug_topic.id}") # can't find a way to set slug column to null using the model end it 'returns a 404 when slug and topic id do not match a topic' do xhr :get, :show, topic_id: 123123, slug: 'topic-that-is-made-up' expect(response.status).to eq(404) end end context 'permission errors' do let(:allowed_user) { Fabricate(:user) } let(:allowed_group) { Fabricate(:group) } let(:secure_category) { c = Fabricate(:category) c.permissions = [[allowed_group, :full]] c.save allowed_user.groups = [allowed_group] allowed_user.save c } let(:normal_topic) { Fabricate(:topic) } let(:secure_topic) { Fabricate(:topic, category: secure_category) } let(:private_topic) { Fabricate(:private_message_topic, user: allowed_user) } let(:deleted_topic) { Fabricate(:deleted_topic) } let(:deleted_secure_topic) { Fabricate(:topic, category: secure_category, deleted_at: 1.day.ago) } let(:deleted_private_topic) { Fabricate(:private_message_topic, user: allowed_user, deleted_at: 1.day.ago) } let(:nonexist_topic_id) { Topic.last.id + 10000 } context 'anonymous' do expected = { :normal_topic => 200, :secure_topic => 403, :private_topic => 302, :deleted_topic => 410, :deleted_secure_topic => 403, :deleted_private_topic => 302, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end context 'anonymous with login required' do before do SiteSetting.login_required = true end expected = { :normal_topic => 302, :secure_topic => 302, :private_topic => 302, :deleted_topic => 302, :deleted_secure_topic => 302, :deleted_private_topic => 302, :nonexist => 302 } topics_controller_show_gen_perm_tests(expected, self) end context 'normal user' do before do log_in(:user) end expected = { :normal_topic => 200, :secure_topic => 403, :private_topic => 403, :deleted_topic => 410, :deleted_secure_topic => 403, :deleted_private_topic => 403, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end context 'allowed user' do before do log_in_user(allowed_user) end expected = { :normal_topic => 200, :secure_topic => 200, :private_topic => 200, :deleted_topic => 410, :deleted_secure_topic => 410, :deleted_private_topic => 410, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end context 'moderator' do before do log_in(:moderator) end expected = { :normal_topic => 200, :secure_topic => 403, :private_topic => 403, :deleted_topic => 200, :deleted_secure_topic => 403, :deleted_private_topic => 403, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end context 'admin' do before do log_in(:admin) end expected = { :normal_topic => 200, :secure_topic => 200, :private_topic => 200, :deleted_topic => 200, :deleted_secure_topic => 200, :deleted_private_topic => 200, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end end it 'records a view' do expect { xhr :get, :show, topic_id: topic.id, slug: topic.slug }.to change(TopicViewItem, :count).by(1) end it 'records incoming links' do user = Fabricate(:user) get :show, topic_id: topic.id, slug: topic.slug, u: user.username expect(IncomingLink.count).to eq(1) end it 'records redirects' do @request.env['HTTP_REFERER'] = 'http://twitter.com' get :show, { id: topic.id } @request.env['HTTP_REFERER'] = nil get :show, topic_id: topic.id, slug: topic.slug link = IncomingLink.first expect(link.referer).to eq('http://twitter.com') end it 'tracks a visit for all html requests' do current_user = log_in(:coding_horror) TopicUser.expects(:track_visit!).with(topic.id, current_user.id) get :show, topic_id: topic.id, slug: topic.slug end context 'consider for a promotion' do let!(:user) { log_in(:coding_horror) } let(:promotion) do result = double Promotion.stubs(:new).with(user).returns(result) result end it "reviews the user for a promotion if they're new" do user.update_column(:trust_level, TrustLevel[0]) Promotion.any_instance.expects(:review) get :show, topic_id: topic.id, slug: topic.slug end end context 'filters' do it 'grabs first page when no filter is provided' do TopicView.any_instance.expects(:filter_posts_in_range).with(0, 19) xhr :get, :show, topic_id: topic.id, slug: topic.slug end it 'grabs first page when first page is provided' do TopicView.any_instance.expects(:filter_posts_in_range).with(0, 19) xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 1 end it 'grabs correct range when a page number is provided' do TopicView.any_instance.expects(:filter_posts_in_range).with(20, 39) xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 2 end it 'delegates a post_number param to TopicView#filter_posts_near' do TopicView.any_instance.expects(:filter_posts_near).with(p2.post_number) xhr :get, :show, topic_id: topic.id, slug: topic.slug, post_number: p2.post_number end end context "when 'login required' site setting has been enabled" do before { SiteSetting.login_required = true } context 'and the user is logged in' do before { log_in(:coding_horror) } it 'shows the topic' do get :show, topic_id: topic.id, slug: topic.slug expect(response).to be_successful end end context 'and the user is not logged in' do let(:api_key) { topic.user.generate_api_key(topic.user) } it 'redirects to the login page' do get :show, topic_id: topic.id, slug: topic.slug expect(response).to redirect_to login_path end it 'shows the topic if valid api key is provided' do get :show, topic_id: topic.id, slug: topic.slug, api_key: api_key.key expect(response).to be_successful topic.reload # free test, only costs a reload expect(topic.views).to eq(1) end it 'returns 403 for an invalid key' do get :show, topic_id: topic.id, slug: topic.slug, api_key: "bad" expect(response.code.to_i).to be(403) end end end end describe '#feed' do let(:topic) { Fabricate(:post).topic } it 'renders rss of the topic' do get :feed, topic_id: topic.id, slug: 'foo', format: :rss expect(response).to be_success expect(response.content_type).to eq('application/rss+xml') end end describe 'update' do it "won't allow us to update a topic when we're not logged in" do expect { xhr :put, :update, topic_id: 1, slug: 'xyz' }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do before do @topic = Fabricate(:topic, user: log_in) Fabricate(:post, topic: @topic) end describe 'without permission' do it "raises an exception when the user doesn't have permission to update the topic" do Guardian.any_instance.expects(:can_edit?).with(@topic).returns(false) xhr :put, :update, topic_id: @topic.id, slug: @topic.title expect(response).to be_forbidden end end describe 'with permission' do before do Guardian.any_instance.expects(:can_edit?).with(@topic).returns(true) end it 'succeeds' do xhr :put, :update, topic_id: @topic.id, slug: @topic.title expect(response).to be_success expect(::JSON.parse(response.body)['basic_topic']).to be_present end it 'allows a change of title' do xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'This is a new title for the topic' @topic.reload expect(@topic.title).to eq('This is a new title for the topic') end it 'triggers a change of category' do Topic.any_instance.expects(:change_category_to_id).with(123).returns(true) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: 123 end it 'allows to change category to "uncategorized"' do Topic.any_instance.expects(:change_category_to_id).with(0).returns(true) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: "" end it "returns errors with invalid titles" do xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'asdf' expect(response).not_to be_success end it "returns errors when the rate limit is exceeded" do EditRateLimiter.any_instance.expects(:performed!).raises(RateLimiter::LimitExceeded.new(60)) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'This is a new title for the topic' expect(response).not_to be_success end it "returns errors with invalid categories" do Topic.any_instance.expects(:change_category_to_id).returns(false) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: -1 expect(response).not_to be_success end it "doesn't call the PostRevisor when there is no changes" do PostRevisor.any_instance.expects(:revise!).never xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: @topic.title, category_id: @topic.category_id expect(response).to be_success end context 'when topic is private' do before do @topic.archetype = Archetype.private_message @topic.category = nil @topic.save! end context 'when there are no changes' do it 'does not call the PostRevisor' do PostRevisor.any_instance.expects(:revise!).never xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: @topic.title, category_id: nil expect(response).to be_success end end end context "allow_uncategorized_topics is false" do before do SiteSetting.stubs(:allow_uncategorized_topics).returns(false) end it "can add a category to an uncategorized topic" do Topic.any_instance.expects(:change_category_to_id).with(456).returns(true) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: 456 expect(response).to be_success end end end end end describe 'invite' do describe "group invites" do it "works correctly" do group = Fabricate(:group) topic = Fabricate(:topic) _admin = log_in(:admin) xhr :post, :invite, topic_id: topic.id, email: 'hiro@from.heros', group_ids: "#{group.id}" expect(response).to be_success invite = Invite.find_by(email: 'hiro@from.heros') groups = invite.groups.to_a expect(groups.count).to eq(1) expect(groups[0].id).to eq(group.id) end end it "won't allow us to invite toa topic when we're not logged in" do expect { xhr :post, :invite, topic_id: 1, email: 'jake@adventuretime.ooo' }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in as group manager' do let(:group_manager) { log_in } let(:group) { Fabricate(:group).tap { |g| g.add_owner(group_manager) } } let(:private_category) { Fabricate(:private_category, group: group) } let(:group_private_topic) { Fabricate(:topic, category: private_category, user: group_manager) } let(:recipient) { 'jake@adventuretime.ooo' } it "should attach group to the invite" do xhr :post, :invite, topic_id: group_private_topic.id, user: recipient expect(response).to be_success expect(Invite.find_by(email: recipient).groups).to eq([group]) end end describe 'when logged in' do before do @topic = Fabricate(:topic, user: log_in) end it 'requires an email parameter' do expect { xhr :post, :invite, topic_id: @topic.id }.to raise_error(ActionController::ParameterMissing) end describe 'without permission' do it "raises an exception when the user doesn't have permission to invite to the topic" do xhr :post, :invite, topic_id: @topic.id, user: 'jake@adventuretime.ooo' expect(response).to be_forbidden end end describe 'with admin permission' do let!(:admin) do log_in :admin end it 'should work as expected' do xhr :post, :invite, topic_id: @topic.id, user: 'jake@adventuretime.ooo' expect(response).to be_success expect(::JSON.parse(response.body)).to eq({'success' => 'OK'}) expect(Invite.where(invited_by_id: admin.id).count).to eq(1) end it 'should fail on shoddy email' do xhr :post, :invite, topic_id: @topic.id, user: 'i_am_not_an_email' expect(response).not_to be_success expect(::JSON.parse(response.body)).to eq({'failed' => 'FAILED'}) end end end end describe 'autoclose' do it 'needs you to be logged in' do expect { xhr :put, :autoclose, topic_id: 99, auto_close_time: '24', auto_close_based_on_last_post: false }.to raise_error(Discourse::NotLoggedIn) end it 'needs you to be an admin or mod' do log_in xhr :put, :autoclose, topic_id: 99, auto_close_time: '24', auto_close_based_on_last_post: false expect(response).to be_forbidden end describe 'when logged in' do before do @admin = log_in(:admin) @topic = Fabricate(:topic, user: @admin) end it "can set a topic's auto close time and 'based on last post' property" do Topic.any_instance.expects(:set_auto_close).with("24", {by_user: @admin, timezone_offset: -240}) xhr :put, :autoclose, topic_id: @topic.id, auto_close_time: '24', auto_close_based_on_last_post: true, timezone_offset: -240 json = ::JSON.parse(response.body) expect(json).to have_key('auto_close_at') expect(json).to have_key('auto_close_hours') end it "can remove a topic's auto close time" do Topic.any_instance.expects(:set_auto_close).with(nil, anything) xhr :put, :autoclose, topic_id: @topic.id, auto_close_time: nil, auto_close_based_on_last_post: false, timezone_offset: -240 end it "will close a topic when the time expires" do topic = Fabricate(:topic) Timecop.freeze(20.hours.ago) do create_post(topic: topic, raw: "This is the body of my cool post in the topic, but it's a bit old now") end topic.save Jobs.expects(:enqueue_at).at_least_once xhr :put, :autoclose, topic_id: topic.id, auto_close_time: 24, auto_close_based_on_last_post: true topic.reload expect(topic.closed).to eq(false) expect(topic.posts.last.raw).to match(/cool post/) Timecop.freeze(5.hours.from_now) do Jobs::CloseTopic.new.execute({topic_id: topic.id, user_id: @admin.id}) end topic.reload expect(topic.closed).to eq(true) expect(topic.posts.last.raw).to match(/automatically closed/) end it "will immediately close if the last post is old enough" do topic = Fabricate(:topic) Timecop.freeze(20.hours.ago) do create_post(topic: topic) end topic.save Topic.reset_highest(topic.id) topic.reload xhr :put, :autoclose, topic_id: topic.id, auto_close_time: 10, auto_close_based_on_last_post: true topic.reload expect(topic.closed).to eq(true) expect(topic.posts.last.raw).to match(/after the last reply/) expect(topic.posts.last.raw).to match(/10 hours/) end end end describe 'make_banner' do it 'needs you to be a staff member' do log_in xhr :put, :make_banner, topic_id: 99 expect(response).to be_forbidden end describe 'when logged in' do it "changes the topic archetype to 'banner'" do topic = Fabricate(:topic, user: log_in(:admin)) Topic.any_instance.expects(:make_banner!) xhr :put, :make_banner, topic_id: topic.id expect(response).to be_success end end end describe 'remove_banner' do it 'needs you to be a staff member' do log_in xhr :put, :remove_banner, topic_id: 99 expect(response).to be_forbidden end describe 'when logged in' do it "resets the topic archetype" do topic = Fabricate(:topic, user: log_in(:admin)) Topic.any_instance.expects(:remove_banner!) xhr :put, :remove_banner, topic_id: topic.id expect(response).to be_success end end end describe "bulk" do it 'needs you to be logged in' do expect { xhr :put, :bulk }.to raise_error(Discourse::NotLoggedIn) end describe "when logged in" do let!(:user) { log_in } let(:operation) { {type: 'change_category', category_id: '1'} } let(:topic_ids) { [1,2,3] } it "requires a list of topic_ids or filter" do expect { xhr :put, :bulk, operation: operation }.to raise_error(ActionController::ParameterMissing) end it "requires an operation param" do expect { xhr :put, :bulk, topic_ids: topic_ids}.to raise_error(ActionController::ParameterMissing) end it "requires a type field for the operation param" do expect { xhr :put, :bulk, topic_ids: topic_ids, operation: {}}.to raise_error(ActionController::ParameterMissing) end it "delegates work to `TopicsBulkAction`" do topics_bulk_action = mock TopicsBulkAction.expects(:new).with(user, topic_ids, operation, group: nil).returns(topics_bulk_action) topics_bulk_action.expects(:perform!) xhr :put, :bulk, topic_ids: topic_ids, operation: operation end end end describe 'remove_bookmarks' do it "should remove bookmarks properly from non first post" do bookmark = PostActionType.types[:bookmark] user = log_in post = create_post post2 = create_post(topic_id: post.topic_id) PostAction.act(user, post2, bookmark) xhr :put, :bookmark, topic_id: post.topic_id expect(PostAction.where(user_id: user.id, post_action_type: bookmark).count).to eq(2) xhr :put, :remove_bookmarks, topic_id: post.topic_id expect(PostAction.where(user_id: user.id, post_action_type: bookmark).count).to eq(0) end end describe 'reset_new' do it 'needs you to be logged in' do expect { xhr :put, :reset_new }.to raise_error(Discourse::NotLoggedIn) end let(:user) { log_in(:user) } it "updates the `new_since` date" do old_date = 2.years.ago user.user_stat.update_column(:new_since, old_date) xhr :put, :reset_new user.reload expect(user.user_stat.new_since.to_date).not_to eq(old_date.to_date) end end describe "feature_stats" do it "works" do xhr :get, :feature_stats, category_id: 1 expect(response).to be_success json = JSON.parse(response.body) expect(json["pinned_in_category_count"]).to eq(0) expect(json["pinned_globally_count"]).to eq(0) expect(json["banner_count"]).to eq(0) end it "allows unlisted banner topic" do Fabricate(:topic, category_id: 1, archetype: Archetype.banner, visible: false) xhr :get, :feature_stats, category_id: 1 json = JSON.parse(response.body) expect(json["banner_count"]).to eq(1) end end describe "x-robots-tag" do it "is included for unlisted topics" do topic = Fabricate(:topic, visible: false) get :show, topic_id: topic.id, slug: topic.slug expect(response.headers['X-Robots-Tag']).to eq('noindex') end it "is not included for normal topics" do topic = Fabricate(:topic, visible: true) get :show, topic_id: topic.id, slug: topic.slug expect(response.headers['X-Robots-Tag']).to eq(nil) end end end
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from subscriber.models import Consumer, ConsumerType, Recharge, TotalRecharge, ACL from product.models import Product from voice_records.models import VoiceRecord, VoiceReg from sms.models import SMSPayment # from local_lib.v3 import is_number, is_float from local_lib.v3 import is_number, is_float, is_bangladeshi_number, is_japanese_number, send_sms from transaction.models import Transaction, ProductsInTransaction, BuyerSellerAccount, dueTransaction from shop_inventory.models import Inventory, BuySellProfitInventoryIndividual, BuySellProfitInventory from transcriber_management.models import Transcriber, TranscriberInTranscription, FailedTranscription import datetime from django.db.models import Q from django.contrib.auth.models import User from django.contrib.sessions.backends.db import SessionStore from django.db.models import Count @csrf_exempt def login_page(request): return render(request, 'pages/login.html') @csrf_exempt def login_auth(request): postdata = request.POST print(postdata) if 'username' and 'password' in postdata: print(postdata['username']) login_username = postdata['username'] print(postdata['password']) if ACL.objects.filter(loginID=postdata['username'][-9:]).exists(): login_username = login_username[-9:] else: login_username = login_username user = authenticate(username=login_username, password=postdata['password']) if user is not None: if user.is_active: login(request, user) request.session['user'] = login_username if user.is_superuser: res = redirect('/admin') else: res = redirect('/') else: res = render(request, 'pages/login.html', {'wrong': True, 'text': 'The password is valid, but the account has been disabled!'}) else: res = render(request, 'pages/login.html', {'wrong': True, 'text': 'The username and password you have entered is not correct. Please retry'}) else: res = render(request, 'pages/login.html', {'wrong': False}) res['Access-Control-Allow-Origin'] = "*" res['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept" res['Access-Control-Allow-Methods'] = "PUT, GET, POST, DELETE, OPTIONS" return res def logout_now(request): logout(request) return render(request, 'pages/login.html') @login_required(login_url='/login/') def home(request): transcriber_name = request.session['user'] print request.session['user'] if ACL.objects.filter(loginID=transcriber_name).exists(): login_user = ACL.objects.get(loginID=transcriber_name) print(login_user.loginUser.name) transcriber_name = login_user.loginUser.name if login_user.loginUser.type.type_name == 'Distributor': if login_user.loginUser.number_of_child == 'CHANGED !!!': return render(request, 'pages/Distributor/index.html', {'transcriber_name': transcriber_name}) else: return redirect('/change_password/') elif login_user.loginUser.type.type_name == 'SR': if login_user.loginUser.number_of_child == 'CHANGED !!!': return render(request, 'pages/SR/index.html', {'transcriber_name': transcriber_name}) else: return redirect('/change_password/') elif login_user.loginUser.type.type_name == 'Seller': if login_user.loginUser.number_of_child == 'CHANGED !!!': return render(request, 'pages/Shop/index.html', {'transcriber_name': transcriber_name}) else: return redirect('/change_password/') elif login_user.loginUser.type.type_name == 'Buyer': if login_user.loginUser.number_of_child == 'CHANGED !!!': return render(request, 'pages/Consumer/index.html', {'transcriber_name': transcriber_name}) else: return redirect('/change_password/') else: number_of_reg_calls = VoiceReg.objects.filter().count() number_of_transaction_calls = VoiceRecord.objects.filter().count() total = number_of_reg_calls + number_of_transaction_calls if total > 0: reg_call_percentage = (number_of_reg_calls / float(total)) * 100 transaction_call_percentage = (number_of_transaction_calls / float(total)) * 100 else: transaction_call_percentage = 0 reg_call_percentage = 0 today_month = datetime.date.today().month today_year = datetime.date.today().year count = 1 data_2 = '' data_3 = '' data_4 = '' data_5 = '' data_6 = '' max = 0 max_table_2 = 0 total_sell = VoiceRecord.objects.filter(purpose='sell').count() total_buy = VoiceRecord.objects.filter(purpose='buy').count() total_money_transaction = SMSPayment.objects.filter().count() total_for_chart2 = number_of_reg_calls + number_of_transaction_calls if total_for_chart2 > 0: sell_percentage = (total_sell / float(total_for_chart2)) * 100 buy_percentage = (total_buy / float(total_for_chart2)) * 100 money_transaction_percentage = (total_money_transaction / float(total_for_chart2)) * 100 else: sell_percentage = 0 buy_percentage = 0 money_transaction_percentage = 0 while count < 32: total_call_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count).count() total_reg_that_day = VoiceReg.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count).count() if max < total_call_that_day: max = total_call_that_day + 2 if max < total_reg_that_day: max = total_reg_that_day + 2 data_2 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_call_that_day) data_3 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_reg_that_day) total_buy_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count, purpose='buy').count() total_sell_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count, purpose='sell').count() total_payment_that_day = SMSPayment.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count).count() if max_table_2 < total_buy_that_day: max_table_2 = total_buy_that_day + 2 if max_table_2 < total_sell_that_day: max_table_2 = total_sell_that_day + 2 if max_table_2 < total_payment_that_day: max_table_2 = total_payment_that_day + 2 data_4 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_buy_that_day) data_5 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_sell_that_day) data_6 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_payment_that_day) count += 1 data_2 = data_2[:-1] data_3 = data_3[:-1] data_4 = data_4[:-1] data_5 = data_5[:-1] data_6 = data_6[:-1] number_of_transactions = Transaction.objects.filter().count() number_of_transactions_with_due = Transaction.objects.filter(total_due__gt=0).count() number_of_transactions_without_due = Transaction.objects.filter(total_due__lte=0).count() shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) print(all_consumer_for_base.count) return render(request, 'pages/index.html', {'shop_list_base': all_shop_for_base, 'number_of_reg_calls': number_of_reg_calls, 'transcriber_name': transcriber_name, 'number_of_transaction_calls': number_of_transaction_calls, 'all_consumer_for_base' :all_consumer_for_base, 'reg_call_percentage': reg_call_percentage, 'transaction_call_percentage': transaction_call_percentage, 'data_2': data_2, 'data_3': data_3, 'data_4': data_4, 'data_5': data_5, 'data_6': data_6, 'max': max, 'number_of_transactions': number_of_transactions, 'number_of_transactions_with_due': number_of_transactions_with_due, 'number_of_transactions_without_due': number_of_transactions_without_due, 'max_table_2': max_table_2, 'total_sell': total_sell, 'total_buy': total_buy, 'total_money_transaction': total_money_transaction, 'sell_percentage': sell_percentage, 'buy_percentage': buy_percentage, 'money_transaction_percentage': money_transaction_percentage, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def translator_page(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/translator.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) # all report views are here @login_required(login_url='/login/') def report_monthly_shop(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id total_sell = 0 total_sell_due = 0 total_sell_paid = 0 total_purchase = 0 total_purchase_due = 0 total_purchase_paid = 0 for month_sell in BuyerSellerAccount.objects.filter(seller=shop_object): total_sell += month_sell.total_amount_of_transaction total_sell_due += month_sell.total_due total_sell_paid += month_sell.total_paid for month_purchase in BuyerSellerAccount.objects.filter(buyer=shop_object): total_purchase += month_purchase.total_amount_of_transaction total_purchase_due += month_purchase.total_due total_purchase_paid += month_purchase.total_paid shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_monthly_shop.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'shop_id': shop_id, 'all_consumer_for_base' :all_consumer_for_base, 'total_sell': total_sell, 'transcriber_name': transcriber_name, 'total_sell_due': total_sell_due, 'total_sell_paid': total_sell_paid, 'bangla': bangla, 'total_purchase': total_purchase, 'total_purchase_due': total_purchase_due, 'total_purchase_paid': total_purchase_paid, 'all_user_for_base': all_user_for_base}) # report_monthly_shop_json @login_required(login_url='/login/') def report_monthly_shop_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') output = '{"data": [ ' if get_data['t'] == '1': rank = 1 this_year = datetime.date.today().year # this_month = 1 this_day = 1 for this_month in range(1, 13, 1): count = 0 for this_day in range(1, 32, 1): for a_product in Product.objects.all(): product_price = 0 product_name = a_product.name total_sell = 0 total_due = 0 total_paid = 0 for this_day_sell_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=this_day): total_sell += this_day_sell_transaction.total_amount total_due += this_day_sell_transaction.total_due total_paid += this_day_sell_transaction.total_paid count += 1 total_purchase = 0 total_purchase_due = 0 total_purchase_paid = 0 for this_day_purchase_transaction in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=this_day): total_purchase += this_day_purchase_transaction.total_amount total_purchase_due += this_day_purchase_transaction.total_due total_purchase_paid += this_day_purchase_transaction.total_paid count += 1 if count > 0: output += '["%s/%s/%s","%s","%s","%s","%s","%s","%s"] ,' % (this_day, this_month, this_year, total_sell, total_paid, total_due, total_purchase, total_purchase_paid, total_purchase_due) count = 0 # this_day += 1 # this_month = this_month + 1 if get_data['t'] == '2': for this_day_transaction in Transaction.objects.filter(Q(seller=shop_object) | Q(buyer=shop_object)): # start counting for this product id = this_day_transaction.pk date = this_day_transaction.DateAdded if this_day_transaction.seller == shop_object: with_trade = this_day_transaction.buyer trade_type = 'Sell' elif this_day_transaction.buyer == shop_object: with_trade = this_day_transaction.seller trade_type = 'Buy' number_of_items = ProductsInTransaction.objects.filter(TID=this_day_transaction).count() total_amount = this_day_transaction.total_amount total_paid = this_day_transaction.total_paid total_due = this_day_transaction.total_due output += '["%s","%s","%s","%s","%s","%s","%s","%s"] ,' % (id, date, with_trade, trade_type, number_of_items, total_amount, total_paid, total_due) output = output[:-1] output += ']}' return HttpResponse(output, content_type="text/plain") @login_required(login_url='/login/') def report_sales_analysis(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() if 'ban' in get_data: bangla = True else: bangla = False transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_sales_analysis.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'all_consumer_for_base' :all_consumer_for_base, 'shop_id': shop_id, 'bangla': bangla, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_sales_analysis_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') output = '{"data": [ ' if get_data['t'] == '1': rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: output += '["%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit) rank += 1 if get_data['t'] == '2': rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 previous_product_price = 0 change = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if count == 0: previous_product_price = product_in_this_transaction.price_per_unit product_price = product_in_this_transaction.price_per_unit change += abs(previous_product_price - product_price) count += 1 if count > 0: output += '["%s","%s","%s","%s"] ,' % (rank, product_name, count, change/count) rank += 1 if get_data['t'] == '3': this_year = datetime.date.today().year this_month = datetime.date.today().month day = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 32: day_string = True rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit, float(product_price / count)) rank += 1 day += 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) if get_data['t'] == '4': day = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 8: day_string = True rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__week_day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: if day == 1: output += '["%s","","","",""] ,' % 'Sunday' elif day == 2: output += '["%s","","","",""] ,' % 'Monday' elif day == 3: output += '["%s","","","",""] ,' % 'Tuesday' elif day == 4: output += '["%s","","","",""] ,' % 'Wednesday' elif day == 5: output += '["%s","","","",""] ,' % 'Thursday' elif day == 6: output += '["%s","","","",""] ,' % 'Friday' elif day == 7: output += '["%s","","","",""] ,' % 'Saturday' day_string = False output += '["","%s","%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit, float(product_price / count)) rank += 1 day += 1 if get_data['t'] == '5': this_year = datetime.date.today().year day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) output = output[:-1] output += ']}' return HttpResponse(output, content_type="text/plain") @login_required(login_url='/login/') def report_payment(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__lte=0) buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__lte=0) shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__lte=0) seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__lte=0) all_user_for_base = Consumer.objects.all() shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) transcriber_name = request.session['user'] return render(request, 'pages/report_payment.html', {'shop_list_base': all_shop_for_base, 'sell_transaction_with_due': sell_transaction_with_due, 'buy_transaction_with_due': buy_transaction_with_due, 'all_consumer_for_base' :all_consumer_for_base, 'buyer_account': buyer_account, 'transcriber_name': transcriber_name, 'seller_account': seller_account, 'shop_name': shop_name, 'bangla': bangla, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_due(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__gt=0) buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__gt=0) shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) buyer_account = SMSPayment.objects.filter(seller=shop_object) seller_account = SMSPayment.objects.filter(buyer=shop_object) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_due.html', {'shop_list_base': all_shop_for_base, 'sell_transaction_with_due': sell_transaction_with_due, 'buy_transaction_with_due': buy_transaction_with_due, 'buyer_account': buyer_account, 'all_consumer_for_base' :all_consumer_for_base, 'bangla': bangla, 'seller_account': seller_account, 'transcriber_name': transcriber_name, 'shop_name': shop_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_profit(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id if 'ban' in get_data: bangla = True else: bangla = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_profit.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'shop_id': shop_id, 'all_consumer_for_base' :all_consumer_for_base, 'bangla': bangla, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_profit_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') output = '{"data": [ ' if get_data['t'] == '1': this_year = datetime.date.today().year this_month = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while this_month < 13: day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 if count > 0: if day_string: if this_month == 1: output += '["January","",""], ' elif this_month == 2: output += '["February","",""], ' elif this_month == 3: output += '["March","",""], ' elif this_month == 4: output += '["April","",""], ' elif this_month == 5: output += '["May","",""], ' elif this_month == 6: output += '["June","",""], ' elif this_month == 7: output += '["July","",""], ' elif this_month == 8: output += '["August","",""], ' elif this_month == 9: output += '["September","",""], ' elif this_month == 10: output += '["October","",""], ' elif this_month == 11: output += '["November","",""], ' elif this_month == 12: output += '["December","",""], ' day_string = False output += '["","%s","%s"] ,' % (product_name, product_profit) # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) this_month += 1 if get_data['t'] == '2': this_year = datetime.date.today().year this_month = 1 while this_month < 13: day = 1 while day < 32: day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 if count > 0: if day_string: output += '["%s/%s/%s","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s"] ,' % (product_name, product_profit) day += 1 this_month += 1 if get_data['t'] == '3': this_year = datetime.date.today().year this_month = datetime.date.today().month # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) if get_data['t'] == '4': this_year = datetime.date.today().year day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object, DateAdded__year=this_year): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) if get_data['t'] == '5': this_year = datetime.date.today().year day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) output = output[:-1] output += ']}' return HttpResponse(output, content_type="text/plain") @login_required(login_url='/login/') def report_product(request): get_data = request.GET shop_name = get_data['shop'] if 'ban' in get_data: bangla = True else: bangla = False shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id shop_inventory = Inventory.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') selected_products = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(seller=shop_object)) selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object)) all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_product.html', {'shop_list_base': all_shop_for_base, 'shop_inventory': shop_inventory, 'shop_name': shop_name, 'shop_id': shop_id, 'bangla': bangla, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'selected_products_buy': selected_products_buy, 'selected_products': selected_products, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_product_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = Inventory.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') output = '{"data": [ ' if get_data['t'] == '1': this_year = datetime.date.today().year this_month = datetime.date.today().month day = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 32: day_string = True for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: # if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: # if a_product.bulk_to_retail_unit == 0: # count = count + product_in_this_transaction.quantity # product_price = product_price + product_in_this_transaction.price_per_unit # else: # count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit # product_price = product_price + product_in_this_transaction.price_per_unit # else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit * product_in_this_transaction.quantity if count > 0: if day_string: output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s","%s","%s"] ,' % (product_name, count, a_product.retail_unit, float(product_price / count)) day += 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) if get_data['t'] == '2': this_year = datetime.date.today().year this_month = datetime.date.today().month day = 1 while day < 32: day_string = True for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s","%s","%s"] ,' % (product_name, count, a_product.bulk_wholesale_unit, float(product_price / count)) day += 1 if get_data['t'] == '3': this_year = datetime.date.today().year this_month = datetime.date.today().month for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: output += '["%s","%s","%s","%s"] ,' % (product_name, count, a_product.retail_unit, float(product_price / count)) if get_data['t'] == '4': this_year = datetime.date.today().year this_month = datetime.date.today().month for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: output += '["%s","%s","%s","%s"] ,' % (product_name, count, a_product.retail_unit, float(product_price / count)) output = output[:-1] output += ']}' selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object)) all_shop_for_base = Consumer.objects.filter(type=shop_consumer) return HttpResponse(output, content_type="text/plain") # paste the template name of the report_analytical instead of report_product here @login_required(login_url='/login/') def report_analytical(request): all_product = Product.objects.all() final_output = '' get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id for product in all_product: print(product.name) if ProductsInTransaction.objects.filter(product=product).exists(): product_output = "[%s, " % product.name sold_amount = 0 for product_details in ProductsInTransaction.objects.filter(product=product): sold_amount = sold_amount + product_details.quantity product_output += str(sold_amount) final_output += product_output final_output += "] ," print(final_output) final_output = final_output[:-1] print(final_output) add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/reports_analytical.html', {'all_product': all_product, 'add_notification': add_notification, 'shop_list_base': all_shop_for_base, 'product_sell': final_output, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'shop_name': shop_name, 'shop_id': shop_id, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_analytical_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) if get_data['t'] == '1': all_product = Product.objects.all() final_output = '{"cols": [ { "id": "", "label": "Topping", "pattern": "", "type": "string" }, ' \ '{ "id": "", "label": "Units", "pattern": "", "type": "number" } ], "rows": [ ' for product in all_product: print(product.name) if ProductsInTransaction.objects.filter(product=product).exists(): product_name = product.name sold_amount = 0 for transaction_id in Transaction.objects.filter(seller=shop_object): for product_details in ProductsInTransaction.objects.filter(product=product, TID=transaction_id): sold_amount = sold_amount + product_details.quantity final_output += '{"c": [{"v": "%s","f": null},{"v": %s,"f": null}]},' % (product_name, sold_amount) final_output = final_output[:-1] print(final_output) if get_data['t'] == '2': all_product = BuySellProfitInventory.objects.filter(shop=shop_object) final_output = '{"cols": [ { "id": "", "label": "Topping", "pattern": "", "type": "string" }, ' \ '{ "id": "", "label": "Profit", "pattern": "", "type": "number" } ], "rows": [ ' for product in all_product: final_output += '{"c": [{"v": "%s","f": null},{"v": %s,"f": null}]},' % (product.product, product.profit) final_output = final_output[:-1] print(final_output) final_output += ']}' print(final_output) return HttpResponse(final_output, content_type="text/plain") # till this views created based on the list from mail @login_required(login_url='/login/') def report_recharge(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_recharge.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_callduration(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_callduration_graph.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) # not necessary @login_required(login_url='/login/') def report_transaction(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_transaction.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_calltranscription(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_transcription.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_usercall(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_user_call_recharge.html', {'shop_list_base': all_shop_for_base, 'transcriber_name': transcriber_name, 'all_consumer_for_base' :all_consumer_for_base, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def transcription_page(request): print(request.POST) number_of_pending_calls = VoiceRecord.objects.filter(transcribed=False).count() number_of_pending_reg_calls = VoiceReg.objects.filter(completed=False).count() type_of_subscriber = ConsumerType.objects.all() number_of_fail_calls = VoiceRecord.objects.filter(with_error=True).count() number_of_completed_calls = VoiceRecord.objects.filter(with_error=False, transcribed=True).count() shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] return render(request, 'pages/transcription.html', dict(pending_calls=number_of_pending_calls, types=type_of_subscriber, pending_calls_reg=number_of_pending_reg_calls, number_of_fail_calls=str(number_of_fail_calls), number_of_completed_calls=number_of_completed_calls, transcriber_name=transcriber_name, shop_list_base=all_shop_for_base,all_consumer_for_base=all_consumer_for_base, all_user_for_base=all_user_for_base)) # report views ends here @login_required(login_url='/login/') def add_subscriber_page(request): all_subscriber = Consumer.objects.all() type_of_subscriber = ConsumerType.objects.all() add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) notification = '' if 'delete' in request.GET: get_data = request.GET add_notification = True delID = get_data['delete'] if Consumer.objects.filter(id=delID).exists(): item_for_delete = Consumer.objects.get(id=delID) notification = 'Daily statement for the user : ' + item_for_delete.name + ' is sent successfully.' # item_for_delete.delete() sales_statement = '' purchase_statement = '' today_date = datetime.date.today() today_day = today_date.day today_month = today_date.month today_year = today_date.year # for selling sell_transactions = Transaction.objects.filter(seller=item_for_delete, DateAdded__day=today_day, DateAdded__month=today_month, DateAdded__year=today_year) total_sales = 0 total_due = 0 total_paid = 0 for sell_transaction in sell_transactions: total_sales += sell_transaction.total_amount total_paid += sell_transaction.total_paid total_due += sell_transaction.total_due if total_sales > 0: sales_statement = ' bikroy korechen mot: ' + str(total_sales) + ' takar. nogod peyechen : ' + \ str(total_paid) + ' taka ebong baki royeche ' + str(total_due) + ' taka.' buy_transactions = Transaction.objects.filter(buyer=item_for_delete, DateAdded__day=today_day, DateAdded__month=today_month, DateAdded__year=today_year) total_purchase = 0 total_due = 0 total_paid = 0 for buy_transaction in buy_transactions: total_purchase += buy_transaction.total_amount total_paid += buy_transaction.total_paid total_due += buy_transaction.total_due if total_purchase > 0: purchase_statement = ' kinechen mot: ' + str(total_purchase) + ' takar. Nogod diyechen : ' + \ str(total_paid) + ' taka ebong baki royeche ' + str(total_due) + ' taka.' final_text = 'Aj apni' + sales_statement + purchase_statement + ' Dhonnobad' if total_purchase > 0 or total_sales > 0: print(final_text) send_sms(final_text, item_for_delete.phone) else: notification = 'Item not found' return render(request, 'pages/add_subscriber.html', {'subscribers': all_subscriber, 'types': type_of_subscriber, 'add_notification': add_notification, 'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'notification':notification, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def add_product_page(request): all_product = Product.objects.all() add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) notification = '' if 'delete' in request.GET: get_data = request.GET add_notification = True delID = get_data['delete'] if Product.objects.filter(id=delID).exists(): item_for_delete = Product.objects.get(id=delID) notification = 'The product : ' + item_for_delete.name + ' is deleted successfully.' item_for_delete.delete() else: notification = 'Item not found' return render(request, 'pages/add_product.html', {'all_product': all_product, 'add_notification': add_notification, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name,'notification': notification, 'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_transcriber_performance(request): all_product = Product.objects.all() add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_transcriber_performance.html', {'all_product': all_product, 'add_notification': add_notification, 'transcriber_name': transcriber_name, 'all_consumer_for_base' :all_consumer_for_base, 'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_transcriber_performance_json(request): final_output = '{"data": [ ' for transcriber in Transcriber.objects.all(): number_of_transcriptions = TranscriberInTranscription.objects.filter(name=transcriber).count() total_time_taken = 0 total_product_trancribed = 0 for transcriber_in_transaction in TranscriberInTranscription.objects.filter(name=transcriber): total_time_taken += float(transcriber_in_transaction.time_taken) total_product_trancribed += transcriber_in_transaction.number_of_products if number_of_transcriptions > 0: avg_time = total_time_taken / number_of_transcriptions avg_product = total_product_trancribed / number_of_transcriptions final_output += '["%s","%s","%s","%s","%s"] ,' % (transcriber.id, transcriber.name, number_of_transcriptions, avg_time, avg_product) final_output = final_output[:-1] final_output += ']}' return HttpResponse(final_output, content_type="text/plain") @login_required(login_url='/login/') def user_balance_recharge(request): post_data = request.POST notification = '' for all_consumers in Consumer.objects.all(): if Recharge.objects.filter(user=all_consumers).exists(): print('Already_Added') else: new_added = Recharge(user=all_consumers) new_added.save() if TotalRecharge.objects.filter(user=all_consumers).exists(): print('Already_Added') else: new_added = TotalRecharge(user=all_consumers) new_added.save() add_notification = False if 'user' in post_data and 'recharge_amount' in post_data: user_name = post_data['user'] user_object = Consumer.objects.get(name=user_name) if is_number(post_data['recharge_amount']) or is_float(post_data['recharge_amount']): new_recharge_added = Recharge(user=user_object, amount=float(post_data['recharge_amount'])) new_recharge_added.save() new_recharge_update = TotalRecharge.objects.get(user=user_object) new_recharge_update.amount += float(post_data['recharge_amount']) new_recharge_update.save() add_notification = True notification = 'Amount %s has been added to the number %s' %(post_data['recharge_amount'], user_object.phone) else: notification = 'Something went wrong. Please try again.' recharge_all = TotalRecharge.objects.all() today_date = datetime.date.today() today_day = today_date.day today_month = today_date.month today_year = today_date.year recharge_today = Recharge.objects.filter(DateAdded__day=today_day, DateAdded__month=today_month, DateAdded__year=today_year, amount__gt=0) all_product = Product.objects.all() shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_user_call_recharge.html', {'all_product': all_product, 'add_notification': add_notification, 'all_consumer_for_base' :all_consumer_for_base, 'shop_list_base': all_shop_for_base, 'recharge_all': recharge_all, 'transcriber_name': transcriber_name, 'recharge_today': recharge_today, 'all_user_for_base': all_user_for_base, 'notification': notification}) # views for printing @login_required(login_url='/login/') def report_monthly_shop_print(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) total_sell = 0 total_sell_due = 0 total_sell_paid = 0 total_purchase = 0 total_purchase_due = 0 total_purchase_paid = 0 for month_sell in BuyerSellerAccount.objects.filter(seller=shop_object): total_sell += month_sell.total_amount_of_transaction total_sell_due += month_sell.total_due total_sell_paid += month_sell.total_paid for month_purchase in BuyerSellerAccount.objects.filter(buyer=shop_object): total_purchase += month_purchase.total_amount_of_transaction total_purchase_due += month_purchase.total_due total_purchase_paid += month_purchase.total_paid shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) transcriber_name = request.session['user'] return render(request, 'print/report_monthly_shop.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'all_consumer_for_base' :all_consumer_for_base, 'total_sell': total_sell, 'transcriber_name': transcriber_name, 'total_sell_due': total_sell_due, 'total_sell_paid': total_sell_paid, 'bangla': bangla, 'total_purchase': total_purchase, 'total_purchase_due': total_purchase_due, 'total_purchase_paid': total_purchase_paid, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_due_print(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__gt=0) buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__gt=0) shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__gt=0) seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__gt=0) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_due.html', {'shop_list_base': all_shop_for_base, 'sell_transaction_with_due': sell_transaction_with_due, 'buy_transaction_with_due': buy_transaction_with_due, 'buyer_account': buyer_account, 'all_consumer_for_base' :all_consumer_for_base, 'bangla': bangla, 'seller_account': seller_account, 'transcriber_name': transcriber_name, 'shop_name': shop_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_payment_print(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__lte=0) buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__lte=0) shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__lte=0) seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__lte=0) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_payment.html', {'shop_list_base': all_shop_for_base, 'sell_transaction_with_due': sell_transaction_with_due, 'buy_transaction_with_due': buy_transaction_with_due, 'all_consumer_for_base' :all_consumer_for_base, 'buyer_account': buyer_account, 'transcriber_name': transcriber_name, 'seller_account': seller_account, 'shop_name': shop_name, 'bangla': bangla, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_product_print(request): get_data = request.GET shop_name = get_data['shop'] if 'ban' in get_data: bangla = True else: bangla = False shop_object = Consumer.objects.get(name=shop_name) shop_inventory = Inventory.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') selected_products = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(seller=shop_object)) selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object)) all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_product.html', {'shop_list_base': all_shop_for_base, 'shop_inventory': shop_inventory, 'shop_name': shop_name, 'bangla': bangla, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'selected_products_buy': selected_products_buy, 'selected_products': selected_products, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_sales_analysis_print(request): get_data = request.GET shop_name = get_data['shop'] shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) transcriber_name = request.session['user'] return render(request, 'print/report_sales_analysis.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'shop_name': shop_name, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_profit_print(request): get_data = request.GET shop_name = get_data['shop'] shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_profit.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'all_consumer_for_base':all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_transcriber_performance_print(request): all_product = Product.objects.all() add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_transcriber_performance.html', {'all_product': all_product, 'add_notification': add_notification, 'all_consumer_for_base':all_consumer_for_base, 'transcriber_name': transcriber_name, 'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base}) # SR section @login_required(login_url='/login/') def sr_monthly_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/SR/report_monthly.html', {'transcriber_name': transcriber_name, 'allTransaction': allTransaction}) @login_required(login_url='/login/') def sr_due_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name allBalance = BuyerSellerAccount.objects.filter(seller=sr_object) sell_transaction = Transaction.objects.filter(seller=sr_object) dueTransactions = dueTransaction.objects.filter(seller=sr_object) return render(request, 'pages/SR/report_due.html', {'transcriber_name': transcriber_name, 'sell_transaction': sell_transaction, 'dueTransactions': dueTransactions, 'allBalance': allBalance}) @login_required(login_url='/login/') def sr_report_sales_analysis(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name post_data = request.POST print(post_data) shop_object = sr_object shop_name = shop_object.name shop_id = shop_object.id if 'month' in post_data and 'year' in post_data: month = post_data['month'] year = post_data['year'] else: month = datetime.date.today().month year = datetime.date.today().year return render(request, 'pages/SR/report_sales_analysis.html', {'shop_name': shop_name, # 'all_consumer_for_base' :all_consumer_for_base, 'shop_id': shop_id, # 'bangla': bangla, 'transcriber_name': transcriber_name, 'month': month, 'year': year}) @login_required(login_url='/login/') def sr_report_sales_analysis_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') this_year = get_data['year'] print(this_year) this_month = get_data['month'] output = '{"data": [ ' if get_data['t'] == '1': rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: output += '["%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit) rank += 1 if get_data['t'] == '2': rank = 1 for a_product in Product.objects.all(): count = 0 # product_price = 0 previous_product_price = 0 change = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if count == 0: previous_product_price = product_in_this_transaction.price_per_unit product_price = product_in_this_transaction.price_per_unit change += abs(previous_product_price - product_price) count += 1 if count > 0: output += '["%s","%s","%s","%s"] ,' % (rank, product_name, count, change/count) rank += 1 if get_data['t'] == '3': print(this_month) day = 1 # # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 32: day_string = True rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit, float(product_price / count)) rank += 1 day += 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) if get_data['t'] == '4': day = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 8: day_string = True rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__week_day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: if day == 1: output += '["%s","","","",""] ,' % 'Sunday' elif day == 2: output += '["%s","","","",""] ,' % 'Monday' elif day == 3: output += '["%s","","","",""] ,' % 'Tuesday' elif day == 4: output += '["%s","","","",""] ,' % 'Wednesday' elif day == 5: output += '["%s","","","",""] ,' % 'Thursday' elif day == 6: output += '["%s","","","",""] ,' % 'Friday' elif day == 7: output += '["%s","","","",""] ,' % 'Saturday' day_string = False output += '["","%s","%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit, float(product_price / count)) rank += 1 day += 1 if get_data['t'] == '5': this_year = datetime.date.today().year day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) output = output[:-1] output += ']}' return HttpResponse(output, content_type="text/plain") # Distributor Section @login_required(login_url='/login/') def add_sr_page(request): dr_name = request.session['user'] dr_object = ACL.objects.get(loginID=dr_name).loginUser transcriber_name = dr_object.name all_subscriber = ACL.objects.filter(distUser=dr_object) # type_of_subscriber = ConsumerType.objects.all() add_notification = False # shop_consumer = ConsumerType.objects.get(type_name='Seller') # all_shop_for_base = Consumer.objects.filter(type=shop_consumer) # all_user_for_base = Consumer.objects.all() # transcriber_name = request.session['user'] # shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') # all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) notification = '' if 'delete' in request.GET: get_data = request.GET add_notification = True delID = get_data['delete'] if Consumer.objects.filter(id=delID).exists(): item_for_delete = Consumer.objects.get(id=delID) notification = 'The Consumer : ' + item_for_delete.name + ' is deleted successfully.' item_for_delete.delete() else: notification = 'Item not found' return render(request, 'pages/Distributor/add_SR.html', {'subscribers': all_subscriber,'add_notification': add_notification, # 'shop_list_base': all_shop_for_base, # 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'notification': notification}) @login_required(login_url='/login/') def dr_monthly_report(request): dr_name = request.session['user'] dr_object = ACL.objects.get(loginID=dr_name).loginUser transcriber_name = dr_object.name transcriber_id = dr_object.id all_subscriber = ACL.objects.filter(distUser=dr_object) post_data = request.POST print(post_data) if 'sr' in post_data: sr_object = Consumer.objects.get(id=post_data['sr']) allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/Distributor/report_monthly.html', {'transcriber_name': transcriber_name, 'hasReport': True, 'subscribers': all_subscriber, 'transcriber_id': transcriber_id, 'allTransaction': allTransaction}) else: # allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/Distributor/report_monthly.html', {'transcriber_name': transcriber_name, 'transcriber_id': transcriber_id, 'subscribers': all_subscriber, 'hasReport': False}) @login_required(login_url='/login/') def dr_due_report(request): sr_name = request.session['user'] dr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = dr_object.name transcriber_id = dr_object.id all_subscriber = ACL.objects.filter(distUser=dr_object) post_data = request.POST if 'sr' in post_data: sr_object = Consumer.objects.get(id=post_data['sr']) allBalance = BuyerSellerAccount.objects.filter(seller=sr_object) sell_transaction = Transaction.objects.filter(seller=sr_object) dueTransactions = dueTransaction.objects.filter(seller=sr_object) # allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/Distributor/report_due.html', {'transcriber_name': transcriber_name, 'sell_transaction': sell_transaction, 'dueTransactions': dueTransactions, 'transcriber_id': transcriber_id, 'hasReport': True, 'subscribers': all_subscriber, 'allBalance': allBalance}) else: # allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/Distributor/report_due.html', {'transcriber_name': transcriber_name, 'transcriber_id': transcriber_id, 'subscribers': all_subscriber, 'hasReport': False}) @login_required(login_url='/login/') def dr_report_sales_analysis(request): dr_name = request.session['user'] dr_object = ACL.objects.get(loginID=dr_name).loginUser transcriber_name = dr_object.name transcriber_id = dr_object.id post_data = request.POST print(post_data) # shop_object = sr_object # all_subscriber = ACL.objects.filter(distUser=dr_object) hasReport = False if 'sr' in post_data: shop_id = post_data['sr'] shop_name = Consumer.objects.get(id=shop_id).name hasReport = True if 'month' in post_data and 'year' in post_data: month = post_data['month'] year = post_data['year'] else: month = datetime.date.today().month year = datetime.date.today().year return render(request, 'pages/Distributor/report_sales_analysis.html', {'shop_name': shop_name, 'transcriber_id': transcriber_id, 'shop_id': shop_id, 'subscribers': all_subscriber, 'transcriber_name': transcriber_name, 'month': month, 'hasReport': hasReport, 'year': year}) else: return render(request, 'pages/Distributor/report_sales_analysis.html', {'shop_name': 'Not Selected', 'transcriber_id': transcriber_id, 'subscribers': all_subscriber, 'transcriber_name': transcriber_name, 'hasReport': hasReport}) # Shop Module @login_required(login_url='/login/') def shop_monthly_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) allTransactionIn = BuyerSellerAccount.objects.filter(buyer=sr_object) return render(request, 'pages/Shop/report_monthly.html', {'transcriber_name': transcriber_name, 'allTransactionIn': allTransactionIn, 'allTransaction': allTransaction}) @login_required(login_url='/login/') def shop_due_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name allBalance = BuyerSellerAccount.objects.filter(seller=sr_object) sell_transaction = Transaction.objects.filter(seller=sr_object) dueTransactions = dueTransaction.objects.filter(seller=sr_object) allBalanceIn = BuyerSellerAccount.objects.filter(buyer=sr_object) sell_transactionIn = Transaction.objects.filter(buyer=sr_object) dueTransactionsIn = dueTransaction.objects.filter(buyer=sr_object) return render(request, 'pages/Shop/report_due.html', {'transcriber_name': transcriber_name, 'sell_transaction': sell_transaction, 'dueTransactions': dueTransactions, 'allBalance': allBalance, 'sell_transactionIn': sell_transactionIn, 'dueTransactionsIn': dueTransactionsIn, 'allBalanceIn': allBalanceIn}) @login_required(login_url='/login/') def shop_report_sales_analysis(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name post_data = request.POST print(post_data) shop_object = sr_object shop_name = shop_object.name shop_id = shop_object.id if 'month' in post_data and 'year' in post_data: month = post_data['month'] year = post_data['year'] else: month = datetime.date.today().month year = datetime.date.today().year return render(request, 'pages/Shop/report_sales_analysis.html', {'shop_name': shop_name, # 'all_consumer_for_base' :all_consumer_for_base, 'shop_id': shop_id, # 'bangla': bangla, 'transcriber_name': transcriber_name, 'month': month, 'year': year}) # Consumer Module @login_required(login_url='/login/') def user_monthly_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name # allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) allTransactionIn = BuyerSellerAccount.objects.filter(buyer=sr_object) return render(request, 'pages/Consumer/report_monthly.html', {'transcriber_name': transcriber_name, 'allTransactionIn': allTransactionIn}) @login_required(login_url='/login/') def user_due_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name # allBalance = BuyerSellerAccount.objects.filter(seller=sr_object) # sell_transaction = Transaction.objects.filter(seller=sr_object) # dueTransactions = dueTransaction.objects.filter(seller=sr_object) allBalanceIn = BuyerSellerAccount.objects.filter(buyer=sr_object) sell_transactionIn = Transaction.objects.filter(buyer=sr_object) dueTransactionsIn = dueTransaction.objects.filter(buyer=sr_object) return render(request, 'pages/Consumer/report_due.html', {'transcriber_name': transcriber_name, # 'sell_transaction': sell_transaction, # 'dueTransactions': dueTransactions, # 'allBalance': allBalance, 'sell_transactionIn': sell_transactionIn, 'dueTransactionsIn': dueTransactionsIn, 'allBalanceIn': allBalanceIn}) @login_required(login_url='/login/') def change_password(request): # user = request.session['user'] post_data = request.POST user_name = request.session['user'] user_object = ACL.objects.get(loginID=user_name).loginUser transcriber_name = user_object.name user = user_object.phone[-9:] wrong = False text = '' if 'csrfmiddlewaretoken' in post_data: if post_data['password'] == post_data['re-password']: if User.objects.filter(username=user).exists(): u = User.objects.get(username=user) u.set_password(post_data['password']) u.save() user_ID = user_object.id this_user = Consumer.objects.get(id=user_ID) this_user.number_of_child = 'CHANGED !!!' this_user.save() wrong = True text = 'Password is successfully changed' if user_object.type.type_name == 'Distributor': display = render(request, 'pages/Distributor/index.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'SR': display = render(request, 'pages/SR/index.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Seller': display = render(request, 'pages/Shop/index.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Buyer': display = render(request, 'pages/Consumer/index.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) else: wrong = True text = 'Something Wrong' if user_object.type.type_name == 'Distributor': display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'SR': display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Seller': display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Buyer': display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) else: wrong = True text = 'Passwords do NOT match. Please try again' if user_object.type.type_name == 'Distributor': display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'SR': display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Seller': display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Buyer': display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) else: wrong = False if user_object.type.type_name == 'Distributor': display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'SR': display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Seller': display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Buyer': display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong}) return display
Java
<?php /** * Display single product reviews (comments) * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ global $woocommerce, $product; if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if ( ! comments_open() ) return; ?> <div id="reviews"> <div id="comments"> <h2><?php if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' && ( $count = $product->get_rating_count() ) ) printf( _n('%s review for %s', '%s reviews for %s', $count, 'woocommerce'), $count, get_the_title() ); else _e( 'Reviews', 'woocommerce' ); ?></h2> <?php if ( have_comments() ) : ?> <ol class="commentlist"> <?php wp_list_comments( apply_filters( 'woocommerce_product_review_list_args', array( 'callback' => 'woocommerce_comments' ) ) ); ?> </ol> <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : echo '<nav class="woocommerce-pagination">'; paginate_comments_links( apply_filters( 'woocommerce_comment_pagination_args', array( 'prev_text' => '&larr;', 'next_text' => '&rarr;', 'type' => 'list', ) ) ); echo '</nav>'; endif; ?> <?php else : ?> <p class="woocommerce-noreviews"><?php _e( 'There are no reviews yet.', 'woocommerce' ); ?></p> <?php endif; ?> </div> <?php if ( get_option( 'woocommerce_review_rating_verification_required' ) === 'no' || wc_customer_bought_product( '', get_current_user_id(), $product->id ) ) : ?> <div id="review_form_wrapper"> <div id="review_form"> <?php $commenter = wp_get_current_commenter(); $comment_form = array( 'title_reply' => have_comments() ? __( 'Add a review', 'woocommerce' ) : __( 'Be the first to review', 'woocommerce' ) . ' &ldquo;' . get_the_title() . '&rdquo;', 'title_reply_to' => __( 'Leave a Reply to %s', 'woocommerce' ), 'comment_notes_before' => '', 'comment_notes_after' => '', 'fields' => array( 'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name', 'woocommerce' ) . ' <span class="required">*</span></label> ' . '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30" aria-required="true" /></p>', 'email' => '<p class="comment-form-email"><label for="email">' . __( 'Email', 'woocommerce' ) . ' <span class="required">*</span></label> ' . '<input id="email" name="email" type="text" value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30" aria-required="true" /></p>', ), 'label_submit' => __( 'Submit', 'woocommerce' ), 'logged_in_as' => '', 'comment_field' => '' ); if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' ) { $comment_form['comment_field'] = '<p class="comment-form-rating"><label for="rating">' . __( 'Your Rating', 'woocommerce' ) .'</label><select name="rating" id="rating"> <option value="">' . __( 'Rate&hellip;', 'woocommerce' ) . '</option> <option value="5">' . __( 'Perfect', 'woocommerce' ) . '</option> <option value="4">' . __( 'Good', 'woocommerce' ) . '</option> <option value="3">' . __( 'Average', 'woocommerce' ) . '</option> <option value="2">' . __( 'Not that bad', 'woocommerce' ) . '</option> <option value="1">' . __( 'Very Poor', 'woocommerce' ) . '</option> </select></p>'; } $comment_form['comment_field'] .= '<p class="comment-form-comment"><label for="comment">' . __( 'Your Review', 'woocommerce' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>' . wp_nonce_field( 'woocommerce-comment_rating', '_wpnonce', true, false ) . '</p>'; comment_form( apply_filters( 'woocommerce_product_review_comment_form_args', $comment_form ) ); ?> </div> </div> <?php else : ?> <p class="woocommerce-verification-required"><?php _e( 'Only logged in customers who have purchased this product may leave a review.', 'woocommerce' ); ?></p> <?php endif; ?> <div class="clear"></div> </div>
Java
package com.atux.bean.consulta; import com.atux.comun.FilterBaseLocal; /** * Created by MATRIX-JAVA on 27/11/2014. */ public class UnidadFlt extends FilterBaseLocal { public static final String PICK = "PICK"; public UnidadFlt(String unidad) { this.unidad = unidad; } public UnidadFlt() { } private String unidad; private String coUnidad; public String getUnidad() { return unidad; } public void setUnidad(String unidad) { this.unidad = unidad; } public String getCoUnidad() { return coUnidad; } public void setCoUnidad(String coUnidad) { this.coUnidad = coUnidad; } }
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Project WiSH</title> <style fprolloverstyle>A:hover {color: red; font-weight: bold} </style> </head> <body style="background-attachment: fixed"> <p align="center"> <A href="http://sourceforge.net"> <IMG src="http://sourceforge.net/sflogo.php?group_id=68802&amp;type=5" border="0" alt="SourceForge Logo"></A> <h1 align="center"><b>Linux X10 universal device driver</b></h1> <h2 align="center"><b>(aka Project WiSH)</b></h2> <ul> <li> <p align="left"><a href="http://wish.sourceforge.net/index1.html">x10dev (Version 1.X</a>) for <b>Kernel 2.4.X:</b>&nbsp; Linux driver for Kernel 2.4 supporting the CM11A, CM17A, SmartHome PowerLink Serial, and SmartHome PowerLink USB transceivers.</p></li> <li> <p align="left"><a href="http://wish.sourceforge.net/index2.html">x10dev-2 (Version 2.X</a>) for <b>Kernel 2.6.7+ and Kernel 2.4</b>:&nbsp; for Kernel 2.6.7 and higher supporting the CM11A, SmartHome PowerLink Serial, and SmartHome PowerLink USB.&nbsp; For Kernel 2.4 supporting the CM11A and SmartHome PowerLink Serial.</p></li> <li> <p align="left"><a href="http://wish.sourceforge.net/x10web.html">x10web (Java GUI) Version 1.X</a>:&nbsp; Java client GUI and socket server for both wish Version 1.X and Version 2.X</p> </li> </ul> <hr> <p> This module is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as publised by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. </p><p> This module is distributed 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. </p><p> You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA </p><p> Should you need to contact the author, you can do so by email to <wsh@sprintmail.com>. </p> </body> </html>
Java
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * Copyright © 2000-2004 Marco Pesenti Gritti * Copyright © 2009 Collabora Ltd. * Copyright © 2011 Igalia S.L. * * 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "config.h" #include "window-commands.h" #include "ephy-bookmarks-editor.h" #include "ephy-bookmarks-ui.h" #include "ephy-debug.h" #include "ephy-dialog.h" #include "ephy-embed-container.h" #include "ephy-embed-prefs.h" #include "ephy-embed-shell.h" #include "ephy-embed-single.h" #include "ephy-embed-utils.h" #include "ephy-embed.h" #include "ephy-file-chooser.h" #include "ephy-file-helpers.h" #include "ephy-find-toolbar.h" #include "ephy-gui.h" #include "ephy-history-window.h" #include "ephy-link.h" #include "ephy-location-entry.h" #include "ephy-notebook.h" #include "ephy-prefs.h" #include "ephy-private.h" #include "ephy-settings.h" #include "ephy-shell.h" #include "ephy-state.h" #include "ephy-string.h" #include "ephy-web-app-utils.h" #include "ephy-zoom.h" #include "pdm-dialog.h" #include <gio/gio.h> #include <glib.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #include <libnotify/notify.h> #include <libsoup/soup.h> #include <string.h> #ifdef HAVE_WEBKIT2 #include <webkit2/webkit2.h> #else #include <webkit/webkit.h> #endif void window_cmd_file_print (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; EphyWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (EPHY_IS_EMBED (embed)); view = ephy_embed_get_web_view (embed); ephy_web_view_print (view); } void window_cmd_file_send_to (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; char *command, *subject, *body; const char *location, *title; GdkScreen *screen; GError *error = NULL; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); location = ephy_web_view_get_address (ephy_embed_get_web_view (embed)); title = ephy_web_view_get_title (ephy_embed_get_web_view (embed)); subject = g_uri_escape_string (title, NULL, TRUE); body = g_uri_escape_string (location, NULL, TRUE); command = g_strconcat ("mailto:", "?Subject=", subject, "&Body=", body, NULL); g_free (subject); g_free (body); if (window) { screen = gtk_widget_get_screen (GTK_WIDGET (window)); } else { screen = gdk_screen_get_default (); } if (!gtk_show_uri (screen, command, gtk_get_current_event_time(), &error)) { g_warning ("Unable to send link by email: %s\n", error->message); g_error_free (error); } g_free (command); } static gboolean event_with_shift (void) { GdkEvent *event; GdkEventType type = 0; guint state = 0; event = gtk_get_current_event (); if (event) { type = event->type; if (type == GDK_BUTTON_RELEASE) { state = event->button.state; } else if (type == GDK_KEY_PRESS || type == GDK_KEY_RELEASE) { state = event->key.state; } gdk_event_free (event); } return (state & GDK_SHIFT_MASK) != 0; } void window_cmd_go_location (GtkAction *action, EphyWindow *window) { ephy_window_activate_location (window); } void window_cmd_view_stop (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); gtk_widget_grab_focus (GTK_WIDGET (embed)); webkit_web_view_stop_loading (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); } void window_cmd_view_reload (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; WebKitWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); gtk_widget_grab_focus (GTK_WIDGET (embed)); view = EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed); if (event_with_shift ()) webkit_web_view_reload_bypass_cache (view); else webkit_web_view_reload (view); } void window_cmd_file_bookmark_page (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); ephy_bookmarks_ui_add_bookmark (GTK_WINDOW (window), ephy_web_view_get_address (ephy_embed_get_web_view (embed)), ephy_web_view_get_title (ephy_embed_get_web_view (embed))); } static void open_response_cb (GtkDialog *dialog, int response, EphyWindow *window) { if (response == GTK_RESPONSE_ACCEPT) { char *uri, *converted; uri = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (dialog)); if (uri != NULL) { converted = g_filename_to_utf8 (uri, -1, NULL, NULL, NULL); if (converted != NULL) { ephy_window_load_url (window, converted); } g_free (converted); g_free (uri); } } gtk_widget_destroy (GTK_WIDGET (dialog)); } static void save_response_cb (GtkDialog *dialog, int response, EphyEmbed *embed) { if (response == GTK_RESPONSE_ACCEPT) { char *uri, *converted; uri = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (dialog)); if (uri != NULL) { converted = g_filename_to_utf8 (uri, -1, NULL, NULL, NULL); if (converted != NULL) { EphyWebView *web_view = ephy_embed_get_web_view (embed); ephy_web_view_save (web_view, converted); } g_free (converted); g_free (uri); } } gtk_widget_destroy (GTK_WIDGET (dialog)); } void window_cmd_file_open (GtkAction *action, EphyWindow *window) { EphyFileChooser *dialog; dialog = ephy_file_chooser_new (_("Open"), GTK_WIDGET (window), GTK_FILE_CHOOSER_ACTION_OPEN, EPHY_PREFS_STATE_OPEN_DIR, EPHY_FILE_FILTER_ALL_SUPPORTED); g_signal_connect (dialog, "response", G_CALLBACK (open_response_cb), window); gtk_widget_show (GTK_WIDGET (dialog)); } static char * get_suggested_filename (EphyWebView *view) { char *suggested_filename; const char *mimetype; #ifdef HAVE_WEBKIT2 WebKitURIResponse *response; #else WebKitWebFrame *frame; WebKitWebDataSource *data_source; #endif WebKitWebResource *web_resource; #ifdef HAVE_WEBKIT2 web_resource = webkit_web_view_get_main_resource (WEBKIT_WEB_VIEW (view)); response = webkit_web_resource_get_response (web_resource); mimetype = webkit_uri_response_get_mime_type (response); #else frame = webkit_web_view_get_main_frame (WEBKIT_WEB_VIEW (view)); data_source = webkit_web_frame_get_data_source (frame); web_resource = webkit_web_data_source_get_main_resource (data_source); mimetype = webkit_web_resource_get_mime_type (web_resource); #endif if ((g_ascii_strncasecmp (mimetype, "text/html", 9)) == 0) { /* Web Title will be used as suggested filename*/ suggested_filename = g_strconcat (ephy_web_view_get_title (view), ".html", NULL); } else { SoupURI *soup_uri = soup_uri_new (webkit_web_resource_get_uri (web_resource)); suggested_filename = g_path_get_basename (soup_uri->path); soup_uri_free (soup_uri); } return suggested_filename; } void window_cmd_file_save_as (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; EphyFileChooser *dialog; char *suggested_filename; EphyWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); dialog = ephy_file_chooser_new (_("Save"), GTK_WIDGET (window), GTK_FILE_CHOOSER_ACTION_SAVE, EPHY_PREFS_STATE_SAVE_DIR, EPHY_FILE_FILTER_NONE); gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE); view = ephy_embed_get_web_view (embed); suggested_filename = get_suggested_filename (view); gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), suggested_filename); g_free (suggested_filename); g_signal_connect (dialog, "response", G_CALLBACK (save_response_cb), embed); gtk_widget_show (GTK_WIDGET (dialog)); } typedef struct { EphyWebView *view; GtkWidget *image; GtkWidget *entry; GtkWidget *spinner; GtkWidget *box; char *icon_href; } EphyApplicationDialogData; static void ephy_application_dialog_data_free (EphyApplicationDialogData *data) { g_free (data->icon_href); g_slice_free (EphyApplicationDialogData, data); } static void take_page_snapshot_and_set_image (EphyApplicationDialogData *data) { GdkPixbuf *snapshot; int x, y, w, h; x = y = 0; w = h = 128; /* GNOME hi-res icon size. */ snapshot = ephy_web_view_get_snapshot (data->view, x, y, w, h); gtk_image_set_from_pixbuf (GTK_IMAGE (data->image), snapshot); g_object_unref (snapshot); } #ifdef HAVE_WEBKIT2 static void download_finished_cb (WebKitDownload *download, EphyApplicationDialogData *data) { char *filename; filename = g_filename_from_uri (webkit_download_get_destination (download), NULL, NULL); gtk_image_set_from_file (GTK_IMAGE (data->image), filename); g_free (filename); } static void download_failed_cb (WebKitDownload *download, GError *error, EphyApplicationDialogData *data) { g_signal_handlers_disconnect_by_func (download, download_finished_cb, data); /* Something happened, default to a page snapshot. */ take_page_snapshot_and_set_image (data); } #else static void download_status_changed_cb (WebKitDownload *download, GParamSpec *spec, EphyApplicationDialogData *data) { WebKitDownloadStatus status = webkit_download_get_status (download); char *filename; switch (status) { case WEBKIT_DOWNLOAD_STATUS_FINISHED: filename = g_filename_from_uri (webkit_download_get_destination_uri (download), NULL, NULL); gtk_image_set_from_file (GTK_IMAGE (data->image), filename); g_free (filename); break; case WEBKIT_DOWNLOAD_STATUS_ERROR: case WEBKIT_DOWNLOAD_STATUS_CANCELLED: /* Something happened, default to a page snapshot. */ take_page_snapshot_and_set_image (data); break; default: break; } } #endif static void download_icon_and_set_image (EphyApplicationDialogData *data) { #ifndef HAVE_WEBKIT2 WebKitNetworkRequest *request; #endif WebKitDownload *download; char *destination, *destination_uri, *tmp_filename; #ifdef HAVE_WEBKIT2 download = webkit_web_context_download_uri (webkit_web_context_get_default (), data->icon_href); #else request = webkit_network_request_new (data->icon_href); download = webkit_download_new (request); g_object_unref (request); #endif tmp_filename = ephy_file_tmp_filename ("ephy-download-XXXXXX", NULL); destination = g_build_filename (ephy_file_tmp_dir (), tmp_filename, NULL); destination_uri = g_filename_to_uri (destination, NULL, NULL); #ifdef HAVE_WEBKIT2 webkit_download_set_destination (download, destination_uri); #else webkit_download_set_destination_uri (download, destination_uri); #endif g_free (destination); g_free (destination_uri); g_free (tmp_filename); #ifdef HAVE_WEBKIT2 g_signal_connect (download, "finished", G_CALLBACK (download_finished_cb), data); g_signal_connect (download, "failed", G_CALLBACK (download_failed_cb), data); #else g_signal_connect (download, "notify::status", G_CALLBACK (download_status_changed_cb), data); webkit_download_start (download); #endif } static void fill_default_application_image (EphyApplicationDialogData *data) { #ifdef HAVE_WEBKIT2 /* TODO: DOM Bindindgs */ #else WebKitDOMDocument *document; WebKitDOMNodeList *links; gulong length, i; document = webkit_web_view_get_dom_document (WEBKIT_WEB_VIEW (data->view)); links = webkit_dom_document_get_elements_by_tag_name (document, "link"); length = webkit_dom_node_list_get_length (links); for (i = 0; i < length; i++) { char *rel; WebKitDOMNode *node = webkit_dom_node_list_item (links, i); rel = webkit_dom_html_link_element_get_rel (WEBKIT_DOM_HTML_LINK_ELEMENT (node)); /* TODO: support more than one possible icon. */ if (g_strcmp0 (rel, "apple-touch-icon") == 0 || g_strcmp0 (rel, "apple-touch-icon-precomposed") == 0) { data->icon_href = webkit_dom_html_link_element_get_href (WEBKIT_DOM_HTML_LINK_ELEMENT (node)); download_icon_and_set_image (data); g_free (rel); return; } } #endif /* If we make it here, no "apple-touch-icon" link was * found. Take a snapshot of the page. */ take_page_snapshot_and_set_image (data); } static void fill_default_application_title (EphyApplicationDialogData *data) { const char *title = ephy_web_view_get_title (data->view); gtk_entry_set_text (GTK_ENTRY (data->entry), title); } static void notify_launch_cb (NotifyNotification *notification, char *action, gpointer user_data) { char * desktop_file = user_data; /* A gross hack to be able to launch epiphany from within * Epiphany. Might be a good idea to figure out a better * solution... */ g_unsetenv (EPHY_UUID_ENVVAR); ephy_file_launch_desktop_file (desktop_file, NULL, 0, NULL); g_free (desktop_file); } static gboolean confirm_web_application_overwrite (GtkWindow *parent, const char *title) { GtkResponseType response; GtkWidget *dialog; dialog = gtk_message_dialog_new (parent, 0, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("A web application named '%s' already exists. Do you want to replace it?"), title); gtk_dialog_add_buttons (GTK_DIALOG (dialog), _("Cancel"), GTK_RESPONSE_CANCEL, _("Replace"), GTK_RESPONSE_OK, NULL); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), _("An application with the same name already exists. Replacing it will " "overwrite it.")); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); return response == GTK_RESPONSE_OK; } static void dialog_save_as_application_response_cb (GtkDialog *dialog, gint response, EphyApplicationDialogData *data) { const char *app_name; char *desktop_file; char *message; NotifyNotification *notification; if (response == GTK_RESPONSE_OK) { app_name = gtk_entry_get_text (GTK_ENTRY (data->entry)); if (ephy_web_application_exists (app_name)) { if (confirm_web_application_overwrite (GTK_WINDOW (dialog), app_name)) ephy_web_application_delete (app_name); else return; } /* Create Web Application, including a new profile and .desktop file. */ desktop_file = ephy_web_application_create (webkit_web_view_get_uri (WEBKIT_WEB_VIEW (data->view)), app_name, gtk_image_get_pixbuf (GTK_IMAGE (data->image))); if (desktop_file) message = g_strdup_printf (_("The application '%s' is ready to be used"), app_name); else message = g_strdup_printf (_("The application '%s' could not be created"), app_name); notification = notify_notification_new (message, NULL, NULL); g_free (message); if (desktop_file) { notify_notification_add_action (notification, "launch", _("Launch"), (NotifyActionCallback)notify_launch_cb, g_path_get_basename (desktop_file), NULL); notify_notification_set_icon_from_pixbuf (notification, gtk_image_get_pixbuf (GTK_IMAGE (data->image))); g_free (desktop_file); } notify_notification_set_timeout (notification, NOTIFY_EXPIRES_DEFAULT); notify_notification_set_urgency (notification, NOTIFY_URGENCY_LOW); notify_notification_set_hint (notification, "transient", g_variant_new_boolean (TRUE)); notify_notification_show (notification, NULL); } ephy_application_dialog_data_free (data); gtk_widget_destroy (GTK_WIDGET (dialog)); } void window_cmd_file_save_as_application (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; GtkWidget *dialog, *box, *image, *entry, *content_area; EphyWebView *view; EphyApplicationDialogData *data; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); view = EPHY_WEB_VIEW (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); /* Show dialog with icon, title. */ dialog = gtk_dialog_new_with_buttons (_("Create Web Application"), GTK_WINDOW (window), 0, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, _("C_reate"), GTK_RESPONSE_OK, NULL); content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog)); gtk_container_set_border_width (GTK_CONTAINER (dialog), 5); gtk_box_set_spacing (GTK_BOX (content_area), 14); /* 14 + 2 * 5 = 24 */ box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5); gtk_container_add (GTK_CONTAINER (content_area), box); image = gtk_image_new (); gtk_widget_set_size_request (image, 128, 128); gtk_container_add (GTK_CONTAINER (box), image); entry = gtk_entry_new (); gtk_entry_set_activates_default (GTK_ENTRY (entry), TRUE); gtk_box_pack_end (GTK_BOX (box), entry, FALSE, FALSE, 0); data = g_slice_new0 (EphyApplicationDialogData); data->view = view; data->image = image; data->entry = entry; fill_default_application_image (data); fill_default_application_title (data); gtk_widget_show_all (dialog); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_OK); g_signal_connect (dialog, "response", G_CALLBACK (dialog_save_as_application_response_cb), data); gtk_widget_show_all (dialog); } void window_cmd_file_work_offline (GtkAction *action, EphyWindow *window) { /* TODO: WebKitGTK+ does not currently support offline status. */ #if 0 EphyEmbedSingle *single; gboolean offline; single = EPHY_EMBED_SINGLE (ephy_embed_shell_get_embed_single (embed_shell)); offline = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); ephy_embed_single_set_network_status (single, !offline); #endif } void window_cmd_file_close_window (GtkAction *action, EphyWindow *window) { GtkWidget *notebook; EphyEmbed *embed; notebook = ephy_window_get_notebook (window); if (g_settings_get_boolean (EPHY_SETTINGS_LOCKDOWN, EPHY_PREFS_LOCKDOWN_QUIT) && gtk_notebook_get_n_pages (GTK_NOTEBOOK (notebook)) == 1) { return; } embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); g_signal_emit_by_name (notebook, "tab-close-request", embed); } void window_cmd_edit_undo (GtkAction *action, EphyWindow *window) { GtkWidget *widget; GtkWidget *embed; GtkWidget *location_entry; widget = gtk_window_get_focus (GTK_WINDOW (window)); location_entry = gtk_widget_get_ancestor (widget, EPHY_TYPE_LOCATION_ENTRY); if (location_entry) { ephy_location_entry_reset (EPHY_LOCATION_ENTRY (location_entry)); } else { embed = gtk_widget_get_ancestor (widget, EPHY_TYPE_EMBED); if (embed) { #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed)), "Undo"); #else webkit_web_view_undo (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed))); #endif } } } void window_cmd_edit_redo (GtkAction *action, EphyWindow *window) { GtkWidget *widget; GtkWidget *embed; GtkWidget *location_entry; widget = gtk_window_get_focus (GTK_WINDOW (window)); location_entry = gtk_widget_get_ancestor (widget, EPHY_TYPE_LOCATION_ENTRY); if (location_entry) { ephy_location_entry_undo_reset (EPHY_LOCATION_ENTRY (location_entry)); } else { embed = gtk_widget_get_ancestor (widget, EPHY_TYPE_EMBED); if (embed) { #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed)), "Redo"); #else webkit_web_view_redo (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed))); #endif } } } void window_cmd_edit_cut (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_cut_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_CUT); #else webkit_web_view_cut_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_copy (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_copy_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_COPY); #else webkit_web_view_copy_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_paste (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_paste_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_PASTE); #else webkit_web_view_paste_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_delete (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_delete_text (GTK_EDITABLE (widget), 0, -1); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); /* FIXME: TODO */ #if 0 ephy_command_manager_do_command (EPHY_COMMAND_MANAGER (embed), "cmd_delete"); #endif } } void window_cmd_edit_select_all (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_select_region (GTK_EDITABLE (widget), 0, -1); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), "SelectAll"); #else webkit_web_view_select_all (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_find (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_open (toolbar, FALSE, FALSE); } void window_cmd_edit_find_next (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_find_next (toolbar); } void window_cmd_edit_find_prev (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_find_previous (toolbar); } void window_cmd_view_fullscreen (GtkAction *action, EphyWindow *window) { if (gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action))) gtk_window_fullscreen (GTK_WINDOW (window)); else gtk_window_unfullscreen (GTK_WINDOW (window)); } void window_cmd_view_zoom_in (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, ZOOM_IN); } void window_cmd_view_zoom_out (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, ZOOM_OUT); } void window_cmd_view_zoom_normal (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, 1.0); } static void view_source_embedded (const char *uri, EphyEmbed *embed) { EphyEmbed *new_embed; new_embed = ephy_shell_new_tab (ephy_shell_get_default (), EPHY_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (embed))), embed, NULL, EPHY_NEW_TAB_JUMP | EPHY_NEW_TAB_IN_EXISTING_WINDOW | EPHY_NEW_TAB_APPEND_AFTER); #ifdef HAVE_WEBKIT2 /* TODO: View Source */ #else webkit_web_view_set_view_source_mode (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (new_embed), TRUE); webkit_web_view_load_uri (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (new_embed), uri); #endif } static void save_temp_source_close_cb (GOutputStream *ostream, GAsyncResult *result, gpointer data) { char *uri; GFile *file; GError *error = NULL; g_output_stream_close_finish (ostream, result, &error); if (error) { g_warning ("Unable to close file: %s", error->message); g_error_free (error); return; } uri = (char*)g_object_get_data (G_OBJECT (ostream), "ephy-save-temp-source-uri"); file = g_file_new_for_uri (uri); if (!ephy_file_launch_handler ("text/plain", file, gtk_get_current_event_time ())) { /* Fallback to view the source inside the browser */ const char *uri; EphyEmbed *embed; uri = (const char*) g_object_get_data (G_OBJECT (ostream), "ephy-original-source-uri"); embed = (EphyEmbed*)g_object_get_data (G_OBJECT (ostream), "ephy-save-temp-source-embed"); view_source_embedded (uri, embed); } g_object_unref (ostream); g_object_unref (file); } static void save_temp_source_write_cb (GOutputStream *ostream, GAsyncResult *result, GString *data) { GError *error = NULL; gssize written; written = g_output_stream_write_finish (ostream, result, &error); if (error) { g_string_free (data, TRUE); g_warning ("Unable to write to file: %s", error->message); g_error_free (error); g_output_stream_close_async (ostream, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_close_cb, NULL); return; } if (written == data->len) { g_string_free (data, TRUE); g_output_stream_close_async (ostream, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_close_cb, NULL); return; } data->len -= written; data->str += written; g_output_stream_write_async (ostream, data->str, data->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data); } #ifdef HAVE_WEBKIT2 static void get_main_resource_data_cb (WebKitWebResource *resource, GAsyncResult *result, GOutputStream *ostream) { guchar *data; gsize data_length; GString *data_str; GError *error = NULL; data = webkit_web_resource_get_data_finish (resource, result, &data_length, &error); if (error) { g_warning ("Unable to get main resource data: %s", error->message); g_error_free (error); return; } /* We create a new GString here because we need to make sure * we keep writing in case of partial writes */ data_str = g_string_new_len ((gchar *)data, data_length); g_free (data); g_output_stream_write_async (ostream, data_str->str, data_str->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data_str); } #endif static void save_temp_source_replace_cb (GFile *file, GAsyncResult *result, EphyEmbed *embed) { EphyWebView *view; #ifdef HAVE_WEBKIT2 WebKitWebResource *resource; #else WebKitWebFrame *frame; WebKitWebDataSource *data_source; GString *const_data; GString *data; #endif GFileOutputStream *ostream; GError *error = NULL; ostream = g_file_replace_finish (file, result, &error); if (error) { g_warning ("Unable to replace file: %s", error->message); g_error_free (error); return; } g_object_set_data_full (G_OBJECT (ostream), "ephy-save-temp-source-uri", g_file_get_uri (file), g_free); view = ephy_embed_get_web_view (embed); g_object_set_data_full (G_OBJECT (ostream), "ephy-original-source-uri", g_strdup (webkit_web_view_get_uri (WEBKIT_WEB_VIEW (view))), g_free), g_object_set_data_full (G_OBJECT (ostream), "ephy-save-temp-source-embed", g_object_ref (embed), g_object_unref); #ifdef HAVE_WEBKIT2 resource = webkit_web_view_get_main_resource (WEBKIT_WEB_VIEW (view)); webkit_web_resource_get_data (resource, NULL, (GAsyncReadyCallback)get_main_resource_data_cb, ostream); #else frame = webkit_web_view_get_main_frame (WEBKIT_WEB_VIEW (view)); data_source = webkit_web_frame_get_data_source (frame); const_data = webkit_web_data_source_get_data (data_source); /* We create a new GString here because we need to make sure * we keep writing in case of partial writes */ if (const_data) data = g_string_new_len (const_data->str, const_data->len); else data = g_string_new_len ("", 0); g_output_stream_write_async (G_OUTPUT_STREAM (ostream), data->str, data->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data); #endif } static void save_temp_source (EphyEmbed *embed, guint32 user_time) { GFile *file; char *tmp, *base; const char *static_temp_dir; static_temp_dir = ephy_file_tmp_dir (); if (static_temp_dir == NULL) { return; } base = g_build_filename (static_temp_dir, "viewsourceXXXXXX", NULL); tmp = ephy_file_tmp_filename (base, "html"); g_free (base); if (tmp == NULL) { return; } file = g_file_new_for_path (tmp); g_file_replace_async (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION|G_FILE_CREATE_PRIVATE, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_replace_cb, embed); g_object_unref (file); g_free (tmp); } void window_cmd_view_page_source (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; const char *address; guint32 user_time; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); address = ephy_web_view_get_address (ephy_embed_get_web_view (embed)); #ifdef HAVE_WEBKIT2 /* TODO: View Source */ #else if (g_settings_get_boolean (EPHY_SETTINGS_MAIN, EPHY_PREFS_INTERNAL_VIEW_SOURCE)) { view_source_embedded (address, embed); return; } #endif user_time = gtk_get_current_event_time (); if (g_str_has_prefix (address, "file://")) { GFile *file; file = g_file_new_for_uri (address); ephy_file_launch_handler ("text/plain", file, user_time); g_object_unref (file); } else { save_temp_source (embed, user_time); } } #define ABOUT_GROUP "About" void window_cmd_help_about (GtkAction *action, GtkWidget *window) { const char *licence_part[] = { N_("Web 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."), N_("The GNOME Web Browser 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."), N_("You should have received a copy of the GNU General Public License " "along with the GNOME Web Browser; if not, write to the Free Software Foundation, Inc., " "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA") }; char *licence = NULL, *comments = NULL; GKeyFile *key_file; GError *error = NULL; char **list, **authors, **contributors, **past_authors, **artists, **documenters; gsize n_authors, n_contributors, n_past_authors, n_artists, n_documenters, i, j; key_file = g_key_file_new (); if (!g_key_file_load_from_file (key_file, DATADIR G_DIR_SEPARATOR_S "about.ini", 0, &error)) { g_warning ("Couldn't load about data: %s\n", error->message); g_error_free (error); return; } list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Authors", &n_authors, NULL); contributors = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Contributors", &n_contributors, NULL); past_authors = g_key_file_get_string_list (key_file, ABOUT_GROUP, "PastAuthors", &n_past_authors, NULL); #define APPEND(_to,_from) \ _to[i++] = g_strdup (_from); #define APPEND_STRV_AND_FREE(_to,_from) \ if (_from)\ {\ for (j = 0; _from[j] != NULL; ++j)\ {\ _to[i++] = _from[j];\ }\ g_free (_from);\ } authors = g_new (char *, (list ? n_authors : 0) + (contributors ? n_contributors : 0) + (past_authors ? n_past_authors : 0) + 7 + 1); i = 0; APPEND_STRV_AND_FREE (authors, list); APPEND (authors, ""); APPEND (authors, _("Contact us at:")); APPEND (authors, "<epiphany-list@gnome.org>"); APPEND (authors, ""); APPEND (authors, _("Contributors:")); APPEND_STRV_AND_FREE (authors, contributors); APPEND (authors, ""); APPEND (authors, _("Past developers:")); APPEND_STRV_AND_FREE (authors, past_authors); authors[i++] = NULL; list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Artists", &n_artists, NULL); artists = g_new (char *, (list ? n_artists : 0) + 4 + 1); i = 0; APPEND_STRV_AND_FREE (artists, list); APPEND (artists, ""); APPEND (artists, _("Contact us at:")); APPEND (artists, "<gnome-art-list@gnome.org>"); APPEND (artists, "<gnome-themes-list@gnome.org>"); artists[i++] = NULL; list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Documenters", &n_documenters, NULL); documenters = g_new (char *, (list ? n_documenters : 0) + 3 + 1); i = 0; APPEND_STRV_AND_FREE (documenters, list); APPEND (documenters, ""); APPEND (documenters, _("Contact us at:")); APPEND (documenters, "<gnome-doc-list@gnome.org>"); documenters[i++] = NULL; #undef APPEND #undef APPEND_STRV_AND_FREE g_key_file_free (key_file); #ifdef HAVE_WEBKIT2 comments = g_strdup_printf (_("Lets you view web pages and find information on the internet.\n" "Powered by WebKit %d.%d.%d"), webkit_get_major_version (), webkit_get_minor_version (), webkit_get_micro_version ()); #else comments = g_strdup_printf (_("Lets you view web pages and find information on the internet.\n" "Powered by WebKit %d.%d.%d"), webkit_major_version (), webkit_minor_version (), webkit_micro_version ()); #endif licence = g_strjoin ("\n\n", _(licence_part[0]), _(licence_part[1]), _(licence_part[2]), NULL); gtk_show_about_dialog (window ? GTK_WINDOW (window) : NULL, "program-name", _("Web"), "version", VERSION, "copyright", "Copyright © 2002–2004 Marco Pesenti Gritti\n" "Copyright © 2003–2012 The Web Developers", "artists", artists, "authors", authors, "comments", comments, "documenters", documenters, /* Translators: This is a special message that shouldn't be translated * literally. It is used in the about box to give credits to * the translators. * Thus, you should translate it to your name and email address. * You should also include other translators who have contributed to * this translation; in that case, please write each of them on a separate * line seperated by newlines (\n). */ "translator-credits", _("translator-credits"), "logo-icon-name", "web-browser", "website", "http://www.gnome.org/projects/epiphany", "website-label", _("Web Website"), "license", licence, "wrap-license", TRUE, NULL); g_free (comments); g_free (licence); g_strfreev (artists); g_strfreev (authors); g_strfreev (documenters); } void window_cmd_tabs_next (GtkAction *action, EphyWindow *window) { GtkWidget *nb; nb = ephy_window_get_notebook (window); g_return_if_fail (nb != NULL); ephy_notebook_next_page (EPHY_NOTEBOOK (nb)); } void window_cmd_tabs_previous (GtkAction *action, EphyWindow *window) { GtkWidget *nb; nb = ephy_window_get_notebook (window); g_return_if_fail (nb != NULL); ephy_notebook_prev_page (EPHY_NOTEBOOK (nb)); } void window_cmd_tabs_move_left (GtkAction *action, EphyWindow *window) { GtkWidget *child; GtkNotebook *notebook; int page; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); page = gtk_notebook_get_current_page (notebook); if (page < 1) return; child = gtk_notebook_get_nth_page (notebook, page); gtk_notebook_reorder_child (notebook, child, page - 1); } void window_cmd_tabs_move_right (GtkAction *action, EphyWindow *window) { GtkWidget *child; GtkNotebook *notebook; int page, n_pages; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); page = gtk_notebook_get_current_page (notebook); n_pages = gtk_notebook_get_n_pages (notebook) - 1; if (page > n_pages - 1) return; child = gtk_notebook_get_nth_page (notebook, page); gtk_notebook_reorder_child (notebook, child, page + 1); } void window_cmd_tabs_detach (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; GtkNotebook *notebook; EphyWindow *new_window; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); if (gtk_notebook_get_n_pages (notebook) <= 1) return; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_object_ref_sink (embed); gtk_notebook_remove_page (notebook, gtk_notebook_page_num (notebook, GTK_WIDGET (embed))); new_window = ephy_window_new (); ephy_embed_container_add_child (EPHY_EMBED_CONTAINER (new_window), embed, 0, FALSE); g_object_unref (embed); gtk_window_present (GTK_WINDOW (new_window)); } void window_cmd_load_location (GtkAction *action, EphyWindow *window) { const char *location; location = ephy_window_get_location (window); if (location) { EphyBookmarks *bookmarks; char *address; bookmarks = ephy_shell_get_bookmarks (ephy_shell_get_default ()); address = ephy_bookmarks_resolve_address (bookmarks, location, NULL); g_return_if_fail (address != NULL); ephy_link_open (EPHY_LINK (window), address, ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)), ephy_link_flags_from_current_event ()); } } void window_cmd_browse_with_caret (GtkAction *action, EphyWindow *window) { gboolean active; EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); active = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); /* FIXME: perhaps a bit of a kludge; we check if there's an * active embed because we don't want to show the dialog on * startup when we sync the GtkAction with our GConf * preference */ if (active && embed) { GtkWidget *dialog; int response; dialog = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_CANCEL, _("Enable caret browsing mode?")); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), _("Pressing F7 turns caret browsing on or off. This feature " "places a moveable cursor in web pages, allowing you to move " "around with your keyboard. Do you want to enable caret browsing on?")); gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Enable"), GTK_RESPONSE_ACCEPT); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); if (response == GTK_RESPONSE_CANCEL) { gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), FALSE); return; } } g_settings_set_boolean (EPHY_SETTINGS_MAIN, EPHY_PREFS_ENABLE_CARET_BROWSING, active); }
Java
<?php /** * Kumbia Enterprise Framework * * LICENSE * * This source file is subject to the New BSD License that is bundled * with this package in the file docs/LICENSE.txt. * * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@loudertechnology.com so we can send you a copy immediately. * * @category Kumbia * @package Generator * @subpackage GeneratorReport * @copyright Copyright (c) 2008-2009 Louder Technology COL. (http://www.loudertechnology.com) * @copyright Copyright (c) 2005-2008 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com) * @license New BSD License * @version $Id: Doc.php 82 2009-09-13 21:06:31Z gutierrezandresfelipe $ */ /** * DocGenerator * * Generador de Reportes en Word * * @category Kumbia * @package Generator * @subpackage GeneratorReport * @copyright Copyright (c) 2008-2009 Louder Technology COL. (http://www.loudertechnology.com) * @copyright Copyright (c) 2005-2008 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com) * @license New BSD License */ function doc($result, $sumArray, $title, $weightArray, $headerArray){ $config = CoreConfig::readAppConfig(); $active_app = Router::getApplication(); $file = md5(uniqid()); $content = " <html> <head> <title>REPORTE DE ".i18n::strtoupper($title)."</title> </head> <body bgcolor='white'> <div style='font-size:20px;font-family:Verdana;color:#000000'>".i18n::strtoupper($config->application->name)."</div>\n <div style='font-size:18px;font-family:Verdana;color:#000000'>REPORTE DE ".i18n::strtoupper($title)."</div>\n <div style='font-size:18px;font-family:Verdana;color:#000000'>".date("Y-m-d H:i")."</div>\n <br/> <table cellspacing='0' border=1 style='border:1px solid #969696'> "; $content.= "<tr bgcolor='#F2F2F2'>\n"; $numberHeaders = count($headerArray); for($i=0;$i<$numberHeaders;++$i){ $content.= "<th style='font-family:Verdana;font-size:12px'>".$headerArray[$i]."</th>\n"; } $content.= "</tr>\n"; $l = 5; foreach($result as $row){ $content.= "<tr bgcolor='white'>\n"; $numberColumns = count($row); for($i=0;$i<$numberColumns;++$i){ if(is_numeric($row[$i])){ $content.= "<td style='font-family:Verdana;font-size:12px' align='center'>{$row[$i]}</td>"; } else { $content.= "<td style='font-family:Verdana;font-size:12px'>{$row[$i]}&nbsp;</td>"; } } $content.= "</tr>\n"; ++$l; } file_put_contents("public/temp/$file.doc", $content); if(isset($raw_output)){ echo "<script type='text/javascript'> window.open('".Core::getInstancePath()."temp/".$file.".doc', null); </script>"; } else { Generator::formsPrint("<script type='text/javascript'> window.open('".Core::getInstancePath()."temp/".$file.".doc', null); </script>"); } }
Java
#ifndef __INC_USERVIA_H #define __INC_USERVIA_H #include "via.h" extern VIA uservia; extern ALLEGRO_USTR *prt_clip_str; extern FILE *prt_fp; void uservia_reset(void); void uservia_write(uint16_t addr, uint8_t val); uint8_t uservia_read(uint16_t addr); void uservia_savestate(FILE *f); void uservia_loadstate(FILE *f); extern uint8_t lpt_dac; void uservia_set_ca1(int level); void uservia_set_ca2(int level); void uservia_set_cb1(int level); void uservia_set_cb2(int level); #endif
Java
// Locale support (codecvt) -*- C++ -*- // Copyright (C) 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/>. #include <codecvt> #include <cstring> // std::memcpy, std::memcmp #include <bits/stl_algobase.h> // std::max #ifdef _GLIBCXX_USE_C99_STDINT_TR1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace { // Largest code point that fits in a single UTF-16 code unit. const char32_t max_single_utf16_unit = 0xFFFF; const char32_t max_code_point = 0x10FFFF; template<typename Elem> struct range { Elem* next; Elem* end; Elem operator*() const { return *next; } range& operator++() { ++next; return *this; } size_t size() const { return end - next; } }; // Multibyte sequences can have "header" consisting of Byte Order Mark const unsigned char utf8_bom[3] = { 0xEF, 0xBB, 0xBF }; const unsigned char utf16_bom[4] = { 0xFE, 0xFF }; const unsigned char utf16le_bom[4] = { 0xFF, 0xFE }; template<size_t N> inline bool write_bom(range<char>& to, const unsigned char (&bom)[N]) { if (to.size() < N) return false; memcpy(to.next, bom, N); to.next += N; return true; } // If generate_header is set in mode write out UTF-8 BOM. bool write_utf8_bom(range<char>& to, codecvt_mode mode) { if (mode & generate_header) return write_bom(to, utf8_bom); return true; } // If generate_header is set in mode write out the UTF-16 BOM indicated // by whether little_endian is set in mode. bool write_utf16_bom(range<char16_t>& to, codecvt_mode mode) { if (mode & generate_header) { if (!to.size()) return false; auto* bom = (mode & little_endian) ? utf16le_bom : utf16_bom; std::memcpy(to.next, bom, 2); ++to.next; } return true; } template<size_t N> inline bool read_bom(range<const char>& from, const unsigned char (&bom)[N]) { if (from.size() >= N && !memcmp(from.next, bom, N)) { from.next += N; return true; } return false; } // If consume_header is set in mode update from.next to after any BOM. void read_utf8_bom(range<const char>& from, codecvt_mode mode) { if (mode & consume_header) read_bom(from, utf8_bom); } // If consume_header is set in mode update from.next to after any BOM. // Return little_endian iff the UTF-16LE BOM was present. codecvt_mode read_utf16_bom(range<const char16_t>& from, codecvt_mode mode) { if (mode & consume_header && from.size()) { if (*from.next == 0xFEFF) ++from.next; else if (*from.next == 0xFFFE) { ++from.next; return little_endian; } } return {}; } // Read a codepoint from a UTF-8 multibyte sequence. // Updates from.next if the codepoint is not greater than maxcode. // Returns -1 if there is an invalid or incomplete multibyte character. char32_t read_utf8_code_point(range<const char>& from, unsigned long maxcode) { size_t avail = from.size(); if (avail == 0) return -1; unsigned char c1 = from.next[0]; // https://en.wikipedia.org/wiki/UTF-8#Sample_code if (c1 < 0x80) { ++from.next; return c1; } else if (c1 < 0xC2) // continuation or overlong 2-byte sequence return -1; else if (c1 < 0xE0) // 2-byte sequence { if (avail < 2) return -1; unsigned char c2 = from.next[1]; if ((c2 & 0xC0) != 0x80) return -1; char32_t c = (c1 << 6) + c2 - 0x3080; if (c <= maxcode) from.next += 2; return c; } else if (c1 < 0xF0) // 3-byte sequence { if (avail < 3) return -1; unsigned char c2 = from.next[1]; if ((c2 & 0xC0) != 0x80) return -1; if (c1 == 0xE0 && c2 < 0xA0) // overlong return -1; unsigned char c3 = from.next[2]; if ((c3 & 0xC0) != 0x80) return -1; char32_t c = (c1 << 12) + (c2 << 6) + c3 - 0xE2080; if (c <= maxcode) from.next += 3; return c; } else if (c1 < 0xF5) // 4-byte sequence { if (avail < 4) return -1; unsigned char c2 = from.next[1]; if ((c2 & 0xC0) != 0x80) return -1; if (c1 == 0xF0 && c2 < 0x90) // overlong return -1; if (c1 == 0xF4 && c2 >= 0x90) // > U+10FFFF return -1; unsigned char c3 = from.next[2]; if ((c3 & 0xC0) != 0x80) return -1; unsigned char c4 = from.next[3]; if ((c4 & 0xC0) != 0x80) return -1; char32_t c = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4 - 0x3C82080; if (c <= maxcode) from.next += 4; return c; } else // > U+10FFFF return -1; } bool write_utf8_code_point(range<char>& to, char32_t code_point) { if (code_point < 0x80) { if (to.size() < 1) return false; *to.next++ = code_point; } else if (code_point <= 0x7FF) { if (to.size() < 2) return false; *to.next++ = (code_point >> 6) + 0xC0; *to.next++ = (code_point & 0x3F) + 0x80; } else if (code_point <= 0xFFFF) { if (to.size() < 3) return false; *to.next++ = (code_point >> 12) + 0xE0; *to.next++ = ((code_point >> 6) & 0x3F) + 0x80; *to.next++ = (code_point & 0x3F) + 0x80; } else if (code_point <= 0x10FFFF) { if (to.size() < 4) return false; *to.next++ = (code_point >> 18) + 0xF0; *to.next++ = ((code_point >> 12) & 0x3F) + 0x80; *to.next++ = ((code_point >> 6) & 0x3F) + 0x80; *to.next++ = (code_point & 0x3F) + 0x80; } else return false; return true; } inline char16_t adjust_byte_order(char16_t c, codecvt_mode mode) { #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ return (mode & little_endian) ? __builtin_bswap16(c) : c; #else return (mode & little_endian) ? c : __builtin_bswap16(c); #endif } // Read a codepoint from a UTF-16 multibyte sequence. // The sequence's endianness is indicated by (mode & little_endian). // Updates from.next if the codepoint is not greater than maxcode. // Returns -1 if there is an incomplete multibyte character. char32_t read_utf16_code_point(range<const char16_t>& from, unsigned long maxcode, codecvt_mode mode) { int inc = 1; char32_t c = adjust_byte_order(from.next[0], mode); if (c >= 0xD800 && c <= 0xDBFF) { if (from.size() < 2) return -1; const char16_t c2 = adjust_byte_order(from.next[1], mode); if (c2 >= 0xDC00 && c2 <= 0xDFFF) { c = (c << 10) + c2 - 0x35FDC00; inc = 2; } } if (c <= maxcode) from.next += inc; return c; } template<typename C> bool write_utf16_code_point(range<C>& to, char32_t codepoint, codecvt_mode mode) { static_assert(sizeof(C) >= 2, "a code unit must be at least 16-bit"); if (codepoint < max_single_utf16_unit) { if (to.size() > 0) { *to.next = codepoint; ++to.next; return true; } } else if (to.size() > 1) { // Algorithm from http://www.unicode.org/faq/utf_bom.html#utf16-4 const char32_t LEAD_OFFSET = 0xD800 - (0x10000 >> 10); char16_t lead = LEAD_OFFSET + (codepoint >> 10); char16_t trail = 0xDC00 + (codepoint & 0x3FF); to.next[0] = adjust_byte_order(lead, mode); to.next[1] = adjust_byte_order(trail, mode); to.next += 2; return true; } return false; } // utf8 -> ucs4 codecvt_base::result ucs4_in(range<const char>& from, range<char32_t>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { read_utf8_bom(from, mode); while (from.size() && to.size()) { const char32_t codepoint = read_utf8_code_point(from, maxcode); if (codepoint == char32_t(-1)) break; if (codepoint > maxcode) return codecvt_base::error; *to.next++ = codepoint; } return from.size() ? codecvt_base::partial : codecvt_base::ok; } // ucs4 -> utf8 codecvt_base::result ucs4_out(range<const char32_t>& from, range<char>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { if (!write_utf8_bom(to, mode)) return codecvt_base::partial; while (from.size()) { const char32_t c = from.next[0]; if (c > maxcode) return codecvt_base::error; if (!write_utf8_code_point(to, c)) return codecvt_base::partial; ++from.next; } return codecvt_base::ok; } // utf16 -> ucs4 codecvt_base::result ucs4_in(range<const char16_t>& from, range<char32_t>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { if (read_utf16_bom(from, mode) == little_endian) mode = codecvt_mode(mode & little_endian); while (from.size() && to.size()) { const char32_t codepoint = read_utf16_code_point(from, maxcode, mode); if (codepoint == char32_t(-1)) break; if (codepoint > maxcode) return codecvt_base::error; *to.next++ = codepoint; } return from.size() ? codecvt_base::partial : codecvt_base::ok; } // ucs4 -> utf16 codecvt_base::result ucs4_out(range<const char32_t>& from, range<char16_t>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { if (!write_utf16_bom(to, mode)) return codecvt_base::partial; while (from.size()) { const char32_t c = from.next[0]; if (c > maxcode) return codecvt_base::error; if (!write_utf16_code_point(to, c, mode)) return codecvt_base::partial; ++from.next; } return codecvt_base::ok; } // utf8 -> utf16 template<typename C> codecvt_base::result utf16_in(range<const char>& from, range<C>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { read_utf8_bom(from, mode); while (from.size() && to.size()) { const char* first = from.next; if ((unsigned char)*first >= 0xF0 && to.size() < 2) return codecvt_base::partial; const char32_t codepoint = read_utf8_code_point(from, maxcode); if (codepoint == char32_t(-1)) return codecvt_base::partial; if (codepoint > maxcode) return codecvt_base::error; if (!write_utf16_code_point(to, codepoint, mode)) { from.next = first; return codecvt_base::partial; } } return codecvt_base::ok; } // utf16 -> utf8 template<typename C> codecvt_base::result utf16_out(range<const C>& from, range<char>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { if (!write_utf8_bom(to, mode)) return codecvt_base::partial; while (from.size()) { char32_t c = from.next[0]; int inc = 1; if (c >= 0xD800 && c <= 0xDBFF) // start of surrogate pair { if (from.size() < 2) return codecvt_base::ok; // stop converting at this point const char32_t c2 = from.next[1]; if (c2 >= 0xDC00 && c2 <= 0xDFFF) { inc = 2; c = (c << 10) + c2 - 0x35FDC00; } else return codecvt_base::error; } if (c > maxcode) return codecvt_base::error; if (!write_utf8_code_point(to, c)) return codecvt_base::partial; from.next += inc; } return codecvt_base::ok; } // return pos such that [begin,pos) is valid UTF-16 string no longer than max const char* utf16_span(const char* begin, const char* end, size_t max, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { range<const char> from{ begin, end }; read_utf8_bom(from, mode); size_t count = 0; while (count+1 < max) { char32_t c = read_utf8_code_point(from, maxcode); if (c == char32_t(-1)) break; else if (c > max_single_utf16_unit) ++count; ++count; } if (count+1 == max) // take one more character if it fits in a single unit read_utf8_code_point(from, std::max(max_single_utf16_unit, maxcode)); return from.next; } // utf8 -> ucs2 codecvt_base::result ucs2_in(range<const char>& from, range<char16_t>& to, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { return utf16_in(from, to, std::max(max_single_utf16_unit, maxcode), mode); } // ucs2 -> utf8 codecvt_base::result ucs2_out(range<const char16_t>& from, range<char>& to, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { return utf16_out(from, to, std::max(max_single_utf16_unit, maxcode), mode); } // ucs2 -> utf16 codecvt_base::result ucs2_out(range<const char16_t>& from, range<char16_t>& to, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { if (!write_utf16_bom(to, mode)) return codecvt_base::partial; while (from.size() && to.size()) { char16_t c = from.next[0]; if (c >= 0xD800 && c <= 0xDBFF) // start of surrogate pair return codecvt_base::error; if (c > maxcode) return codecvt_base::error; *to.next++ = adjust_byte_order(c, mode); ++from.next; } return from.size() == 0 ? codecvt_base::ok : codecvt_base::partial; } // utf16 -> ucs2 codecvt_base::result ucs2_in(range<const char16_t>& from, range<char16_t>& to, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { if (read_utf16_bom(from, mode) == little_endian) mode = codecvt_mode(mode & little_endian); maxcode = std::max(max_single_utf16_unit, maxcode); while (from.size() && to.size()) { const char32_t c = read_utf16_code_point(from, maxcode, mode); if (c == char32_t(-1)) break; if (c >= maxcode) return codecvt_base::error; *to.next++ = c; } return from.size() == 0 ? codecvt_base::ok : codecvt_base::partial; } const char16_t* ucs2_span(const char16_t* begin, const char16_t* end, size_t max, char32_t maxcode, codecvt_mode mode) { range<const char16_t> from{ begin, end }; if (read_utf16_bom(from, mode) == little_endian) mode = codecvt_mode(mode & little_endian); maxcode = std::max(max_single_utf16_unit, maxcode); char32_t c = 0; while (max-- && c <= maxcode) c = read_utf16_code_point(from, maxcode, mode); return from.next; } const char* ucs2_span(const char* begin, const char* end, size_t max, char32_t maxcode, codecvt_mode mode) { range<const char> from{ begin, end }; read_utf8_bom(from, mode); maxcode = std::max(max_single_utf16_unit, maxcode); char32_t c = 0; while (max-- && c <= maxcode) c = read_utf8_code_point(from, maxcode); return from.next; } // return pos such that [begin,pos) is valid UCS-4 string no longer than max const char* ucs4_span(const char* begin, const char* end, size_t max, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { range<const char> from{ begin, end }; read_utf8_bom(from, mode); char32_t c = 0; while (max-- && c <= maxcode) c = read_utf8_code_point(from, maxcode); return from.next; } // return pos such that [begin,pos) is valid UCS-4 string no longer than max const char16_t* ucs4_span(const char16_t* begin, const char16_t* end, size_t max, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { range<const char16_t> from{ begin, end }; if (read_utf16_bom(from, mode) == little_endian) mode = codecvt_mode(mode & little_endian); char32_t c = 0; while (max-- && c <= maxcode) c = read_utf16_code_point(from, maxcode, mode); return from.next; } } // Define members of codecvt<char16_t, char, mbstate_t> specialization. // Converts from UTF-8 to UTF-16. locale::id codecvt<char16_t, char, mbstate_t>::id; codecvt<char16_t, char, mbstate_t>::~codecvt() { } codecvt_base::result codecvt<char16_t, char, mbstate_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char16_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = utf16_out(from, to); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result codecvt<char16_t, char, mbstate_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; // we don't use mbstate_t for the unicode facets } codecvt_base::result codecvt<char16_t, char, mbstate_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char16_t> to{ __to, __to_end }; #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ codecvt_mode mode = {}; #else codecvt_mode mode = little_endian; #endif auto res = utf16_in(from, to, max_code_point, mode); __from_next = from.next; __to_next = to.next; return res; } int codecvt<char16_t, char, mbstate_t>::do_encoding() const throw() { return 0; } bool codecvt<char16_t, char, mbstate_t>::do_always_noconv() const throw() { return false; } int codecvt<char16_t, char, mbstate_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = utf16_span(__from, __end, __max); return __end - __from; } int codecvt<char16_t, char, mbstate_t>::do_max_length() const throw() { // Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit, // whereas 4 byte sequences require two 16-bit code units. return 3; } // Define members of codecvt<char32_t, char, mbstate_t> specialization. // Converts from UTF-8 to UTF-32 (aka UCS-4). locale::id codecvt<char32_t, char, mbstate_t>::id; codecvt<char32_t, char, mbstate_t>::~codecvt() { } codecvt_base::result codecvt<char32_t, char, mbstate_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char32_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = ucs4_out(from, to); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result codecvt<char32_t, char, mbstate_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result codecvt<char32_t, char, mbstate_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char32_t> to{ __to, __to_end }; auto res = ucs4_in(from, to); __from_next = from.next; __to_next = to.next; return res; } int codecvt<char32_t, char, mbstate_t>::do_encoding() const throw() { return 0; } bool codecvt<char32_t, char, mbstate_t>::do_always_noconv() const throw() { return false; } int codecvt<char32_t, char, mbstate_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = ucs4_span(__from, __end, __max); return __end - __from; } int codecvt<char32_t, char, mbstate_t>::do_max_length() const throw() { return 4; } // Define members of codecvt_utf8<char16_t> base class implementation. // Converts from UTF-8 to UCS-2. __codecvt_utf8_base<char16_t>::~__codecvt_utf8_base() { } codecvt_base::result __codecvt_utf8_base<char16_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char16_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = ucs2_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_base<char16_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_base<char16_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char16_t> to{ __to, __to_end }; auto res = ucs2_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_base<char16_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_base<char16_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_base<char16_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = ucs2_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_base<char16_t>::do_max_length() const throw() { return 3; } // Define members of codecvt_utf8<char32_t> base class implementation. // Converts from UTF-8 to UTF-32 (aka UCS-4). __codecvt_utf8_base<char32_t>::~__codecvt_utf8_base() { } codecvt_base::result __codecvt_utf8_base<char32_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char32_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = ucs4_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_base<char32_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_base<char32_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char32_t> to{ __to, __to_end }; auto res = ucs4_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_base<char32_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_base<char32_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_base<char32_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = ucs4_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_base<char32_t>::do_max_length() const throw() { return 4; } #ifdef _GLIBCXX_USE_WCHAR_T // Define members of codecvt_utf8<wchar_t> base class implementation. // Converts from UTF-8 to UCS-2 or UCS-4 depending on sizeof(wchar_t). __codecvt_utf8_base<wchar_t>::~__codecvt_utf8_base() { } codecvt_base::result __codecvt_utf8_base<wchar_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<char> to{ __to, __to_end }; #if __SIZEOF_WCHAR_T__ == 2 range<const char16_t> from{ reinterpret_cast<const char16_t*>(__from), reinterpret_cast<const char16_t*>(__from_end) }; auto res = ucs2_out(from, to, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 range<const char32_t> from{ reinterpret_cast<const char32_t*>(__from), reinterpret_cast<const char32_t*>(__from_end) }; auto res = ucs4_out(from, to, _M_maxcode, _M_mode); #else return codecvt_base::error; #endif __from_next = reinterpret_cast<const wchar_t*>(from.next); __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_base<wchar_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_base<wchar_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; #if __SIZEOF_WCHAR_T__ == 2 range<char16_t> to{ reinterpret_cast<char16_t*>(__to), reinterpret_cast<char16_t*>(__to_end) }; auto res = ucs2_in(from, to, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 range<char32_t> to{ reinterpret_cast<char32_t*>(__to), reinterpret_cast<char32_t*>(__to_end) }; auto res = ucs4_in(from, to, _M_maxcode, _M_mode); #else return codecvt_base::error; #endif __from_next = from.next; __to_next = reinterpret_cast<wchar_t*>(to.next); return res; } int __codecvt_utf8_base<wchar_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_base<wchar_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_base<wchar_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { #if __SIZEOF_WCHAR_T__ == 2 __end = ucs2_span(__from, __end, __max, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 __end = ucs4_span(__from, __end, __max, _M_maxcode, _M_mode); #else __end = __from; #endif return __end - __from; } int __codecvt_utf8_base<wchar_t>::do_max_length() const throw() { return 4; } #endif // Define members of codecvt_utf16<char16_t> base class implementation. // Converts from UTF-16 to UCS-2. __codecvt_utf16_base<char16_t>::~__codecvt_utf16_base() { } codecvt_base::result __codecvt_utf16_base<char16_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char16_t> from{ __from, __from_end }; range<char16_t> to{ reinterpret_cast<char16_t*>(__to), reinterpret_cast<char16_t*>(__to_end) }; auto res = ucs2_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = reinterpret_cast<char*>(to.next); return res; } codecvt_base::result __codecvt_utf16_base<char16_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf16_base<char16_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char16_t> from{ reinterpret_cast<const char16_t*>(__from), reinterpret_cast<const char16_t*>(__from_end) }; range<char16_t> to{ __to, __to_end }; auto res = ucs2_in(from, to, _M_maxcode, _M_mode); __from_next = reinterpret_cast<const char*>(from.next); __to_next = to.next; return res; } int __codecvt_utf16_base<char16_t>::do_encoding() const throw() { return 1; } bool __codecvt_utf16_base<char16_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf16_base<char16_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { auto next = reinterpret_cast<const char16_t*>(__from); next = ucs2_span(next, reinterpret_cast<const char16_t*>(__end), __max, _M_maxcode, _M_mode); return reinterpret_cast<const char*>(next) - __from; } int __codecvt_utf16_base<char16_t>::do_max_length() const throw() { return 3; } // Define members of codecvt_utf16<char32_t> base class implementation. // Converts from UTF-16 to UTF-32 (aka UCS-4). __codecvt_utf16_base<char32_t>::~__codecvt_utf16_base() { } codecvt_base::result __codecvt_utf16_base<char32_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char32_t> from{ __from, __from_end }; range<char16_t> to{ reinterpret_cast<char16_t*>(__to), reinterpret_cast<char16_t*>(__to_end) }; auto res = ucs4_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = reinterpret_cast<char*>(to.next); return res; } codecvt_base::result __codecvt_utf16_base<char32_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf16_base<char32_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char16_t> from{ reinterpret_cast<const char16_t*>(__from), reinterpret_cast<const char16_t*>(__from_end) }; range<char32_t> to{ __to, __to_end }; auto res = ucs4_in(from, to, _M_maxcode, _M_mode); __from_next = reinterpret_cast<const char*>(from.next); __to_next = to.next; return res; } int __codecvt_utf16_base<char32_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf16_base<char32_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf16_base<char32_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { auto next = reinterpret_cast<const char16_t*>(__from); next = ucs4_span(next, reinterpret_cast<const char16_t*>(__end), __max, _M_maxcode, _M_mode); return reinterpret_cast<const char*>(next) - __from; } int __codecvt_utf16_base<char32_t>::do_max_length() const throw() { return 3; } #ifdef _GLIBCXX_USE_WCHAR_T // Define members of codecvt_utf16<wchar_t> base class implementation. // Converts from UTF-8 to UCS-2 or UCS-4 depending on sizeof(wchar_t). __codecvt_utf16_base<wchar_t>::~__codecvt_utf16_base() { } codecvt_base::result __codecvt_utf16_base<wchar_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<char> to{ __to, __to_end }; #if __SIZEOF_WCHAR_T__ == 2 range<const char16_t> from{ reinterpret_cast<const char16_t*>(__from), reinterpret_cast<const char16_t*>(__from_end) }; auto res = ucs2_out(from, to, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 range<const char32_t> from{ reinterpret_cast<const char32_t*>(__from), reinterpret_cast<const char32_t*>(__from_end) }; auto res = ucs4_out(from, to, _M_maxcode, _M_mode); #else return codecvt_base::error; #endif __from_next = reinterpret_cast<const wchar_t*>(from.next); __to_next = to.next; return res; } codecvt_base::result __codecvt_utf16_base<wchar_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf16_base<wchar_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; #if __SIZEOF_WCHAR_T__ == 2 range<char16_t> to{ reinterpret_cast<char16_t*>(__to), reinterpret_cast<char16_t*>(__to_end) }; auto res = ucs2_in(from, to, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 range<char32_t> to{ reinterpret_cast<char32_t*>(__to), reinterpret_cast<char32_t*>(__to_end) }; auto res = ucs4_in(from, to, _M_maxcode, _M_mode); #else return codecvt_base::error; #endif __from_next = from.next; __to_next = reinterpret_cast<wchar_t*>(to.next); return res; } int __codecvt_utf16_base<wchar_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf16_base<wchar_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf16_base<wchar_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { auto next = reinterpret_cast<const char16_t*>(__from); #if __SIZEOF_WCHAR_T__ == 2 next = ucs2_span(next, reinterpret_cast<const char16_t*>(__end), __max, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 next = ucs4_span(next, reinterpret_cast<const char16_t*>(__end), __max, _M_maxcode, _M_mode); #endif return reinterpret_cast<const char*>(next) - __from; } int __codecvt_utf16_base<wchar_t>::do_max_length() const throw() { return 4; } #endif // Define members of codecvt_utf8_utf16<char16_t> base class implementation. // Converts from UTF-8 to UTF-16. __codecvt_utf8_utf16_base<char16_t>::~__codecvt_utf8_utf16_base() { } codecvt_base::result __codecvt_utf8_utf16_base<char16_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char16_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = utf16_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_utf16_base<char16_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_utf16_base<char16_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char16_t> to{ __to, __to_end }; auto res = utf16_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_utf16_base<char16_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_utf16_base<char16_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_utf16_base<char16_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_utf16_base<char16_t>::do_max_length() const throw() { // Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit, // whereas 4 byte sequences require two 16-bit code units. return 3; } // Define members of codecvt_utf8_utf16<char32_t> base class implementation. // Converts from UTF-8 to UTF-16. __codecvt_utf8_utf16_base<char32_t>::~__codecvt_utf8_utf16_base() { } codecvt_base::result __codecvt_utf8_utf16_base<char32_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char32_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = utf16_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_utf16_base<char32_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_utf16_base<char32_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char32_t> to{ __to, __to_end }; auto res = utf16_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_utf16_base<char32_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_utf16_base<char32_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_utf16_base<char32_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_utf16_base<char32_t>::do_max_length() const throw() { // Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit, // whereas 4 byte sequences require two 16-bit code units. return 3; } #ifdef _GLIBCXX_USE_WCHAR_T // Define members of codecvt_utf8_utf16<wchar_t> base class implementation. // Converts from UTF-8 to UTF-16. __codecvt_utf8_utf16_base<wchar_t>::~__codecvt_utf8_utf16_base() { } codecvt_base::result __codecvt_utf8_utf16_base<wchar_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const wchar_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = utf16_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_utf16_base<wchar_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_utf16_base<wchar_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<wchar_t> to{ __to, __to_end }; auto res = utf16_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_utf16_base<wchar_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_utf16_base<wchar_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_utf16_base<wchar_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_utf16_base<wchar_t>::do_max_length() const throw() { // Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit, // whereas 4 byte sequences require two 16-bit code units. return 3; } #endif inline template class __codecvt_abstract_base<char16_t, char, mbstate_t>; inline template class __codecvt_abstract_base<char32_t, char, mbstate_t>; template class codecvt_byname<char16_t, char, mbstate_t>; template class codecvt_byname<char32_t, char, mbstate_t>; _GLIBCXX_END_NAMESPACE_VERSION } #endif // _GLIBCXX_USE_C99_STDINT_TR1
Java
/** * Provides a DataSchema implementation which can be used to work with * delimited text data. * * @module dataschema * @submodule dataschema-text */ /** Provides a DataSchema implementation which can be used to work with delimited text data. See the `apply` method for usage. @class DataSchema.Text @extends DataSchema.Base @static **/ var Lang = Y.Lang, isString = Lang.isString, isUndef = Lang.isUndefined, SchemaText = { //////////////////////////////////////////////////////////////////////// // // DataSchema.Text static methods // //////////////////////////////////////////////////////////////////////// /** Applies a schema to a string of delimited data, returning a normalized object with results in the `results` property. The `meta` property of the response object is present for consistency, but is assigned an empty object. If the input data is absent or not a string, an `error` property will be added. Use _schema.resultDelimiter_ and _schema.fieldDelimiter_ to instruct `apply` how to split up the string into an array of data arrays for processing. Use _schema.resultFields_ to specify the keys in the generated result objects in `response.results`. The key:value pairs will be assigned in the order of the _schema.resultFields_ array, assuming the values in the data records are defined in the same order. _schema.resultFields_ field identifiers are objects with the following properties: * `key` : <strong>(required)</strong> The property name you want the data value assigned to in the result object (String) * `parser`: A function or the name of a function on `Y.Parsers` used to convert the input value into a normalized type. Parser functions are passed the value as input and are expected to return a value. If no value parsing is needed, you can use just the desired property name string as the field identifier instead of an object (see example below). @example // Process simple csv var schema = { resultDelimiter: "\n", fieldDelimiter: ",", resultFields: [ 'fruit', 'color' ] }, data = "Banana,yellow\nOrange,orange\nEggplant,purple"; var response = Y.DataSchema.Text.apply(schema, data); // response.results[0] is { fruit: "Banana", color: "yellow" } // Use parsers schema.resultFields = [ { key: 'fruit', parser: function (val) { return val.toUpperCase(); } }, 'color' // mix and match objects and strings ]; response = Y.DataSchema.Text.apply(schema, data); // response.results[0] is { fruit: "BANANA", color: "yellow" } @method apply @param {Object} schema Schema to apply. Supported configuration properties are: @param {String} schema.resultDelimiter Character or character sequence that marks the end of one record and the start of another. @param {String} [schema.fieldDelimiter] Character or character sequence that marks the end of a field and the start of another within the same record. @param {Array} [schema.resultFields] Field identifiers to assign values in the response records. See above for details. @param {String} data Text data. @return {Object} An Object with properties `results` and `meta` @static **/ apply: function(schema, data) { var data_in = data, data_out = { results: [], meta: {} }; if (isString(data) && schema && isString(schema.resultDelimiter)) { // Parse results data data_out = SchemaText._parseResults.call(this, schema, data_in, data_out); } else { Y.log("Text data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-text"); data_out.error = new Error("Text schema parse failure"); } return data_out; }, /** * Schema-parsed list of results from full data * * @method _parseResults * @param schema {Array} Schema to parse against. * @param text_in {String} Text to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Parsed data object. * @static * @protected */ _parseResults: function(schema, text_in, data_out) { var resultDelim = schema.resultDelimiter, fieldDelim = isString(schema.fieldDelimiter) && schema.fieldDelimiter, fields = schema.resultFields || [], results = [], parse = Y.DataSchema.Base.parse, results_in, fields_in, result, item, field, key, value, i, j; // Delete final delimiter at end of string if there if (text_in.slice(-resultDelim.length) === resultDelim) { text_in = text_in.slice(0, -resultDelim.length); } // Split into results results_in = text_in.split(schema.resultDelimiter); if (fieldDelim) { for (i = results_in.length - 1; i >= 0; --i) { result = {}; item = results_in[i]; fields_in = item.split(schema.fieldDelimiter); for (j = fields.length - 1; j >= 0; --j) { field = fields[j]; key = (!isUndef(field.key)) ? field.key : field; // FIXME: unless the key is an array index, this test // for fields_in[key] is useless. value = (!isUndef(fields_in[key])) ? fields_in[key] : fields_in[j]; result[key] = parse.call(this, value, field); } results[i] = result; } } else { results = results_in; } data_out.results = results; return data_out; } }; Y.DataSchema.Text = Y.mix(SchemaText, Y.DataSchema.Base);
Java
# -*- coding: utf-8 -*- # # Watermarks documentation build configuration file, created by # sphinx-quickstart on Tue Apr 8 16:49:39 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os src_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'src') sys.path.insert(0, src_dir) import watermarks # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Watermarks' copyright = u'2014, Vladimir Chovanec' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = watermarks.__version__ # The full version, including alpha/beta/rc tags. release = watermarks.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Watermarksdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Watermarks.tex', u'Watermarks Documentation', u'Vladimir Chovanec', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'watermarks', u'Watermarks Documentation', [u'Vladimir Chovanec'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Watermarks', u'Watermarks Documentation', u'Vladimir Chovanec', 'Watermarks', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
Java
<?php /* * Page that is shown to the user when the plugin was not correctly installed. * This is just a fallback in case something went wrong somewhere. * Maybe it just needs to be removed alltogether. */ function gwolle_gb_installSplash() { ?> <div class="wrap"> <div id="icon-gwolle-gb"><br /></div> <h1>Gwolle-GB &#8212; <?php _e('Installation','gwolle-gb'); ?> </h1> <div> <?php if ( !isset($_REQUEST['install_gwolle_gb']) || $_REQUEST['install_gwolle_gb'] != 'install_gwolle_gb') { _e('Welcome!<br>It seems that either you\'re using this plugin for the first time or you\'ve deleted all settings.<br>However, to use this plugin we have to setup the database tables. Good for you, we\'ve made this as easy as possible.<br>All you\'ve got to do is click on that button below, and that\'s it.','gwolle-gb'); ?> <br /><br /> <div> <form action="<?php echo $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page']; ?>" method="POST"> <input type="hidden" id="install_gwolle_gb" name="install_gwolle_gb" value="install_gwolle_gb" /> <input type="submit" class="button button-primary" value="<?php esc_attr_e('Sure, let\'s do this!', 'gwolle-gb'); ?>"> </form> </div> <?php } elseif ( isset($_REQUEST['install_gwolle_gb']) && $_REQUEST['install_gwolle_gb'] == 'install_gwolle_gb' && !get_option('gwolle_gb_version') ) { // perform installation gwolle_gb_install(); echo sprintf( __('Allright, we\'re done. <a href="%s">Click here to continue...</a>', 'gwolle-gb'), $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'] ); } else { echo sprintf( __('It looks like there has been an error. <a href="%s">Click here to continue...</a>', 'gwolle-gb'), $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'] ); } ?> </div> </div> <?php }
Java
/* This file was generated by SableCC (http://www.sablecc.org/). */ package se.sics.kola.node; public abstract class PResource extends Node { // Empty body }
Java
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #define _CRT_SECURE_NO_WARNINGS #pragma once #include "targetver.h" #include <stdio.h> #include <stdlib.h> #include <tchar.h> #include <direct.h> #include <string.h> // TODO: reference additional headers your program requires here
Java
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 2.2 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2009 | +--------------------------------------------------------------------+ | 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. | | | | 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 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 | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2009 * $Id$ * */ require_once 'CRM/Core/Selector/Base.php'; require_once 'CRM/Core/Selector/API.php'; require_once 'CRM/Utils/Pager.php'; require_once 'CRM/Utils/Sort.php'; require_once 'CRM/Contact/BAO/Query.php'; /** * This class is used to retrieve and display a range of * contacts that match the given criteria (specifically for * results of advanced search options. * */ class CRM_Grant_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API { /** * This defines two actions- View and Edit. * * @var array * @static */ static $_links = null; /** * we use desc to remind us what that column is, name is used in the tpl * * @var array * @static */ static $_columnHeaders; /** * Properties of contact we're interested in displaying * @var array * @static */ static $_properties = array( 'contact_id', 'contact_type', 'sort_name', 'grant_id', 'grant_status_id', 'grant_type_id', 'grant_amount_total', 'grant_amount_requested', 'grant_amount_granted', 'grant_application_received_date', 'grant_report_received', 'grant_money_transfer_date', ); /** * are we restricting ourselves to a single contact * * @access protected * @var boolean */ protected $_single = false; /** * are we restricting ourselves to a single contact * * @access protected * @var boolean */ protected $_limit = null; /** * what context are we being invoked from * * @access protected * @var string */ protected $_context = null; /** * queryParams is the array returned by exportValues called on * the HTML_QuickForm_Controller for that page. * * @var array * @access protected */ public $_queryParams; /** * represent the type of selector * * @var int * @access protected */ protected $_action; /** * The additional clause that we restrict the search with * * @var string */ protected $_grantClause = null; /** * The query object * * @var string */ protected $_query; /** * Class constructor * * @param array $queryParams array of parameters for query * @param int $action - action of search basic or advanced. * @param string $grantClause if the caller wants to further restrict the search * @param boolean $single are we dealing only with one contact? * @param int $limit how many participations do we want returned * * @return CRM_Contact_Selector * @access public */ function __construct(&$queryParams, $action = CRM_Core_Action::NONE, $grantClause = null, $single = false, $limit = null, $context = 'search' ) { // submitted form values $this->_queryParams =& $queryParams; $this->_single = $single; $this->_limit = $limit; $this->_context = $context; $this->_grantClause = $grantClause; // type of selector $this->_action = $action; $this->_query =& new CRM_Contact_BAO_Query( $this->_queryParams, null, null, false, false, CRM_Contact_BAO_Query::MODE_GRANT ); }//end of constructor /** * This method returns the links that are given for each search row. * currently the links added for each row are * * - View * - Edit * * @return array * @access public * */ static function &links() { $cid = CRM_Utils_Request::retrieve('cid', 'Integer', $this); if (!(self::$_links)) { self::$_links = array( CRM_Core_Action::VIEW => array( 'name' => ts('View'), 'url' => 'civicrm/contact/view/grant', 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=grant', 'title' => ts('View Grant'), ), CRM_Core_Action::UPDATE => array( 'name' => ts('Edit'), 'url' => 'civicrm/contact/view/grant', 'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%', 'title' => ts('Edit Grant'), ), ); if ( $cid ) { $deleteExtra = ts('Are you sure you want to delete this grant?'); $delLink = array( CRM_Core_Action::DELETE => array( 'name' => ts('Delete'), 'url' => 'civicrm/contact/view/grant', 'qs' => 'action=delete&reset=1&cid=%%cid%%&id=%%id%%&selectedChild=grant', 'extra' => 'onclick = "if (confirm(\'' . $deleteExtra . '\') ) this.href+=\'&amp;confirmed=1\'; else return false;"', 'title' => ts('Delete Grant') ) ); self::$_links = self::$_links + $delLink ; } } return self::$_links; } //end of function /** * getter for array of the parameters required for creating pager. * * @param * @access public */ function getPagerParams($action, &$params) { $params['status'] = ts('Grant') . ' %%StatusMessage%%'; $params['csvString'] = null; if ( $this->_limit ) { $params['rowCount'] = $this->_limit; } else { $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT; } $params['buttonTop'] = 'PagerTopButton'; $params['buttonBottom'] = 'PagerBottomButton'; } //end of function /** * Returns total number of rows for the query. * * @param * @return int Total number of rows * @access public */ function getTotalCount($action) { return $this->_query->searchQuery( 0, 0, null, true, false, false, false, false, $this->_grantClause ); } /** * returns all the rows in the given offset and rowCount * * @param enum $action the action being performed * @param int $offset the row number to start from * @param int $rowCount the number of rows to return * @param string $sort the sql string that describes the sort order * @param enum $output what should the result set include (web/email/csv) * * @return int the total number of rows for this action */ function &getRows($action, $offset, $rowCount, $sort, $output = null) { $result = $this->_query->searchQuery( $offset, $rowCount, $sort, false, false, false, false, false, $this->_grantClause ); // process the result of the query $rows = array( ); // check is the user has view/edit permission $permission = CRM_Core_Permission::VIEW; if ( CRM_Core_Permission::check( 'edit grants' ) ) { $permission = CRM_Core_Permission::EDIT; } require_once 'CRM/Grant/PseudoConstant.php'; $grantStatus = array( ); $grantStatus = CRM_Grant_PseudoConstant::grantStatus( ); $grantType = array( ); $grantType = CRM_Grant_PseudoConstant::grantType( ); $mask = CRM_Core_Action::mask( $permission ); while ($result->fetch()) { $row = array(); // the columns we are interested in foreach (self::$_properties as $property) { if ( isset( $result->$property ) ) { $row[$property] = $result->$property; } } //fix status display $row['grant_status'] = $grantStatus[$row['grant_status_id']]; $row['grant_type'] = $grantType[$row['grant_type_id']]; if ($this->_context == 'search') { $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->grant_id; } $row['action'] = CRM_Core_Action::formLink( self::links(), $mask, array( 'id' => $result->grant_id, 'cid' => $result->contact_id, 'cxt' => $this->_context ) ); require_once( 'CRM/Contact/BAO/Contact/Utils.php' ); $row['contact_type' ] = CRM_Contact_BAO_Contact_Utils::getImage( $result->contact_type ); $rows[] = $row; } return $rows; } /** * @return array $qill which contains an array of strings * @access public */ // the current internationalisation is bad, but should more or less work // for most of "European" languages public function getQILL( ) { return $this->_query->qill( ); } /** * returns the column headers as an array of tuples: * (name, sortName (key to the sort array)) * * @param string $action the action being performed * @param enum $output what should the result set include (web/email/csv) * * @return array the column headers that need to be displayed * @access public */ public function &getColumnHeaders( $action = null, $output = null ) { if ( ! isset( self::$_columnHeaders ) ) { self::$_columnHeaders = array( array('name' => ts('Status'), 'sort' => 'grant_status_id', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Type'), 'sort' => 'grant_type_id', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Amount Requested'), 'sort' => 'grant_amount_total', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Amount Granted'), 'sort' => 'grant_amount_granted', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Application Received'), 'sort' => 'grant_application_received_date', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Report Received'), 'sort' => 'grant_report_received', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Money Transferred'), 'sort' => 'money_transfer_date', 'direction' => CRM_Utils_Sort::DONTCARE, ), array('desc' => ts('Actions') ), ); if ( ! $this->_single ) { $pre = array( array('desc' => ts('Contact Type') ), array( 'name' => ts('Name'), 'sort' => 'sort_name', 'direction' => CRM_Utils_Sort::ASCENDING, ) ); self::$_columnHeaders = array_merge( $pre, self::$_columnHeaders ); } } return self::$_columnHeaders; } function &getQuery( ) { return $this->_query; } /** * name of export file. * * @param string $output type of output * @return string name of the file */ function getExportFileName( $output = 'csv') { return ts('CiviCRM Grant Search'); } }//end of class
Java
/* * Copyright (C) 2013 Andreas Steffen * HSR Hochschule fuer Technik Rapperswil * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. */ #include "tcg_swid_attr_tag_inv.h" #include <pa_tnc/pa_tnc_msg.h> #include <bio/bio_writer.h> #include <bio/bio_reader.h> #include <utils/debug.h> typedef struct private_tcg_swid_attr_tag_inv_t private_tcg_swid_attr_tag_inv_t; /** * SWID Tag Inventory * see section 4.10 of TCG TNC SWID Message and Attributes for IF-M * * 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reserved | Tag ID Count | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Request ID Copy | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | EID Epoch | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Last EID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Unique Sequence ID Length |Unique Sequence ID (var length)| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Tag Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Tag (Variable) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ #define SWID_TAG_INV_SIZE 16 #define SWID_TAG_INV_RESERVED 0x00 /** * Private data of an tcg_swid_attr_tag_inv_t object. */ struct private_tcg_swid_attr_tag_inv_t { /** * Public members of tcg_swid_attr_tag_inv_t */ tcg_swid_attr_tag_inv_t public; /** * Vendor-specific attribute type */ pen_type_t type; /** * Attribute value */ chunk_t value; /** * Noskip flag */ bool noskip_flag; /** * Request ID */ u_int32_t request_id; /** * Event ID Epoch */ u_int32_t eid_epoch; /** * Last Event ID */ u_int32_t last_eid; /** * SWID Tag Inventory */ swid_inventory_t *inventory; /** * Reference count */ refcount_t ref; }; METHOD(pa_tnc_attr_t, get_type, pen_type_t, private_tcg_swid_attr_tag_inv_t *this) { return this->type; } METHOD(pa_tnc_attr_t, get_value, chunk_t, private_tcg_swid_attr_tag_inv_t *this) { return this->value; } METHOD(pa_tnc_attr_t, get_noskip_flag, bool, private_tcg_swid_attr_tag_inv_t *this) { return this->noskip_flag; } METHOD(pa_tnc_attr_t, set_noskip_flag,void, private_tcg_swid_attr_tag_inv_t *this, bool noskip) { this->noskip_flag = noskip; } METHOD(pa_tnc_attr_t, build, void, private_tcg_swid_attr_tag_inv_t *this) { bio_writer_t *writer; swid_tag_t *tag; enumerator_t *enumerator; if (this->value.ptr) { return; } writer = bio_writer_create(SWID_TAG_INV_SIZE); writer->write_uint8 (writer, SWID_TAG_INV_RESERVED); writer->write_uint24(writer, this->inventory->get_count(this->inventory)); writer->write_uint32(writer, this->request_id); writer->write_uint32(writer, this->eid_epoch); writer->write_uint32(writer, this->last_eid); enumerator = this->inventory->create_enumerator(this->inventory); while (enumerator->enumerate(enumerator, &tag)) { writer->write_data16(writer, tag->get_unique_seq_id(tag)); writer->write_data32(writer, tag->get_encoding(tag)); } enumerator->destroy(enumerator); this->value = writer->extract_buf(writer); writer->destroy(writer); } METHOD(pa_tnc_attr_t, process, status_t, private_tcg_swid_attr_tag_inv_t *this, u_int32_t *offset) { bio_reader_t *reader; u_int32_t tag_count; u_int8_t reserved; chunk_t tag_encoding, unique_seq_id; swid_tag_t *tag; if (this->value.len < SWID_TAG_INV_SIZE) { DBG1(DBG_TNC, "insufficient data for SWID Tag Inventory"); *offset = 0; return FAILED; } reader = bio_reader_create(this->value); reader->read_uint8 (reader, &reserved); reader->read_uint24(reader, &tag_count); reader->read_uint32(reader, &this->request_id); reader->read_uint32(reader, &this->eid_epoch); reader->read_uint32(reader, &this->last_eid); *offset = SWID_TAG_INV_SIZE; while (tag_count--) { if (!reader->read_data16(reader, &unique_seq_id)) { DBG1(DBG_TNC, "insufficient data for Unique Sequence ID"); return FAILED; } *offset += 2 + unique_seq_id.len; if (!reader->read_data32(reader, &tag_encoding)) { DBG1(DBG_TNC, "insufficient data for Tag"); return FAILED; } *offset += 4 + tag_encoding.len; tag = swid_tag_create(tag_encoding, unique_seq_id); this->inventory->add(this->inventory, tag); } reader->destroy(reader); return SUCCESS; } METHOD(pa_tnc_attr_t, get_ref, pa_tnc_attr_t*, private_tcg_swid_attr_tag_inv_t *this) { ref_get(&this->ref); return &this->public.pa_tnc_attribute; } METHOD(pa_tnc_attr_t, destroy, void, private_tcg_swid_attr_tag_inv_t *this) { if (ref_put(&this->ref)) { this->inventory->destroy(this->inventory); free(this->value.ptr); free(this); } } METHOD(tcg_swid_attr_tag_inv_t, get_request_id, u_int32_t, private_tcg_swid_attr_tag_inv_t *this) { return this->request_id; } METHOD(tcg_swid_attr_tag_inv_t, get_last_eid, u_int32_t, private_tcg_swid_attr_tag_inv_t *this, u_int32_t *eid_epoch) { if (eid_epoch) { *eid_epoch = this->eid_epoch; } return this->last_eid; } METHOD(tcg_swid_attr_tag_inv_t, get_inventory, swid_inventory_t*, private_tcg_swid_attr_tag_inv_t *this) { return this->inventory; } /** * Described in header. */ pa_tnc_attr_t *tcg_swid_attr_tag_inv_create(u_int32_t request_id, u_int32_t eid_epoch, u_int32_t eid, swid_inventory_t *inventory) { private_tcg_swid_attr_tag_inv_t *this; INIT(this, .public = { .pa_tnc_attribute = { .get_type = _get_type, .get_value = _get_value, .get_noskip_flag = _get_noskip_flag, .set_noskip_flag = _set_noskip_flag, .build = _build, .process = _process, .get_ref = _get_ref, .destroy = _destroy, }, .get_request_id = _get_request_id, .get_last_eid = _get_last_eid, .get_inventory = _get_inventory, }, .type = { PEN_TCG, TCG_SWID_TAG_INVENTORY }, .request_id = request_id, .eid_epoch = eid_epoch, .last_eid = eid, .inventory = inventory, .ref = 1, ); return &this->public.pa_tnc_attribute; } /** * Described in header. */ pa_tnc_attr_t *tcg_swid_attr_tag_inv_create_from_data(chunk_t data) { private_tcg_swid_attr_tag_inv_t *this; INIT(this, .public = { .pa_tnc_attribute = { .get_type = _get_type, .get_value = _get_value, .get_noskip_flag = _get_noskip_flag, .set_noskip_flag = _set_noskip_flag, .build = _build, .process = _process, .get_ref = _get_ref, .destroy = _destroy, }, .get_request_id = _get_request_id, .get_last_eid = _get_last_eid, .get_inventory = _get_inventory, }, .type = { PEN_TCG, TCG_SWID_TAG_INVENTORY }, .value = chunk_clone(data), .inventory = swid_inventory_create(TRUE), .ref = 1, ); return &this->public.pa_tnc_attribute; }
Java
<?php /** * @file * Drupal site-specific configuration file. * * IMPORTANT NOTE: * This file may have been set to read-only by the Drupal installation program. * If you make changes to this file, be sure to protect it again after making * your modifications. Failure to remove write permissions to this file is a * security risk. * * The configuration file to be loaded is based upon the rules below. However * if the multisite aliasing file named sites/sites.php is present, it will be * loaded, and the aliases in the array $sites will override the default * directory rules below. See sites/example.sites.php for more information about * aliases. * * The configuration directory will be discovered by stripping the website's * hostname from left to right and pathname from right to left. The first * configuration file found will be used and any others will be ignored. If no * other configuration file is found then the default configuration file at * 'sites/default' will be used. * * For example, for a fictitious site installed at * http://www.drupal.org:8080/mysite/test/, the 'settings.php' file is searched * for in the following directories: * * - sites/8080.www.drupal.org.mysite.test * - sites/www.drupal.org.mysite.test * - sites/drupal.org.mysite.test * - sites/org.mysite.test * * - sites/8080.www.drupal.org.mysite * - sites/www.drupal.org.mysite * - sites/drupal.org.mysite * - sites/org.mysite * * - sites/8080.www.drupal.org * - sites/www.drupal.org * - sites/drupal.org * - sites/org * * - sites/default * * Note that if you are installing on a non-standard port number, prefix the * hostname with that number. For example, * http://www.drupal.org:8080/mysite/test/ could be loaded from * sites/8080.www.drupal.org.mysite.test/. * * @see example.sites.php * @see conf_path() */ /** * Database settings: * * The $databases array specifies the database connection or * connections that Drupal may use. Drupal is able to connect * to multiple databases, including multiple types of databases, * during the same request. * * Each database connection is specified as an array of settings, * similar to the following: * @code * array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'port' => 3306, * 'prefix' => 'myprefix_', * 'collation' => 'utf8_general_ci', * ); * @endcode * * The "driver" property indicates what Drupal database driver the * connection should use. This is usually the same as the name of the * database type, such as mysql or sqlite, but not always. The other * properties will vary depending on the driver. For SQLite, you must * specify a database file name in a directory that is writable by the * webserver. For most other drivers, you must specify a * username, password, host, and database name. * * Some database engines support transactions. In order to enable * transaction support for a given database, set the 'transactions' key * to TRUE. To disable it, set it to FALSE. Note that the default value * varies by driver. For MySQL, the default is FALSE since MyISAM tables * do not support transactions. * * For each database, you may optionally specify multiple "target" databases. * A target database allows Drupal to try to send certain queries to a * different database if it can but fall back to the default connection if not. * That is useful for master/slave replication, as Drupal may try to connect * to a slave server when appropriate and if one is not available will simply * fall back to the single master server. * * The general format for the $databases array is as follows: * @code * $databases['default']['default'] = $info_array; * $databases['default']['slave'][] = $info_array; * $databases['default']['slave'][] = $info_array; * $databases['extra']['default'] = $info_array; * @endcode * * In the above example, $info_array is an array of settings described above. * The first line sets a "default" database that has one master database * (the second level default). The second and third lines create an array * of potential slave databases. Drupal will select one at random for a given * request as needed. The fourth line creates a new database with a name of * "extra". * * For a single database configuration, the following is sufficient: * @code * $databases['default']['default'] = array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => 'main_', * 'collation' => 'utf8_general_ci', * ); * @endcode * * You can optionally set prefixes for some or all database table names * by using the 'prefix' setting. If a prefix is specified, the table * name will be prepended with its value. Be sure to use valid database * characters only, usually alphanumeric and underscore. If no prefixes * are desired, leave it as an empty string ''. * * To have all database names prefixed, set 'prefix' as a string: * @code * 'prefix' => 'main_', * @endcode * To provide prefixes for specific tables, set 'prefix' as an array. * The array's keys are the table names and the values are the prefixes. * The 'default' element is mandatory and holds the prefix for any tables * not specified elsewhere in the array. Example: * @code * 'prefix' => array( * 'default' => 'main_', * 'users' => 'shared_', * 'sessions' => 'shared_', * 'role' => 'shared_', * 'authmap' => 'shared_', * ), * @endcode * You can also use a reference to a schema/database as a prefix. This may be * useful if your Drupal installation exists in a schema that is not the default * or you want to access several databases from the same code base at the same * time. * Example: * @code * 'prefix' => array( * 'default' => 'main.', * 'users' => 'shared.', * 'sessions' => 'shared.', * 'role' => 'shared.', * 'authmap' => 'shared.', * ); * @endcode * NOTE: MySQL and SQLite's definition of a schema is a database. * * Advanced users can add or override initial commands to execute when * connecting to the database server, as well as PDO connection settings. For * example, to enable MySQL SELECT queries to exceed the max_join_size system * variable, and to reduce the database connection timeout to 5 seconds: * * @code * $databases['default']['default'] = array( * 'init_commands' => array( * 'big_selects' => 'SET SQL_BIG_SELECTS=1', * ), * 'pdo' => array( * PDO::ATTR_TIMEOUT => 5, * ), * ); * @endcode * * WARNING: These defaults are designed for database portability. Changing them * may cause unexpected behavior, including potential data loss. * * @see DatabaseConnection_mysql::__construct * @see DatabaseConnection_pgsql::__construct * @see DatabaseConnection_sqlite::__construct * * Database configuration format: * @code * $databases['default']['default'] = array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => '', * ); * $databases['default']['default'] = array( * 'driver' => 'pgsql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => '', * ); * $databases['default']['default'] = array( * 'driver' => 'sqlite', * 'database' => '/path/to/databasefilename', * ); * @endcode */ $databases = array ( 'default' => array ( 'default' => array ( 'database' => 'm4c_wiki', 'username' => 'root', 'password' => '', 'host' => 'localhost', 'port' => '', 'driver' => 'mysql', 'prefix' => '', ), ), ); /** * Access control for update.php script. * * If you are updating your Drupal installation using the update.php script but * are not logged in using either an account with the "Administer software * updates" permission or the site maintenance account (the account that was * created during installation), you will need to modify the access check * statement below. Change the FALSE to a TRUE to disable the access check. * After finishing the upgrade, be sure to open this file again and change the * TRUE back to a FALSE! */ $update_free_access = FALSE; /** * Salt for one-time login links and cancel links, form tokens, etc. * * This variable will be set to a random value by the installer. All one-time * login links will be invalidated if the value is changed. Note that if your * site is deployed on a cluster of web servers, you must ensure that this * variable has the same value on each server. If this variable is empty, a hash * of the serialized database credentials will be used as a fallback salt. * * For enhanced security, you may set this variable to a value using the * contents of a file outside your docroot that is never saved together * with any backups of your Drupal files and database. * * Example: * $drupal_hash_salt = file_get_contents('/home/example/salt.txt'); * */ $drupal_hash_salt = 'SVoT4MlhRtpQNiBHSKMQJQAuaidUYAtUQ6X80sP8q7U'; /** * Base URL (optional). * * If Drupal is generating incorrect URLs on your site, which could * be in HTML headers (links to CSS and JS files) or visible links on pages * (such as in menus), uncomment the Base URL statement below (remove the * leading hash sign) and fill in the absolute URL to your Drupal installation. * * You might also want to force users to use a given domain. * See the .htaccess file for more information. * * Examples: * $base_url = 'http://www.example.com'; * $base_url = 'http://www.example.com:8888'; * $base_url = 'http://www.example.com/drupal'; * $base_url = 'https://www.example.com:8888/drupal'; * * It is not allowed to have a trailing slash; Drupal will add it * for you. */ # $base_url = 'http://www.example.com'; // NO trailing slash! /** * PHP settings: * * To see what PHP settings are possible, including whether they can be set at * runtime (by using ini_set()), read the PHP documentation: * http://www.php.net/manual/en/ini.list.php * See drupal_environment_initialize() in includes/bootstrap.inc for required * runtime settings and the .htaccess file for non-runtime settings. Settings * defined there should not be duplicated here so as to avoid conflict issues. */ /** * Some distributions of Linux (most notably Debian) ship their PHP * installations with garbage collection (gc) disabled. Since Drupal depends on * PHP's garbage collection for clearing sessions, ensure that garbage * collection occurs by using the most common settings. */ ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 100); /** * Set session lifetime (in seconds), i.e. the time from the user's last visit * to the active session may be deleted by the session garbage collector. When * a session is deleted, authenticated users are logged out, and the contents * of the user's $_SESSION variable is discarded. */ ini_set('session.gc_maxlifetime', 200000); /** * Set session cookie lifetime (in seconds), i.e. the time from the session is * created to the cookie expires, i.e. when the browser is expected to discard * the cookie. The value 0 means "until the browser is closed". */ ini_set('session.cookie_lifetime', 2000000); /** * If you encounter a situation where users post a large amount of text, and * the result is stripped out upon viewing but can still be edited, Drupal's * output filter may not have sufficient memory to process it. If you * experience this issue, you may wish to uncomment the following two lines * and increase the limits of these variables. For more information, see * http://php.net/manual/en/pcre.configuration.php. */ # ini_set('pcre.backtrack_limit', 200000); # ini_set('pcre.recursion_limit', 200000); /** * Drupal automatically generates a unique session cookie name for each site * based on its full domain name. If you have multiple domains pointing at the * same Drupal site, you can either redirect them all to a single domain (see * comment in .htaccess), or uncomment the line below and specify their shared * base domain. Doing so assures that users remain logged in as they cross * between your various domains. Make sure to always start the $cookie_domain * with a leading dot, as per RFC 2109. */ # $cookie_domain = '.example.com'; /** * Variable overrides: * * To override specific entries in the 'variable' table for this site, * set them here. You usually don't need to use this feature. This is * useful in a configuration file for a vhost or directory, rather than * the default settings.php. Any configuration setting from the 'variable' * table can be given a new value. Note that any values you provide in * these variable overrides will not be modifiable from the Drupal * administration interface. * * The following overrides are examples: * - site_name: Defines the site's name. * - theme_default: Defines the default theme for this site. * - anonymous: Defines the human-readable name of anonymous users. * Remove the leading hash signs to enable. */ # $conf['site_name'] = 'My Drupal site'; # $conf['theme_default'] = 'garland'; # $conf['anonymous'] = 'Visitor'; /** * A custom theme can be set for the offline page. This applies when the site * is explicitly set to maintenance mode through the administration page or when * the database is inactive due to an error. It can be set through the * 'maintenance_theme' key. The template file should also be copied into the * theme. It is located inside 'modules/system/maintenance-page.tpl.php'. * Note: This setting does not apply to installation and update pages. */ # $conf['maintenance_theme'] = 'bartik'; /** * Reverse Proxy Configuration: * * Reverse proxy servers are often used to enhance the performance * of heavily visited sites and may also provide other site caching, * security, or encryption benefits. In an environment where Drupal * is behind a reverse proxy, the real IP address of the client should * be determined such that the correct client IP address is available * to Drupal's logging, statistics, and access management systems. In * the most simple scenario, the proxy server will add an * X-Forwarded-For header to the request that contains the client IP * address. However, HTTP headers are vulnerable to spoofing, where a * malicious client could bypass restrictions by setting the * X-Forwarded-For header directly. Therefore, Drupal's proxy * configuration requires the IP addresses of all remote proxies to be * specified in $conf['reverse_proxy_addresses'] to work correctly. * * Enable this setting to get Drupal to determine the client IP from * the X-Forwarded-For header (or $conf['reverse_proxy_header'] if set). * If you are unsure about this setting, do not have a reverse proxy, * or Drupal operates in a shared hosting environment, this setting * should remain commented out. * * In order for this setting to be used you must specify every possible * reverse proxy IP address in $conf['reverse_proxy_addresses']. * If a complete list of reverse proxies is not available in your * environment (for example, if you use a CDN) you may set the * $_SERVER['REMOTE_ADDR'] variable directly in settings.php. * Be aware, however, that it is likely that this would allow IP * address spoofing unless more advanced precautions are taken. */ # $conf['reverse_proxy'] = TRUE; /** * Specify every reverse proxy IP address in your environment. * This setting is required if $conf['reverse_proxy'] is TRUE. */ # $conf['reverse_proxy_addresses'] = array('a.b.c.d', ...); /** * Set this value if your proxy server sends the client IP in a header * other than X-Forwarded-For. */ # $conf['reverse_proxy_header'] = 'HTTP_X_CLUSTER_CLIENT_IP'; /** * Page caching: * * By default, Drupal sends a "Vary: Cookie" HTTP header for anonymous page * views. This tells a HTTP proxy that it may return a page from its local * cache without contacting the web server, if the user sends the same Cookie * header as the user who originally requested the cached page. Without "Vary: * Cookie", authenticated users would also be served the anonymous page from * the cache. If the site has mostly anonymous users except a few known * editors/administrators, the Vary header can be omitted. This allows for * better caching in HTTP proxies (including reverse proxies), i.e. even if * clients send different cookies, they still get content served from the cache. * However, authenticated users should access the site directly (i.e. not use an * HTTP proxy, and bypass the reverse proxy if one is used) in order to avoid * getting cached pages from the proxy. */ # $conf['omit_vary_cookie'] = TRUE; /** * CSS/JS aggregated file gzip compression: * * By default, when CSS or JS aggregation and clean URLs are enabled Drupal will * store a gzip compressed (.gz) copy of the aggregated files. If this file is * available then rewrite rules in the default .htaccess file will serve these * files to browsers that accept gzip encoded content. This allows pages to load * faster for these users and has minimal impact on server load. If you are * using a webserver other than Apache httpd, or a caching reverse proxy that is * configured to cache and compress these files itself you may want to uncomment * one or both of the below lines, which will prevent gzip files being stored. */ # $conf['css_gzip_compression'] = FALSE; # $conf['js_gzip_compression'] = FALSE; /** * String overrides: * * To override specific strings on your site with or without enabling the Locale * module, add an entry to this list. This functionality allows you to change * a small number of your site's default English language interface strings. * * Remove the leading hash signs to enable. */ # $conf['locale_custom_strings_en'][''] = array( # 'forum' => 'Discussion board', # '@count min' => '@count minutes', # ); /** * * IP blocking: * * To bypass database queries for denied IP addresses, use this setting. * Drupal queries the {blocked_ips} table by default on every page request * for both authenticated and anonymous users. This allows the system to * block IP addresses from within the administrative interface and before any * modules are loaded. However on high traffic websites you may want to avoid * this query, allowing you to bypass database access altogether for anonymous * users under certain caching configurations. * * If using this setting, you will need to add back any IP addresses which * you may have blocked via the administrative interface. Each element of this * array represents a blocked IP address. Uncommenting the array and leaving it * empty will have the effect of disabling IP blocking on your site. * * Remove the leading hash signs to enable. */ # $conf['blocked_ips'] = array( # 'a.b.c.d', # ); /** * Fast 404 pages: * * Drupal can generate fully themed 404 pages. However, some of these responses * are for images or other resource files that are not displayed to the user. * This can waste bandwidth, and also generate server load. * * The options below return a simple, fast 404 page for URLs matching a * specific pattern: * - 404_fast_paths_exclude: A regular expression to match paths to exclude, * such as images generated by image styles, or dynamically-resized images. * If you need to add more paths, you can add '|path' to the expression. * - 404_fast_paths: A regular expression to match paths that should return a * simple 404 page, rather than the fully themed 404 page. If you don't have * any aliases ending in htm or html you can add '|s?html?' to the expression. * - 404_fast_html: The html to return for simple 404 pages. * * Add leading hash signs if you would like to disable this functionality. */ $conf['404_fast_paths_exclude'] = '/\/(?:styles)\//'; $conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i'; $conf['404_fast_html'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>'; /** * By default the page request process will return a fast 404 page for missing * files if they match the regular expression set in '404_fast_paths' and not * '404_fast_paths_exclude' above. 404 errors will simultaneously be logged in * the Drupal system log. * * You can choose to return a fast 404 page earlier for missing pages (as soon * as settings.php is loaded) by uncommenting the line below. This speeds up * server response time when loading 404 error pages and prevents the 404 error * from being logged in the Drupal system log. In order to prevent valid pages * such as image styles and other generated content that may match the * '404_fast_html' regular expression from returning 404 errors, it is necessary * to add them to the '404_fast_paths_exclude' regular expression above. Make * sure that you understand the effects of this feature before uncommenting the * line below. */ # drupal_fast_404(); /** * External access proxy settings: * * If your site must access the Internet via a web proxy then you can enter * the proxy settings here. Currently only basic authentication is supported * by using the username and password variables. The proxy_user_agent variable * can be set to NULL for proxies that require no User-Agent header or to a * non-empty string for proxies that limit requests to a specific agent. The * proxy_exceptions variable is an array of host names to be accessed directly, * not via proxy. */ # $conf['proxy_server'] = ''; # $conf['proxy_port'] = 8080; # $conf['proxy_username'] = ''; # $conf['proxy_password'] = ''; # $conf['proxy_user_agent'] = ''; # $conf['proxy_exceptions'] = array('127.0.0.1', 'localhost'); /** * Authorized file system operations: * * The Update manager module included with Drupal provides a mechanism for * site administrators to securely install missing updates for the site * directly through the web user interface. On securely-configured servers, * the Update manager will require the administrator to provide SSH or FTP * credentials before allowing the installation to proceed; this allows the * site to update the new files as the user who owns all the Drupal files, * instead of as the user the webserver is running as. On servers where the * webserver user is itself the owner of the Drupal files, the administrator * will not be prompted for SSH or FTP credentials (note that these server * setups are common on shared hosting, but are inherently insecure). * * Some sites might wish to disable the above functionality, and only update * the code directly via SSH or FTP themselves. This setting completely * disables all functionality related to these authorized file operations. * * @see http://drupal.org/node/244924 * * Remove the leading hash signs to disable. */ # $conf['allow_authorize_operations'] = FALSE;
Java
using System; namespace Server.Items { public class LanternHand : BaseLight, IFlipable { public override int LabelNumber { get { return 1011221; } } // lantern public override int LitItemID { get { return ItemID == 0xA471 ? 0xA472 : 0xA476; } } public override int UnlitItemID { get { return ItemID == 0xA472 ? 0xA471 : 0xA475; } } public int NorthID { get { return Burning ? 0xA472 : 0xA471; } } public int WestID { get { return Burning ? 0xA476 : 0xA475; } } [Constructable] public LanternHand() : base(0xA471) { Weight = 1; } public void OnFlip(Mobile from) { if (ItemID == NorthID) ItemID = WestID; else if (ItemID == WestID) ItemID = NorthID; } public LanternHand(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
Java
class Extended_GetIn_EventHandlers { class StaticMGWeapon { class ace_ifa3staticweapon { getIn = "_this call ace_ifa3staticweapon_fnc_getIn"; }; }; class StaticMortar { class ace_ifa3staticweapon { getIn = "_this call ace_ifa3staticweapon_fnc_getIn"; }; }; };
Java
/* HTVMS_WAISProt.c ** ** Adaptation for Lynx by F.Macrides (macrides@sci.wfeb.edu) ** ** 31-May-1994 FM Initial version. ** **----------------------------------------------------------------------*/ /* ** Routines originally from WProt.c -- FM ** **----------------------------------------------------------------------*/ /* WIDE AREA INFORMATION SERVER SOFTWARE: No guarantees or restrictions. See the readme file for the full standard disclaimer. 3.26.90 Harry Morris, morris@think.com 3.30.90 Harry Morris - removed chunk code from WAISSearchAPDU, - added makeWAISQueryType1Query() and readWAISType1Query() which replace makeWAISQueryTerms() and makeWAISQueryDocs(). 4.11.90 HWM - generalized conditional includes (see c-dialect.h) - renamed makeWAISType1Query() to makeWAISTextQuery() renamed readWAISType1Query() to readWAISTextQuery() 5.29.90 TS - fixed bug in makeWAISQueryDocs added CSTFreeWAISFoo functions */ #define _C_WAIS_protocol_ /* This file implements the Z39.50 extensions required for WAIS */ #include <HTUtils.h> #include <HTVMS_WaisUI.h> #include <HTVMS_WaisProt.h> #include <LYLeaks.h> /* very rough estimates of the size of an object */ #define DefWAISInitResponseSize (size_t)200 #define DefWAISSearchSize (size_t)3000 #define DefWAISSearchResponseSize (size_t)6000 #define DefWAISPresentSize (size_t)1000 #define DefWAISPresentResponseSize (size_t)6000 #define DefWAISDocHeaderSize (size_t)500 #define DefWAISShortHeaderSize (size_t)200 #define DefWAISLongHeaderSize (size_t)800 #define DefWAISDocTextSize (size_t)6000 #define DefWAISDocHeadlineSize (size_t)500 #define DefWAISDocCodeSize (size_t)500 #define RESERVE_SPACE_FOR_WAIS_HEADER(len) \ if (*len > 0) \ *len -= header_len; /*----------------------------------------------------------------------*/ static unsigned long userInfoTagSize PARAMS((data_tag tag, unsigned long length)); static unsigned long userInfoTagSize(tag,length) data_tag tag; unsigned long length; /* return the number of bytes required to write the user info tag and length */ { unsigned long size; /* calculate bytes required to represent tag. max tag is 16K */ size = writtenCompressedIntSize(tag); size += writtenCompressedIntSize(length); return(size); } /*----------------------------------------------------------------------*/ static char* writeUserInfoHeader PARAMS((data_tag tag,long infoSize, long estHeaderSize,char* buffer, long* len)); static char* writeUserInfoHeader(tag,infoSize,estHeaderSize,buffer,len) data_tag tag; long infoSize; long estHeaderSize; char* buffer; long* len; /* write the tag and size, making sure the info fits. return the true end of the info (after adjustment) note that the argument infoSize includes estHeaderSize. Note that the argument len is the number of bytes remaining in the buffer. Since we write the tag and size at the begining of the buffer (in space that we reserved) we don't want to pass len the calls which do that writing. */ { long dummyLen = 100; /* plenty of space for a tag and size */ char* buf = buffer; long realSize = infoSize - estHeaderSize; long realHeaderSize = userInfoTagSize(tag,realSize); if (buffer == NULL || *len == 0) return(NULL); /* write the tag */ buf = writeTag(tag,buf,&dummyLen); /* see if the if the header size was correct. if not, we have to shift the info to fit the real header size */ if (estHeaderSize != realHeaderSize) { /* make sure there is enough space */ CHECK_FOR_SPACE_LEFT(realHeaderSize - estHeaderSize,len); memmove(buffer + realHeaderSize,buffer + estHeaderSize,(size_t)(realSize)); } /* write the size */ writeCompressedInteger(realSize,buf,&dummyLen); /* return the true end of buffer */ return(buffer + realHeaderSize + realSize); } /*----------------------------------------------------------------------*/ static char* readUserInfoHeader PARAMS((data_tag* tag,unsigned long* num, char* buffer)); static char* readUserInfoHeader(tag,num,buffer) data_tag* tag; unsigned long* num; char* buffer; /* read the tag and size */ { char* buf = buffer; buf = readTag(tag,buf); buf = readCompressedInteger(num,buf); return(buf); } /*----------------------------------------------------------------------*/ WAISInitResponse* makeWAISInitResponse(chunkCode, chunkIDLen, chunkMarker, highlightMarker, deHighlightMarker, newLineChars) long chunkCode; long chunkIDLen; char* chunkMarker; char* highlightMarker; char* deHighlightMarker; char* newLineChars; /* create a WAIS init response object */ { WAISInitResponse* init = (WAISInitResponse*)s_malloc((size_t)sizeof(WAISInitResponse)); init->ChunkCode = chunkCode; /* note: none are copied! */ init->ChunkIDLength = chunkIDLen; init->ChunkMarker = chunkMarker; init->HighlightMarker = highlightMarker; init->DeHighlightMarker = deHighlightMarker; init->NewlineCharacters = newLineChars; return(init); } /*----------------------------------------------------------------------*/ void freeWAISInitResponse(init) WAISInitResponse* init; /* free an object made with makeWAISInitResponse */ { s_free(init->ChunkMarker); s_free(init->HighlightMarker); s_free(init->DeHighlightMarker); s_free(init->NewlineCharacters); s_free(init); } /*----------------------------------------------------------------------*/ char* writeInitResponseInfo(init,buffer,len) InitResponseAPDU* init; char* buffer; long* len; /* write an init response object */ { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISInitResponseSize); char* buf = buffer + header_len; WAISInitResponse* info = (WAISInitResponse*)init->UserInformationField; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeNum(info->ChunkCode,DT_ChunkCode,buf,len); buf = writeNum(info->ChunkIDLength,DT_ChunkIDLength,buf,len); buf = writeString(info->ChunkMarker,DT_ChunkMarker,buf,len); buf = writeString(info->HighlightMarker,DT_HighlightMarker,buf,len); buf = writeString(info->DeHighlightMarker,DT_DeHighlightMarker,buf,len); buf = writeString(info->NewlineCharacters,DT_NewlineCharacters,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readInitResponseInfo(info,buffer) void** info; char* buffer; /* read an init response object */ { char* buf = buffer; unsigned long size; unsigned long headerSize; long chunkCode,chunkIDLen; data_tag tag1; char* chunkMarker = NULL; char* highlightMarker = NULL; char* deHighlightMarker = NULL; char* newLineChars = NULL; chunkCode = chunkIDLen = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_ChunkCode: buf = readNum(&chunkCode,buf); break; case DT_ChunkIDLength: buf = readNum(&chunkIDLen,buf); break; case DT_ChunkMarker: buf = readString(&chunkMarker,buf); break; case DT_HighlightMarker: buf = readString(&highlightMarker,buf); break; case DT_DeHighlightMarker: buf = readString(&deHighlightMarker,buf); break; case DT_NewlineCharacters: buf = readString(&newLineChars,buf); break; default: s_free(highlightMarker); s_free(deHighlightMarker); s_free(newLineChars); REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISInitResponse(chunkCode,chunkIDLen,chunkMarker, highlightMarker,deHighlightMarker, newLineChars); return(buf); } /*----------------------------------------------------------------------*/ WAISSearch* makeWAISSearch(seedWords, docs, textList, dateFactor, beginDateRange, endDateRange, maxDocsRetrieved) char* seedWords; DocObj** docs; char** textList; long dateFactor; char* beginDateRange; char* endDateRange; long maxDocsRetrieved; /* create a type 3 query object */ { WAISSearch* query = (WAISSearch*)s_malloc((size_t)sizeof(WAISSearch)); query->SeedWords = seedWords; /* not copied! */ query->Docs = docs; /* not copied! */ query->TextList = textList; /* not copied! */ query->DateFactor = dateFactor; query->BeginDateRange = beginDateRange; query->EndDateRange = endDateRange; query->MaxDocumentsRetrieved = maxDocsRetrieved; return(query); } /*----------------------------------------------------------------------*/ void freeWAISSearch(query) WAISSearch* query; /* destroy an object made with makeWAISSearch() */ { void* ptr = NULL; long i; s_free(query->SeedWords); if (query->Docs != NULL) for (i = 0,ptr = (void *)query->Docs[i]; ptr != NULL; ptr = (void *)query->Docs[++i]) freeDocObj((DocObj*)ptr); s_free(query->Docs); if (query->TextList != NULL) /* XXX revisit when textlist is fully defined */ for (i = 0,ptr = (void *)query->TextList[i]; ptr != NULL; ptr = (void *)query->TextList[++i]) s_free(ptr); s_free(query->TextList); s_free(query->BeginDateRange); s_free(query->EndDateRange); s_free(query); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingWholeDocument(docID,type) any* docID; char* type; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->DocumentID = docID; /* not copied! */ doc->Type = type; /* not copied! */ doc->ChunkCode = CT_document; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingLines(docID,type,start,end) any* docID; char* type; long start; long end; /* construct a document object using line chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_line; doc->DocumentID = docID; /* not copied */ doc->Type = type; /* not copied! */ doc->ChunkStart.Pos = start; doc->ChunkEnd.Pos = end; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingBytes(docID,type,start,end) any* docID; char* type; long start; long end; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_byte; doc->DocumentID = docID; /* not copied */ doc->Type = type; /* not copied! */ doc->ChunkStart.Pos = start; doc->ChunkEnd.Pos = end; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingParagraphs(docID,type,start,end) any* docID; char* type; any* start; any* end; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_paragraph; doc->DocumentID = docID; /* not copied */ doc->Type = type; doc->ChunkStart.ID = start; doc->ChunkEnd.ID = end; return(doc); } /*----------------------------------------------------------------------*/ void freeDocObj(doc) DocObj* doc; /* free a docObj */ { freeAny(doc->DocumentID); s_free(doc->Type); if (doc->ChunkCode == CT_paragraph) { freeAny(doc->ChunkStart.ID); freeAny(doc->ChunkEnd.ID); } s_free(doc); } /*----------------------------------------------------------------------*/ static char* writeDocObj PARAMS((DocObj* doc,char* buffer,long* len)); static char* writeDocObj(doc,buffer,len) DocObj* doc; char* buffer; long* len; /* write as little as we can about the doc obj */ { char* buf = buffer; /* we alwasy have to write the id, but its tag depends on if its a chunk */ if (doc->ChunkCode == CT_document) buf = writeAny(doc->DocumentID,DT_DocumentID,buf,len); else buf = writeAny(doc->DocumentID,DT_DocumentIDChunk,buf,len); if (doc->Type != NULL) buf = writeString(doc->Type,DT_TYPE,buf,len); switch (doc->ChunkCode) { case CT_document: /* do nothing - there is no chunk data */ break; case CT_byte: case CT_line: buf = writeNum(doc->ChunkCode,DT_ChunkCode,buf,len); buf = writeNum(doc->ChunkStart.Pos,DT_ChunkStartID,buf,len); buf = writeNum(doc->ChunkEnd.Pos,DT_ChunkEndID,buf,len); break; case CT_paragraph: buf = writeNum(doc->ChunkCode,DT_ChunkCode,buf,len); buf = writeAny(doc->ChunkStart.ID,DT_ChunkStartID,buf,len); buf = writeAny(doc->ChunkEnd.ID,DT_ChunkEndID,buf,len); break; default: panic("Implementation error: unknown chuck type %ld", doc->ChunkCode); break; } return(buf); } /*----------------------------------------------------------------------*/ static char* readDocObj PARAMS((DocObj** doc,char* buffer)); static char* readDocObj(doc,buffer) DocObj** doc; char* buffer; /* read whatever we have about the new document */ { char* buf = buffer; data_tag tag; *doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); tag = peekTag(buf); buf = readAny(&((*doc)->DocumentID),buf); if (tag == DT_DocumentID) { (*doc)->ChunkCode = CT_document; tag = peekTag(buf); if (tag == DT_TYPE) /* XXX depends on DT_TYPE != what comes next */ buf = readString(&((*doc)->Type),buf); /* ChunkStart and ChunkEnd are undefined */ } else if (tag == DT_DocumentIDChunk) { boolean readParagraphs = false; /* for cleanup */ tag = peekTag(buf); if (tag == DT_TYPE) /* XXX depends on DT_TYPE != CT_FOO */ buf = readString(&((*doc)->Type),buf); buf = readNum(&((*doc)->ChunkCode),buf); switch ((*doc)->ChunkCode) { case CT_byte: case CT_line: buf = readNum(&((*doc)->ChunkStart.Pos),buf); buf = readNum(&((*doc)->ChunkEnd.Pos),buf); break; case CT_paragraph: readParagraphs = true; buf = readAny(&((*doc)->ChunkStart.ID),buf); buf = readAny(&((*doc)->ChunkEnd.ID),buf); break; default: freeAny((*doc)->DocumentID); if (readParagraphs) { freeAny((*doc)->ChunkStart.ID); freeAny((*doc)->ChunkEnd.ID); } s_free(doc); REPORT_READ_ERROR(buf); break; } } else { freeAny((*doc)->DocumentID); s_free(*doc); REPORT_READ_ERROR(buf); } return(buf); } /*----------------------------------------------------------------------*/ char* writeSearchInfo(query,buffer,len) SearchAPDU* query; char* buffer; long* len; /* write out a WAIS query (type 1 or 3) */ { if (strcmp(query->QueryType,QT_TextRetrievalQuery) == 0) { return(writeAny((any*)query->Query,DT_Query,buffer,len)); } else { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISSearchSize); char* buf = buffer + header_len; WAISSearch* info = (WAISSearch*)query->Query; unsigned long size; long i; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeString(info->SeedWords,DT_SeedWords,buf,len); if (info->Docs != NULL) { for (i = 0; info->Docs[i] != NULL; i++) { buf = writeDocObj(info->Docs[i],buf,len); } } /* XXX text list */ buf = writeNum(info->DateFactor,DT_DateFactor,buf,len); buf = writeString(info->BeginDateRange,DT_BeginDateRange,buf,len); buf = writeString(info->EndDateRange,DT_EndDateRange,buf,len); buf = writeNum(info->MaxDocumentsRetrieved,DT_MaxDocumentsRetrieved,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } } /*----------------------------------------------------------------------*/ char* readSearchInfo(info,buffer) void** info; char* buffer; /* read a WAIS query (type 1 or 3) */ { data_tag type = peekTag(buffer); if (type == DT_Query) /* this is a type 1 query */ { char* buf = buffer; any* query = NULL; buf = readAny(&query,buf); *info = (void *)query; return(buf); } else /* a type 3 query */ { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; char* seedWords = NULL; char* beginDateRange = NULL; char* endDateRange = NULL; long dateFactor,maxDocsRetrieved; char** textList = NULL; DocObj** docIDs = NULL; DocObj* doc = NULL; long docs = 0; long i; void* ptr = NULL; dateFactor = maxDocsRetrieved = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_SeedWords: buf = readString(&seedWords,buf); break; case DT_DocumentID: case DT_DocumentIDChunk: if (docIDs == NULL) /* create a new doc list */ { docIDs = (DocObj**)s_malloc((size_t)sizeof(DocObj*) * 2); } else /* grow the doc list */ { docIDs = (DocObj**)s_realloc((char*)docIDs,(size_t)(sizeof(DocObj*) * (docs + 2))); } buf = readDocObj(&doc,buf); if (buf == NULL) { s_free(seedWords); s_free(beginDateRange); s_free(endDateRange); if (docIDs != NULL) for (i = 0,ptr = (void *)docIDs[i]; ptr != NULL; ptr = (void *)docIDs[++i]) freeDocObj((DocObj*)ptr); s_free(docIDs); /* XXX should also free textlist when it is fully defined */ } RETURN_ON_NULL(buf); docIDs[docs++] = doc; /* put it in the list */ docIDs[docs] = NULL; break; case DT_TextList: /* XXX */ break; case DT_DateFactor: buf = readNum(&dateFactor,buf); break; case DT_BeginDateRange: buf = readString(&beginDateRange,buf); break; case DT_EndDateRange: buf = readString(&endDateRange,buf); break; case DT_MaxDocumentsRetrieved: buf = readNum(&maxDocsRetrieved,buf); break; default: s_free(seedWords); s_free(beginDateRange); s_free(endDateRange); if (docIDs != NULL) for (i = 0,ptr = (void *)docIDs[i]; ptr != NULL; ptr = (void *)docIDs[++i]) freeDocObj((DocObj*)ptr); s_free(docIDs); /* XXX should also free textlist when it is fully defined */ REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISSearch(seedWords,docIDs,textList, dateFactor,beginDateRange,endDateRange, maxDocsRetrieved); return(buf); } } /*----------------------------------------------------------------------*/ WAISDocumentHeader* makeWAISDocumentHeader(docID, versionNumber, score, bestMatch, docLen, lines, types, source, date, headline, originCity) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; char** types; char* source; char* date; char* headline; char* originCity; /* construct a standard document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentHeader* header = (WAISDocumentHeader*)s_malloc((size_t)sizeof(WAISDocumentHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; header->Types = types; header->Source = source; header->Date = date; header->Headline = headline; header->OriginCity = originCity; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentHeader(header) WAISDocumentHeader* header; { freeAny(header->DocumentID); doList((void**)header->Types,fs_free); /* can't use the macro here ! */ s_free(header->Types); s_free(header->Source); s_free(header->Date); s_free(header->Headline); s_free(header->OriginCity); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentHeader(header,buffer,len) WAISDocumentHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentHeaderGroup , DefWAISDocHeaderSize); char* buf = buffer + header_len; unsigned long size1; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); if (header->Types != NULL) { long size; char* ptr = NULL; long i; buf = writeTag(DT_TYPE_BLOCK,buf,len); for (i = 0,size = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) { long typeSize = strlen(ptr); size += writtenTagSize(DT_TYPE); size += writtenCompressedIntSize(typeSize); size += typeSize; } buf = writeCompressedInteger((unsigned long)size,buf,len); for (i = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) buf = writeString(ptr,DT_TYPE,buf,len); } buf = writeString(header->Source,DT_Source,buf,len); buf = writeString(header->Date,DT_Date,buf,len); buf = writeString(header->Headline,DT_Headline,buf,len); buf = writeString(header->OriginCity,DT_OriginCity,buf,len); /* now write the header and size */ size1 = buf - buffer; buf = writeUserInfoHeader(DT_DocumentHeaderGroup,size1,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentHeader(header,buffer) WAISDocumentHeader** header; char* buffer; { char* buf = buffer; unsigned long size1; unsigned long headerSize; data_tag tag1; any* docID = NULL; long versionNumber,score,bestMatch,docLength,lines; char** types = NULL; char *source = NULL; char *date = NULL; char *headline = NULL; char *originCity = NULL; versionNumber = score = bestMatch = docLength = lines = UNUSED; buf = readUserInfoHeader(&tag1,&size1,buf); headerSize = buf - buffer; while (buf < (buffer + size1 + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; case DT_TYPE_BLOCK: { unsigned long size = -1; long numTypes = 0; buf = readTag(&tag,buf); buf = readCompressedInteger(&size,buf); while (size > 0) { char* type = NULL; char* originalBuf = buf; buf = readString(&type,buf); types = (char**)s_realloc(types,(size_t)(sizeof(char*) * (numTypes + 2))); types[numTypes++] = type; types[numTypes] = NULL; size -= (buf - originalBuf); } } /* FALLTHRU */ case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentHeader(docID,versionNumber,score,bestMatch, docLength,lines,types,source,date,headline, originCity); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentShortHeader* makeWAISDocumentShortHeader(docID, versionNumber, score, bestMatch, docLen, lines) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; /* construct a short document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentShortHeader* header = (WAISDocumentShortHeader*)s_malloc((size_t)sizeof(WAISDocumentShortHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentShortHeader(header) WAISDocumentShortHeader* header; { freeAny(header->DocumentID); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentShortHeader(header,buffer,len) WAISDocumentShortHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentShortHeaderGroup , DefWAISShortHeaderSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentShortHeaderGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentShortHeader(header,buffer) WAISDocumentShortHeader** header; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID = NULL; long versionNumber,score,bestMatch,docLength,lines; versionNumber = score = bestMatch = docLength = lines = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; default: freeAny(docID); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentShortHeader(docID,versionNumber,score,bestMatch, docLength,lines); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentLongHeader* makeWAISDocumentLongHeader(docID, versionNumber, score, bestMatch, docLen, lines, types, source, date, headline, originCity, stockCodes, companyCodes, industryCodes) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; char** types; char* source; char* date; char* headline; char* originCity; char* stockCodes; char* companyCodes; char* industryCodes; /* construct a long document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentLongHeader* header = (WAISDocumentLongHeader*)s_malloc((size_t)sizeof(WAISDocumentLongHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; header->Types = types; header->Source = source; header->Date = date; header->Headline = headline; header->OriginCity = originCity; header->StockCodes = stockCodes; header->CompanyCodes = companyCodes; header->IndustryCodes = industryCodes; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentLongHeader(header) WAISDocumentLongHeader* header; { freeAny(header->DocumentID); doList((void**)header->Types,fs_free); /* can't use the macro here! */ s_free(header->Source); s_free(header->Date); s_free(header->Headline); s_free(header->OriginCity); s_free(header->StockCodes); s_free(header->CompanyCodes); s_free(header->IndustryCodes); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentLongHeader(header,buffer,len) WAISDocumentLongHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentLongHeaderGroup , DefWAISLongHeaderSize); char* buf = buffer + header_len; unsigned long size1; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); if (header->Types != NULL) { long size; char* ptr = NULL; long i; buf = writeTag(DT_TYPE_BLOCK,buf,len); for (i = 0,size = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) { long typeSize = strlen(ptr); size += writtenTagSize(DT_TYPE); size += writtenCompressedIntSize(typeSize); size += typeSize; } buf = writeCompressedInteger((unsigned long)size,buf,len); for (i = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) buf = writeString(ptr,DT_TYPE,buf,len); } buf = writeString(header->Source,DT_Source,buf,len); buf = writeString(header->Date,DT_Date,buf,len); buf = writeString(header->Headline,DT_Headline,buf,len); buf = writeString(header->OriginCity,DT_OriginCity,buf,len); buf = writeString(header->StockCodes,DT_StockCodes,buf,len); buf = writeString(header->CompanyCodes,DT_CompanyCodes,buf,len); buf = writeString(header->IndustryCodes,DT_IndustryCodes,buf,len); /* now write the header and size */ size1 = buf - buffer; buf = writeUserInfoHeader(DT_DocumentLongHeaderGroup,size1,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentLongHeader(header,buffer) WAISDocumentLongHeader** header; char* buffer; { char* buf = buffer; unsigned long size1; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber,score,bestMatch,docLength,lines; char **types; char *source,*date,*headline,*originCity,*stockCodes,*companyCodes,*industryCodes; docID = NULL; versionNumber = score = bestMatch = docLength = lines = UNUSED; types = NULL; source = date = headline = originCity = stockCodes = companyCodes = industryCodes = NULL; buf = readUserInfoHeader(&tag1,&size1,buf); headerSize = buf - buffer; while (buf < (buffer + size1 + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; case DT_TYPE_BLOCK: { unsigned long size = -1; long numTypes = 0; buf = readTag(&tag,buf); readCompressedInteger(&size,buf); while (size > 0) { char* type = NULL; char* originalBuf = buf; buf = readString(&type,buf); types = (char**)s_realloc(types,(size_t)(sizeof(char*) * (numTypes + 2))); types[numTypes++] = type; types[numTypes] = NULL; size -= (buf - originalBuf); } } /* FALLTHRU */ case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; case DT_StockCodes: buf = readString(&stockCodes,buf); break; case DT_CompanyCodes: buf = readString(&companyCodes,buf); break; case DT_IndustryCodes: buf = readString(&industryCodes,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); s_free(stockCodes); s_free(companyCodes); s_free(industryCodes); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentLongHeader(docID,versionNumber,score,bestMatch, docLength,lines,types,source,date,headline, originCity,stockCodes,companyCodes, industryCodes); return(buf); } /*----------------------------------------------------------------------*/ WAISSearchResponse* makeWAISSearchResponse(seedWordsUsed, docHeaders, shortHeaders, longHeaders, text, headlines, codes, diagnostics) char* seedWordsUsed; WAISDocumentHeader** docHeaders; WAISDocumentShortHeader** shortHeaders; WAISDocumentLongHeader** longHeaders; WAISDocumentText** text; WAISDocumentHeadlines** headlines; WAISDocumentCodes** codes; diagnosticRecord** diagnostics; { WAISSearchResponse* response = (WAISSearchResponse*)s_malloc((size_t)sizeof(WAISSearchResponse)); response->SeedWordsUsed = seedWordsUsed; response->DocHeaders = docHeaders; response->ShortHeaders = shortHeaders; response->LongHeaders = longHeaders; response->Text = text; response->Headlines = headlines; response->Codes = codes; response->Diagnostics = diagnostics; return(response); } /*----------------------------------------------------------------------*/ void freeWAISSearchResponse(response) WAISSearchResponse* response; { void* ptr = NULL; long i; s_free(response->SeedWordsUsed); if (response->DocHeaders != NULL) for (i = 0,ptr = (void *)response->DocHeaders[i]; ptr != NULL; ptr = (void *)response->DocHeaders[++i]) freeWAISDocumentHeader((WAISDocumentHeader*)ptr); s_free(response->DocHeaders); if (response->ShortHeaders != NULL) for (i = 0,ptr = (void *)response->ShortHeaders[i]; ptr != NULL; ptr = (void *)response->ShortHeaders[++i]) freeWAISDocumentShortHeader((WAISDocumentShortHeader*)ptr); s_free(response->ShortHeaders); if (response->LongHeaders != NULL) for (i = 0,ptr = (void *)response->LongHeaders[i]; ptr != NULL; ptr = (void *)response->LongHeaders[++i]) freeWAISDocumentLongHeader((WAISDocumentLongHeader*)ptr); s_free(response->LongHeaders); if (response->Text != NULL) for (i = 0,ptr = (void *)response->Text[i]; ptr != NULL; ptr = (void *)response->Text[++i]) freeWAISDocumentText((WAISDocumentText*)ptr); s_free(response->Text); if (response->Headlines != NULL) for (i = 0,ptr = (void *)response->Headlines[i]; ptr != NULL; ptr = (void *)response->Headlines[++i]) freeWAISDocumentHeadlines((WAISDocumentHeadlines*)ptr); s_free(response->Headlines); if (response->Codes != NULL) for (i = 0,ptr = (void *)response->Codes[i]; ptr != NULL; ptr = (void *)response->Codes[++i]) freeWAISDocumentCodes((WAISDocumentCodes*)ptr); s_free(response->Codes); if (response->Diagnostics != NULL) for (i = 0,ptr = (void *)response->Diagnostics[i]; ptr != NULL; ptr = (void *)response->Diagnostics[++i]) freeDiag((diagnosticRecord*)ptr); s_free(response->Diagnostics); s_free(response); } /*----------------------------------------------------------------------*/ char* writeSearchResponseInfo(query,buffer,len) SearchResponseAPDU* query; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISSearchResponseSize); char* buf = buffer + header_len; WAISSearchResponse* info = (WAISSearchResponse*)query->DatabaseDiagnosticRecords; unsigned long size; void* header = NULL; long i; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeString(info->SeedWordsUsed,DT_SeedWordsUsed,buf,len); /* write out all the headers */ if (info->DocHeaders != NULL) { for (i = 0,header = (void *)info->DocHeaders[i]; header != NULL; header = (void *)info->DocHeaders[++i]) buf = writeWAISDocumentHeader((WAISDocumentHeader*)header,buf,len); } if (info->ShortHeaders != NULL) { for (i = 0,header = (void *)info->ShortHeaders[i]; header != NULL; header = (void *)info->ShortHeaders[++i]) buf = writeWAISDocumentShortHeader((WAISDocumentShortHeader*)header,buf,len); } if (info->LongHeaders != NULL) { for (i = 0,header = (void *)info->LongHeaders[i]; header != NULL; header = (void *)info->LongHeaders[++i]) buf = writeWAISDocumentLongHeader((WAISDocumentLongHeader*)header,buf,len); } if (info->Text != NULL) { for (i = 0,header = (void *)info->Text[i]; header != NULL; header = (void *)info->Text[++i]) buf = writeWAISDocumentText((WAISDocumentText*)header,buf,len); } if (info->Headlines != NULL) { for (i = 0,header = (void *)info->Headlines[i]; header != NULL; header = (void *)info->Headlines[++i]) buf = writeWAISDocumentHeadlines((WAISDocumentHeadlines*)header,buf,len); } if (info->Codes != NULL) { for (i = 0,header = (void *)info->Codes[i]; header != NULL;header = (void *)info->Codes[++i]) buf = writeWAISDocumentCodes((WAISDocumentCodes*)header,buf,len); } if (info->Diagnostics != NULL) { for (i = 0, header = (void *)info->Diagnostics[i]; header != NULL; header = (void *)info->Diagnostics[++i]) buf = writeDiag((diagnosticRecord*)header,buf,len); } /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ static void cleanUpWaisSearchResponse PARAMS((char* buf,char* seedWordsUsed, WAISDocumentHeader** docHeaders, WAISDocumentShortHeader** shortHeaders, WAISDocumentLongHeader** longHeaders, WAISDocumentText** text, WAISDocumentHeadlines** headlines, WAISDocumentCodes** codes, diagnosticRecord**diags)); static void cleanUpWaisSearchResponse (buf,seedWordsUsed,docHeaders,shortHeaders, longHeaders,text,headlines,codes,diags) char* buf; char* seedWordsUsed; WAISDocumentHeader** docHeaders; WAISDocumentShortHeader** shortHeaders; WAISDocumentLongHeader** longHeaders; WAISDocumentText** text; WAISDocumentHeadlines** headlines; WAISDocumentCodes** codes; diagnosticRecord** diags; /* if buf is NULL, we have just gotten a read error, and need to clean up any state we have built. If not, then everything is going fine, and we should just hang loose */ { void* ptr = NULL; long i; if (buf == NULL) { s_free(seedWordsUsed); if (docHeaders != NULL) for (i = 0,ptr = (void *)docHeaders[i]; ptr != NULL; ptr = (void *)docHeaders[++i]) freeWAISDocumentHeader((WAISDocumentHeader*)ptr); s_free(docHeaders); if (shortHeaders != NULL) for (i = 0,ptr = (void *)shortHeaders[i]; ptr != NULL; ptr = (void *)shortHeaders[++i]) freeWAISDocumentShortHeader((WAISDocumentShortHeader*)ptr); s_free(shortHeaders); if (longHeaders != NULL) for (i = 0,ptr = (void *)longHeaders[i]; ptr != NULL; ptr = (void *)longHeaders[++i]) freeWAISDocumentLongHeader((WAISDocumentLongHeader*)ptr); s_free(longHeaders); if (text != NULL) for (i = 0,ptr = (void *)text[i]; ptr != NULL; ptr = (void *)text[++i]) freeWAISDocumentText((WAISDocumentText*)ptr); s_free(text); if (headlines != NULL) for (i = 0,ptr = (void *)headlines[i]; ptr != NULL; ptr = (void *)headlines[++i]) freeWAISDocumentHeadlines((WAISDocumentHeadlines*)ptr); s_free(headlines); if (codes != NULL) for (i = 0,ptr = (void *)codes[i]; ptr != NULL; ptr = (void *)codes[++i]) freeWAISDocumentCodes((WAISDocumentCodes*)ptr); s_free(codes); if (diags != NULL) for (i = 0,ptr = (void *)diags[i]; ptr != NULL; ptr = (void *)diags[++i]) freeDiag((diagnosticRecord*)ptr); s_free(diags); } } /*----------------------------------------------------------------------*/ char* readSearchResponseInfo(info,buffer) void** info; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; void* header = NULL; WAISDocumentHeader** docHeaders = NULL; WAISDocumentShortHeader** shortHeaders = NULL; WAISDocumentLongHeader** longHeaders = NULL; WAISDocumentText** text = NULL; WAISDocumentHeadlines** headlines = NULL; WAISDocumentCodes** codes = NULL; long numDocHeaders,numLongHeaders,numShortHeaders,numText,numHeadlines; long numCodes; char* seedWordsUsed = NULL; diagnosticRecord** diags = NULL; diagnosticRecord* diag = NULL; long numDiags = 0; numDocHeaders = numLongHeaders = numShortHeaders = numText = numHeadlines = numCodes = 0; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_SeedWordsUsed: buf = readString(&seedWordsUsed,buf); break; case DT_DatabaseDiagnosticRecords: if (diags == NULL) /* create a new diag list */ { diags = (diagnosticRecord**)s_malloc((size_t)sizeof(diagnosticRecord*) * 2); } else /* grow the diag list */ { diags = (diagnosticRecord**)s_realloc((char*)diags,(size_t)(sizeof(diagnosticRecord*) * (numDiags + 2))); } buf = readDiag(&diag,buf); diags[numDiags++] = diag; /* put it in the list */ diags[numDiags] = NULL; break; case DT_DocumentHeaderGroup: if (docHeaders == NULL) /* create a new header list */ { docHeaders = (WAISDocumentHeader**)s_malloc((size_t)sizeof(WAISDocumentHeader*) * 2); } else /* grow the doc list */ { docHeaders = (WAISDocumentHeader**)s_realloc((char*)docHeaders,(size_t)(sizeof(WAISDocumentHeader*) * (numDocHeaders + 2))); } buf = readWAISDocumentHeader((WAISDocumentHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); docHeaders[numDocHeaders++] = (WAISDocumentHeader*)header; /* put it in the list */ docHeaders[numDocHeaders] = NULL; break; case DT_DocumentShortHeaderGroup: if (shortHeaders == NULL) /* create a new header list */ { shortHeaders = (WAISDocumentShortHeader**)s_malloc((size_t)sizeof(WAISDocumentShortHeader*) * 2); } else /* grow the doc list */ { shortHeaders = (WAISDocumentShortHeader**)s_realloc((char*)shortHeaders,(size_t)(sizeof(WAISDocumentShortHeader*) * (numShortHeaders + 2))); } buf = readWAISDocumentShortHeader((WAISDocumentShortHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); shortHeaders[numShortHeaders++] = (WAISDocumentShortHeader*)header; /* put it in the list */ shortHeaders[numShortHeaders] = NULL; break; case DT_DocumentLongHeaderGroup: if (longHeaders == NULL) /* create a new header list */ { longHeaders = (WAISDocumentLongHeader**)s_malloc((size_t)sizeof(WAISDocumentLongHeader*) * 2); } else /* grow the doc list */ { longHeaders = (WAISDocumentLongHeader**)s_realloc((char*)longHeaders,(size_t)(sizeof(WAISDocumentLongHeader*) * (numLongHeaders + 2))); } buf = readWAISDocumentLongHeader((WAISDocumentLongHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); longHeaders[numLongHeaders++] = (WAISDocumentLongHeader*)header; /* put it in the list */ longHeaders[numLongHeaders] = NULL; break; case DT_DocumentTextGroup: if (text == NULL) /* create a new list */ { text = (WAISDocumentText**)s_malloc((size_t)sizeof(WAISDocumentText*) * 2); } else /* grow the list */ { text = (WAISDocumentText**)s_realloc((char*)text,(size_t)(sizeof(WAISDocumentText*) * (numText + 2))); } buf = readWAISDocumentText((WAISDocumentText**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); text[numText++] = (WAISDocumentText*)header; /* put it in the list */ text[numText] = NULL; break; case DT_DocumentHeadlineGroup: if (headlines == NULL) /* create a new list */ { headlines = (WAISDocumentHeadlines**)s_malloc((size_t)sizeof(WAISDocumentHeadlines*) * 2); } else /* grow the list */ { headlines = (WAISDocumentHeadlines**)s_realloc((char*)headlines,(size_t)(sizeof(WAISDocumentHeadlines*) * (numHeadlines + 2))); } buf = readWAISDocumentHeadlines((WAISDocumentHeadlines**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); headlines[numHeadlines++] = (WAISDocumentHeadlines*)header; /* put it in the list */ headlines[numHeadlines] = NULL; break; case DT_DocumentCodeGroup: if (codes == NULL) /* create a new list */ { codes = (WAISDocumentCodes**)s_malloc((size_t)sizeof(WAISDocumentCodes*) * 2); } else /* grow the list */ { codes = (WAISDocumentCodes**)s_realloc((char*)codes,(size_t)(sizeof(WAISDocumentCodes*) * (numCodes + 2))); } buf = readWAISDocumentCodes((WAISDocumentCodes**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); codes[numCodes++] = (WAISDocumentCodes*)header; /* put it in the list */ codes[numCodes] = NULL; break; default: cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISSearchResponse(seedWordsUsed,docHeaders,shortHeaders, longHeaders,text,headlines,codes,diags); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentText* makeWAISDocumentText(docID,versionNumber,documentText) any* docID; long versionNumber; any* documentText; { WAISDocumentText* docText = (WAISDocumentText*)s_malloc((size_t)sizeof(WAISDocumentText)); docText->DocumentID = docID; docText->VersionNumber = versionNumber; docText->DocumentText = documentText; return(docText); } /*----------------------------------------------------------------------*/ void freeWAISDocumentText(docText) WAISDocumentText* docText; { freeAny(docText->DocumentID); freeAny(docText->DocumentText); s_free(docText); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentText(docText,buffer,len) WAISDocumentText* docText; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentTextGroup, DefWAISDocTextSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docText->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docText->VersionNumber,DT_VersionNumber,buf,len); buf = writeAny(docText->DocumentText,DT_DocumentText,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentTextGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentText(docText,buffer) WAISDocumentText** docText; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any *docID,*documentText; long versionNumber; docID = documentText = NULL; versionNumber = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_DocumentText: buf = readAny(&documentText,buf); break; default: freeAny(docID); freeAny(documentText); REPORT_READ_ERROR(buf); break; } } *docText = makeWAISDocumentText(docID,versionNumber,documentText); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentHeadlines* makeWAISDocumentHeadlines(docID, versionNumber, source, date, headline, originCity) any* docID; long versionNumber; char* source; char* date; char* headline; char* originCity; { WAISDocumentHeadlines* docHeadline = (WAISDocumentHeadlines*)s_malloc((size_t)sizeof(WAISDocumentHeadlines)); docHeadline->DocumentID = docID; docHeadline->VersionNumber = versionNumber; docHeadline->Source = source; docHeadline->Date = date; docHeadline->Headline = headline; docHeadline->OriginCity = originCity; return(docHeadline); } /*----------------------------------------------------------------------*/ void freeWAISDocumentHeadlines(docHeadline) WAISDocumentHeadlines* docHeadline; { freeAny(docHeadline->DocumentID); s_free(docHeadline->Source); s_free(docHeadline->Date); s_free(docHeadline->Headline); s_free(docHeadline->OriginCity); s_free(docHeadline); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentHeadlines(docHeadline,buffer,len) WAISDocumentHeadlines* docHeadline; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentHeadlineGroup, DefWAISDocHeadlineSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docHeadline->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docHeadline->VersionNumber,DT_VersionNumber,buf,len); buf = writeString(docHeadline->Source,DT_Source,buf,len); buf = writeString(docHeadline->Date,DT_Date,buf,len); buf = writeString(docHeadline->Headline,DT_Headline,buf,len); buf = writeString(docHeadline->OriginCity,DT_OriginCity,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentHeadlineGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentHeadlines(docHeadline,buffer) WAISDocumentHeadlines** docHeadline; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber; char *source,*date,*headline,*originCity; docID = NULL; versionNumber = UNUSED; source = date = headline = originCity = NULL; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); REPORT_READ_ERROR(buf); break; } } *docHeadline = makeWAISDocumentHeadlines(docID,versionNumber,source,date, headline,originCity); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentCodes* makeWAISDocumentCodes(docID, versionNumber, stockCodes, companyCodes, industryCodes) any* docID; long versionNumber; char* stockCodes; char* companyCodes; char* industryCodes; { WAISDocumentCodes* docCodes = (WAISDocumentCodes*)s_malloc((size_t)sizeof(WAISDocumentCodes)); docCodes->DocumentID = docID; docCodes->VersionNumber = versionNumber; docCodes->StockCodes = stockCodes; docCodes->CompanyCodes = companyCodes; docCodes->IndustryCodes = industryCodes; return(docCodes); } /*----------------------------------------------------------------------*/ void freeWAISDocumentCodes(docCodes) WAISDocumentCodes* docCodes; { freeAny(docCodes->DocumentID); s_free(docCodes->StockCodes); s_free(docCodes->CompanyCodes); s_free(docCodes->IndustryCodes); s_free(docCodes); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentCodes(docCodes,buffer,len) WAISDocumentCodes* docCodes; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentCodeGroup , DefWAISDocCodeSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docCodes->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docCodes->VersionNumber,DT_VersionNumber,buf,len); buf = writeString(docCodes->StockCodes,DT_StockCodes,buf,len); buf = writeString(docCodes->CompanyCodes,DT_CompanyCodes,buf,len); buf = writeString(docCodes->IndustryCodes,DT_IndustryCodes,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentCodeGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentCodes(docCodes,buffer) WAISDocumentCodes** docCodes; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber; char *stockCodes,*companyCodes,*industryCodes; docID = NULL; versionNumber = UNUSED; stockCodes = companyCodes = industryCodes = NULL; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_StockCodes: buf = readString(&stockCodes,buf); break; case DT_CompanyCodes: buf = readString(&companyCodes,buf); break; case DT_IndustryCodes: buf = readString(&industryCodes,buf); break; default: freeAny(docID); s_free(stockCodes); s_free(companyCodes); s_free(industryCodes); REPORT_READ_ERROR(buf); break; } } *docCodes = makeWAISDocumentCodes(docID,versionNumber,stockCodes, companyCodes,industryCodes); return(buf); } /*----------------------------------------------------------------------*/ char* writePresentInfo(present,buffer,len) PresentAPDU* present GCC_UNUSED; char* buffer; long* len GCC_UNUSED; { /* The WAIS protocol doesn't use present info */ return(buffer); } /*----------------------------------------------------------------------*/ char* readPresentInfo(info,buffer) void** info; char* buffer; { /* The WAIS protocol doesn't use present info */ *info = NULL; return(buffer); } /*----------------------------------------------------------------------*/ char* writePresentResponseInfo(response,buffer,len) PresentResponseAPDU* response GCC_UNUSED; char* buffer; long* len GCC_UNUSED; { /* The WAIS protocol doesn't use presentResponse info */ return(buffer); } /*----------------------------------------------------------------------*/ char* readPresentResponseInfo(info,buffer) void** info; char* buffer; { /* The WAIS protocol doesn't use presentResponse info */ *info = NULL; return(buffer); } /*----------------------------------------------------------------------*/ /* support for type 1 queries */ /* new use values (for the chunk types) */ #define BYTE "wb" #define LINE "wl" #define PARAGRAPH "wp" #define DATA_TYPE "wt" /* WAIS supports the following semantics for type 1 queries: 1. retrieve the header/codes from a document: System_Control_Number = docID Data Type = type (optional) And 2. retrieve a fragment of the text of a document: System_Control_Number = docID Data Type = type (optional) And Chunk >= start And Chunk < end And Information from multiple documents may be requested by using groups of the above joined by: OR ( XXX does an OR come after every group but the first, or do they all come at the end? ) ( XXX return type could be in the element set) */ static query_term** makeWAISQueryTerms PARAMS((DocObj** docs)); static query_term** makeWAISQueryTerms(docs) DocObj** docs; /* given a null terminated list of docObjs, construct the appropriate query of the form given above */ { query_term** terms = NULL; long numTerms = 0; DocObj* doc = NULL; long i; if (docs == NULL) return((query_term**)NULL); terms = (query_term**)s_malloc((size_t)(sizeof(query_term*) * 1)); terms[numTerms] = NULL; /* loop through the docs making terms for them all */ for (i = 0,doc = docs[i]; doc != NULL; doc = docs[++i]) { any* type = NULL; if (doc->Type != NULL) type = stringToAny(doc->Type); if (doc->ChunkCode == CT_document) /* a whole document */ { terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 3 + 1))); terms[numTerms++] = makeAttributeTerm(SYSTEM_CONTROL_NUMBER, EQUAL,IGNORE,IGNORE, IGNORE,IGNORE,doc->DocumentID); if (type != NULL) { terms[numTerms++] = makeAttributeTerm(DATA_TYPE,EQUAL, IGNORE,IGNORE,IGNORE, IGNORE,type); terms[numTerms++] = makeOperatorTerm(AND); } terms[numTerms] = NULL; } else /* a document fragment */ { char chunk_att[ATTRIBUTE_SIZE]; any* startChunk = NULL; any* endChunk = NULL; terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 7 + 1))); switch (doc->ChunkCode) { case CT_byte: case CT_line: { char start[20],end[20]; (doc->ChunkCode == CT_byte) ? strncpy(chunk_att,BYTE,ATTRIBUTE_SIZE) : strncpy(chunk_att,LINE,ATTRIBUTE_SIZE); sprintf(start,"%ld",doc->ChunkStart.Pos); startChunk = stringToAny(start); sprintf(end,"%ld",doc->ChunkEnd.Pos); endChunk = stringToAny(end); } break; case CT_paragraph: strncpy(chunk_att,PARAGRAPH,ATTRIBUTE_SIZE); startChunk = doc->ChunkStart.ID; endChunk = doc->ChunkEnd.ID; break; default: /* error */ break; } terms[numTerms++] = makeAttributeTerm(SYSTEM_CONTROL_NUMBER, EQUAL,IGNORE,IGNORE, IGNORE, IGNORE,doc->DocumentID); if (type != NULL) { terms[numTerms++] = makeAttributeTerm(DATA_TYPE,EQUAL,IGNORE, IGNORE,IGNORE,IGNORE, type); terms[numTerms++] = makeOperatorTerm(AND); } terms[numTerms++] = makeAttributeTerm(chunk_att, GREATER_THAN_OR_EQUAL, IGNORE,IGNORE,IGNORE, IGNORE, startChunk); terms[numTerms++] = makeOperatorTerm(AND); terms[numTerms++] = makeAttributeTerm(chunk_att,LESS_THAN, IGNORE,IGNORE,IGNORE, IGNORE, endChunk); terms[numTerms++] = makeOperatorTerm(AND); terms[numTerms] = NULL; if (doc->ChunkCode == CT_byte || doc->ChunkCode == CT_line) { freeAny(startChunk); freeAny(endChunk); } } freeAny(type); if (i != 0) /* multiple independent queries, need a disjunction */ { terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 1 + 1))); terms[numTerms++] = makeOperatorTerm(OR); terms[numTerms] = NULL; } } return(terms); } /*----------------------------------------------------------------------*/ static DocObj** makeWAISQueryDocs PARAMS((query_term** terms)); static DocObj** makeWAISQueryDocs(terms) query_term** terms; /* given a list of terms in the form given above, convert them to DocObjs. */ { query_term* docTerm = NULL; query_term* fragmentTerm = NULL; DocObj** docs = NULL; DocObj* doc = NULL; long docNum,termNum; docNum = termNum = 0; docs = (DocObj**)s_malloc((size_t)(sizeof(DocObj*) * 1)); docs[docNum] = NULL; /* translate the terms into DocObjs */ while (true) { query_term* typeTerm = NULL; char* type = NULL; long startTermOffset; docTerm = terms[termNum]; if (docTerm == NULL) break; /* we're done converting */ typeTerm = terms[termNum + 1]; /* get the lead Term if it exists */ if (strcmp(typeTerm->Use,DATA_TYPE) == 0) /* we do have a type */ { startTermOffset = 3; type = anyToString(typeTerm->Term); } else /* no type */ { startTermOffset = 1; typeTerm = NULL; type = NULL; } /* grow the doc list */ docs = (DocObj**)s_realloc((char*)docs,(size_t)(sizeof(DocObj*) * (docNum + 1 + 1))); /* figure out what kind of docObj to build - and build it */ fragmentTerm = terms[termNum + startTermOffset]; if (fragmentTerm != NULL && fragmentTerm->TermType == TT_Attribute) { /* build a document fragment */ query_term* startTerm = fragmentTerm; query_term* endTerm = terms[termNum + startTermOffset + 2]; if (strcmp(startTerm->Use,BYTE) == 0){ /* a byte chunk */ doc = makeDocObjUsingBytes(duplicateAny(docTerm->Term), type, anyToLong(startTerm->Term), anyToLong(endTerm->Term)); log_write("byte"); }else if (strcmp(startTerm->Use,LINE) == 0){ /* a line chunk */ doc = makeDocObjUsingLines(duplicateAny(docTerm->Term), type, anyToLong(startTerm->Term), anyToLong(endTerm->Term)); log_write("line"); }else{ log_write("chunk"); /* a paragraph chunk */ doc = makeDocObjUsingParagraphs(duplicateAny(docTerm->Term), type, duplicateAny(startTerm->Term), duplicateAny(endTerm->Term)); } termNum += (startTermOffset + 4); /* point to next term */ } else /* build a full document */ { doc = makeDocObjUsingWholeDocument(duplicateAny(docTerm->Term), type); log_write("whole doc"); termNum += startTermOffset; /* point to next term */ } docs[docNum++] = doc; /* insert the new document */ docs[docNum] = NULL; /* keep the doc list terminated */ if (terms[termNum] != NULL) termNum++; /* skip the OR operator it necessary */ else break; /* we are done */ } return(docs); } /*----------------------------------------------------------------------*/ any* makeWAISTextQuery(docs) DocObj** docs; /* given a list of DocObjs, return an any whose contents is the corresponding type 1 query */ { any *buf = NULL; query_term** terms = NULL; terms = makeWAISQueryTerms(docs); buf = writeQuery(terms); doList((void**)terms,freeTerm); s_free(terms); return(buf); } /*----------------------------------------------------------------------*/ DocObj** readWAISTextQuery(buf) any* buf; /* given an any whose contents are type 1 queries of the WAIS sort, construct a list of the corresponding DocObjs */ { query_term** terms = NULL; DocObj** docs = NULL; terms = readQuery(buf); docs = makeWAISQueryDocs(terms); doList((void**)terms,freeTerm); s_free(terms); return(docs); } /*----------------------------------------------------------------------*/ /* Customized free WAIS object routines: */ /* */ /* This set of procedures is for applications to free a WAIS object */ /* which was made with makeWAISFOO. */ /* Each procedure frees only the memory that was allocated in its */ /* associated makeWAISFOO routine, thus it's not necessary for the */ /* caller to assign nulls to the pointer fields of the WAIS object. */ /*----------------------------------------------------------------------*/ void CSTFreeWAISInitResponse(init) WAISInitResponse* init; /* free an object made with makeWAISInitResponse */ { s_free(init); } /*----------------------------------------------------------------------*/ void CSTFreeWAISSearch(query) WAISSearch* query; /* destroy an object made with makeWAISSearch() */ { s_free(query); } /*----------------------------------------------------------------------*/ void CSTFreeDocObj(doc) DocObj* doc; /* free a docObj */ { s_free(doc); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentHeader(header) WAISDocumentHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentShortHeader(header) WAISDocumentShortHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentLongHeader(header) WAISDocumentLongHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISSearchResponse(response) WAISSearchResponse* response; { s_free(response); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentText(docText) WAISDocumentText* docText; { s_free(docText); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocHeadlines(docHeadline) WAISDocumentHeadlines* docHeadline; { s_free(docHeadline); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentCodes(docCodes) WAISDocumentCodes* docCodes; { s_free(docCodes); } /*----------------------------------------------------------------------*/ void CSTFreeWAISTextQuery(query) any* query; { freeAny(query); } /*----------------------------------------------------------------------*/ /* ** Routines originally from WMessage.c -- FM ** **----------------------------------------------------------------------*/ /* WIDE AREA INFORMATION SERVER SOFTWARE No guarantees or restrictions. See the readme file for the full standard disclaimer. 3.26.90 */ /* This file is for reading and writing the wais packet header. * Morris@think.com */ /* to do: * add check sum * what do you do when checksum is wrong? */ /*---------------------------------------------------------------------*/ void readWAISPacketHeader(msgBuffer,header_struct) char* msgBuffer; WAISMessage *header_struct; { /* msgBuffer is a string containing at least HEADER_LENGTH bytes. */ memmove(header_struct->msg_len,msgBuffer,(size_t)10); header_struct->msg_type = char_downcase((unsigned long)msgBuffer[10]); header_struct->hdr_vers = char_downcase((unsigned long)msgBuffer[11]); memmove(header_struct->server,(void*)(msgBuffer + 12),(size_t)10); header_struct->compression = char_downcase((unsigned long)msgBuffer[22]); header_struct->encoding = char_downcase((unsigned long)msgBuffer[23]); header_struct->msg_checksum = char_downcase((unsigned long)msgBuffer[24]); } /*---------------------------------------------------------------------*/ /* this modifies the header argument. See wais-message.h for the different * options for the arguments. */ void writeWAISPacketHeader(header, dataLen, type, server, compression, encoding, version) char* header; long dataLen; long type; char* server; long compression; long encoding; long version; /* Puts together the new wais before-the-z39-packet header. */ { char lengthBuf[11]; char serverBuf[11]; long serverLen = strlen(server); if (serverLen > 10) serverLen = 10; sprintf(lengthBuf, "%010ld", dataLen); strncpy(header,lengthBuf,10); header[10] = type & 0xFF; header[11] = version & 0xFF; strncpy(serverBuf,server,serverLen); strncpy((char*)(header + 12),serverBuf,serverLen); header[22] = compression & 0xFF; header[23] = encoding & 0xFF; header[24] = '0'; /* checkSum(header + HEADER_LENGTH,dataLen); XXX the result must be ascii */ } /*---------------------------------------------------------------------*/
Java
<?php defined('ABSPATH') OR exit; if(!class_exists('Picturefill_WP_Function_Helpers')){ class Picturefill_WP_Function_Helpers{ private $filter = ''; private $cache_duration = 86400; private $image_sizes_to_remove = array(); private $image_size_to_add = ''; private $insert_before = ''; private $image_size_array = array(); private $new_image_size_queue = array(); public $post_type_to_exclude = ''; public $post_id_to_exclude = ''; public $post_slug_to_exclude = ''; public $post_tag_to_exclude = ''; public $post_category_to_exclude = ''; public static function retina_only($default_image_sizes, $image_attributes){ if('full' === $image_attributes['size'][1]){ return array($image_attributes['size'][1]); }else{ return array( $image_attributes['size'][1], $image_attributes['size'][1] . '@2x' ); } } public static function remove_line_breaks($output){ return str_replace("\n", '', $output); } public static function min_template($template_file_path, $template, $template_path){ return $template_path . 'min/' . $template . '-template.php'; } public function apply_to_filter($filter){ $this->filter = $filter; add_filter($filter, array($this, '_apply_picturefill_wp_to_filter')); } public function set_cache_duration($cache_duration){ $this->cache_duration = $cache_duration; add_filter('picturefill_wp_cache_duration', array($this, '_set_cache_duration')); } public function remove_image_from_responsive_list($image_size){ if('string' === gettype($image_size)){ $this->image_sizes_to_remove = array($image_size, $image_size . '@2x'); }elseif('array' === gettype($image_size)){ $this->image_sizes_to_remove = array(); foreach($image_size as $size){ $this->image_sizes_to_remove[] = $size; $this->image_sizes_to_remove[] = $size . '@2x'; } } add_filter('picturefill_wp_image_sizes', array($this, '_remove_image_from_responsive_list'), 10, 2); } public function add_image_to_responsive_queue($image_size, $insert_before){ $this->image_size_to_add = $image_size; $this->insert_before = $insert_before; add_filter('picturefill_wp_image_attachment_data', array($this, '_add_size_attachment_data'), 10, 2); add_filter('picturefill_wp_image_sizes', array($this, '_add_size_to_responsive_image_list'), 11, 2); } public function set_responsive_image_sizes($image_size_array){ $this->image_size_array = $image_size_array; $this->new_image_size_queue = $this->setup_responsive_image_sizes($image_size_array); add_filter('picturefill_wp_image_sizes', array($this, '_set_responsive_image_sizes'), 10, 2); add_filter('picturefill_wp_image_attachment_data', array($this, '_set_new_responsive_image_attachment_data'), 10, 2); } public function apply_to_post_thumbnail(){ $this->image_size_to_add = 'post-thumbnail'; add_action('init', array($this, '_add_retina_post_thumbnail')); add_filter('post_thumbnail_html', array($this, '_add_size_to_post_thumbnail_class'), 9, 5); add_filter('picturefill_wp_image_attachment_data', array($this, '_add_size_attachment_data'), 10, 2); add_filter('picturefill_wp_image_sizes', array($this, '_post_thumbnail_sizes'), 10, 2); $this->apply_to_filter('post_thumbnail_html'); } public function exclude_post_type($post){ if($this->post_type_to_exclude === $post->post_type){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function exclude_post_id($post){ if($this->post_id_to_exclude === $post->ID){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function exclude_post_slug($post){ if($this->post_slug_to_exclude === $post->post_name){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function exclude_post_tag($post){ $post_tags = wp_get_post_tags($post->ID, array('fields' => 'names')); if(in_array($this->post_tag_to_exclude, $post_tags)){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function exclude_post_category($post){ $post_tags = wp_get_post_categories($post->ID, array('fields' => 'names')); if(in_array($this->post_category_to_exclude, $post_tags)){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function _set_responsive_image_sizes($image_queue, $image_attributes){ $new_image_queue = array(); $minimum_reached = empty($image_attributes['min-size'][1]) ? true : false; foreach($this->new_image_size_queue as $image_name){ if($minimum_reached || $image_attributes['min-size'][1] === $image_name){ $minimum_reached = true; $new_image_queue[] = $image_name; $new_image_queue[] = $image_name . '@2x'; } if($image_attributes['size'][1] === $image_name){ return $new_image_queue; } } return !empty($new_image_queue) ? $new_image_queue : $image_queue; } public function _set_new_responsive_image_attachment_data($attachment_data, $id){ $new_attachment_data = array(); foreach($this->new_image_size_queue as $size){ $new_attachment_data[$size] = wp_get_attachment_image_src($id, $size); } return array_merge($attachment_data, $new_attachment_data); } public function _post_thumbnail_sizes($default_image_sizes, $image_attributes){ return 'post-thumbnail' === $image_attributes['size'][1] ? array( 'post-thumbnail', 'post-thumbnail@2x' ) : $default_image_sizes; } public function _add_retina_post_thumbnail(){ global $_wp_additional_image_sizes; add_image_size('post-thumbnail@2x', $_wp_additional_image_sizes['post-thumbnail']['width'] * 2, $_wp_additional_image_sizes['post-thumbnail']['height'] * 2, $_wp_additional_image_sizes['post-thumbnail']['crop']); } public function _add_size_to_post_thumbnail_class($html, $post_id, $post_thumbnail_id, $size, $attr){ return preg_replace('/class="([^"]+)"/', 'class="$1 size-' . $size . '"', $html); } public function _add_size_to_responsive_image_list($image_sizes, $image_attributes){ if('@2x' === substr($this->insert_before, -3)){ return $image_sizes; } $position = array_search($this->insert_before, $image_sizes); if($image_attributes['min_size'] !== $this->insert_before){ if(1 > $position){ return array_merge(array($this->image_size_to_add, $this->image_size_to_add . '@2x'), $image_sizes); }else{ array_splice($image_sizes, $position, 0, array($this->image_size_to_add, $this->image_size_to_add . '@2x')); return $image_sizes; } }else{ return $image_sizes; } } public function _add_size_attachment_data($attachment_data, $attachment_id){ $new_size_data = array( $this->image_size_to_add => wp_get_attachment_image_src($attachment_id, $this->image_size_to_add), $this->image_size_to_add . '@2x' => wp_get_attachment_image_src($attachment_id, $this->image_size_to_add . '@2x') ); return array_merge($attachment_data, $new_size_data); } public function _apply_picturefill_wp_to_filter($content){ return Picturefill_WP::get_instance()->cache_picturefill_output($content, $this->filter); } public function _set_cache_duration($old_cache_duration){ return $this->cache_duration; } public function _remove_image_from_responsive_list($image_sizes, $image_attributes){ return array_diff($image_sizes, $this->image_sizes_to_remove); } private function setup_responsive_image_sizes($image_size_array){ global $_wp_additional_image_sizes; $existing_image_sizes = get_intermediate_image_sizes(); $new_image_queue = array(); foreach($image_size_array as $image_name){ if('@2x' === substr($image_name, -3) || !in_array($image_name, $existing_image_sizes)){ return $new_image_queue; } if(!in_array($image_name . '@2x', $existing_image_sizes)){ add_image_size($image_name . '@2x', $_wp_additional_image_sizes[$image_name]['width'] * 2, $_wp_additional_image_sizes[$image_name]['height'] * 2, $_wp_additional_image_sizes[$image_name]['crop']); } $new_image_queue[] = $image_name; // $new_image_queue[] = $image_name . '@2x'; } return $new_image_queue; } } }
Java
/****************************************************************************** ** kjmp2 -- a minimal MPEG-1/2 Audio Layer II decoder library ** ** version 1.1 ** ******************************************************************************* ** Copyright (C) 2006-2013 Martin J. Fiedler <martin.fiedler@gmx.net> ** ** ** ** This software is provided 'as-is', without any express or implied ** ** warranty. In no event will the authors be held liable for any damages ** ** arising from the use of this software. ** ** ** ** Permission is granted to anyone to use this software for any purpose, ** ** including commercial applications, and to alter it and redistribute it ** ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** ** claim that you wrote the original software. If you use this software ** ** in a product, an acknowledgment in the product documentation would ** ** be appreciated but is not required. ** ** 2. Altered source versions must be plainly marked as such, and must not ** ** be misrepresented as being the original software. ** ** 3. This notice may not be removed or altered from any source ** ** distribution. ** ******************************************************************************/ // // Code adapted of the original code: // - it is made into a class for use within the framework // of the sdr-j DAB/DAB+ software // #include "mp2processor.h" #include "radio.h" #include "pad-handler.h" #ifdef _MSC_VER #define FASTCALL __fastcall #else #define FASTCALL #endif //////////////////////////////////////////////////////////////////////////////// // TABLES AND CONSTANTS // //////////////////////////////////////////////////////////////////////////////// // mode constants #define STEREO 0 #define JOINT_STEREO 1 #define DUAL_CHANNEL 2 #define MONO 3 // sample rate table static const unsigned short sample_rates[8] = { 44100, 48000, 32000, 0, // MPEG-1 22050, 24000, 16000, 0 // MPEG-2 }; // bitrate table static const short bitrates[28] = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, // MPEG-1 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 // MPEG-2 }; // scale factor base values (24-bit fixed-point) static const int scf_base [3] = {0x02000000, 0x01965FEA, 0x01428A30}; // synthesis window static const int D[512] = { 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,-0x00001, -0x00001,-0x00001,-0x00001,-0x00002,-0x00002,-0x00003,-0x00003,-0x00004, -0x00004,-0x00005,-0x00006,-0x00006,-0x00007,-0x00008,-0x00009,-0x0000A, -0x0000C,-0x0000D,-0x0000F,-0x00010,-0x00012,-0x00014,-0x00017,-0x00019, -0x0001C,-0x0001E,-0x00022,-0x00025,-0x00028,-0x0002C,-0x00030,-0x00034, -0x00039,-0x0003E,-0x00043,-0x00048,-0x0004E,-0x00054,-0x0005A,-0x00060, -0x00067,-0x0006E,-0x00074,-0x0007C,-0x00083,-0x0008A,-0x00092,-0x00099, -0x000A0,-0x000A8,-0x000AF,-0x000B6,-0x000BD,-0x000C3,-0x000C9,-0x000CF, 0x000D5, 0x000DA, 0x000DE, 0x000E1, 0x000E3, 0x000E4, 0x000E4, 0x000E3, 0x000E0, 0x000DD, 0x000D7, 0x000D0, 0x000C8, 0x000BD, 0x000B1, 0x000A3, 0x00092, 0x0007F, 0x0006A, 0x00053, 0x00039, 0x0001D,-0x00001,-0x00023, -0x00047,-0x0006E,-0x00098,-0x000C4,-0x000F3,-0x00125,-0x0015A,-0x00190, -0x001CA,-0x00206,-0x00244,-0x00284,-0x002C6,-0x0030A,-0x0034F,-0x00396, -0x003DE,-0x00427,-0x00470,-0x004B9,-0x00502,-0x0054B,-0x00593,-0x005D9, -0x0061E,-0x00661,-0x006A1,-0x006DE,-0x00718,-0x0074D,-0x0077E,-0x007A9, -0x007D0,-0x007EF,-0x00808,-0x0081A,-0x00824,-0x00826,-0x0081F,-0x0080E, 0x007F5, 0x007D0, 0x007A0, 0x00765, 0x0071E, 0x006CB, 0x0066C, 0x005FF, 0x00586, 0x00500, 0x0046B, 0x003CA, 0x0031A, 0x0025D, 0x00192, 0x000B9, -0x0002C,-0x0011F,-0x00220,-0x0032D,-0x00446,-0x0056B,-0x0069B,-0x007D5, -0x00919,-0x00A66,-0x00BBB,-0x00D16,-0x00E78,-0x00FDE,-0x01148,-0x012B3, -0x01420,-0x0158C,-0x016F6,-0x0185C,-0x019BC,-0x01B16,-0x01C66,-0x01DAC, -0x01EE5,-0x02010,-0x0212A,-0x02232,-0x02325,-0x02402,-0x024C7,-0x02570, -0x025FE,-0x0266D,-0x026BB,-0x026E6,-0x026ED,-0x026CE,-0x02686,-0x02615, -0x02577,-0x024AC,-0x023B2,-0x02287,-0x0212B,-0x01F9B,-0x01DD7,-0x01BDD, 0x019AE, 0x01747, 0x014A8, 0x011D1, 0x00EC0, 0x00B77, 0x007F5, 0x0043A, 0x00046,-0x003E5,-0x00849,-0x00CE3,-0x011B4,-0x016B9,-0x01BF1,-0x0215B, -0x026F6,-0x02CBE,-0x032B3,-0x038D3,-0x03F1A,-0x04586,-0x04C15,-0x052C4, -0x05990,-0x06075,-0x06771,-0x06E80,-0x0759F,-0x07CCA,-0x083FE,-0x08B37, -0x09270,-0x099A7,-0x0A0D7,-0x0A7FD,-0x0AF14,-0x0B618,-0x0BD05,-0x0C3D8, -0x0CA8C,-0x0D11D,-0x0D789,-0x0DDC9,-0x0E3DC,-0x0E9BD,-0x0EF68,-0x0F4DB, -0x0FA12,-0x0FF09,-0x103BD,-0x1082C,-0x10C53,-0x1102E,-0x113BD,-0x116FB, -0x119E8,-0x11C82,-0x11EC6,-0x120B3,-0x12248,-0x12385,-0x12467,-0x124EF, 0x1251E, 0x124F0, 0x12468, 0x12386, 0x12249, 0x120B4, 0x11EC7, 0x11C83, 0x119E9, 0x116FC, 0x113BE, 0x1102F, 0x10C54, 0x1082D, 0x103BE, 0x0FF0A, 0x0FA13, 0x0F4DC, 0x0EF69, 0x0E9BE, 0x0E3DD, 0x0DDCA, 0x0D78A, 0x0D11E, 0x0CA8D, 0x0C3D9, 0x0BD06, 0x0B619, 0x0AF15, 0x0A7FE, 0x0A0D8, 0x099A8, 0x09271, 0x08B38, 0x083FF, 0x07CCB, 0x075A0, 0x06E81, 0x06772, 0x06076, 0x05991, 0x052C5, 0x04C16, 0x04587, 0x03F1B, 0x038D4, 0x032B4, 0x02CBF, 0x026F7, 0x0215C, 0x01BF2, 0x016BA, 0x011B5, 0x00CE4, 0x0084A, 0x003E6, -0x00045,-0x00439,-0x007F4,-0x00B76,-0x00EBF,-0x011D0,-0x014A7,-0x01746, 0x019AE, 0x01BDE, 0x01DD8, 0x01F9C, 0x0212C, 0x02288, 0x023B3, 0x024AD, 0x02578, 0x02616, 0x02687, 0x026CF, 0x026EE, 0x026E7, 0x026BC, 0x0266E, 0x025FF, 0x02571, 0x024C8, 0x02403, 0x02326, 0x02233, 0x0212B, 0x02011, 0x01EE6, 0x01DAD, 0x01C67, 0x01B17, 0x019BD, 0x0185D, 0x016F7, 0x0158D, 0x01421, 0x012B4, 0x01149, 0x00FDF, 0x00E79, 0x00D17, 0x00BBC, 0x00A67, 0x0091A, 0x007D6, 0x0069C, 0x0056C, 0x00447, 0x0032E, 0x00221, 0x00120, 0x0002D,-0x000B8,-0x00191,-0x0025C,-0x00319,-0x003C9,-0x0046A,-0x004FF, -0x00585,-0x005FE,-0x0066B,-0x006CA,-0x0071D,-0x00764,-0x0079F,-0x007CF, 0x007F5, 0x0080F, 0x00820, 0x00827, 0x00825, 0x0081B, 0x00809, 0x007F0, 0x007D1, 0x007AA, 0x0077F, 0x0074E, 0x00719, 0x006DF, 0x006A2, 0x00662, 0x0061F, 0x005DA, 0x00594, 0x0054C, 0x00503, 0x004BA, 0x00471, 0x00428, 0x003DF, 0x00397, 0x00350, 0x0030B, 0x002C7, 0x00285, 0x00245, 0x00207, 0x001CB, 0x00191, 0x0015B, 0x00126, 0x000F4, 0x000C5, 0x00099, 0x0006F, 0x00048, 0x00024, 0x00002,-0x0001C,-0x00038,-0x00052,-0x00069,-0x0007E, -0x00091,-0x000A2,-0x000B0,-0x000BC,-0x000C7,-0x000CF,-0x000D6,-0x000DC, -0x000DF,-0x000E2,-0x000E3,-0x000E3,-0x000E2,-0x000E0,-0x000DD,-0x000D9, 0x000D5, 0x000D0, 0x000CA, 0x000C4, 0x000BE, 0x000B7, 0x000B0, 0x000A9, 0x000A1, 0x0009A, 0x00093, 0x0008B, 0x00084, 0x0007D, 0x00075, 0x0006F, 0x00068, 0x00061, 0x0005B, 0x00055, 0x0004F, 0x00049, 0x00044, 0x0003F, 0x0003A, 0x00035, 0x00031, 0x0002D, 0x00029, 0x00026, 0x00023, 0x0001F, 0x0001D, 0x0001A, 0x00018, 0x00015, 0x00013, 0x00011, 0x00010, 0x0000E, 0x0000D, 0x0000B, 0x0000A, 0x00009, 0x00008, 0x00007, 0x00007, 0x00006, 0x00005, 0x00005, 0x00004, 0x00004, 0x00003, 0x00003, 0x00002, 0x00002, 0x00002, 0x00002, 0x00001, 0x00001, 0x00001, 0x00001, 0x00001, 0x00001 }; ///////////// Table 3-B.2: Possible quantization per subband /////////////////// // quantizer lookup, step 1: bitrate classes static uint8_t quant_lut_step1[2][16] = { // 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384 <- bitrate { 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, // mono // 16, 24, 28, 32, 40, 48, 56, 64, 80, 96,112,128,160,192 <- BR / chan { 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2 } // stereo }; // quantizer lookup, step 2: bitrate class, sample rate -> B2 table idx, sblimit #define QUANT_TAB_A (27 | 64) // Table 3-B.2a: high-rate, sblimit = 27 #define QUANT_TAB_B (30 | 64) // Table 3-B.2b: high-rate, sblimit = 30 #define QUANT_TAB_C 8 // Table 3-B.2c: low-rate, sblimit = 8 #define QUANT_TAB_D 12 // Table 3-B.2d: low-rate, sblimit = 12 static const char quant_lut_step2 [3][4] = { // 44.1 kHz, 48 kHz, 32 kHz { QUANT_TAB_C, QUANT_TAB_C, QUANT_TAB_D }, // 32 - 48 kbit/sec/ch { QUANT_TAB_A, QUANT_TAB_A, QUANT_TAB_A }, // 56 - 80 kbit/sec/ch { QUANT_TAB_B, QUANT_TAB_A, QUANT_TAB_B }, // 96+ kbit/sec/ch }; // quantizer lookup, step 3: B2 table, subband -> nbal, row index // (upper 4 bits: nbal, lower 4 bits: row index) static uint8_t quant_lut_step3 [3][32] = { // low-rate table (3-B.2c and 3-B.2d) { 0x44,0x44, // SB 0 - 1 0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34 // SB 2 - 12 }, // high-rate table (3-B.2a and 3-B.2b) { 0x43,0x43,0x43, // SB 0 - 2 0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42, // SB 3 - 10 0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31, // SB 11 - 22 0x20,0x20,0x20,0x20,0x20,0x20,0x20 // SB 23 - 29 }, // MPEG-2 LSR table (B.2 in ISO 13818-3) { 0x45,0x45,0x45,0x45, // SB 0 - 3 0x34,0x34,0x34,0x34,0x34,0x34,0x34, // SB 4 - 10 0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24, // SB 11 - 0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24 // - 29 } }; // quantizer lookup, step 4: table row, allocation[] value -> quant table index static const char quant_lut_step4 [6][16] = { { 0, 1, 2, 17 }, { 0, 1, 2, 3, 4, 5, 6, 17 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17 }, { 0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }, { 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } }; // quantizer table static struct quantizer_spec quantizer_table [17] = { { 3, 1, 5 }, // 1 { 5, 1, 7 }, // 2 { 7, 0, 3 }, // 3 { 9, 1, 10 }, // 4 { 15, 0, 4 }, // 5 { 31, 0, 5 }, // 6 { 63, 0, 6 }, // 7 { 127, 0, 7 }, // 8 { 255, 0, 8 }, // 9 { 511, 0, 9 }, // 10 { 1023, 0, 10 }, // 11 { 2047, 0, 11 }, // 12 { 4095, 0, 12 }, // 13 { 8191, 0, 13 }, // 14 { 16383, 0, 14 }, // 15 { 32767, 0, 15 }, // 16 { 65535, 0, 16 } // 17 }; //////////////////////////////////////////////////////////////////////////////// // The initialization is now done in the constructor // (J van Katwijk) //////////////////////////////////////////////////////////////////////////////// mp2Processor::mp2Processor (RadioInterface *mr, int16_t bitRate, RingBuffer<int16_t> *buffer, RingBuffer<uint8_t> *frameBuffer): my_padhandler (mr) { int16_t i, j; int16_t *nPtr = &N [0][0]; // compute N[i][j] for (i = 0; i < 64; i ++) for (j = 0; j < 32; ++j) *nPtr++ = (int16_t) (256.0 * cos(((16 + i) * ((j << 1) + 1)) * 0.0490873852123405)); // perform local initialization: for (i = 0; i < 2; ++i) for (j = 1023; j >= 0; j--) V [i][j] = 0; myRadioInterface = mr; this -> buffer = buffer; this -> bitRate = bitRate; connect (this, SIGNAL (show_frameErrors (int)), mr, SLOT (show_frameErrors (int))); connect (this, SIGNAL (newAudio (int, int)), mr, SLOT (newAudio (int, int))); connect (this, SIGNAL (isStereo (bool)), mr, SLOT (setStereo (bool))); Voffs = 0; baudRate = 48000; // default for DAB MP2framesize = 24 * bitRate; // may be changed MP2frame = new uint8_t [2 * MP2framesize]; MP2Header_OK = 0; MP2headerCount = 0; MP2bitCount = 0; numberofFrames = 0; errorFrames = 0; } mp2Processor::~mp2Processor() { delete[] MP2frame; } // #define valid(x) ((x == 48000) || (x == 24000)) void mp2Processor::setSamplerate (int32_t rate) { if (baudRate == rate) return; if (!valid (rate)) return; // ourSink -> setMode (0, rate); baudRate = rate; } //////////////////////////////////////////////////////////////////////////////// // INITIALIZATION: is moved into the constructor for the class // // //////////////////////////////////////////////////////////////////////////////// int32_t mp2Processor::mp2sampleRate (uint8_t *frame) { if (!frame) return 0; if (( frame[0] != 0xFF) // no valid syncword? || ((frame[1] & 0xF6) != 0xF4) // no MPEG-1/2 Audio Layer II? || ((frame[2] - 0x10) >= 0xE0)) // invalid bitrate? return 0; return sample_rates[(((frame[1] & 0x08) >> 1) ^ 4) // MPEG-1/2 switch + ((frame[2] >> 2) & 3)]; // actual rate } //////////////////////////////////////////////////////////////////////////////// // DECODE HELPER FUNCTIONS // //////////////////////////////////////////////////////////////////////////////// struct quantizer_spec* mp2Processor::read_allocation (int sb, int b2_table) { int table_idx = quant_lut_step3 [b2_table][sb]; table_idx = quant_lut_step4 [table_idx & 15] [get_bits(table_idx >> 4)]; return table_idx ? (&quantizer_table[table_idx - 1]) : nullptr; } void mp2Processor::read_samples (struct quantizer_spec *q, int scalefactor, int *sample) { int idx, adj, scale; int val; if (!q) { // no bits allocated for this subband sample[0] = sample[1] = sample[2] = 0; return; } // resolve scalefactor if (scalefactor == 63) { scalefactor = 0; } else { adj = scalefactor / 3; scalefactor = (scf_base[scalefactor % 3] + ((1 << adj) >> 1)) >> adj; } // decode samples adj = q -> nlevels; if (q -> grouping) { // decode grouped samples val = get_bits (q -> cw_bits); sample [0] = val % adj; val /= adj; sample [1] = val % adj; sample [2] = val / adj; } else { // decode direct samples for (idx = 0; idx < 3; ++idx) sample [idx] = get_bits (q -> cw_bits); } // postmultiply samples scale = 65536 / (adj + 1); adj = ((adj + 1) >> 1) - 1; for (idx = 0; idx < 3; ++idx) { // step 1: renormalization to [-1..1] val = (adj - sample[idx]) * scale; // step 2: apply scalefactor sample[idx] = ( val * (scalefactor >> 12) // upper part + ((val * (scalefactor & 4095) + 2048) >> 12)) // lower part >> 12; // scale adjust } } #define show_bits(bit_count) (bit_window >> (24 - (bit_count))) int32_t mp2Processor::get_bits (int32_t bit_count) { //int32_t result = show_bits (bit_count); int32_t result = bit_window >> (24 - bit_count); bit_window = (bit_window << bit_count) & 0xFFFFFF; bits_in_window -= bit_count; while (bits_in_window < 16) { bit_window |= (*frame_pos++) << (16 - bits_in_window); bits_in_window += 8; } return result; } //////////////////////////////////////////////////////////////////////////////// // FRAME DECODE FUNCTION // //////////////////////////////////////////////////////////////////////////////// int32_t mp2Processor::mp2decodeFrame (uint8_t *frame, int16_t *pcm) { uint32_t bit_rate_index_minus1; uint32_t sampling_frequency; uint32_t padding_bit; uint32_t mode; uint32_t frame_size; int32_t bound, sblimit; int32_t sb, ch, gr, part, idx, nch, i, j, sum; int32_t table_idx; numberofFrames ++; if (numberofFrames >= 25) { show_frameErrors (errorFrames); numberofFrames = 0; errorFrames = 0; } // check for valid header: syncword OK, MPEG-Audio Layer 2 if (( frame[0] != 0xFF) // no valid syncword? || ((frame[1] & 0xF6) != 0xF4) // no MPEG-1/2 Audio Layer II? || ((frame[2] - 0x10) >= 0xE0)) { // invalid bitrate? errorFrames ++; return 0; } // set up the bitstream reader bit_window = frame [2] << 16; bits_in_window = 8; frame_pos = &frame[3]; // read the rest of the header bit_rate_index_minus1 = get_bits(4) - 1; if (bit_rate_index_minus1 > 13) return 0; // invalid bit rate or 'free format' sampling_frequency = get_bits(2); if (sampling_frequency == 3) return 0; if ((frame[1] & 0x08) == 0) { // MPEG-2 sampling_frequency += 4; bit_rate_index_minus1 += 14; } padding_bit = get_bits(1); get_bits(1); // discard private_bit mode = get_bits(2); // parse the mode_extension, set up the stereo bound if (mode == JOINT_STEREO) bound = (get_bits(2) + 1) << 2; else { get_bits(2); bound = (mode == MONO) ? 0 : 32; } emit isStereo ((mode == JOINT_STEREO) || (mode == STEREO)); // discard the last 4 bits of the header and the CRC value, if present get_bits(4); if ((frame [1] & 1) == 0) get_bits(16); // compute the frame size frame_size = (144000 * bitrates[bit_rate_index_minus1] / sample_rates [sampling_frequency]) + padding_bit; if (!pcm) return frame_size; // no decoding // prepare the quantizer table lookups if (sampling_frequency & 4) { // MPEG-2 (LSR) table_idx = 2; sblimit = 30; } else { // MPEG-1 table_idx = (mode == MONO) ? 0 : 1; table_idx = quant_lut_step1[table_idx][bit_rate_index_minus1]; table_idx = quant_lut_step2[table_idx][sampling_frequency]; sblimit = table_idx & 63; table_idx >>= 6; } if (bound > sblimit) bound = sblimit; // read the allocation information for (sb = 0; sb < bound; ++sb) for (ch = 0; ch < 2; ++ch) allocation [ch][sb] = read_allocation(sb, table_idx); for (sb = bound; sb < sblimit; ++sb) allocation[0][sb] = allocation[1][sb] = read_allocation (sb, table_idx); // read scale factor selector information nch = (mode == MONO) ? 1 : 2; for (sb = 0; sb < sblimit; ++sb) { for (ch = 0; ch < nch; ++ch) if (allocation [ch][sb]) scfsi [ch][sb] = get_bits (2); if (mode == MONO) scfsi[1][sb] = scfsi[0][sb]; } // read scale factors for (sb = 0; sb < sblimit; ++sb) { for (ch = 0; ch < nch; ++ch) { if (allocation[ch][sb]) { switch (scfsi[ch][sb]) { case 0: scalefactor[ch][sb][0] = get_bits(6); scalefactor[ch][sb][1] = get_bits(6); scalefactor[ch][sb][2] = get_bits(6); break; case 1: scalefactor[ch][sb][0] = scalefactor[ch][sb][1] = get_bits(6); scalefactor[ch][sb][2] = get_bits(6); break; case 2: scalefactor[ch][sb][0] = scalefactor[ch][sb][1] = scalefactor[ch][sb][2] = get_bits(6); break; case 3: scalefactor[ch][sb][0] = get_bits(6); scalefactor[ch][sb][1] = scalefactor[ch][sb][2] = get_bits(6); break; } } } if (mode == MONO) for (part = 0; part < 3; ++part) scalefactor[1][sb][part] = scalefactor[0][sb][part]; } // coefficient input and reconstruction for (part = 0; part < 3; ++part) { for (gr = 0; gr < 4; ++gr) { // read the samples for (sb = 0; sb < bound; ++sb) for (ch = 0; ch < 2; ++ch) read_samples (allocation[ch][sb], scalefactor[ch][sb][part], &sample[ch][sb][0]); for (sb = bound; sb < sblimit; ++sb) { read_samples (allocation[0][sb], scalefactor[0][sb][part], &sample[0][sb][0]); for (idx = 0; idx < 3; ++idx) sample[1][sb][idx] = sample[0][sb][idx]; } for (ch = 0; ch < 2; ++ch) for (sb = sblimit; sb < 32; ++sb) for (idx = 0; idx < 3; ++idx) sample[ch][sb][idx] = 0; // synthesis loop for (idx = 0; idx < 3; ++idx) { // shifting step Voffs = table_idx = (Voffs - 64) & 1023; for (ch = 0; ch < 2; ++ch) { // matrixing for (i = 0; i < 64; ++i) { sum = 0; for (j = 0; j < 32; ++j) // 8b*15b=23b sum += N[i][j] * sample[ch][j][idx]; // intermediate value is 28 bit (23 + 5), clamp to 14b // V [ch][table_idx + i] = (sum + 8192) >> 14; } // construction of U for (i = 0; i < 8; ++i) for (j = 0; j < 32; ++j) { U [(i << 6) + j] = V [ch][(table_idx + (i << 7) + j) & 1023]; U [(i << 6) + j + 32] = V [ch][(table_idx + (i << 7) + j + 96) & 1023]; } // apply window for (i = 0; i < 512; ++i) U [i] = (U [i] * D [i] + 32) >> 6; // output samples for (j = 0; j < 32; ++j) { sum = 0; for (i = 0; i < 16; ++i) sum -= U [(i << 5) + j]; sum = (sum + 8) >> 4; if (sum < -32768) sum = -32768; if (sum > 32767) sum = 32767; pcm[(idx << 6) | (j << 1) | ch] = (uint16_t) sum; } } // end of synthesis channel loop } // end of synthesis sub-block loop // adjust PCM output pointer: decoded 3 * 32 = 96 stereo samples pcm += 192; } // decoding of the granule finished } return frame_size; } // // bits to MP2 frames, amount is amount of bits void mp2Processor::addtoFrame (std::vector<uint8_t> v) { int16_t i, j; int16_t lf = baudRate == 48000 ? MP2framesize : 2 * MP2framesize; int16_t amount = MP2framesize; uint8_t help [24 * bitRate / 8]; int16_t vLength = 24 * bitRate / 8; //fprintf (stderr, "baudrate = %d, inputsize = %d\n", // baudRate, v. size ()); // fprintf (stderr, "\n"); for (i = 0; i < 24 * bitRate / 8; i ++) { help [i] = 0; for (j = 0; j < 8; j ++) { help [i] <<= 1; help [i] |= v [8 * i + j] & 01; } } { uint8_t L0 = help [vLength - 1]; uint8_t L1 = help [vLength - 2]; int16_t down = bitRate * 1000 >= 56000 ? 4 : 2; my_padhandler. processPAD (help, vLength - 2 - down - 1, L1, L0); } for (i = 0; i < amount; i ++) { if (MP2Header_OK == 2) { addbittoMP2 (MP2frame, v [i], MP2bitCount ++); if (MP2bitCount >= lf) { int16_t sample_buf [KJMP2_SAMPLES_PER_FRAME * 2]; if (mp2decodeFrame (MP2frame, sample_buf)) { buffer -> putDataIntoBuffer (sample_buf, 2 * (int32_t)KJMP2_SAMPLES_PER_FRAME); if (buffer -> GetRingBufferReadAvailable () > baudRate / 8) newAudio (2 * (int32_t)KJMP2_SAMPLES_PER_FRAME, baudRate); } MP2Header_OK = 0; MP2headerCount = 0; MP2bitCount = 0; } } else if (MP2Header_OK == 0) { // apparently , we are not in sync yet if (v [i] == 01) { if (++ MP2headerCount == 12) { MP2bitCount = 0; for (j = 0; j < 12; j ++) addbittoMP2 (MP2frame, 1, MP2bitCount ++); MP2Header_OK = 1; } } else MP2headerCount = 0; } else if (MP2Header_OK == 1) { addbittoMP2 (MP2frame, v [i], MP2bitCount ++); if (MP2bitCount == 24) { setSamplerate (mp2sampleRate (MP2frame)); MP2Header_OK = 2; } } } } void mp2Processor::addbittoMP2 (uint8_t *v, uint8_t b, int16_t nm) { uint8_t byte = v [nm / 8]; int16_t bitnr = 7 - (nm & 7); uint8_t newbyte = (01 << bitnr); if (b == 0) byte &= ~newbyte; else byte |= newbyte; v [nm / 8] = byte; }
Java
#include <QApplication> #include <QMenuBar> #include <QMessageBox> #include <QFileDialog> #include <QVBoxLayout> #include <QDockWidget> #include <QProgressDialog> #include <QDesktopWidget> #include "vfs_dialog.h" #include "save_manager_dialog.h" #include "kernel_explorer.h" #include "game_list_frame.h" #include "debugger_frame.h" #include "log_frame.h" #include "settings_dialog.h" #include "auto_pause_settings_dialog.h" #include "cg_disasm_window.h" #include "memory_string_searcher.h" #include "memory_viewer_panel.h" #include "rsx_debugger.h" #include "main_window.h" #include "emu_settings.h" #include "about_dialog.h" #include "gamepads_settings_dialog.h" #include <thread> #include "stdafx.h" #include "Emu/System.h" #include "Emu/Memory/Memory.h" #include "Crypto/unpkg.h" #include "Crypto/unself.h" #include "Loader/PUP.h" #include "Loader/TAR.h" #include "Utilities/Thread.h" #include "Utilities/StrUtil.h" #include "rpcs3_version.h" #include "Utilities/sysinfo.h" #include "ui_main_window.h" inline std::string sstr(const QString& _in) { return _in.toUtf8().toStdString(); } main_window::main_window(std::shared_ptr<gui_settings> guiSettings, QWidget *parent) : QMainWindow(parent), guiSettings(guiSettings), m_sys_menu_opened(false), ui(new Ui::main_window) { } main_window::~main_window() { delete ui; } auto Pause = []() { if (Emu.IsReady()) Emu.Run(); else if (Emu.IsPaused()) Emu.Resume(); else if (Emu.IsRunning()) Emu.Pause(); else if (!Emu.GetPath().empty()) Emu.Load(); }; /* An init method is used so that RPCS3App can create the necessary connects before calling init (specifically the stylesheet connect). * Simplifies logic a bit. */ void main_window::Init() { ui->setupUi(this); m_appIcon = QIcon(":/rpcs3.ico"); // hide utilities from the average user ui->menuUtilities->menuAction()->setVisible(guiSettings->GetValue(GUI::m_showDebugTab).toBool()); // add toolbar widgets (crappy Qt designer is not able to) ui->toolBar->setObjectName("mw_toolbar"); ui->sizeSlider->setRange(0, GUI::gl_max_slider_pos); ui->sizeSlider->setSliderPosition(guiSettings->GetValue(GUI::gl_iconSize).toInt()); ui->toolBar->addWidget(ui->sizeSliderContainer); ui->toolBar->addSeparator(); ui->toolBar->addWidget(ui->mw_searchbar); // for highdpi resize toolbar icons and height dynamically // choose factors to mimic Gui-Design in main_window.ui // TODO: in case Qt::AA_EnableHighDpiScaling is enabled in main.cpp we only need the else branch #ifdef _WIN32 const int toolBarHeight = menuBar()->sizeHint().height() * 1.5; ui->toolBar->setIconSize(QSize(toolBarHeight, toolBarHeight)); #else const int toolBarHeight = ui->toolBar->iconSize().height(); #endif ui->sizeSliderContainer->setFixedWidth(toolBarHeight * 5); ui->sizeSlider->setFixedHeight(toolBarHeight * 0.65f); CreateActions(); CreateDockWindows(); setMinimumSize(350, minimumSizeHint().height()); // seems fine on win 10 CreateConnects(); setWindowTitle(QString::fromStdString("RPCS3 v" + rpcs3::version.to_string())); !m_appIcon.isNull() ? setWindowIcon(m_appIcon) : LOG_WARNING(GENERAL, "AppImage could not be loaded!"); Q_EMIT RequestGlobalStylesheetChange(guiSettings->GetCurrentStylesheetPath()); ConfigureGuiFromSettings(true); RepaintToolBarIcons(); m_gameListFrame->RepaintToolBarIcons(); if (!utils::has_ssse3()) { QMessageBox::critical(this, "SSSE3 Error (with three S, not two)", "Your system does not meet the minimum requirements needed to run RPCS3.\n" "Your CPU does not support SSSE3 (with three S, not two).\n"); std::exit(EXIT_FAILURE); } #ifdef BRANCH if ("RPCS3/rpcs3/master"s != STRINGIZE(BRANCH)) #elif _MSC_VER fs::stat_t st; if (!fs::stat(fs::get_config_dir() + "rpcs3.pdb", st) || st.is_directory || st.size < 1024 * 1024 * 100) #else if (false) #endif { LOG_WARNING(GENERAL, "Experimental Build Warning! Build origin: " STRINGIZE(BRANCH)); QMessageBox msg; msg.setWindowTitle("Experimental Build Warning"); msg.setWindowIcon(m_appIcon); msg.setIcon(QMessageBox::Critical); msg.setTextFormat(Qt::RichText); msg.setText("Please understand that this build is not an official RPCS3 release.<br>This build contains changes that may break games, or even <b>damage</b> your data.<br>It's recommended to download and use the official build from <a href='https://rpcs3.net/download'>RPCS3 website</a>.<br><br>Build origin: " STRINGIZE(BRANCH) "<br>Do you wish to use this build anyway?"); msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msg.setDefaultButton(QMessageBox::No); if (msg.exec() == QMessageBox::No) { std::exit(EXIT_SUCCESS); } } } void main_window::CreateThumbnailToolbar() { #ifdef _WIN32 m_icon_thumb_play = QIcon(":/Icons/play_blue.png"); m_icon_thumb_pause = QIcon(":/Icons/pause_blue.png"); m_icon_thumb_stop = QIcon(":/Icons/stop_blue.png"); m_icon_thumb_restart = QIcon(":/Icons/restart_blue.png"); m_thumb_bar = new QWinThumbnailToolBar(this); m_thumb_bar->setWindow(windowHandle()); m_thumb_playPause = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_playPause->setToolTip(tr("Pause")); m_thumb_playPause->setIcon(m_icon_thumb_pause); m_thumb_playPause->setEnabled(false); m_thumb_stop = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_stop->setToolTip(tr("Stop")); m_thumb_stop->setIcon(m_icon_thumb_stop); m_thumb_stop->setEnabled(false); m_thumb_restart = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_restart->setToolTip(tr("Restart")); m_thumb_restart->setIcon(m_icon_thumb_restart); m_thumb_restart->setEnabled(false); m_thumb_bar->addButton(m_thumb_playPause); m_thumb_bar->addButton(m_thumb_stop); m_thumb_bar->addButton(m_thumb_restart); connect(m_thumb_stop, &QWinThumbnailToolButton::clicked, [=]() { Emu.Stop(); }); connect(m_thumb_restart, &QWinThumbnailToolButton::clicked, [=]() { Emu.Stop(); Emu.Load(); }); connect(m_thumb_playPause, &QWinThumbnailToolButton::clicked, Pause); #endif } // returns appIcon QIcon main_window::GetAppIcon() { return m_appIcon; } // loads the appIcon from path and embeds it centered into an empty square icon void main_window::SetAppIconFromPath(const std::string path) { // get Icon for the gs_frame from path. this handles presumably all possible use cases QString qpath = qstr(path); std::string icon_list[] = { "/ICON0.PNG", "/PS3_GAME/ICON0.PNG" }; std::string path_list[] = { path, sstr(qpath.section("/", 0, -2)), sstr(qpath.section("/", 0, -3)) }; for (std::string pth : path_list) { if (!fs::is_dir(pth)) continue; for (std::string ico : icon_list) { ico = pth + ico; if (fs::is_file(ico)) { // load the image from path. It will most likely be a rectangle QImage source = QImage(qstr(ico)); int edgeMax = std::max(source.width(), source.height()); // create a new transparent image with square size and same format as source (maybe handle other formats than RGB32 as well?) QImage::Format format = source.format() == QImage::Format_RGB32 ? QImage::Format_ARGB32 : source.format(); QImage dest = QImage(edgeMax, edgeMax, format); dest.fill(QColor("transparent")); // get the location to draw the source image centered within the dest image. QPoint destPos = source.width() > source.height() ? QPoint(0, (source.width() - source.height()) / 2) : QPoint((source.height() - source.width()) / 2, 0); // Paint the source into/over the dest QPainter painter(&dest); painter.drawImage(destPos, source); painter.end(); // set Icon m_appIcon = QIcon(QPixmap::fromImage(dest)); return; } } } // if nothing was found reset the icon to default m_appIcon = QIcon(":/rpcs3.ico"); } void main_window::BootElf() { bool stopped = false; if (Emu.IsRunning()) { Emu.Pause(); stopped = true; } QString path_last_ELF = guiSettings->GetValue(GUI::fd_boot_elf).toString(); QString filePath = QFileDialog::getOpenFileName(this, tr("Select (S)ELF To Boot"), path_last_ELF, tr( "(S)ELF files (*BOOT.BIN *.elf *.self);;" "ELF files (BOOT.BIN *.elf);;" "SELF files (EBOOT.BIN *.self);;" "BOOT files (*BOOT.BIN);;" "BIN files (*.bin);;" "All files (*.*)"), Q_NULLPTR, QFileDialog::DontResolveSymlinks); if (filePath == NULL) { if (stopped) Emu.Resume(); return; } LOG_NOTICE(LOADER, "(S)ELF: booting..."); // If we resolved the filepath earlier we would end up setting the last opened dir to the unwanted // game folder in case of having e.g. a Game Folder with collected links to elf files. // Don't set last path earlier in case of cancelled dialog guiSettings->SetValue(GUI::fd_boot_elf, filePath); const std::string path = sstr(QFileInfo(filePath).canonicalFilePath()); SetAppIconFromPath(path); Emu.Stop(); if (!Emu.BootGame(path, true)) { LOG_ERROR(GENERAL, "PS3 executable not found at path (%s)", path); } else { LOG_SUCCESS(LOADER, "(S)ELF: boot done."); const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] "; AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle()))); m_gameListFrame->Refresh(true); } } void main_window::BootGame() { bool stopped = false; if (Emu.IsRunning()) { Emu.Pause(); stopped = true; } QString path_last_Game = guiSettings->GetValue(GUI::fd_boot_game).toString(); QString dirPath = QFileDialog::getExistingDirectory(this, tr("Select Game Folder"), path_last_Game, QFileDialog::ShowDirsOnly); if (dirPath == NULL) { if (stopped) Emu.Resume(); return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_boot_game, QFileInfo(dirPath).path()); const std::string path = sstr(dirPath); SetAppIconFromPath(path); if (!Emu.BootGame(path)) { LOG_ERROR(GENERAL, "PS3 executable not found in selected folder (%s)", path); } else { LOG_SUCCESS(LOADER, "Boot Game: boot done."); const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] "; AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle()))); m_gameListFrame->Refresh(true); } } void main_window::InstallPkg(const QString& dropPath) { QString filePath = dropPath; if (filePath.isEmpty()) { QString path_last_PKG = guiSettings->GetValue(GUI::fd_install_pkg).toString(); filePath = QFileDialog::getOpenFileName(this, tr("Select PKG To Install"), path_last_PKG, tr("PKG files (*.pkg);;All files (*.*)")); } else { if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Install package: %1?").arg(filePath), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_NOTICE(LOADER, "PKG: Cancelled installation from drop. File: %s", sstr(filePath)); return; } } if (filePath == NULL) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_install_pkg, QFileInfo(filePath).path()); const std::string fileName = sstr(QFileInfo(filePath).fileName()); const std::string path = sstr(filePath); // Open PKG file fs::file pkg_f(path); if (!pkg_f || pkg_f.size() < 64) { LOG_ERROR(LOADER, "PKG: Failed to open %s", path); return; } //Check header u32 pkg_signature; pkg_f.seek(0); pkg_f.read(pkg_signature); if (pkg_signature != "\x7FPKG"_u32) { LOG_ERROR(LOADER, "PKG: %s is not a pkg file", fileName); return; } // Get title ID std::vector<char> title_id(9); pkg_f.seek(55); pkg_f.read(title_id); pkg_f.seek(0); // Get full path const auto& local_path = Emu.GetHddDir() + "game/" + std::string(std::begin(title_id), std::end(title_id)); if (!fs::create_dir(local_path)) { if (fs::is_dir(local_path)) { if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Another installation found. Do you want to overwrite it?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_ERROR(LOADER, "PKG: Cancelled installation to existing directory %s", local_path); return; } } else { LOG_ERROR(LOADER, "PKG: Could not create the installation directory %s", local_path); return; } } QProgressDialog pdlg(tr("Installing package ... please wait ..."), tr("Cancel"), 0, 1000, this); pdlg.setWindowTitle(tr("RPCS3 Package Installer")); pdlg.setWindowModality(Qt::WindowModal); pdlg.setFixedSize(500, pdlg.height()); pdlg.show(); #ifdef _WIN32 QWinTaskbarButton *taskbar_button = new QWinTaskbarButton(); taskbar_button->setWindow(windowHandle()); QWinTaskbarProgress *taskbar_progress = taskbar_button->progress(); taskbar_progress->setRange(0, 1000); taskbar_progress->setVisible(true); #endif // Synchronization variable atomic_t<double> progress(0.); { // Run PKG unpacking asynchronously scope_thread worker("PKG Installer", [&] { if (pkg_install(pkg_f, local_path + '/', progress, path)) { progress = 1.; return; } // TODO: Ask user to delete files on cancellation/failure? progress = -1.; }); // Wait for the completion while (std::this_thread::sleep_for(5ms), std::abs(progress) < 1.) { if (pdlg.wasCanceled()) { progress -= 1.; #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Remove incomplete folder?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { fs::remove_all(local_path); m_gameListFrame->Refresh(true); LOG_SUCCESS(LOADER, "PKG: removed incomplete installation in %s", local_path); return; } break; } // Update progress window pdlg.setValue(static_cast<int>(progress * pdlg.maximum())); #ifdef _WIN32 taskbar_progress->setValue(static_cast<int>(progress * taskbar_progress->maximum())); #endif QCoreApplication::processEvents(); } if (progress > 0.) { pdlg.setValue(pdlg.maximum()); #ifdef _WIN32 taskbar_progress->setValue(taskbar_progress->maximum()); #endif std::this_thread::sleep_for(100ms); } } if (progress >= 1.) { m_gameListFrame->Refresh(true); LOG_SUCCESS(GENERAL, "Successfully installed %s.", fileName); guiSettings->ShowInfoBox(GUI::ib_pkg_success, tr("Success!"), tr("Successfully installed software from package!"), this); #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif } } void main_window::InstallPup(const QString& dropPath) { QString filePath = dropPath; if (filePath.isEmpty()) { QString path_last_PUP = guiSettings->GetValue(GUI::fd_install_pup).toString(); filePath = QFileDialog::getOpenFileName(this, tr("Select PS3UPDAT.PUP To Install"), path_last_PUP, tr("PS3 update file (PS3UPDAT.PUP)")); } else { if (QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Install firmware: %1?").arg(filePath), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_NOTICE(LOADER, "Firmware: Cancelled installation from drop. File: %s", sstr(filePath)); return; } } if (filePath == NULL) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_install_pup, QFileInfo(filePath).path()); const std::string path = sstr(filePath); fs::file pup_f(path); pup_object pup(pup_f); if (!pup) { LOG_ERROR(GENERAL, "Error while installing firmware: PUP file is invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP file is invalid.")); return; } fs::file update_files_f = pup.get_file(0x300); tar_object update_files(update_files_f); auto updatefilenames = update_files.get_filenames(); updatefilenames.erase(std::remove_if( updatefilenames.begin(), updatefilenames.end(), [](std::string s) { return s.find("dev_flash_") == std::string::npos; }), updatefilenames.end()); std::string version_string = pup.get_file(0x100).to_string(); version_string.erase(version_string.find('\n')); const std::string cur_version = "4.81"; if (version_string < cur_version && QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Old firmware detected.\nThe newest firmware version is %1 and you are trying to install version %2\nContinue installation?").arg(QString::fromStdString(cur_version), QString::fromStdString(version_string)), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No) { return; } QProgressDialog pdlg(tr("Installing firmware version %1\nPlease wait...").arg(QString::fromStdString(version_string)), tr("Cancel"), 0, static_cast<int>(updatefilenames.size()), this); pdlg.setWindowTitle(tr("RPCS3 Firmware Installer")); pdlg.setWindowModality(Qt::WindowModal); pdlg.setFixedSize(500, pdlg.height()); pdlg.show(); #ifdef _WIN32 QWinTaskbarButton *taskbar_button = new QWinTaskbarButton(); taskbar_button->setWindow(windowHandle()); QWinTaskbarProgress *taskbar_progress = taskbar_button->progress(); taskbar_progress->setRange(0, static_cast<int>(updatefilenames.size())); taskbar_progress->setVisible(true); #endif // Synchronization variable atomic_t<int> progress(0); { // Run asynchronously scope_thread worker("Firmware Installer", [&] { for (auto updatefilename : updatefilenames) { if (progress == -1) break; fs::file updatefile = update_files.get_file(updatefilename); SCEDecrypter self_dec(updatefile); self_dec.LoadHeaders(); self_dec.LoadMetadata(SCEPKG_ERK, SCEPKG_RIV); self_dec.DecryptData(); auto dev_flash_tar_f = self_dec.MakeFile(); if (dev_flash_tar_f.size() < 3) { LOG_ERROR(GENERAL, "Error while installing firmware: PUP contents are invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP contents are invalid.")); progress = -1; } tar_object dev_flash_tar(dev_flash_tar_f[2]); if (!dev_flash_tar.extract(fs::get_config_dir())) { LOG_ERROR(GENERAL, "Error while installing firmware: TAR contents are invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: TAR contents are invalid.")); progress = -1; } if (progress >= 0) progress += 1; } }); // Wait for the completion while (std::this_thread::sleep_for(5ms), std::abs(progress) < pdlg.maximum()) { if (pdlg.wasCanceled()) { progress = -1; #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif break; } // Update progress window pdlg.setValue(static_cast<int>(progress)); #ifdef _WIN32 taskbar_progress->setValue(static_cast<int>(progress)); #endif QCoreApplication::processEvents(); } update_files_f.close(); pup_f.close(); if (progress > 0) { pdlg.setValue(pdlg.maximum()); #ifdef _WIN32 taskbar_progress->setValue(taskbar_progress->maximum()); #endif std::this_thread::sleep_for(100ms); } } if (progress > 0) { LOG_SUCCESS(GENERAL, "Successfully installed PS3 firmware version %s.", version_string); guiSettings->ShowInfoBox(GUI::ib_pup_success, tr("Success!"), tr("Successfully installed PS3 firmware and LLE Modules!"), this); #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif } } // This is ugly, but PS3 headers shall not be included there. extern void sysutil_send_system_cmd(u64 status, u64 param); void main_window::DecryptSPRXLibraries() { QString path_last_SPRX = guiSettings->GetValue(GUI::fd_decrypt_sprx).toString(); QStringList modules = QFileDialog::getOpenFileNames(this, tr("Select SPRX files"), path_last_SPRX, tr("SPRX files (*.sprx)")); if (modules.isEmpty()) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_decrypt_sprx, QFileInfo(modules.first()).path()); LOG_NOTICE(GENERAL, "Decrypting SPRX libraries..."); for (QString& module : modules) { std::string prx_path = sstr(module); const std::string& prx_dir = fs::get_parent_dir(prx_path); fs::file elf_file(prx_path); if (elf_file && elf_file.size() >= 4 && elf_file.read<u32>() == "SCE\0"_u32) { const std::size_t prx_ext_pos = prx_path.find_last_of('.'); const std::string& prx_name = prx_path.substr(prx_dir.size()); elf_file = decrypt_self(std::move(elf_file)); prx_path.erase(prx_path.size() - 4, 1); // change *.sprx to *.prx if (elf_file) { if (fs::file new_file{ prx_path, fs::rewrite }) { new_file.write(elf_file.to_string()); LOG_SUCCESS(GENERAL, "Decrypted %s", prx_dir + prx_name); } else { LOG_ERROR(GENERAL, "Failed to create %s", prx_path); } } else { LOG_ERROR(GENERAL, "Failed to decrypt %s", prx_dir + prx_name); } } } LOG_NOTICE(GENERAL, "Finished decrypting all SPRX libraries."); } /** Needed so that when a backup occurs of window state in guisettings, the state is current. * Also, so that on close, the window state is preserved. */ void main_window::SaveWindowState() { // Save gui settings guiSettings->SetValue(GUI::mw_geometry, saveGeometry()); guiSettings->SetValue(GUI::mw_windowState, saveState()); guiSettings->SetValue(GUI::mw_mwState, m_mw->saveState()); // Save column settings m_gameListFrame->SaveSettings(); // Save splitter state m_debuggerFrame->SaveSettings(); } void main_window::RepaintToolBarIcons() { QColor newColor; if (guiSettings->GetValue(GUI::m_enableUIColors).toBool()) { newColor = guiSettings->GetValue(GUI::mw_toolIconColor).value<QColor>(); } else { newColor = GUI::get_Label_Color("toolbar_icon_color"); } auto icon = [&newColor](const QString& path) { return gui_settings::colorizedIcon(QIcon(path), GUI::mw_tool_icon_color, newColor); }; m_icon_play = icon(":/Icons/play.png"); m_icon_pause = icon(":/Icons/pause.png"); m_icon_stop = icon(":/Icons/stop.png"); m_icon_restart = icon(":/Icons/restart.png"); m_icon_fullscreen_on = icon(":/Icons/fullscreen.png"); m_icon_fullscreen_off = icon(":/Icons/fullscreen_invert.png"); ui->toolbar_config ->setIcon(icon(":/Icons/configure.png")); ui->toolbar_controls->setIcon(icon(":/Icons/controllers.png")); ui->toolbar_disc ->setIcon(icon(":/Icons/disc.png")); ui->toolbar_grid ->setIcon(icon(":/Icons/grid.png")); ui->toolbar_list ->setIcon(icon(":/Icons/list.png")); ui->toolbar_refresh ->setIcon(icon(":/Icons/refresh.png")); ui->toolbar_snap ->setIcon(icon(":/Icons/screenshot.png")); ui->toolbar_sort ->setIcon(icon(":/Icons/sort.png")); ui->toolbar_stop ->setIcon(icon(":/Icons/stop.png")); if (Emu.IsRunning()) { ui->toolbar_start->setIcon(m_icon_pause); } else if (Emu.IsStopped() && !Emu.GetPath().empty()) { ui->toolbar_start->setIcon(m_icon_restart); } else { ui->toolbar_start->setIcon(m_icon_play); } if (isFullScreen()) { ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } else { ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off); } ui->sizeSlider->setStyleSheet(ui->sizeSlider->styleSheet().append("QSlider::handle:horizontal{ background: rgba(%1, %2, %3, %4); }") .arg(newColor.red()).arg(newColor.green()).arg(newColor.blue()).arg(newColor.alpha())); } void main_window::OnEmuRun() { m_debuggerFrame->EnableButtons(true); #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Pause emulation")); m_thumb_playPause->setIcon(m_icon_thumb_pause); #endif ui->sysPauseAct->setText(tr("&Pause\tCtrl+P")); ui->sysPauseAct->setIcon(m_icon_pause); ui->toolbar_start->setIcon(m_icon_pause); ui->toolbar_start->setToolTip(tr("Pause emulation")); EnableMenus(true); } void main_window::OnEmuResume() { #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Pause emulation")); m_thumb_playPause->setIcon(m_icon_thumb_pause); #endif ui->sysPauseAct->setText(tr("&Pause\tCtrl+P")); ui->sysPauseAct->setIcon(m_icon_pause); ui->toolbar_start->setIcon(m_icon_pause); ui->toolbar_start->setToolTip(tr("Pause emulation")); } void main_window::OnEmuPause() { #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif ui->sysPauseAct->setText(tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(tr("Resume emulation")); } void main_window::OnEmuStop() { m_debuggerFrame->EnableButtons(false); m_debuggerFrame->ClearBreakpoints(); ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); #ifdef _WIN32 m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif EnableMenus(false); if (!Emu.GetPath().empty()) { ui->toolbar_start->setEnabled(true); ui->toolbar_start->setIcon(m_icon_restart); ui->toolbar_start->setToolTip(tr("Restart emulation")); ui->sysRebootAct->setEnabled(true); #ifdef _WIN32 m_thumb_restart->setEnabled(true); #endif } else { ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); } } void main_window::OnEmuReady() { m_debuggerFrame->EnableButtons(true); #ifdef _WIN32 m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); EnableMenus(true); } void main_window::EnableMenus(bool enabled) { // Thumbnail Buttons #ifdef _WIN32 m_thumb_playPause->setEnabled(enabled); m_thumb_stop->setEnabled(enabled); m_thumb_restart->setEnabled(enabled); #endif // Toolbar ui->toolbar_start->setEnabled(enabled); ui->toolbar_stop->setEnabled(enabled); // Emulation ui->sysPauseAct->setEnabled(enabled); ui->sysStopAct->setEnabled(enabled); ui->sysRebootAct->setEnabled(enabled); // PS3 Commands ui->sysSendOpenMenuAct->setEnabled(enabled); ui->sysSendExitAct->setEnabled(enabled); // Tools ui->toolskernel_explorerAct->setEnabled(enabled); ui->toolsmemory_viewerAct->setEnabled(enabled); ui->toolsRsxDebuggerAct->setEnabled(enabled); ui->toolsStringSearchAct->setEnabled(enabled); } void main_window::BootRecentAction(const QAction* act) { if (Emu.IsRunning()) { return; } const QString pth = act->data().toString(); QString nam; bool containsPath = false; int idx = -1; for (int i = 0; i < m_rg_entries.count(); i++) { if (m_rg_entries.at(i).first == pth) { idx = i; containsPath = true; nam = m_rg_entries.at(idx).second; } } // path is invalid: remove action from list return if ((containsPath && nam.isEmpty()) || (!QFileInfo(pth).isDir() && !QFileInfo(pth).isFile())) { if (containsPath) { // clear menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } // remove action from list m_rg_entries.removeAt(idx); m_recentGameActs.removeAt(idx); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); LOG_ERROR(GENERAL, "Recent Game not valid, removed from Boot Recent list: %s", sstr(pth)); // refill menu with actions for (int i = 0; i < m_recentGameActs.count(); i++) { m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i + 1)); m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second); ui->bootRecentMenu->addAction(m_recentGameActs[i]); } LOG_WARNING(GENERAL, "Boot Recent list refreshed"); return; } LOG_ERROR(GENERAL, "Path invalid and not in m_rg_paths: %s", sstr(pth)); return; } SetAppIconFromPath(sstr(pth)); Emu.Stop(); if (!Emu.BootGame(sstr(pth), true)) { LOG_ERROR(LOADER, "Failed to boot %s", sstr(pth)); } else { LOG_SUCCESS(LOADER, "Boot from Recent List: done"); AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), nam)); m_gameListFrame->Refresh(true); } }; QAction* main_window::CreateRecentAction(const q_string_pair& entry, const uint& sc_idx) { // if path is not valid remove from list if (entry.second.isEmpty() || (!QFileInfo(entry.first).isDir() && !QFileInfo(entry.first).isFile())) { if (m_rg_entries.contains(entry)) { LOG_ERROR(GENERAL, "Recent Game not valid, removing from Boot Recent list: %s", sstr(entry.first)); int idx = m_rg_entries.indexOf(entry); m_rg_entries.removeAt(idx); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); } return nullptr; } // if name is a path get filename QString shown_name = entry.second; if (QFileInfo(entry.second).isFile()) { shown_name = entry.second.section('/', -1); } // create new action QAction* act = new QAction(shown_name, this); act->setData(entry.first); act->setToolTip(entry.second); act->setShortcut(tr("Ctrl+%1").arg(sc_idx)); // truncate if too long if (shown_name.length() > 60) { act->setText(shown_name.left(27) + "(....)" + shown_name.right(27)); } // connect boot connect(act, &QAction::triggered, [=]() {BootRecentAction(act); }); return act; }; void main_window::AddRecentAction(const q_string_pair& entry) { // don't change list on freeze if (ui->freezeRecentAct->isChecked()) { return; } // create new action, return if not valid QAction* act = CreateRecentAction(entry, 1); if (!act) { return; } // clear menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } // if path already exists, remove it in order to get it to beginning if (m_rg_entries.contains(entry)) { int idx = m_rg_entries.indexOf(entry); m_rg_entries.removeAt(idx); m_recentGameActs.removeAt(idx); } // remove oldest action at the end if needed if (m_rg_entries.count() == 9) { m_rg_entries.removeLast(); m_recentGameActs.removeLast(); } else if (m_rg_entries.count() > 9) { LOG_ERROR(LOADER, "Recent games entrylist too big"); } if (m_rg_entries.count() < 9) { // add new action at the beginning m_rg_entries.prepend(entry); m_recentGameActs.prepend(act); } // refill menu with actions for (int i = 0; i < m_recentGameActs.count(); i++) { m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i+1)); m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second); ui->bootRecentMenu->addAction(m_recentGameActs[i]); } guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); } void main_window::RepaintGui() { m_gameListFrame->RepaintIcons(true); m_gameListFrame->RepaintToolBarIcons(); RepaintToolbar(); RepaintToolBarIcons(); } void main_window::RepaintToolbar() { if (guiSettings->GetValue(GUI::m_enableUIColors).toBool()) { QColor tbc = guiSettings->GetValue(GUI::mw_toolBarColor).value<QColor>(); ui->toolBar->setStyleSheet(GUI::stylesheet + QString( "QToolBar { background-color: rgba(%1, %2, %3, %4); }" "QToolBar::separator {background-color: rgba(%5, %6, %7, %8); width: 1px; margin-top: 2px; margin-bottom: 2px;}" "QSlider { background-color: rgba(%1, %2, %3, %4); }" "QLineEdit { background-color: rgba(%1, %2, %3, %4); }") .arg(tbc.red()).arg(tbc.green()).arg(tbc.blue()).arg(tbc.alpha()) .arg(tbc.red() - 20).arg(tbc.green() - 20).arg(tbc.blue() - 20).arg(tbc.alpha() - 20) ); } else { ui->toolBar->setStyleSheet(GUI::stylesheet); } } void main_window::CreateActions() { ui->exitAct->setShortcuts(QKeySequence::Quit); ui->toolbar_start->setEnabled(false); ui->toolbar_stop->setEnabled(false); m_categoryVisibleActGroup = new QActionGroup(this); m_categoryVisibleActGroup->addAction(ui->showCatHDDGameAct); m_categoryVisibleActGroup->addAction(ui->showCatDiscGameAct); m_categoryVisibleActGroup->addAction(ui->showCatHomeAct); m_categoryVisibleActGroup->addAction(ui->showCatAudioVideoAct); m_categoryVisibleActGroup->addAction(ui->showCatGameDataAct); m_categoryVisibleActGroup->addAction(ui->showCatUnknownAct); m_categoryVisibleActGroup->addAction(ui->showCatOtherAct); m_categoryVisibleActGroup->setExclusive(false); m_iconSizeActGroup = new QActionGroup(this); m_iconSizeActGroup->addAction(ui->setIconSizeTinyAct); m_iconSizeActGroup->addAction(ui->setIconSizeSmallAct); m_iconSizeActGroup->addAction(ui->setIconSizeMediumAct); m_iconSizeActGroup->addAction(ui->setIconSizeLargeAct); m_listModeActGroup = new QActionGroup(this); m_listModeActGroup->addAction(ui->setlistModeListAct); m_listModeActGroup->addAction(ui->setlistModeGridAct); } void main_window::CreateConnects() { connect(ui->bootElfAct, &QAction::triggered, this, &main_window::BootElf); connect(ui->bootGameAct, &QAction::triggered, this, &main_window::BootGame); connect(ui->bootRecentMenu, &QMenu::aboutToShow, [=] { // Enable/Disable Recent Games List const bool stopped = Emu.IsStopped(); for (auto act : ui->bootRecentMenu->actions()) { if (act != ui->freezeRecentAct && act != ui->clearRecentAct) { act->setEnabled(stopped); } } }); connect(ui->clearRecentAct, &QAction::triggered, [this] { if (ui->freezeRecentAct->isChecked()) { return; } m_rg_entries.clear(); for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } m_recentGameActs.clear(); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(q_pair_list())); }); connect(ui->freezeRecentAct, &QAction::triggered, [=](bool checked) { guiSettings->SetValue(GUI::rg_freeze, checked); }); connect(ui->bootInstallPkgAct, &QAction::triggered, [this] {InstallPkg(); }); connect(ui->bootInstallPupAct, &QAction::triggered, [this] {InstallPup(); }); connect(ui->exitAct, &QAction::triggered, this, &QWidget::close); connect(ui->sysPauseAct, &QAction::triggered, Pause); connect(ui->sysStopAct, &QAction::triggered, [=]() { Emu.Stop(); }); connect(ui->sysRebootAct, &QAction::triggered, [=]() { Emu.Stop(); Emu.Load(); }); connect(ui->sysSendOpenMenuAct, &QAction::triggered, [=] { sysutil_send_system_cmd(m_sys_menu_opened ? 0x0132 /* CELL_SYSUTIL_SYSTEM_MENU_CLOSE */ : 0x0131 /* CELL_SYSUTIL_SYSTEM_MENU_OPEN */, 0); m_sys_menu_opened = !m_sys_menu_opened; ui->sysSendOpenMenuAct->setText(tr("Send &%0 system menu cmd").arg(m_sys_menu_opened ? tr("close") : tr("open"))); }); connect(ui->sysSendExitAct, &QAction::triggered, [=] { sysutil_send_system_cmd(0x0101 /* CELL_SYSUTIL_REQUEST_EXITGAME */, 0); }); auto openSettings = [=](int tabIndex) { settings_dialog dlg(guiSettings, m_Render_Creator, tabIndex, this); connect(&dlg, &settings_dialog::GuiSettingsSaveRequest, this, &main_window::SaveWindowState); connect(&dlg, &settings_dialog::GuiSettingsSyncRequest, [=]() {ConfigureGuiFromSettings(true); }); connect(&dlg, &settings_dialog::GuiStylesheetRequest, this, &main_window::RequestGlobalStylesheetChange); connect(&dlg, &settings_dialog::GuiRepaintRequest, this, &main_window::RepaintGui); dlg.exec(); }; connect(ui->confCPUAct, &QAction::triggered, [=]() { openSettings(0); }); connect(ui->confGPUAct, &QAction::triggered, [=]() { openSettings(1); }); connect(ui->confAudioAct, &QAction::triggered, [=]() { openSettings(2); }); connect(ui->confIOAct, &QAction::triggered, [=]() { openSettings(3); }); connect(ui->confSystemAct, &QAction::triggered, [=]() { openSettings(4); }); connect(ui->confPadsAct, &QAction::triggered, this, [=] { gamepads_settings_dialog dlg(this); dlg.exec(); }); connect(ui->confAutopauseManagerAct, &QAction::triggered, [=] { auto_pause_settings_dialog dlg(this); dlg.exec(); }); connect(ui->confVFSDialogAct, &QAction::triggered, [=] { vfs_dialog dlg(this); dlg.exec(); m_gameListFrame->Refresh(true); // dev-hdd0 may have changed. Refresh just in case. }); connect(ui->confSavedataManagerAct, &QAction::triggered, [=] { save_manager_dialog* sdid = new save_manager_dialog(); sdid->show(); }); connect(ui->toolsCgDisasmAct, &QAction::triggered, [=] { cg_disasm_window* cgdw = new cg_disasm_window(guiSettings); cgdw->show(); }); connect(ui->toolskernel_explorerAct, &QAction::triggered, [=] { kernel_explorer* kernelExplorer = new kernel_explorer(this); kernelExplorer->show(); }); connect(ui->toolsmemory_viewerAct, &QAction::triggered, [=] { memory_viewer_panel* mvp = new memory_viewer_panel(this); mvp->show(); }); connect(ui->toolsRsxDebuggerAct, &QAction::triggered, [=] { rsx_debugger* rsx = new rsx_debugger(this); rsx->show(); }); connect(ui->toolsStringSearchAct, &QAction::triggered, [=] { memory_string_searcher* mss = new memory_string_searcher(this); mss->show(); }); connect(ui->toolsDecryptSprxLibsAct, &QAction::triggered, this, &main_window::DecryptSPRXLibraries); connect(ui->showDebuggerAct, &QAction::triggered, [=](bool checked) { checked ? m_debuggerFrame->show() : m_debuggerFrame->hide(); guiSettings->SetValue(GUI::mw_debugger, checked); }); connect(ui->showLogAct, &QAction::triggered, [=](bool checked) { checked ? m_logFrame->show() : m_logFrame->hide(); guiSettings->SetValue(GUI::mw_logger, checked); }); connect(ui->showGameListAct, &QAction::triggered, [=](bool checked) { checked ? m_gameListFrame->show() : m_gameListFrame->hide(); guiSettings->SetValue(GUI::mw_gamelist, checked); }); connect(ui->showToolBarAct, &QAction::triggered, [=](bool checked) { ui->toolBar->setVisible(checked); guiSettings->SetValue(GUI::mw_toolBarVisible, checked); }); connect(ui->showGameToolBarAct, &QAction::triggered, [=](bool checked) { m_gameListFrame->SetToolBarVisible(checked); }); connect(ui->refreshGameListAct, &QAction::triggered, [=] { m_gameListFrame->Refresh(true); }); connect(m_categoryVisibleActGroup, &QActionGroup::triggered, [=](QAction* act) { QStringList categories; int id; const bool& checked = act->isChecked(); if (act == ui->showCatHDDGameAct) categories += category::non_disc_games, id = Category::Non_Disc_Game; else if (act == ui->showCatDiscGameAct) categories += category::disc_Game, id = Category::Disc_Game; else if (act == ui->showCatHomeAct) categories += category::home, id = Category::Home; else if (act == ui->showCatAudioVideoAct) categories += category::media, id = Category::Media; else if (act == ui->showCatGameDataAct) categories += category::data, id = Category::Data; else if (act == ui->showCatUnknownAct) categories += category::unknown, id = Category::Unknown_Cat; else if (act == ui->showCatOtherAct) categories += category::others, id = Category::Others; else LOG_WARNING(GENERAL, "categoryVisibleActGroup: category action not found"); m_gameListFrame->SetCategoryActIcon(m_categoryVisibleActGroup->actions().indexOf(act), checked); m_gameListFrame->ToggleCategoryFilter(categories, checked); guiSettings->SetCategoryVisibility(id, checked); }); connect(ui->aboutAct, &QAction::triggered, [this] { about_dialog dlg(this); dlg.exec(); }); connect(ui->aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); auto resizeIcons = [=](const int& index) { int val = ui->sizeSlider->value(); if (val != index) { ui->sizeSlider->setSliderPosition(index); } if (val != m_gameListFrame->GetSliderValue()) { if (m_save_slider_pos) { m_save_slider_pos = false; guiSettings->SetValue(GUI::gl_iconSize, index); } m_gameListFrame->ResizeIcons(index); } }; connect(m_iconSizeActGroup, &QActionGroup::triggered, [=](QAction* act) { int index; if (act == ui->setIconSizeTinyAct) index = 0; else if (act == ui->setIconSizeSmallAct) index = GUI::get_Index(GUI::gl_icon_size_small); else if (act == ui->setIconSizeMediumAct) index = GUI::get_Index(GUI::gl_icon_size_medium); else index = GUI::gl_max_slider_pos; resizeIcons(index); }); connect (m_gameListFrame, &game_list_frame::RequestIconSizeActSet, [=](const int& idx) { if (idx < GUI::get_Index((GUI::gl_icon_size_small + GUI::gl_icon_size_min) / 2)) ui->setIconSizeTinyAct->setChecked(true); else if (idx < GUI::get_Index((GUI::gl_icon_size_medium + GUI::gl_icon_size_small) / 2)) ui->setIconSizeSmallAct->setChecked(true); else if (idx < GUI::get_Index((GUI::gl_icon_size_max + GUI::gl_icon_size_medium) / 2)) ui->setIconSizeMediumAct->setChecked(true); else ui->setIconSizeLargeAct->setChecked(true); resizeIcons(idx); }); connect(m_gameListFrame, &game_list_frame::RequestSaveSliderPos, [=](const bool& save) { Q_UNUSED(save); m_save_slider_pos = true; }); connect(m_gameListFrame, &game_list_frame::RequestListModeActSet, [=](const bool& isList) { isList ? ui->setlistModeListAct->trigger() : ui->setlistModeGridAct->trigger(); }); connect(m_gameListFrame, &game_list_frame::RequestCategoryActSet, [=](const int& id) { m_categoryVisibleActGroup->actions().at(id)->trigger(); }); connect(m_listModeActGroup, &QActionGroup::triggered, [=](QAction* act) { bool isList = act == ui->setlistModeListAct; m_gameListFrame->SetListMode(isList); m_categoryVisibleActGroup->setEnabled(isList); }); connect(ui->toolbar_disc, &QAction::triggered, this, &main_window::BootGame); connect(ui->toolbar_refresh, &QAction::triggered, [=]() { m_gameListFrame->Refresh(true); }); connect(ui->toolbar_stop, &QAction::triggered, [=]() { Emu.Stop(); }); connect(ui->toolbar_start, &QAction::triggered, Pause); connect(ui->toolbar_fullscreen, &QAction::triggered, [=] { if (isFullScreen()) { showNormal(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } else { showFullScreen(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off); } }); connect(ui->toolbar_controls, &QAction::triggered, [=]() { gamepads_settings_dialog dlg(this); dlg.exec(); }); connect(ui->toolbar_config, &QAction::triggered, [=]() { openSettings(0); }); connect(ui->toolbar_list, &QAction::triggered, [=]() { ui->setlistModeListAct->trigger(); }); connect(ui->toolbar_grid, &QAction::triggered, [=]() { ui->setlistModeGridAct->trigger(); }); connect(ui->sizeSlider, &QSlider::valueChanged, resizeIcons); connect(ui->sizeSlider, &QSlider::sliderReleased, this, [&] { guiSettings->SetValue(GUI::gl_iconSize, ui->sizeSlider->value()); }); connect(ui->sizeSlider, &QSlider::actionTriggered, [&](int action) { if (action != QAbstractSlider::SliderNoAction && action != QAbstractSlider::SliderMove) { // we only want to save on mouseclicks or slider release (the other connect handles this) m_save_slider_pos = true; // actionTriggered happens before the value was changed } }); connect(ui->mw_searchbar, &QLineEdit::textChanged, m_gameListFrame, &game_list_frame::SetSearchText); } void main_window::CreateDockWindows() { // new mainwindow widget because existing seems to be bugged for now m_mw = new QMainWindow(); m_gameListFrame = new game_list_frame(guiSettings, m_Render_Creator, m_mw); m_gameListFrame->setObjectName("gamelist"); m_debuggerFrame = new debugger_frame(guiSettings, m_mw); m_debuggerFrame->setObjectName("debugger"); m_logFrame = new log_frame(guiSettings, m_mw); m_logFrame->setObjectName("logger"); m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_gameListFrame); m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_logFrame); m_mw->addDockWidget(Qt::RightDockWidgetArea, m_debuggerFrame); m_mw->setDockNestingEnabled(true); setCentralWidget(m_mw); connect(m_logFrame, &log_frame::LogFrameClosed, [=]() { if (ui->showLogAct->isChecked()) { ui->showLogAct->setChecked(false); guiSettings->SetValue(GUI::mw_logger, false); } }); connect(m_debuggerFrame, &debugger_frame::DebugFrameClosed, [=]() { if (ui->showDebuggerAct->isChecked()) { ui->showDebuggerAct->setChecked(false); guiSettings->SetValue(GUI::mw_debugger, false); } }); connect(m_gameListFrame, &game_list_frame::GameListFrameClosed, [=]() { if (ui->showGameListAct->isChecked()) { ui->showGameListAct->setChecked(false); guiSettings->SetValue(GUI::mw_gamelist, false); } }); connect(m_gameListFrame, &game_list_frame::RequestIconPathSet, this, &main_window::SetAppIconFromPath); connect(m_gameListFrame, &game_list_frame::RequestAddRecentGame, this, &main_window::AddRecentAction); connect(m_gameListFrame, &game_list_frame::RequestPackageInstall, [this](const QStringList& paths) { for (const auto& path : paths) { InstallPkg(path); } }); connect(m_gameListFrame, &game_list_frame::RequestFirmwareInstall, this, &main_window::InstallPup); } void main_window::ConfigureGuiFromSettings(bool configureAll) { // Restore GUI state if needed. We need to if they exist. QByteArray geometry = guiSettings->GetValue(GUI::mw_geometry).toByteArray(); if (geometry.isEmpty() == false) { restoreGeometry(geometry); } else { // By default, set the window to 70% of the screen and the debugger frame is hidden. m_debuggerFrame->hide(); QSize defaultSize = QDesktopWidget().availableGeometry().size() * 0.7; resize(defaultSize); } restoreState(guiSettings->GetValue(GUI::mw_windowState).toByteArray()); m_mw->restoreState(guiSettings->GetValue(GUI::mw_mwState).toByteArray()); ui->freezeRecentAct->setChecked(guiSettings->GetValue(GUI::rg_freeze).toBool()); m_rg_entries = guiSettings->Var2List(guiSettings->GetValue(GUI::rg_entries)); // clear recent games menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } m_recentGameActs.clear(); // Fill the recent games menu for (int i = 0; i < m_rg_entries.count(); i++) { // adjust old unformatted entries (avoid duplication) m_rg_entries[i] = GUI::Recent_Game(m_rg_entries[i].first, m_rg_entries[i].second); // create new action QAction* act = CreateRecentAction(m_rg_entries[i], i + 1); // add action to menu if (act) { m_recentGameActs.append(act); ui->bootRecentMenu->addAction(act); } else { i--; // list count is now an entry shorter so we have to repeat the same index in order to load all other entries } } ui->showLogAct->setChecked(guiSettings->GetValue(GUI::mw_logger).toBool()); ui->showGameListAct->setChecked(guiSettings->GetValue(GUI::mw_gamelist).toBool()); ui->showDebuggerAct->setChecked(guiSettings->GetValue(GUI::mw_debugger).toBool()); ui->showToolBarAct->setChecked(guiSettings->GetValue(GUI::mw_toolBarVisible).toBool()); ui->showGameToolBarAct->setChecked(guiSettings->GetValue(GUI::gl_toolBarVisible).toBool()); m_debuggerFrame->setVisible(ui->showDebuggerAct->isChecked()); m_logFrame->setVisible(ui->showLogAct->isChecked()); m_gameListFrame->setVisible(ui->showGameListAct->isChecked()); m_gameListFrame->SetToolBarVisible(ui->showGameToolBarAct->isChecked()); ui->toolBar->setVisible(ui->showToolBarAct->isChecked()); RepaintToolbar(); ui->showCatHDDGameAct->setChecked(guiSettings->GetCategoryVisibility(Category::Non_Disc_Game)); ui->showCatDiscGameAct->setChecked(guiSettings->GetCategoryVisibility(Category::Disc_Game)); ui->showCatHomeAct->setChecked(guiSettings->GetCategoryVisibility(Category::Home)); ui->showCatAudioVideoAct->setChecked(guiSettings->GetCategoryVisibility(Category::Media)); ui->showCatGameDataAct->setChecked(guiSettings->GetCategoryVisibility(Category::Data)); ui->showCatUnknownAct->setChecked(guiSettings->GetCategoryVisibility(Category::Unknown_Cat)); ui->showCatOtherAct->setChecked(guiSettings->GetCategoryVisibility(Category::Others)); int idx = guiSettings->GetValue(GUI::gl_iconSize).toInt(); int index = GUI::gl_max_slider_pos / 4; if (idx < index) ui->setIconSizeTinyAct->setChecked(true); else if (idx < index * 2) ui->setIconSizeSmallAct->setChecked(true); else if (idx < index * 3) ui->setIconSizeMediumAct->setChecked(true); else ui->setIconSizeLargeAct->setChecked(true); bool isListMode = guiSettings->GetValue(GUI::gl_listMode).toBool(); if (isListMode) ui->setlistModeListAct->setChecked(true); else ui->setlistModeGridAct->setChecked(true); m_categoryVisibleActGroup->setEnabled(isListMode); if (configureAll) { // Handle log settings m_logFrame->LoadSettings(); // Gamelist m_gameListFrame->LoadSettings(); } } void main_window::keyPressEvent(QKeyEvent *keyEvent) { if (((keyEvent->modifiers() & Qt::AltModifier) && keyEvent->key() == Qt::Key_Return) || (isFullScreen() && keyEvent->key() == Qt::Key_Escape)) { ui->toolbar_fullscreen->trigger(); } if (keyEvent->modifiers() & Qt::ControlModifier) { switch (keyEvent->key()) { case Qt::Key_E: if (Emu.IsPaused()) Emu.Resume(); else if (Emu.IsReady()) Emu.Run(); return; case Qt::Key_P: if (Emu.IsRunning()) Emu.Pause(); return; case Qt::Key_S: if (!Emu.IsStopped()) Emu.Stop(); return; case Qt::Key_R: if (!Emu.GetPath().empty()) { Emu.Stop(); Emu.Run(); } return; } } } void main_window::mouseDoubleClickEvent(QMouseEvent *event) { if (isFullScreen()) { if (event->button() == Qt::LeftButton) { showNormal(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } } } /** Override the Qt close event to have the emulator stop and the application die. May add a warning dialog in future. */ void main_window::closeEvent(QCloseEvent* closeEvent) { Q_UNUSED(closeEvent); // Cleanly stop the emulator. Emu.Stop(); SaveWindowState(); // I need the gui settings to sync, and that means having the destructor called as guiSetting's parent is main_window. setAttribute(Qt::WA_DeleteOnClose); QMainWindow::close(); // It's possible to have other windows open, like games. So, force the application to die. QApplication::quit(); }
Java
<?php /** * Elgg Gifts plugin * Send gifts to you friends * * @package Gifts * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2 * @author Christian Heckelmann * @copyright Christian Heckelmann * @link http://www.heckelmann.info * * updated by iionly (iionly@gmx.de) */ // Show your sent gifts elgg_push_breadcrumb(elgg_echo('gifts:menu'), 'gifts/' . elgg_get_logged_in_user_entity()->username. '/index'); $title = elgg_echo('gifts:sent'); elgg_push_breadcrumb($title); if (elgg_is_logged_in()) { elgg_register_menu_item('title', [ 'name' => 'sendgift', 'href' => "gifts/" . elgg_get_logged_in_user_entity()->username . "/sendgift", 'text' => elgg_echo('gifts:sendgifts'), 'link_class' => 'elgg-button elgg-button-action', ]); } $content = elgg_list_entities([ 'type' => 'object', 'subtype' => Gifts::SUBTYPE, 'owner_guid' => elgg_get_logged_in_user_guid(), 'no_results' => elgg_echo('gifts:nogifts'), ]); // Format page $body = elgg_view_layout('content', [ 'content' => $content, 'filter' => '', 'title' => $title, ]); // Draw it echo elgg_view_page($title, $body);
Java
<?php /** * Checkout coupon form * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce; if ( ! WC()->cart->coupons_enabled() ) return; $info_message = apply_filters( 'woocommerce_checkout_coupon_message', __( 'Have a coupon?', 'woocommerce' ) ); $info_message .= ' <a href="#" class="showcoupon">' . __( 'Click here to enter your code', 'woocommerce' ) . '</a>'; ?> <div class="box woocommerce-box border-box"> <?php echo $info_message;?> <form class="checkout_coupon brad-woocommerce-form" method="post" style="display:none"> <p class="form-row form-row-first"> <input type="text" name="coupon_code" class="input-text" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" id="coupon_code" value="" /> </p> <p class="form-row form-row-last"> <input type="submit" class="button" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" /> </p> <div class="clear"></div> </form> </div>
Java
# Mikrotik scripts Here are specific instruction to scripts created for RouterOS platform and were tested across two sites, both running RouterOS of the same version. ## Prerequisites - Configure site-to-site IPsec tunnel across both sites. Public IP is a must for both endpoints. This [webpage](http://wiki.mikrotik.com/wiki/Manual:IP/IPsec) is a good place to start. I've been using IPsec in ESP tunnel mode, but other modes should in theory work just fine. - Set up account on dynamic DNS service provider. The scripts use [freedns.afraid.org](http://freedns.afraid.org/), but other services should work as well. You will just need to modify the scripts to work with different DNS service (make sure they have public API available). ## Description of scripts The scripts want to access specified interfaces or rules directly on the router. Interfaces are matched using _interface-name_, but rules are represented on router just as entries with number. To identify the specific rule with highest confidence, script finds the match using comment on the rule. Therefore make sure the rules and interfaces have proper comment and put this exact comment into scripts. ### mikrotik_dns_update.script This script tracks assigned IP address on WAN interface of the router. It assumes that the interface has assigned public IP address directly from your ISP. If the ISP assigns new IP address, on next scheduled run will the script update the dynamic DNS service. This script makes the assigned IP available as a global variable available to the whole system and other scripts. ### mikrotik_ipsec_update.script This script tracks for changes of locally asigned IP address as well as IP change on remote IPsec endpoint. In either cases it will update IPsec policies, peer information and firewall rules. ### mikrotik_ovpn_update.script This script is not needed in pure IPsec setup. However it may be useful in cases, where there is another VPN on endpoint with dynamic IP. It is running on a client router and is tracking for endpoint IP changes. ## Setup - Before you import the scripts, you should review them and modify to suit your needs. Albeit they are quite generic, some information should be updated. Put there your credentials to dynamic DNS service, domain names and DNS entry name for your sites. You should also configure, which router rules should be updated. You can find commented examples in the scripts. - Import the scripts and configure Scheduler to run them periodically. Alternative is to set up a trigger which tracks reachability of given IP.
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Wed Aug 31 13:06:32 CEST 2011 --> <TITLE> Uses of Class com.algebraweb.editor.shared.exceptions.SqlErrorException </TITLE> <META NAME="date" CONTENT="2011-08-31"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.algebraweb.editor.shared.exceptions.SqlErrorException"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/algebraweb/editor/shared/exceptions/SqlErrorException.html" title="class in com.algebraweb.editor.shared.exceptions"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/algebraweb/editor/shared/exceptions//class-useSqlErrorException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SqlErrorException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>com.algebraweb.editor.shared.exceptions.SqlErrorException</B></H2> </CENTER> No usage of com.algebraweb.editor.shared.exceptions.SqlErrorException <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/algebraweb/editor/shared/exceptions/SqlErrorException.html" title="class in com.algebraweb.editor.shared.exceptions"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/algebraweb/editor/shared/exceptions//class-useSqlErrorException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SqlErrorException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
<?php /** * * @package phpBB.de pastebin * @copyright (c) 2015 phpBB.de, gn#36 * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2 * */ namespace goztow\edit_has_topicreview\event; /** * @ignore */ use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Event listener */ class base_events implements EventSubscriberInterface { static public function getSubscribedEvents() { return array( 'core.posting_modify_template_vars' => 'edit_topicreview', ); } /* @var \phpbb\template\template */ protected $template; /** * Constructor * * @param \phpbb\controller\helper $helper Controller helper object * @param \phpbb\template\template $template Template object */ public function __construct(\phpbb\template\template $template) { $this->template = $template; } public function edit_topicreview($event) { if ($event['mode'] == 'edit' && topic_review($event['topic_id'], $event['forum_id'])) { $this->template->assign_var('S_DISPLAY_REVIEW', true); } } }
Java
<?php /** * Custom template tags for this theme * * Eventually, some of the functionality here could be replaced by core features. * * @package UnlockingSilentHistories */ if ( ! function_exists( 'unlockingsilenthistories_posted_on' ) ) : /** * Prints HTML with meta information for the current post-date/time and author. */ function unlockingsilenthistories_posted_on() { $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>'; if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) { $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>'; } $time_string = sprintf( $time_string, esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ), esc_attr( get_the_modified_date( 'c' ) ), esc_html( get_the_modified_date() ) ); $posted_on = sprintf( /* translators: %s: post date. */ esc_html_x( 'Posted on %s', 'post date', 'unlockingsilenthistories' ), '<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>' ); $byline = sprintf( /* translators: %s: post author. */ esc_html_x( 'by %s', 'post author', 'unlockingsilenthistories' ), '<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>' ); echo '<span class="posted-on">' . $posted_on . '</span><span class="byline"> ' . $byline . '</span>'; // WPCS: XSS OK. } endif; if ( ! function_exists( 'unlockingsilenthistories_entry_footer' ) ) : /** * Prints HTML with meta information for the categories, tags and comments. */ function unlockingsilenthistories_entry_footer() { // Hide category and tag text for pages. if ( 'post' === get_post_type() ) { /* translators: used between list items, there is a space after the comma */ $categories_list = get_the_category_list( esc_html__( ', ', 'unlockingsilenthistories' ) ); if ( $categories_list ) { /* translators: 1: list of categories. */ printf( '<span class="cat-links">' . esc_html__( 'Posted in %1$s', 'unlockingsilenthistories' ) . '</span>', $categories_list ); // WPCS: XSS OK. } /* translators: used between list items, there is a space after the comma */ $tags_list = get_the_tag_list( '', esc_html_x( ', ', 'list item separator', 'unlockingsilenthistories' ) ); if ( $tags_list ) { /* translators: 1: list of tags. */ printf( '<span class="tags-links">' . esc_html__( 'Tagged %1$s', 'unlockingsilenthistories' ) . '</span>', $tags_list ); // WPCS: XSS OK. } } if ( ! is_single() && ! post_password_required() && ( comments_open() || get_comments_number() ) ) { echo '<span class="comments-link">'; comments_popup_link( sprintf( wp_kses( /* translators: %s: post title */ __( 'Leave a Comment<span class="screen-reader-text"> on %s</span>', 'unlockingsilenthistories' ), array( 'span' => array( 'class' => array(), ), ) ), get_the_title() ) ); echo '</span>'; } edit_post_link( sprintf( wp_kses( /* translators: %s: Name of current post. Only visible to screen readers */ __( 'Edit <span class="screen-reader-text">%s</span>', 'unlockingsilenthistories' ), array( 'span' => array( 'class' => array(), ), ) ), get_the_title() ), '<span class="edit-link">', '</span>' ); } endif;
Java
package uq.androidhack.flashspeak; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.io.File; import java.io.InputStream; import java.net.URI; import uq.androidhack.flashspeak.interfaces.TargetFileListener; import uq.androidhack.flashspeak.interfaces.TrialFileListener; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link VisualisationFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link VisualisationFragment#newInstance} factory method to * create an instance of this fragment. */ public class VisualisationFragment extends Fragment implements TargetFileListener,TrialFileListener{ private OnFragmentInteractionListener mListener; //Here is your URL defined String url = "http://vprbbc.streamguys.net/vprbbc24.mp3"; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment VisualisationFragment. */ public static VisualisationFragment newInstance() { VisualisationFragment fragment = new VisualisationFragment(); Bundle args = new Bundle(); //args.putString(ARG_PARAM1, param1); //args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public VisualisationFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_visualisation, container, false); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onFileChange(String uri) { File file = new File (uri); ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation); ogAudioSampleImageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath())); } @Override public void onRecording(URI uri) { ImageView targetAudioSampleImageView = (ImageView)getView().findViewById(R.id.usersAudioSampleVisualisation); targetAudioSampleImageView.setImageResource(android.R.color.transparent); } @Override public void onFinishProcessing(String b) { Log.i("VISUALIZER", "in HERE!"); ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation); //ogAudioSampleImageView.setImageURI(new URI(b)); new DownloadImageTask(ogAudioSampleImageView).execute(b); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { public void onFragmentInteraction(Bitmap uri); } }
Java
using System; using System.IO; static class App{ static void PrintRunningGC(int n){ Console.WriteLine("Running GC for generation " + n); GC.Collect(n); } public static void Main(){ // // Uma instância de FileStream mantém um handle para um recurso nativo, i.e. um ficheiro. // FileStream fs = new FileStream("out.txt", FileMode.Create); // Wait for user to hit <Enter> Console.WriteLine("Wait for user to hit <Enter>"); Console.ReadLine(); PrintRunningGC(0); Console.WriteLine("Wait for user to hit <Enter>"); Console.ReadLine(); } }
Java
package jrpsoft; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.geom.Ellipse2D; import java.util.Random; public class Fantasma extends Actor { protected static final int FANTASMA_SPEED = 1; public boolean up, down, right, left; static Boolean[] dir = new Boolean[4]; int avazarA = 0; Random random; public Fantasma(Point puntoIncio, Color colorPrincipal) { super(puntoIncio, colorPrincipal); random = new Random(); } public Point getPoint() { return p; } public void paint(Graphics2D g2) { g2.setColor(color); Point pixelPoint = Director.getPxOfCell(p); Ellipse2D fantasma = new Ellipse2D.Float(pixelPoint.x, pixelPoint.y, diametro, diametro); g2.fill(fantasma); g2.fill(new Ellipse2D.Float(pixelPoint.x - 1, pixelPoint.y + 12, diametro / 2, diametro / 2)); g2.fill(new Ellipse2D.Float(pixelPoint.x + 5, pixelPoint.y + 12, diametro / 2, diametro / 2)); g2.fill(new Ellipse2D.Float(pixelPoint.x + 11, pixelPoint.y + 12, diametro / 2, diametro / 2)); } public void mover(Pacman pacman, Tablero tablero) { /* * System.out.println("ee "+(random.nextInt(5))); * if(random.nextInt(5)==0){ avanzar((random.nextInt(4)+1),tablero); } */ // avazarA=movAleatorio(tablero); //System.err.println(p); // avazarA=0; Astar.getAstar().getPath(p, pacman.p); Point nextPoint=Astar.getAstar().getNextPoint(); avanzar(getDirToPoint(nextPoint), tablero); } /*@SuppressWarnings("unused") private int movAleatorio(Tablero tablero) { Point aux = (Point) p.clone(); int randDir = 0; do { aux = reverseTranslateDir(aux, randDir); randDir = random.nextInt(4) + 1; translateDir(aux, randDir); // System.out.print("\nwhiling"+randDir+" px:"+aux.x+" py:"+aux.y); } while (!tablero.isWalkable(aux)); return randDir; }*/ private void avanzar(int dir, Tablero tablero) { p=translateDir(p,dir); /*Point anterior = (Point) p.clone(); translateDir(p, dir); if (!tablero.isWalkable(p)) { p = anterior; }*/ } public Point translateDir(Point p, int dir) { switch (dir) { case DUP: p.y += UP; break; case DDOWN: p.y += DOWN; break; case DLEFT: p.x += LEFT; break; case DRIGHT: p.x += RIGHT; break; default: break; } return p; } /* public Point reverseTranslateDir(Point p, int dir) { switch (dir) { case DUP: p.y -= UP; break; case DDOWN: p.y -= DOWN; break; case DLEFT: p.x -= LEFT; break; case DRIGHT: p.x -= RIGHT; break; default: break; } return p; } */ }
Java
ALTER TABLE `characters` ADD `i_equip_s` INT NOT NULL DEFAULT 24 AFTER `mesos`; ALTER TABLE `characters` ADD `i_use_s` INT NOT NULL DEFAULT 24 AFTER `i_equip_s`; ALTER TABLE `characters` ADD `i_setup_s` INT NOT NULL DEFAULT 24 AFTER `i_use_s`; ALTER TABLE `characters` ADD `i_etc_s` INT NOT NULL DEFAULT 24 AFTER `i_setup_s`; ALTER TABLE `characters` ADD `i_cash_s` INT NOT NULL DEFAULT 48 AFTER `i_etc_s`;
Java
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the Graphics Dojo project on Qt Labs. ** ** This file may be used under the terms of the GNU General Public ** License version 2.0 or 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of ** this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include <QtGui> #include <QtWidgets> #include <QtNetwork> #include <iostream> // for the explanation of the trick, check out: // http://www.virtualdub.org/blog/pivot/entry.php?id=116 // http://www.compuphase.com/graphic/scale3.htm #define AVG(a,b) ( ((((a)^(b)) & 0xfefefefeUL) >> 1) + ((a)&(b)) ) QImage halfSized(const QImage &source) { QImage dest(source.size() * 0.5, QImage::Format_ARGB32_Premultiplied); const quint32 *src = reinterpret_cast<const quint32*>(source.bits()); int sx = source.bytesPerLine() >> 2; int sx2 = sx << 1; quint32 *dst = reinterpret_cast<quint32*>(dest.bits()); int dx = dest.bytesPerLine() >> 2; int ww = dest.width(); int hh = dest.height(); for (int y = hh; y; --y, dst += dx, src += sx2) { const quint32 *p1 = src; const quint32 *p2 = src + sx; quint32 *q = dst; for (int x = ww; x; --x, q++, p1 += 2, p2 += 2) * q = AVG(AVG(p1[0], p1[1]), AVG(p2[0], p2[1])); } return dest; } class HalfScaler: public QWidget { Q_OBJECT private: int m_method; QNetworkAccessManager m_manager; QImage m_fastScaled; QImage m_smoothScaled; QImage m_optimizedScaled; public: HalfScaler(): QWidget(), m_method(0) { setAcceptDrops(true); connect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleNetworkData(QNetworkReply*))); setWindowTitle("Drag and drop an image here!"); resize(512, 256); } void loadImage(const QImage &image) { QImage img = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); if (img.isNull()) { resize(512, 256); setWindowTitle("Can't load the image. Please drag and drop an new image."); } else { // we crop the image so that the width and height are even int ww = img.width() >> 1; int hh = img.height() >> 1; img = img.copy(0, 0, ww << 1, hh << 1); m_fastScaled = img.scaled(ww, hh, Qt::IgnoreAspectRatio, Qt::FastTransformation); m_smoothScaled = img.scaled(ww, hh, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); m_optimizedScaled = halfSized(img); resize(20 + ww * 2 + 50, hh * 2 + 30 + 2 * 40); } update(); } public slots: void handleNetworkData(QNetworkReply *networkReply) { m_fastScaled = QImage(); m_smoothScaled = QImage(); m_optimizedScaled = QImage(); QUrl url = networkReply->url(); if (networkReply->error()) { setWindowTitle(QString("Can't download %1: %2").arg(url.toString()).arg(networkReply->errorString())); } else { QImage image; image.load(networkReply, 0); QString fileName = QFileInfo(url.path()).fileName(); setWindowTitle(QString("%1 - press a key to switch the scaling method").arg(fileName)); loadImage(image); } networkReply->deleteLater(); } protected: void dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } void dropEvent(QDropEvent *event) { QList<QUrl> urls = event->mimeData()->urls(); if (urls.count()) { QUrl url = urls[0]; if (event->mimeData()->hasImage()) { QImage img = qvariant_cast<QImage>(event->mimeData()->imageData()); QString fileName = QFileInfo(url.path()).fileName(); setWindowTitle(QString("%1 - press a key to switch the scaling method").arg(fileName)); loadImage(img); } else { m_manager.get(QNetworkRequest(url)); setWindowTitle(QString("Loading %1...").arg(url.toString())); } event->acceptProposedAction(); } } void keyPressEvent(QKeyEvent*) { m_method = (m_method + 1) % 3; update(); } void paintEvent(QPaintEvent*) { if (m_fastScaled.isNull()) return; int w = m_fastScaled.width(); int h = m_optimizedScaled.height(); QPainter painter; painter.begin(this); // top left image: fast painter.translate(10, 40); painter.setPen(Qt::black); painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Qt::FastTransformation"); if (m_method == 0) { painter.setPen(QPen(Qt::red, 2)); painter.drawRect(-2, -2, w + 4, h + 4); painter.drawLine(w + 2, h + 2, w + 50 - 10, h + 50 - 10); } painter.drawImage(0, 0, m_fastScaled); // top right image: smooth painter.translate(w + 50, 0); painter.setPen(Qt::black); painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Qt::SmoothTransformation"); if (m_method == 1) { painter.setPen(QPen(Qt::red, 2)); painter.drawRect(-2, -2, w + 4, h + 4); painter.drawLine(w / 2, h + 2, w / 2, h + 50 - 10); } painter.drawImage(0, 0, m_smoothScaled); // bottom left image: optimized painter.translate(-w - 50, h + 50); painter.setPen(Qt::black); painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Optimized"); if (m_method == 2) { painter.setPen(QPen(Qt::red, 2)); painter.drawRect(-2, -2, w + 4, h + 4); painter.drawLine(w + 2, h / 2, w + 50 - 10, h / 2); } painter.drawImage(0, 0, m_optimizedScaled); // bottom right image: chosen by the user QImage img = (m_method == 0) ? m_fastScaled : (m_method == 1) ? m_smoothScaled : m_optimizedScaled; painter.translate(w + 50, 0); painter.drawImage(0, 0, img); painter.end(); } }; #include "halfscale.moc" int main(int argc, char *argv[]) { QApplication app(argc, argv); HalfScaler widget; widget.show(); return app.exec(); }
Java
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.clients.http; ////import org.tanukisoftware.wrapper.WrapperManager; import freenet.client.filter.HTMLFilter; import freenet.client.filter.LinkFilterExceptionProvider; import freenet.clients.http.FProxyFetchInProgress.REFILTER_POLICY; import freenet.clients.http.PageMaker.THEME; import freenet.clients.http.bookmark.BookmarkManager; import freenet.clients.http.updateableelements.PushDataManager; import freenet.config.EnumerableOptionCallback; import freenet.config.InvalidConfigValueException; import freenet.config.NodeNeedRestartException; import freenet.config.SubConfig; import freenet.crypt.SSL; import freenet.io.AllowedHosts; import freenet.io.NetworkInterface; import freenet.io.SSLNetworkInterface; import freenet.keys.FreenetURI; import freenet.l10n.NodeL10n; import freenet.node.Node; import freenet.node.NodeClientCore; import freenet.node.PrioRunnable; import freenet.node.SecurityLevelListener; import freenet.node.SecurityLevels.NETWORK_THREAT_LEVEL; import freenet.node.SecurityLevels.PHYSICAL_THREAT_LEVEL; import freenet.node.useralerts.UserAlertManager; import freenet.pluginmanager.FredPluginL10n; import freenet.support.*; import freenet.support.Logger.LogLevel; import freenet.support.api.*; import freenet.support.io.ArrayBucketFactory; import freenet.support.io.NativeThread; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.Random; /** * The Toadlet (HTTP) Server * * Provide a HTTP server for FProxy */ public final class SimpleToadletServer implements ToadletContainer, Runnable, LinkFilterExceptionProvider { /** List of urlPrefix / Toadlet */ private final LinkedList<ToadletElement> toadlets; private static class ToadletElement { public ToadletElement(Toadlet t2, String urlPrefix, String menu, String name) { t = t2; prefix = urlPrefix; this.menu = menu; this.name = name; } Toadlet t; String prefix; String menu; String name; } // Socket / Binding private final int port; private String bindTo; private String allowedHosts; private NetworkInterface networkInterface; private boolean ssl = false; public static final int DEFAULT_FPROXY_PORT = 8888; // ACL private final AllowedHosts allowedFullAccess; private boolean publicGatewayMode; private final boolean wasPublicGatewayMode; // Theme private THEME cssTheme; private File cssOverride; private boolean sendAllThemes; private boolean advancedModeEnabled; private final PageMaker pageMaker; // Control private Thread myThread; private final Executor executor; private final Random random; private BucketFactory bf; private volatile NodeClientCore core; // HTTP Option private boolean doRobots; private boolean enablePersistentConnections; private boolean enableInlinePrefetch; private boolean enableActivelinks; private boolean enableExtendedMethodHandling; // Something does not really belongs to here volatile static boolean isPanicButtonToBeShown; // move to QueueToadlet ? volatile static boolean noConfirmPanic; public BookmarkManager bookmarkManager; // move to WelcomeToadlet / BookmarkEditorToadlet ? private volatile boolean fProxyJavascriptEnabled; // ugh? private volatile boolean fProxyWebPushingEnabled; // ugh? private volatile boolean fproxyHasCompletedWizard; // hmmm.. private volatile boolean disableProgressPage; private int maxFproxyConnections; private int fproxyConnections; private boolean finishedStartup; /** The PushDataManager handles all the pushing tasks*/ public PushDataManager pushDataManager; /** The IntervalPusherManager handles interval pushing*/ public IntervalPusherManager intervalPushManager; private static volatile boolean logMINOR; static { Logger.registerLogThresholdCallback(new LogThresholdCallback(){ @Override public void shouldUpdate(){ logMINOR = Logger.shouldLog(LogLevel.MINOR, this); } }); } // Config Callbacks private class FProxySSLCallback extends BooleanCallback { @Override public Boolean get() { return ssl; } @Override public void set(Boolean val) throws InvalidConfigValueException { if (get().equals(val)) return; if(!SSL.available()) { throw new InvalidConfigValueException("Enable SSL support before use ssl with Fproxy"); } ssl = val; throw new InvalidConfigValueException("Cannot change SSL on the fly, please restart freenet"); } @Override public boolean isReadOnly() { return true; } } private static class FProxyPassthruMaxSizeNoProgress extends LongCallback { @Override public Long get() { return FProxyToadlet.MAX_LENGTH_NO_PROGRESS; } @Override public void set(Long val) throws InvalidConfigValueException { if (get().equals(val)) return; FProxyToadlet.MAX_LENGTH_NO_PROGRESS = val; } } private static class FProxyPassthruMaxSizeProgress extends LongCallback { @Override public Long get() { return FProxyToadlet.MAX_LENGTH_WITH_PROGRESS; } @Override public void set(Long val) throws InvalidConfigValueException { if (get().equals(val)) return; FProxyToadlet.MAX_LENGTH_WITH_PROGRESS = val; } } private class FProxyPortCallback extends IntCallback { @Override public Integer get() { return port; } @Override public void set(Integer newPort) throws NodeNeedRestartException { if(port != newPort) { throw new NodeNeedRestartException("Port cannot change on the fly"); } } } private class FProxyBindtoCallback extends StringCallback { @Override public String get() { return bindTo; } @Override public void set(String bindTo) throws InvalidConfigValueException { String oldValue = get(); if(!bindTo.equals(oldValue)) { String[] failedAddresses = networkInterface.setBindTo(bindTo, false); if(failedAddresses == null) { SimpleToadletServer.this.bindTo = bindTo; } else { // This is an advanced option for reasons of reducing clutter, // but it is expected to be used by regular users, not devs. // So we translate the error messages. networkInterface.setBindTo(oldValue, false); throw new InvalidConfigValueException(l10n("couldNotChangeBindTo", "failedInterfaces", Arrays.toString(failedAddresses))); } } } } private class FProxyAllowedHostsCallback extends StringCallback { @Override public String get() { return networkInterface.getAllowedHosts(); } @Override public void set(String allowedHosts) throws InvalidConfigValueException { if (!allowedHosts.equals(get())) { try { networkInterface.setAllowedHosts(allowedHosts); } catch(IllegalArgumentException e) { throw new InvalidConfigValueException(e); } } } } private class FProxyCSSNameCallback extends StringCallback implements EnumerableOptionCallback { @Override public String get() { return cssTheme.code; } @Override public void set(String CSSName) throws InvalidConfigValueException { if((CSSName.indexOf(':') != -1) || (CSSName.indexOf('/') != -1)) throw new InvalidConfigValueException(l10n("illegalCSSName")); cssTheme = THEME.themeFromName(CSSName); pageMaker.setTheme(cssTheme); NodeClientCore core = SimpleToadletServer.this.core; if (core.node.pluginManager != null) core.node.pluginManager.setFProxyTheme(cssTheme); } @Override public String[] getPossibleValues() { return THEME.possibleValues; } } private class FProxyCSSOverrideCallback extends StringCallback { @Override public String get() { return (cssOverride == null ? "" : cssOverride.toString()); } @Override public void set(String val) throws InvalidConfigValueException { NodeClientCore core = SimpleToadletServer.this.core; if(core == null) return; if(val.equals(get()) || val.equals("")) cssOverride = null; else { File tmp = new File(val.trim()); if(!core.allowUploadFrom(tmp)) throw new InvalidConfigValueException(l10n("cssOverrideNotInUploads", "filename", tmp.toString())); else if(!tmp.canRead() || !tmp.isFile()) throw new InvalidConfigValueException(l10n("cssOverrideCantRead", "filename", tmp.toString())); File parent = tmp.getParentFile(); // Basic sanity check. // Prevents user from specifying root dir. // They can still shoot themselves in the foot, but only when developing themes/using custom themes. // Because of the .. check above, any malicious thing cannot break out of the dir anyway. if(parent.getParentFile() == null) throw new InvalidConfigValueException(l10n("cssOverrideCantUseRootDir", "filename", parent.toString())); cssOverride = tmp; } if(cssOverride == null) pageMaker.setOverride(null); else { pageMaker.setOverride(StaticToadlet.OVERRIDE_URL + cssOverride.getName()); } } } private class FProxyEnabledCallback extends BooleanCallback { @Override public Boolean get() { synchronized(SimpleToadletServer.this) { return myThread != null; } } @Override public void set(Boolean val) throws InvalidConfigValueException { if (get().equals(val)) return; synchronized(SimpleToadletServer.this) { if(val) { // Start it myThread = new Thread(SimpleToadletServer.this, "SimpleToadletServer"); } else { myThread.interrupt(); myThread = null; SimpleToadletServer.this.notifyAll(); return; } } createFproxy(); myThread.setDaemon(true); myThread.start(); } } private static class FProxyAdvancedModeEnabledCallback extends BooleanCallback { private final SimpleToadletServer ts; FProxyAdvancedModeEnabledCallback(SimpleToadletServer ts){ this.ts = ts; } @Override public Boolean get() { return ts.isAdvancedModeEnabled(); } @Override public void set(Boolean val) throws InvalidConfigValueException { ts.setAdvancedMode(val); } } private static class FProxyJavascriptEnabledCallback extends BooleanCallback { private final SimpleToadletServer ts; FProxyJavascriptEnabledCallback(SimpleToadletServer ts){ this.ts = ts; } @Override public Boolean get() { return ts.isFProxyJavascriptEnabled(); } @Override public void set(Boolean val) throws InvalidConfigValueException { if (get().equals(val)) return; ts.enableFProxyJavascript(val); } } private static class FProxyWebPushingEnabledCallback extends BooleanCallback{ private final SimpleToadletServer ts; FProxyWebPushingEnabledCallback(SimpleToadletServer ts){ this.ts=ts; } @Override public Boolean get() { return ts.isFProxyWebPushingEnabled(); } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if (get().equals(val)) return; ts.enableFProxyWebPushing(val); } } private boolean haveCalledFProxy = false; // FIXME factor this out to a global helper class somehow? private class ReFilterCallback extends StringCallback implements EnumerableOptionCallback { @Override public String[] getPossibleValues() { REFILTER_POLICY[] possible = REFILTER_POLICY.values(); String[] ret = new String[possible.length]; for(int i=0;i<possible.length;i++) ret[i] = possible[i].name(); return ret; } @Override public String get() { return refilterPolicy.name(); } @Override public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException { refilterPolicy = REFILTER_POLICY.valueOf(val); } }; public void createFproxy() { NodeClientCore core = this.core; Node node = core.node; synchronized(this) { if(haveCalledFProxy) return; haveCalledFProxy = true; } pushDataManager=new PushDataManager(getTicker()); intervalPushManager=new IntervalPusherManager(getTicker(), pushDataManager); bookmarkManager = new BookmarkManager(core, publicGatewayMode()); try { FProxyToadlet.maybeCreateFProxyEtc(core, node, node.config, this); } catch (IOException e) { Logger.error(this, "Could not start fproxy: "+e, e); System.err.println("Could not start fproxy:"); e.printStackTrace(); } } public void setCore(NodeClientCore core) { this.core = core; } /** * Create a SimpleToadletServer, using the settings from the SubConfig (the fproxy.* * config). */ public SimpleToadletServer(SubConfig fproxyConfig, BucketFactory bucketFactory, Executor executor, Node node) throws IOException, InvalidConfigValueException { this.executor = executor; this.core = null; // setCore() will be called later. this.random = new Random(); int configItemOrder = 0; fproxyConfig.register("enabled", true, configItemOrder++, true, true, "SimpleToadletServer.enabled", "SimpleToadletServer.enabledLong", new FProxyEnabledCallback()); boolean enabled = fproxyConfig.getBoolean("enabled"); fproxyConfig.register("ssl", false, configItemOrder++, true, true, "SimpleToadletServer.ssl", "SimpleToadletServer.sslLong", new FProxySSLCallback()); fproxyConfig.register("port", DEFAULT_FPROXY_PORT, configItemOrder++, true, true, "SimpleToadletServer.port", "SimpleToadletServer.portLong", new FProxyPortCallback(), false); fproxyConfig.register("bindTo", NetworkInterface.DEFAULT_BIND_TO, configItemOrder++, true, true, "SimpleToadletServer.bindTo", "SimpleToadletServer.bindToLong", new FProxyBindtoCallback()); fproxyConfig.register("css", "clean-dropdown", configItemOrder++, false, false, "SimpleToadletServer.cssName", "SimpleToadletServer.cssNameLong", new FProxyCSSNameCallback()); fproxyConfig.register("CSSOverride", "", configItemOrder++, true, false, "SimpleToadletServer.cssOverride", "SimpleToadletServer.cssOverrideLong", new FProxyCSSOverrideCallback()); fproxyConfig.register("sendAllThemes", false, configItemOrder++, true, false, "SimpleToadletServer.sendAllThemes", "SimpleToadletServer.sendAllThemesLong", new BooleanCallback() { @Override public Boolean get() { return sendAllThemes; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { sendAllThemes = val; } }); sendAllThemes = fproxyConfig.getBoolean("sendAllThemes"); fproxyConfig.register("advancedModeEnabled", false, configItemOrder++, true, false, "SimpleToadletServer.advancedMode", "SimpleToadletServer.advancedModeLong", new FProxyAdvancedModeEnabledCallback(this)); fproxyConfig.register("enableExtendedMethodHandling", false, configItemOrder++, true, false, "SimpleToadletServer.enableExtendedMethodHandling", "SimpleToadletServer.enableExtendedMethodHandlingLong", new BooleanCallback() { @Override public Boolean get() { return enableExtendedMethodHandling; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if(get().equals(val)) return; enableExtendedMethodHandling = val; } }); fproxyConfig.register("javascriptEnabled", true, configItemOrder++, true, false, "SimpleToadletServer.enableJS", "SimpleToadletServer.enableJSLong", new FProxyJavascriptEnabledCallback(this)); fproxyConfig.register("webPushingEnabled", false, configItemOrder++, true, false, "SimpleToadletServer.enableWP", "SimpleToadletServer.enableWPLong", new FProxyWebPushingEnabledCallback(this)); fproxyConfig.register("hasCompletedWizard", false, configItemOrder++, true, false, "SimpleToadletServer.hasCompletedWizard", "SimpleToadletServer.hasCompletedWizardLong", new BooleanCallback() { @Override public Boolean get() { return fproxyHasCompletedWizard; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if(get().equals(val)) return; fproxyHasCompletedWizard = val; } }); fproxyConfig.register("disableProgressPage", false, configItemOrder++, true, false, "SimpleToadletServer.disableProgressPage", "SimpleToadletServer.disableProgressPageLong", new BooleanCallback() { @Override public Boolean get() { return disableProgressPage; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { disableProgressPage = val; } }); fproxyHasCompletedWizard = fproxyConfig.getBoolean("hasCompletedWizard"); fProxyJavascriptEnabled = fproxyConfig.getBoolean("javascriptEnabled"); fProxyWebPushingEnabled = fproxyConfig.getBoolean("webPushingEnabled"); disableProgressPage = fproxyConfig.getBoolean("disableProgressPage"); enableExtendedMethodHandling = fproxyConfig.getBoolean("enableExtendedMethodHandling"); fproxyConfig.register("showPanicButton", false, configItemOrder++, true, true, "SimpleToadletServer.panicButton", "SimpleToadletServer.panicButtonLong", new BooleanCallback(){ @Override public Boolean get() { return SimpleToadletServer.isPanicButtonToBeShown; } @Override public void set(Boolean value) { if(value == SimpleToadletServer.isPanicButtonToBeShown) return; else SimpleToadletServer.isPanicButtonToBeShown = value; } }); fproxyConfig.register("noConfirmPanic", false, configItemOrder++, true, true, "SimpleToadletServer.noConfirmPanic", "SimpleToadletServer.noConfirmPanicLong", new BooleanCallback() { @Override public Boolean get() { return SimpleToadletServer.noConfirmPanic; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if(val == SimpleToadletServer.noConfirmPanic) return; else SimpleToadletServer.noConfirmPanic = val; } }); fproxyConfig.register("publicGatewayMode", false, configItemOrder++, true, true, "SimpleToadletServer.publicGatewayMode", "SimpleToadletServer.publicGatewayModeLong", new BooleanCallback() { @Override public Boolean get() { return publicGatewayMode; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if(publicGatewayMode == val) return; publicGatewayMode = val; throw new NodeNeedRestartException(l10n("publicGatewayModeNeedsRestart")); } }); wasPublicGatewayMode = publicGatewayMode = fproxyConfig.getBoolean("publicGatewayMode"); // This is OFF BY DEFAULT because for example firefox has a limit of 2 persistent // connections per server, but 8 non-persistent connections per server. We need 8 conns // more than we need the efficiency gain of reusing connections - especially on first // install. fproxyConfig.register("enablePersistentConnections", false, configItemOrder++, true, false, "SimpleToadletServer.enablePersistentConnections", "SimpleToadletServer.enablePersistentConnectionsLong", new BooleanCallback() { @Override public Boolean get() { synchronized(SimpleToadletServer.this) { return enablePersistentConnections; } } @Override public void set(Boolean val) throws InvalidConfigValueException { synchronized(SimpleToadletServer.this) { enablePersistentConnections = val; } } }); enablePersistentConnections = fproxyConfig.getBoolean("enablePersistentConnections"); // Off by default. // I had hoped it would yield a significant performance boost to bootstrap performance // on browsers with low numbers of simultaneous connections. Unfortunately the bottleneck // appears to be that the node does very few local requests compared to external requests // (for anonymity's sake). fproxyConfig.register("enableInlinePrefetch", false, configItemOrder++, true, false, "SimpleToadletServer.enableInlinePrefetch", "SimpleToadletServer.enableInlinePrefetchLong", new BooleanCallback() { @Override public Boolean get() { synchronized(SimpleToadletServer.this) { return enableInlinePrefetch; } } @Override public void set(Boolean val) throws InvalidConfigValueException { synchronized(SimpleToadletServer.this) { enableInlinePrefetch = val; } } }); enableInlinePrefetch = fproxyConfig.getBoolean("enableInlinePrefetch"); fproxyConfig.register("enableActivelinks", false, configItemOrder++, false, false, "SimpleToadletServer.enableActivelinks", "SimpleToadletServer.enableActivelinksLong", new BooleanCallback() { @Override public Boolean get() { return enableActivelinks; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { enableActivelinks = val; } }); enableActivelinks = fproxyConfig.getBoolean("enableActivelinks"); fproxyConfig.register("passthroughMaxSize", FProxyToadlet.MAX_LENGTH_NO_PROGRESS, configItemOrder++, true, false, "SimpleToadletServer.passthroughMaxSize", "SimpleToadletServer.passthroughMaxSizeLong", new FProxyPassthruMaxSizeNoProgress(), true); FProxyToadlet.MAX_LENGTH_NO_PROGRESS = fproxyConfig.getLong("passthroughMaxSize"); fproxyConfig.register("passthroughMaxSizeProgress", FProxyToadlet.MAX_LENGTH_WITH_PROGRESS, configItemOrder++, true, false, "SimpleToadletServer.passthroughMaxSizeProgress", "SimpleToadletServer.passthroughMaxSizeProgressLong", new FProxyPassthruMaxSizeProgress(), true); FProxyToadlet.MAX_LENGTH_WITH_PROGRESS = fproxyConfig.getLong("passthroughMaxSizeProgress"); System.out.println("Set fproxy max length to "+FProxyToadlet.MAX_LENGTH_NO_PROGRESS+" and max length with progress to "+FProxyToadlet.MAX_LENGTH_WITH_PROGRESS+" = "+fproxyConfig.getLong("passthroughMaxSizeProgress")); fproxyConfig.register("allowedHosts", "127.0.0.1,0:0:0:0:0:0:0:1", configItemOrder++, true, true, "SimpleToadletServer.allowedHosts", "SimpleToadletServer.allowedHostsLong", new FProxyAllowedHostsCallback()); fproxyConfig.register("allowedHostsFullAccess", "127.0.0.1,0:0:0:0:0:0:0:1", configItemOrder++, true, true, "SimpleToadletServer.allowedFullAccess", "SimpleToadletServer.allowedFullAccessLong", new StringCallback() { @Override public String get() { return allowedFullAccess.getAllowedHosts(); } @Override public void set(String val) throws InvalidConfigValueException { try { allowedFullAccess.setAllowedHosts(val); } catch(IllegalArgumentException e) { throw new InvalidConfigValueException(e); } } }); allowedFullAccess = new AllowedHosts(fproxyConfig.getString("allowedHostsFullAccess")); fproxyConfig.register("doRobots", false, configItemOrder++, true, false, "SimpleToadletServer.doRobots", "SimpleToadletServer.doRobotsLong", new BooleanCallback() { @Override public Boolean get() { return doRobots; } @Override public void set(Boolean val) throws InvalidConfigValueException { doRobots = val; } }); doRobots = fproxyConfig.getBoolean("doRobots"); // We may not know what the overall thread limit is yet so just set it to 100. fproxyConfig.register("maxFproxyConnections", 100, configItemOrder++, true, false, "SimpleToadletServer.maxFproxyConnections", "SimpleToadletServer.maxFproxyConnectionsLong", new IntCallback() { @Override public Integer get() { synchronized(SimpleToadletServer.this) { return maxFproxyConnections; } } @Override public void set(Integer val) { synchronized(SimpleToadletServer.this) { maxFproxyConnections = val; SimpleToadletServer.this.notifyAll(); } } }, false); maxFproxyConnections = fproxyConfig.getInt("maxFproxyConnections"); fproxyConfig.register("metaRefreshSamePageInterval", 1, configItemOrder++, true, false, "SimpleToadletServer.metaRefreshSamePageInterval", "SimpleToadletServer.metaRefreshSamePageIntervalLong", new IntCallback() { @Override public Integer get() { return HTMLFilter.metaRefreshSamePageMinInterval; } @Override public void set(Integer val) throws InvalidConfigValueException, NodeNeedRestartException { if(val < -1) throw new InvalidConfigValueException("-1 = disabled, 0+ = set a minimum interval"); // FIXME l10n HTMLFilter.metaRefreshSamePageMinInterval = val; } }, false); HTMLFilter.metaRefreshSamePageMinInterval = Math.max(-1, fproxyConfig.getInt("metaRefreshSamePageInterval")); fproxyConfig.register("metaRefreshRedirectInterval", 1, configItemOrder++, true, false, "SimpleToadletServer.metaRefreshRedirectInterval", "SimpleToadletServer.metaRefreshRedirectIntervalLong", new IntCallback() { @Override public Integer get() { return HTMLFilter.metaRefreshRedirectMinInterval; } @Override public void set(Integer val) throws InvalidConfigValueException, NodeNeedRestartException { if(val < -1) throw new InvalidConfigValueException("-1 = disabled, 0+ = set a minimum interval"); // FIXME l10n HTMLFilter.metaRefreshRedirectMinInterval = val; } }, false); HTMLFilter.metaRefreshRedirectMinInterval = Math.max(-1, fproxyConfig.getInt("metaRefreshRedirectInterval")); fproxyConfig.register("refilterPolicy", "RE_FILTER", configItemOrder++, true, false, "SimpleToadletServer.refilterPolicy", "SimpleToadletServer.refilterPolicyLong", new ReFilterCallback()); this.refilterPolicy = REFILTER_POLICY.valueOf(fproxyConfig.getString("refilterPolicy")); // Network seclevel not physical seclevel because bad filtering can cause network level anonymity breaches. SimpleToadletServer.isPanicButtonToBeShown = fproxyConfig.getBoolean("showPanicButton"); SimpleToadletServer.noConfirmPanic = fproxyConfig.getBoolean("noConfirmPanic"); this.bf = bucketFactory; port = fproxyConfig.getInt("port"); bindTo = fproxyConfig.getString("bindTo"); String cssName = fproxyConfig.getString("css"); if((cssName.indexOf(':') != -1) || (cssName.indexOf('/') != -1)) throw new InvalidConfigValueException("CSS name must not contain slashes or colons!"); cssTheme = THEME.themeFromName(cssName); pageMaker = new PageMaker(cssTheme, node); if(!fproxyConfig.getOption("CSSOverride").isDefault()) { cssOverride = new File(fproxyConfig.getString("CSSOverride")); pageMaker.setOverride(StaticToadlet.OVERRIDE_URL + cssOverride.getName()); } else { cssOverride = null; pageMaker.setOverride(null); } this.advancedModeEnabled = fproxyConfig.getBoolean("advancedModeEnabled"); toadlets = new LinkedList<ToadletElement>(); if(SSL.available()) { ssl = fproxyConfig.getBoolean("ssl"); } this.allowedHosts=fproxyConfig.getString("allowedHosts"); if(!enabled) { Logger.normal(SimpleToadletServer.this, "Not starting FProxy as it's disabled"); System.out.println("Not starting FProxy as it's disabled"); } else { maybeGetNetworkInterface(); myThread = new Thread(this, "SimpleToadletServer"); myThread.setDaemon(true); } // Register static toadlet and startup toadlet StaticToadlet statictoadlet = new StaticToadlet(); register(statictoadlet, null, "/static/", false, false); // "Freenet is starting up..." page, to be removed at #removeStartupToadlet() startupToadlet = new StartupToadlet(statictoadlet); register(startupToadlet, null, "/", false, false); } public StartupToadlet startupToadlet; public void removeStartupToadlet() { // setCore() must have been called first. It is in fact called much earlier on. synchronized(this) { unregister(startupToadlet); // Ready to be GCed startupToadlet = null; // Not in the navbar. } } private void maybeGetNetworkInterface() throws IOException { if (this.networkInterface!=null) return; if(ssl) { this.networkInterface = SSLNetworkInterface.create(port, this.bindTo, allowedHosts, executor, true); } else { this.networkInterface = NetworkInterface.create(port, this.bindTo, allowedHosts, executor, true); } } @Override public boolean doRobots() { return doRobots; } @Override public boolean publicGatewayMode() { return wasPublicGatewayMode; } public void start() { if(myThread != null) try { maybeGetNetworkInterface(); myThread.start(); Logger.normal(this, "Starting FProxy on "+bindTo+ ':' +port); System.out.println("Starting FProxy on "+bindTo+ ':' +port); } catch (IOException e) { Logger.error(this, "Could not bind network port for FProxy?", e); } } public void finishStart() { core.node.securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() { @Override public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) { // At LOW, we do ACCEPT_OLD. // Otherwise we do RE_FILTER. // But we don't change it unless it changes from LOW to not LOW. if(newLevel == NETWORK_THREAT_LEVEL.LOW && newLevel != oldLevel) { refilterPolicy = REFILTER_POLICY.ACCEPT_OLD; } else if(oldLevel == NETWORK_THREAT_LEVEL.LOW && newLevel != oldLevel) { refilterPolicy = REFILTER_POLICY.RE_FILTER; } } }); core.node.securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<PHYSICAL_THREAT_LEVEL> () { @Override public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) { if(newLevel != oldLevel && newLevel == PHYSICAL_THREAT_LEVEL.LOW) { isPanicButtonToBeShown = false; } else if(newLevel != oldLevel) { isPanicButtonToBeShown = true; } } }); synchronized(this) { finishedStartup = true; } } @Override public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, boolean fullOnly) { register(t, menu, urlPrefix, atFront, null, null, fullOnly, null, null); } @Override public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, String name, String title, boolean fullOnly, LinkEnabledCallback cb) { register(t, menu, urlPrefix, atFront, name, title, fullOnly, cb, null); } @Override public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, String name, String title, boolean fullOnly, LinkEnabledCallback cb, FredPluginL10n l10n) { ToadletElement te = new ToadletElement(t, urlPrefix, menu, name); synchronized(toadlets) { if(atFront) toadlets.addFirst(te); else toadlets.addLast(te); t.container = this; } if (menu != null && name != null) { pageMaker.addNavigationLink(menu, urlPrefix, name, title, fullOnly, cb, l10n); } } public void registerMenu(String link, String name, String title, FredPluginL10n plugin) { pageMaker.addNavigationCategory(link, name, title, plugin); } @Override public void unregister(Toadlet t) { ToadletElement e = null; synchronized(toadlets) { for(Iterator<ToadletElement> i=toadlets.iterator();i.hasNext();) { e = i.next(); if(e.t == t) { i.remove(); break; } } } if(e != null && e.t == t) { if(e.menu != null && e.name != null) { pageMaker.removeNavigationLink(e.menu, e.name); } } } public StartupToadlet getStartupToadlet() { return startupToadlet; } @Override public boolean fproxyHasCompletedWizard() { return fproxyHasCompletedWizard; } @Override public Toadlet findToadlet(URI uri) throws PermanentRedirectException { String path = uri.getPath(); // Show the wizard until dismissed by the user (See bug #2624) NodeClientCore core = this.core; if(core != null && core.node != null && !fproxyHasCompletedWizard) { //If the user has not completed the wizard, only allow access to the wizard and static //resources. Anything else redirects to the first page of the wizard. if (!(path.startsWith(FirstTimeWizardToadlet.TOADLET_URL) || path.startsWith(StaticToadlet.ROOT_URL) || path.startsWith(ExternalLinkToadlet.PATH) || path.equals("/favicon.ico"))) { try { throw new PermanentRedirectException(new URI(null, null, null, -1, FirstTimeWizardToadlet.TOADLET_URL, uri.getQuery(), null)); } catch(URISyntaxException e) { throw new Error(e); } } } synchronized(toadlets) { for(ToadletElement te: toadlets) { if(path.startsWith(te.prefix)) return te.t; if(te.prefix.length() > 0 && te.prefix.charAt(te.prefix.length()-1) == '/') { if(path.equals(te.prefix.substring(0, te.prefix.length()-1))) { URI newURI; try { newURI = new URI(te.prefix); } catch (URISyntaxException e) { throw new Error(e); } throw new PermanentRedirectException(newURI); } } } } return null; } @Override public void run() { boolean finishedStartup = false; while(true) { synchronized(this) { while(fproxyConnections > maxFproxyConnections) { try { wait(); } catch (InterruptedException e) { // Ignore } } if((!finishedStartup) && this.finishedStartup) finishedStartup = true; if(myThread == null) return; } Socket conn = networkInterface.accept(); //if (WrapperManager.hasShutdownHookBeenTriggered()) //return; if(conn == null) continue; // timeout if(logMINOR) Logger.minor(this, "Accepted connection"); SocketHandler sh = new SocketHandler(conn, finishedStartup); sh.start(); } } public class SocketHandler implements PrioRunnable { Socket sock; final boolean finishedStartup; public SocketHandler(Socket conn, boolean finishedStartup) { this.sock = conn; this.finishedStartup = finishedStartup; } void start() { if(finishedStartup) executor.execute(this, "HTTP socket handler@"+hashCode()); else new Thread(this).start(); synchronized(SimpleToadletServer.this) { fproxyConnections++; } } @Override public void run() { freenet.support.Logger.OSThread.logPID(this); if(logMINOR) Logger.minor(this, "Handling connection"); try { ToadletContextImpl.handle(sock, SimpleToadletServer.this, pageMaker, getUserAlertManager(), bookmarkManager); } catch (Throwable t) { System.err.println("Caught in SimpleToadletServer: "+t); t.printStackTrace(); Logger.error(this, "Caught in SimpleToadletServer: "+t, t); } finally { synchronized(SimpleToadletServer.this) { fproxyConnections--; SimpleToadletServer.this.notifyAll(); } } if(logMINOR) Logger.minor(this, "Handled connection"); } @Override public int getPriority() { return NativeThread.HIGH_PRIORITY-1; } } @Override public THEME getTheme() { return this.cssTheme; } public UserAlertManager getUserAlertManager() { NodeClientCore core = this.core; if(core == null) return null; return core.alerts; } public void setCSSName(THEME theme) { this.cssTheme = theme; } @Override public synchronized boolean sendAllThemes() { return this.sendAllThemes; } @Override public synchronized boolean isAdvancedModeEnabled() { return this.advancedModeEnabled; } @Override public void setAdvancedMode(boolean enabled) { synchronized(this) { if(advancedModeEnabled == enabled) return; advancedModeEnabled = enabled; } core.node.config.store(); } @Override public synchronized boolean isFProxyJavascriptEnabled() { return this.fProxyJavascriptEnabled; } public synchronized void enableFProxyJavascript(boolean b){ fProxyJavascriptEnabled = b; } @Override public synchronized boolean isFProxyWebPushingEnabled() { return this.fProxyWebPushingEnabled; } public synchronized void enableFProxyWebPushing(boolean b){ fProxyWebPushingEnabled = b; } @Override public String getFormPassword() { if(core == null) return ""; return core.formPassword; } @Override public boolean isAllowedFullAccess(InetAddress remoteAddr) { return this.allowedFullAccess.allowed(remoteAddr); } private static String l10n(String key, String pattern, String value) { return NodeL10n.getBase().getString("SimpleToadletServer."+key, pattern, value); } private static String l10n(String key) { return NodeL10n.getBase().getString("SimpleToadletServer."+key); } @Override public HTMLNode addFormChild(HTMLNode parentNode, String target, String id) { HTMLNode formNode = parentNode.addChild("div") .addChild("form", new String[] { "action", "method", "enctype", "id", "accept-charset" }, new String[] { target, "post", "multipart/form-data", id, "utf-8"} ); formNode.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "formPassword", getFormPassword() }); return formNode; } public void setBucketFactory(BucketFactory tempBucketFactory) { this.bf = tempBucketFactory; } public boolean isEnabled() { return myThread != null; } public BookmarkManager getBookmarks() { return bookmarkManager; } public FreenetURI[] getBookmarkURIs() { if(bookmarkManager == null) return new FreenetURI[0]; return bookmarkManager.getBookmarkURIs(); } @Override public boolean enablePersistentConnections() { return enablePersistentConnections; } @Override public boolean enableInlinePrefetch() { return enableInlinePrefetch; } @Override public boolean enableExtendedMethodHandling() { return enableExtendedMethodHandling; } @Override public synchronized boolean allowPosts() { return !(bf instanceof ArrayBucketFactory); } @Override public synchronized BucketFactory getBucketFactory() { return bf; } @Override public boolean enableActivelinks() { return enableActivelinks; } @Override public boolean disableProgressPage() { return disableProgressPage; } @Override public PageMaker getPageMaker() { return pageMaker; } public Ticker getTicker(){ return core.node.getTicker(); } public NodeClientCore getCore(){ return core; } private REFILTER_POLICY refilterPolicy; @Override public REFILTER_POLICY getReFilterPolicy() { return refilterPolicy; } @Override public File getOverrideFile() { return cssOverride; } @Override public String getURL() { return getURL(null); } @Override public String getURL(String host) { StringBuffer sb = new StringBuffer(); if(ssl) sb.append("https"); else sb.append("http"); sb.append("://"); if(host == null) host = "127.0.0.1"; sb.append(host); sb.append(":"); sb.append(this.port); sb.append("/"); return sb.toString(); } @Override public boolean isSSL() { return ssl; } // // LINKFILTEREXCEPTIONPROVIDER METHODS // /** * {@inheritDoc} */ @Override public boolean isLinkExcepted(URI link) { Toadlet toadlet = null; try { toadlet = findToadlet(link); } catch (PermanentRedirectException pre1) { /* ignore. */ } if (toadlet instanceof LinkFilterExceptedToadlet) { return ((LinkFilterExceptedToadlet) toadlet).isLinkExcepted(link); } return false; } @Override public long generateUniqueID() { // FIXME increment a counter? return random.nextLong(); } }
Java
--- layout: default title: (unrecognied function)(FIXME!) --- [Top](../index.html) --- ### 定義場所(file name) hotspot/src/share/vm/prims/jvmtiEnvBase.cpp ### 説明(description) ``` // update the access_flags for the field in the klass ``` ### 名前(function name) ``` void JvmtiEnvBase::update_klass_field_access_flag(fieldDescriptor *fd) { ``` ### 本体部(body) ``` {- ------------------------------------------- (1) fd 引数で指定された fieldDescriptor オブジェクトの _access_flags 情報を, 対応する instanceKlass の fields の中にコピーする ---------------------------------------- -} instanceKlass* ik = instanceKlass::cast(fd->field_holder()); typeArrayOop fields = ik->fields(); fields->ushort_at_put(fd->index(), (jushort)fd->access_flags().as_short()); } ```
Java
<?php defined('_JEXEC') or die(); /** * * Description * * @package VirtueMart * @subpackage Calculation tool * @author Max Milbers * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * @version $Id: default.php 6475 2012-09-21 11:54:21Z Milbo $ */ // Check to ensure this file is included in Joomla! ?> <form action="index.php" method="post" name="adminForm" id="adminForm"> <?php AdminUIHelper::startAdminArea(); ?> <div id="filter-bar" class="btn-toolbar"> <?php echo $this->displayDefaultViewSearch() ?> </div> <div class="clearfix"> </div> <div id="results"> <?php // split to use ajax search echo $this->loadTemplate('results'); ?> </div> <?php AdminUIHelper::endAdminArea(true); ?> </form>
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.10"/> <title>Automated Translation Tries: File Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Automated Translation Tries </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li class="current"><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="globals.html"><span>All</span></a></li> <li><a href="globals_func.html"><span>Functions</span></a></li> <li class="current"><a href="globals_defs.html"><span>Macros</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('globals_defs.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> &#160;<ul> <li>A : <a class="el" href="_hashing_utils_8hpp.html#a955f504eccf76b4eb2489c0adab03121">HashingUtils.hpp</a> </li> <li>B : <a class="el" href="_hashing_utils_8hpp.html#a111da81ae5883147168bbb8366377b10">HashingUtils.hpp</a> </li> <li>BYTES_ONE_MB : <a class="el" href="_globals_8hpp.html#a52055f2355a2ec4d1e883f04023bbf61">Globals.hpp</a> </li> <li>C : <a class="el" href="_hashing_utils_8hpp.html#ac4cf4b2ab929bd23951a8676eeac086b">HashingUtils.hpp</a> </li> <li>DEBUG_OPTION_VALUES : <a class="el" href="_globals_8hpp.html#aafab43b38b1f0088e435452166a53e26">Globals.hpp</a> </li> <li>DEBUG_PARAM_VALUE : <a class="el" href="_globals_8hpp.html#ab433fe232979981ca13d4abc88018217">Globals.hpp</a> </li> <li>EXPECTED_NUMBER_OF_ARGUMENTS : <a class="el" href="_globals_8hpp.html#ab6387e50755e46ace53cb75b6289eba8">Globals.hpp</a> </li> <li>EXPECTED_USER_NUMBER_OF_ARGUMENTS : <a class="el" href="_globals_8hpp.html#a2a9338760b64ba064b8446917f669ed8">Globals.hpp</a> </li> <li>HASHMAPTRIE_HPP : <a class="el" href="_hash_map_trie_8hpp.html#a44555afdc39259ebd960834e39096cee">HashMapTrie.hpp</a> </li> <li>INFO_PARAM_VALUE : <a class="el" href="_globals_8hpp.html#a71979fc65a21e2bf27f0df1f7c9d4721">Globals.hpp</a> </li> <li>LOGER_MAX_LEVEL : <a class="el" href="_logger_8hpp.html#ac44bfa0883a8e25bcc4b05d7b5835054">Logger.hpp</a> </li> <li>LOGGER : <a class="el" href="_logger_8hpp.html#a8909731db6798bb18ac697c179b4dedd">Logger.hpp</a> </li> <li>LOGGER_HPP : <a class="el" href="_logger_8hpp.html#a46c5641c9a0192f415a133917f57b01a">Logger.hpp</a> </li> <li>N_GRAM_PARAM : <a class="el" href="_globals_8hpp.html#a5f3826bb70e91d12acce8d68c346c07b">Globals.hpp</a> </li> <li>PATH_SEPARATION_SYMBOLS : <a class="el" href="_globals_8hpp.html#aa14a56d9d266e780483319faf0a803c1">Globals.hpp</a> </li> <li>PROGRESS_UPDATE_PERIOD : <a class="el" href="_logger_8hpp.html#a6a29bf797538ea7ba250e7ccbc0f9082">Logger.hpp</a> </li> <li>TOKEN_DELIMITER_CHAR : <a class="el" href="_globals_8hpp.html#a63fb6fc7e044c2456baec320d9472899">Globals.hpp</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li> </ul> </div> </body> </html>
Java
/******************************************************************************* * This file contains iSCSI extentions for RDMA (iSER) Verbs * * (c) Copyright 2013 RisingTide Systems LLC. * * Nicholas A. Bellinger <nab@linux-iscsi.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 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. ****************************************************************************/ #include <linux/string.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/in6.h> #include <rdma/ib_verbs.h> #include <rdma/rdma_cm.h> #include <target/target_core_base.h> #include <target/target_core_fabric.h> #include <target/iscsi/iscsi_transport.h> #include "isert_proto.h" #include "ib_isert.h" #define ISERT_MAX_CONN 8 #define ISER_MAX_RX_CQ_LEN (ISERT_QP_MAX_RECV_DTOS * ISERT_MAX_CONN) #define ISER_MAX_TX_CQ_LEN (ISERT_QP_MAX_REQ_DTOS * ISERT_MAX_CONN) static DEFINE_MUTEX(device_list_mutex); static LIST_HEAD(device_list); static struct workqueue_struct *isert_rx_wq; static struct workqueue_struct *isert_comp_wq; static struct kmem_cache *isert_cmd_cache; static void isert_release_work(struct work_struct *work); static void isert_qp_event_callback(struct ib_event *e, void *context) { struct isert_conn *isert_conn = (struct isert_conn *)context; pr_err("isert_qp_event_callback event: %d\n", e->event); switch (e->event) { case IB_EVENT_COMM_EST: rdma_notify(isert_conn->conn_cm_id, IB_EVENT_COMM_EST); break; case IB_EVENT_QP_LAST_WQE_REACHED: pr_warn("Reached TX IB_EVENT_QP_LAST_WQE_REACHED:\n"); break; default: break; } } static int isert_query_device(struct ib_device *ib_dev, struct ib_device_attr *devattr) { int ret; ret = ib_query_device(ib_dev, devattr); if (ret) { pr_err("ib_query_device() failed: %d\n", ret); return ret; } pr_debug("devattr->max_sge: %d\n", devattr->max_sge); pr_debug("devattr->max_sge_rd: %d\n", devattr->max_sge_rd); return 0; } static int isert_conn_setup_qp(struct isert_conn *isert_conn, struct rdma_cm_id *cma_id) { struct isert_device *device = isert_conn->conn_device; struct ib_qp_init_attr attr; struct ib_device_attr devattr; int ret, index, min_index = 0; memset(&devattr, 0, sizeof(struct ib_device_attr)); ret = isert_query_device(cma_id->device, &devattr); if (ret) return ret; mutex_lock(&device_list_mutex); for (index = 0; index < device->cqs_used; index++) if (device->cq_active_qps[index] < device->cq_active_qps[min_index]) min_index = index; device->cq_active_qps[min_index]++; pr_debug("isert_conn_setup_qp: Using min_index: %d\n", min_index); mutex_unlock(&device_list_mutex); memset(&attr, 0, sizeof(struct ib_qp_init_attr)); attr.event_handler = isert_qp_event_callback; attr.qp_context = isert_conn; attr.send_cq = device->dev_tx_cq[min_index]; attr.recv_cq = device->dev_rx_cq[min_index]; attr.cap.max_send_wr = ISERT_QP_MAX_REQ_DTOS; attr.cap.max_recv_wr = ISERT_QP_MAX_RECV_DTOS; /* * FIXME: Use devattr.max_sge - 2 for max_send_sge as * work-around for RDMA_READ.. */ attr.cap.max_send_sge = devattr.max_sge - 2; isert_conn->max_sge = attr.cap.max_send_sge; attr.cap.max_recv_sge = 1; attr.sq_sig_type = IB_SIGNAL_REQ_WR; attr.qp_type = IB_QPT_RC; pr_debug("isert_conn_setup_qp cma_id->device: %p\n", cma_id->device); pr_debug("isert_conn_setup_qp conn_pd->device: %p\n", isert_conn->conn_pd->device); ret = rdma_create_qp(cma_id, isert_conn->conn_pd, &attr); if (ret) { pr_err("rdma_create_qp failed for cma_id %d\n", ret); return ret; } isert_conn->conn_qp = cma_id->qp; pr_debug("rdma_create_qp() returned success >>>>>>>>>>>>>>>>>>>>>>>>>.\n"); return 0; } static void isert_cq_event_callback(struct ib_event *e, void *context) { pr_debug("isert_cq_event_callback event: %d\n", e->event); } static int isert_alloc_rx_descriptors(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iser_rx_desc *rx_desc; struct ib_sge *rx_sg; u64 dma_addr; int i, j; isert_conn->conn_rx_descs = kzalloc(ISERT_QP_MAX_RECV_DTOS * sizeof(struct iser_rx_desc), GFP_KERNEL); if (!isert_conn->conn_rx_descs) goto fail; rx_desc = isert_conn->conn_rx_descs; for (i = 0; i < ISERT_QP_MAX_RECV_DTOS; i++, rx_desc++) { dma_addr = ib_dma_map_single(ib_dev, (void *)rx_desc, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); if (ib_dma_mapping_error(ib_dev, dma_addr)) goto dma_map_fail; rx_desc->dma_addr = dma_addr; rx_sg = &rx_desc->rx_sg; rx_sg->addr = rx_desc->dma_addr; rx_sg->length = ISER_RX_PAYLOAD_SIZE; rx_sg->lkey = isert_conn->conn_mr->lkey; } isert_conn->conn_rx_desc_head = 0; return 0; dma_map_fail: rx_desc = isert_conn->conn_rx_descs; for (j = 0; j < i; j++, rx_desc++) { ib_dma_unmap_single(ib_dev, rx_desc->dma_addr, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); } kfree(isert_conn->conn_rx_descs); isert_conn->conn_rx_descs = NULL; fail: return -ENOMEM; } static void isert_free_rx_descriptors(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_device->ib_device; struct iser_rx_desc *rx_desc; int i; if (!isert_conn->conn_rx_descs) return; rx_desc = isert_conn->conn_rx_descs; for (i = 0; i < ISERT_QP_MAX_RECV_DTOS; i++, rx_desc++) { ib_dma_unmap_single(ib_dev, rx_desc->dma_addr, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); } kfree(isert_conn->conn_rx_descs); isert_conn->conn_rx_descs = NULL; } static void isert_cq_tx_callback(struct ib_cq *, void *); static void isert_cq_rx_callback(struct ib_cq *, void *); static int isert_create_device_ib_res(struct isert_device *device) { struct ib_device *ib_dev = device->ib_device; struct isert_cq_desc *cq_desc; int ret = 0, i, j; device->cqs_used = min_t(int, num_online_cpus(), device->ib_device->num_comp_vectors); device->cqs_used = min(ISERT_MAX_CQ, device->cqs_used); pr_debug("Using %d CQs, device %s supports %d vectors\n", device->cqs_used, device->ib_device->name, device->ib_device->num_comp_vectors); device->cq_desc = kzalloc(sizeof(struct isert_cq_desc) * device->cqs_used, GFP_KERNEL); if (!device->cq_desc) { pr_err("Unable to allocate device->cq_desc\n"); return -ENOMEM; } cq_desc = device->cq_desc; device->dev_pd = ib_alloc_pd(ib_dev); if (IS_ERR(device->dev_pd)) { ret = PTR_ERR(device->dev_pd); pr_err("ib_alloc_pd failed for dev_pd: %d\n", ret); goto out_cq_desc; } for (i = 0; i < device->cqs_used; i++) { cq_desc[i].device = device; cq_desc[i].cq_index = i; device->dev_rx_cq[i] = ib_create_cq(device->ib_device, isert_cq_rx_callback, isert_cq_event_callback, (void *)&cq_desc[i], ISER_MAX_RX_CQ_LEN, i); if (IS_ERR(device->dev_rx_cq[i])) { ret = PTR_ERR(device->dev_rx_cq[i]); device->dev_rx_cq[i] = NULL; goto out_cq; } device->dev_tx_cq[i] = ib_create_cq(device->ib_device, isert_cq_tx_callback, isert_cq_event_callback, (void *)&cq_desc[i], ISER_MAX_TX_CQ_LEN, i); if (IS_ERR(device->dev_tx_cq[i])) { ret = PTR_ERR(device->dev_tx_cq[i]); device->dev_tx_cq[i] = NULL; goto out_cq; } ret = ib_req_notify_cq(device->dev_rx_cq[i], IB_CQ_NEXT_COMP); if (ret) goto out_cq; ret = ib_req_notify_cq(device->dev_tx_cq[i], IB_CQ_NEXT_COMP); if (ret) goto out_cq; } device->dev_mr = ib_get_dma_mr(device->dev_pd, IB_ACCESS_LOCAL_WRITE); if (IS_ERR(device->dev_mr)) { ret = PTR_ERR(device->dev_mr); pr_err("ib_get_dma_mr failed for dev_mr: %d\n", ret); goto out_cq; } return 0; out_cq: for (j = 0; j < i; j++) { cq_desc = &device->cq_desc[j]; if (device->dev_rx_cq[j]) { cancel_work_sync(&cq_desc->cq_rx_work); ib_destroy_cq(device->dev_rx_cq[j]); } if (device->dev_tx_cq[j]) { cancel_work_sync(&cq_desc->cq_tx_work); ib_destroy_cq(device->dev_tx_cq[j]); } } ib_dealloc_pd(device->dev_pd); out_cq_desc: kfree(device->cq_desc); return ret; } static void isert_free_device_ib_res(struct isert_device *device) { struct isert_cq_desc *cq_desc; int i; for (i = 0; i < device->cqs_used; i++) { cq_desc = &device->cq_desc[i]; cancel_work_sync(&cq_desc->cq_rx_work); cancel_work_sync(&cq_desc->cq_tx_work); ib_destroy_cq(device->dev_rx_cq[i]); ib_destroy_cq(device->dev_tx_cq[i]); device->dev_rx_cq[i] = NULL; device->dev_tx_cq[i] = NULL; } ib_dereg_mr(device->dev_mr); ib_dealloc_pd(device->dev_pd); kfree(device->cq_desc); } static void isert_device_try_release(struct isert_device *device) { mutex_lock(&device_list_mutex); device->refcount--; if (!device->refcount) { isert_free_device_ib_res(device); list_del(&device->dev_node); kfree(device); } mutex_unlock(&device_list_mutex); } static struct isert_device * isert_device_find_by_ib_dev(struct rdma_cm_id *cma_id) { struct isert_device *device; int ret; mutex_lock(&device_list_mutex); list_for_each_entry(device, &device_list, dev_node) { if (device->ib_device->node_guid == cma_id->device->node_guid) { device->refcount++; mutex_unlock(&device_list_mutex); return device; } } device = kzalloc(sizeof(struct isert_device), GFP_KERNEL); if (!device) { mutex_unlock(&device_list_mutex); return ERR_PTR(-ENOMEM); } INIT_LIST_HEAD(&device->dev_node); device->ib_device = cma_id->device; ret = isert_create_device_ib_res(device); if (ret) { kfree(device); mutex_unlock(&device_list_mutex); return ERR_PTR(ret); } device->refcount++; list_add_tail(&device->dev_node, &device_list); mutex_unlock(&device_list_mutex); return device; } static int isert_connect_request(struct rdma_cm_id *cma_id, struct rdma_cm_event *event) { struct isert_np *isert_np = cma_id->context; struct iscsi_np *np = isert_np->np; struct isert_conn *isert_conn; struct isert_device *device; struct ib_device *ib_dev = cma_id->device; int ret = 0; spin_lock_bh(&np->np_thread_lock); if (!np->enabled) { spin_unlock_bh(&np->np_thread_lock); pr_debug("iscsi_np is not enabled, reject connect request\n"); return rdma_reject(cma_id, NULL, 0); } spin_unlock_bh(&np->np_thread_lock); pr_debug("Entering isert_connect_request cma_id: %p, context: %p\n", cma_id, cma_id->context); isert_conn = kzalloc(sizeof(struct isert_conn), GFP_KERNEL); if (!isert_conn) { pr_err("Unable to allocate isert_conn\n"); return -ENOMEM; } isert_conn->state = ISER_CONN_INIT; INIT_LIST_HEAD(&isert_conn->conn_accept_node); init_completion(&isert_conn->conn_login_comp); init_completion(&isert_conn->conn_wait); init_completion(&isert_conn->conn_wait_comp_err); kref_init(&isert_conn->conn_kref); kref_get(&isert_conn->conn_kref); mutex_init(&isert_conn->conn_mutex); INIT_WORK(&isert_conn->release_work, isert_release_work); cma_id->context = isert_conn; isert_conn->conn_cm_id = cma_id; isert_conn->responder_resources = event->param.conn.responder_resources; isert_conn->initiator_depth = event->param.conn.initiator_depth; pr_debug("Using responder_resources: %u initiator_depth: %u\n", isert_conn->responder_resources, isert_conn->initiator_depth); isert_conn->login_buf = kzalloc(ISCSI_DEF_MAX_RECV_SEG_LEN + ISER_RX_LOGIN_SIZE, GFP_KERNEL); if (!isert_conn->login_buf) { pr_err("Unable to allocate isert_conn->login_buf\n"); ret = -ENOMEM; goto out; } isert_conn->login_req_buf = isert_conn->login_buf; isert_conn->login_rsp_buf = isert_conn->login_buf + ISCSI_DEF_MAX_RECV_SEG_LEN; pr_debug("Set login_buf: %p login_req_buf: %p login_rsp_buf: %p\n", isert_conn->login_buf, isert_conn->login_req_buf, isert_conn->login_rsp_buf); isert_conn->login_req_dma = ib_dma_map_single(ib_dev, (void *)isert_conn->login_req_buf, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); ret = ib_dma_mapping_error(ib_dev, isert_conn->login_req_dma); if (ret) { pr_err("ib_dma_mapping_error failed for login_req_dma: %d\n", ret); isert_conn->login_req_dma = 0; goto out_login_buf; } isert_conn->login_rsp_dma = ib_dma_map_single(ib_dev, (void *)isert_conn->login_rsp_buf, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); ret = ib_dma_mapping_error(ib_dev, isert_conn->login_rsp_dma); if (ret) { pr_err("ib_dma_mapping_error failed for login_rsp_dma: %d\n", ret); isert_conn->login_rsp_dma = 0; goto out_req_dma_map; } device = isert_device_find_by_ib_dev(cma_id); if (IS_ERR(device)) { ret = PTR_ERR(device); goto out_rsp_dma_map; } isert_conn->conn_device = device; isert_conn->conn_pd = device->dev_pd; isert_conn->conn_mr = device->dev_mr; ret = isert_conn_setup_qp(isert_conn, cma_id); if (ret) goto out_conn_dev; mutex_lock(&isert_np->np_accept_mutex); list_add_tail(&isert_np->np_accept_list, &isert_conn->conn_accept_node); mutex_unlock(&isert_np->np_accept_mutex); pr_debug("isert_connect_request() waking up np_accept_wq: %p\n", np); wake_up(&isert_np->np_accept_wq); return 0; out_conn_dev: isert_device_try_release(device); out_rsp_dma_map: ib_dma_unmap_single(ib_dev, isert_conn->login_rsp_dma, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); out_req_dma_map: ib_dma_unmap_single(ib_dev, isert_conn->login_req_dma, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); out_login_buf: kfree(isert_conn->login_buf); out: kfree(isert_conn); return ret; } static void isert_connect_release(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_device *device = isert_conn->conn_device; int cq_index; pr_debug("Entering isert_connect_release(): >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); if (isert_conn->conn_qp) { cq_index = ((struct isert_cq_desc *) isert_conn->conn_qp->recv_cq->cq_context)->cq_index; pr_debug("isert_connect_release: cq_index: %d\n", cq_index); isert_conn->conn_device->cq_active_qps[cq_index]--; rdma_destroy_qp(isert_conn->conn_cm_id); } isert_free_rx_descriptors(isert_conn); rdma_destroy_id(isert_conn->conn_cm_id); if (isert_conn->login_buf) { ib_dma_unmap_single(ib_dev, isert_conn->login_rsp_dma, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); ib_dma_unmap_single(ib_dev, isert_conn->login_req_dma, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); kfree(isert_conn->login_buf); } kfree(isert_conn); if (device) isert_device_try_release(device); pr_debug("Leaving isert_connect_release >>>>>>>>>>>>\n"); } static void isert_connected_handler(struct rdma_cm_id *cma_id) { struct isert_conn *isert_conn = cma_id->context; kref_get(&isert_conn->conn_kref); } static void isert_release_conn_kref(struct kref *kref) { struct isert_conn *isert_conn = container_of(kref, struct isert_conn, conn_kref); pr_debug("Calling isert_connect_release for final kref %s/%d\n", current->comm, current->pid); isert_connect_release(isert_conn); } static void isert_put_conn(struct isert_conn *isert_conn) { kref_put(&isert_conn->conn_kref, isert_release_conn_kref); } static void isert_disconnect_work(struct work_struct *work) { struct isert_conn *isert_conn = container_of(work, struct isert_conn, conn_logout_work); pr_debug("isert_disconnect_work(): >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); mutex_lock(&isert_conn->conn_mutex); if (isert_conn->state == ISER_CONN_UP) isert_conn->state = ISER_CONN_TERMINATING; if (isert_conn->post_recv_buf_count == 0 && atomic_read(&isert_conn->post_send_buf_count) == 0) { mutex_unlock(&isert_conn->conn_mutex); goto wake_up; } if (!isert_conn->conn_cm_id) { mutex_unlock(&isert_conn->conn_mutex); isert_put_conn(isert_conn); return; } if (isert_conn->disconnect) { /* Send DREQ/DREP towards our initiator */ rdma_disconnect(isert_conn->conn_cm_id); } mutex_unlock(&isert_conn->conn_mutex); wake_up: complete(&isert_conn->conn_wait); } static int isert_disconnected_handler(struct rdma_cm_id *cma_id, bool disconnect) { struct isert_conn *isert_conn; bool terminating = false; if (!cma_id->qp) { struct isert_np *isert_np = cma_id->context; isert_np->np_cm_id = NULL; break; case RDMA_CM_EVENT_ADDR_CHANGE: isert_np->np_cm_id = isert_setup_id(isert_np); if (IS_ERR(isert_np->np_cm_id)) { pr_err("isert np %p setup id failed: %ld\n", isert_np, PTR_ERR(isert_np->np_cm_id)); isert_np->np_cm_id = NULL; } break; default: pr_err("isert np %p Unexpected event %d\n", isert_np, event); } isert_conn = (struct isert_conn *)cma_id->context; isert_conn->disconnect = disconnect; INIT_WORK(&isert_conn->conn_logout_work, isert_disconnect_work); schedule_work(&isert_conn->conn_logout_work); return 0; } static int isert_cma_handler(struct rdma_cm_id *cma_id, struct rdma_cm_event *event) { int ret = 0; bool disconnect = false; pr_debug("isert_cma_handler: event %d status %d conn %p id %p\n", event->event, event->status, cma_id->context, cma_id); switch (event->event) { case RDMA_CM_EVENT_CONNECT_REQUEST: ret = isert_connect_request(cma_id, event); if (ret) pr_err("isert_cma_handler failed RDMA_CM_EVENT: 0x%08x %d\n", event->event, ret); break; case RDMA_CM_EVENT_ESTABLISHED: isert_connected_handler(cma_id); break; case RDMA_CM_EVENT_ADDR_CHANGE: /* FALLTHRU */ case RDMA_CM_EVENT_DISCONNECTED: /* FALLTHRU */ case RDMA_CM_EVENT_DEVICE_REMOVAL: /* FALLTHRU */ disconnect = true; case RDMA_CM_EVENT_TIMEWAIT_EXIT: /* FALLTHRU */ ret = isert_disconnected_handler(cma_id, disconnect); break; case RDMA_CM_EVENT_CONNECT_ERROR: default: pr_err("Unhandled RDMA CMA event: %d\n", event->event); break; } return ret; } static int isert_post_recv(struct isert_conn *isert_conn, u32 count) { struct ib_recv_wr *rx_wr, *rx_wr_failed; int i, ret; unsigned int rx_head = isert_conn->conn_rx_desc_head; struct iser_rx_desc *rx_desc; for (rx_wr = isert_conn->conn_rx_wr, i = 0; i < count; i++, rx_wr++) { rx_desc = &isert_conn->conn_rx_descs[rx_head]; rx_wr->wr_id = (unsigned long)rx_desc; rx_wr->sg_list = &rx_desc->rx_sg; rx_wr->num_sge = 1; rx_wr->next = rx_wr + 1; rx_head = (rx_head + 1) & (ISERT_QP_MAX_RECV_DTOS - 1); } rx_wr--; rx_wr->next = NULL; /* mark end of work requests list */ isert_conn->post_recv_buf_count += count; ret = ib_post_recv(isert_conn->conn_qp, isert_conn->conn_rx_wr, &rx_wr_failed); if (ret) { pr_err("ib_post_recv() failed with ret: %d\n", ret); isert_conn->post_recv_buf_count -= count; } else { pr_debug("isert_post_recv(): Posted %d RX buffers\n", count); isert_conn->conn_rx_desc_head = rx_head; } return ret; } static int isert_post_send(struct isert_conn *isert_conn, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_send_wr send_wr, *send_wr_failed; int ret; ib_dma_sync_single_for_device(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); send_wr.next = NULL; send_wr.wr_id = (unsigned long)tx_desc; send_wr.sg_list = tx_desc->tx_sg; send_wr.num_sge = tx_desc->num_sge; send_wr.opcode = IB_WR_SEND; send_wr.send_flags = IB_SEND_SIGNALED; atomic_inc(&isert_conn->post_send_buf_count); ret = ib_post_send(isert_conn->conn_qp, &send_wr, &send_wr_failed); if (ret) { pr_err("ib_post_send() failed, ret: %d\n", ret); atomic_dec(&isert_conn->post_send_buf_count); } return ret; } static void isert_create_send_desc(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; ib_dma_sync_single_for_cpu(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); memset(&tx_desc->iser_header, 0, sizeof(struct iser_hdr)); tx_desc->iser_header.flags = ISER_VER; tx_desc->num_sge = 1; tx_desc->isert_cmd = isert_cmd; if (tx_desc->tx_sg[0].lkey != isert_conn->conn_mr->lkey) { tx_desc->tx_sg[0].lkey = isert_conn->conn_mr->lkey; pr_debug("tx_desc %p lkey mismatch, fixing\n", tx_desc); } } static int isert_init_tx_hdrs(struct isert_conn *isert_conn, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; u64 dma_addr; dma_addr = ib_dma_map_single(ib_dev, (void *)tx_desc, ISER_HEADERS_LEN, DMA_TO_DEVICE); if (ib_dma_mapping_error(ib_dev, dma_addr)) { pr_err("ib_dma_mapping_error() failed\n"); return -ENOMEM; } tx_desc->dma_addr = dma_addr; tx_desc->tx_sg[0].addr = tx_desc->dma_addr; tx_desc->tx_sg[0].length = ISER_HEADERS_LEN; tx_desc->tx_sg[0].lkey = isert_conn->conn_mr->lkey; pr_debug("isert_init_tx_hdrs: Setup tx_sg[0].addr: 0x%llx length: %u" " lkey: 0x%08x\n", tx_desc->tx_sg[0].addr, tx_desc->tx_sg[0].length, tx_desc->tx_sg[0].lkey); return 0; } static void isert_init_send_wr(struct isert_cmd *isert_cmd, struct ib_send_wr *send_wr) { isert_cmd->rdma_wr.iser_ib_op = ISER_IB_SEND; send_wr->wr_id = (unsigned long)&isert_cmd->tx_desc; send_wr->opcode = IB_WR_SEND; send_wr->send_flags = IB_SEND_SIGNALED; send_wr->sg_list = &isert_cmd->tx_desc.tx_sg[0]; send_wr->num_sge = isert_cmd->tx_desc.num_sge; } static int isert_rdma_post_recvl(struct isert_conn *isert_conn) { struct ib_recv_wr rx_wr, *rx_wr_fail; struct ib_sge sge; int ret; memset(&sge, 0, sizeof(struct ib_sge)); sge.addr = isert_conn->login_req_dma; sge.length = ISER_RX_LOGIN_SIZE; sge.lkey = isert_conn->conn_mr->lkey; pr_debug("Setup sge: addr: %llx length: %d 0x%08x\n", sge.addr, sge.length, sge.lkey); memset(&rx_wr, 0, sizeof(struct ib_recv_wr)); rx_wr.wr_id = (unsigned long)isert_conn->login_req_buf; rx_wr.sg_list = &sge; rx_wr.num_sge = 1; isert_conn->post_recv_buf_count++; ret = ib_post_recv(isert_conn->conn_qp, &rx_wr, &rx_wr_fail); if (ret) { pr_err("ib_post_recv() failed: %d\n", ret); isert_conn->post_recv_buf_count--; } pr_debug("ib_post_recv(): returned success >>>>>>>>>>>>>>>>>>>>>>>>\n"); return ret; } static int isert_put_login_tx(struct iscsi_conn *conn, struct iscsi_login *login, u32 length) { struct isert_conn *isert_conn = conn->context; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iser_tx_desc *tx_desc = &isert_conn->conn_login_tx_desc; int ret; isert_create_send_desc(isert_conn, NULL, tx_desc); memcpy(&tx_desc->iscsi_header, &login->rsp[0], sizeof(struct iscsi_hdr)); isert_init_tx_hdrs(isert_conn, tx_desc); if (length > 0) { struct ib_sge *tx_dsg = &tx_desc->tx_sg[1]; ib_dma_sync_single_for_cpu(ib_dev, isert_conn->login_rsp_dma, length, DMA_TO_DEVICE); memcpy(isert_conn->login_rsp_buf, login->rsp_buf, length); ib_dma_sync_single_for_device(ib_dev, isert_conn->login_rsp_dma, length, DMA_TO_DEVICE); tx_dsg->addr = isert_conn->login_rsp_dma; tx_dsg->length = length; tx_dsg->lkey = isert_conn->conn_mr->lkey; tx_desc->num_sge = 2; } if (!login->login_failed) { if (login->login_complete) { ret = isert_alloc_rx_descriptors(isert_conn); if (ret) return ret; ret = isert_post_recv(isert_conn, ISERT_MIN_POSTED_RX); if (ret) return ret; isert_conn->state = ISER_CONN_UP; goto post_send; } ret = isert_rdma_post_recvl(isert_conn); if (ret) return ret; } post_send: ret = isert_post_send(isert_conn, tx_desc); if (ret) return ret; return 0; } static void isert_rx_login_req(struct iser_rx_desc *rx_desc, int rx_buflen, struct isert_conn *isert_conn) { struct iscsi_conn *conn = isert_conn->conn; struct iscsi_login *login = conn->conn_login; int size; if (!login) { pr_err("conn->conn_login is NULL\n"); dump_stack(); return; } if (login->first_request) { struct iscsi_login_req *login_req = (struct iscsi_login_req *)&rx_desc->iscsi_header; /* * Setup the initial iscsi_login values from the leading * login request PDU. */ login->leading_connection = (!login_req->tsih) ? 1 : 0; login->current_stage = (login_req->flags & ISCSI_FLAG_LOGIN_CURRENT_STAGE_MASK) >> 2; login->version_min = login_req->min_version; login->version_max = login_req->max_version; memcpy(login->isid, login_req->isid, 6); login->cmd_sn = be32_to_cpu(login_req->cmdsn); login->init_task_tag = login_req->itt; login->initial_exp_statsn = be32_to_cpu(login_req->exp_statsn); login->cid = be16_to_cpu(login_req->cid); login->tsih = be16_to_cpu(login_req->tsih); } memcpy(&login->req[0], (void *)&rx_desc->iscsi_header, ISCSI_HDR_LEN); size = min(rx_buflen, MAX_KEY_VALUE_PAIRS); pr_debug("Using login payload size: %d, rx_buflen: %d MAX_KEY_VALUE_PAIRS: %d\n", size, rx_buflen, MAX_KEY_VALUE_PAIRS); memcpy(login->req_buf, &rx_desc->data[0], size); complete(&isert_conn->conn_login_comp); } static void isert_release_cmd(struct iscsi_cmd *cmd) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); pr_debug("Entering isert_release_cmd %p >>>>>>>>>>>>>>>.\n", isert_cmd); kfree(cmd->buf_ptr); kfree(cmd->tmr_req); kmem_cache_free(isert_cmd_cache, isert_cmd); } static struct iscsi_cmd *isert_alloc_cmd(struct iscsi_conn *conn, gfp_t gfp) { struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct isert_cmd *isert_cmd; isert_cmd = kmem_cache_zalloc(isert_cmd_cache, gfp); if (!isert_cmd) { pr_err("Unable to allocate isert_cmd\n"); return NULL; } isert_cmd->conn = isert_conn; isert_cmd->iscsi_cmd.release_cmd = &isert_release_cmd; return &isert_cmd->iscsi_cmd; } static int isert_handle_scsi_cmd(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct iser_rx_desc *rx_desc, unsigned char *buf) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_scsi_req *hdr = (struct iscsi_scsi_req *)buf; struct scatterlist *sg; int imm_data, imm_data_len, unsol_data, sg_nents, rc; bool dump_payload = false; rc = iscsit_setup_scsi_cmd(conn, cmd, buf); if (rc < 0) return rc; imm_data = cmd->immediate_data; imm_data_len = cmd->first_burst_len; unsol_data = cmd->unsolicited_data; rc = iscsit_process_scsi_cmd(conn, cmd, hdr); if (rc < 0) { return 0; } else if (rc > 0) { dump_payload = true; goto sequence_cmd; } if (!imm_data) return 0; sg = &cmd->se_cmd.t_data_sg[0]; sg_nents = max(1UL, DIV_ROUND_UP(imm_data_len, PAGE_SIZE)); pr_debug("Copying Immediate SG: %p sg_nents: %u from %p imm_data_len: %d\n", sg, sg_nents, &rx_desc->data[0], imm_data_len); sg_copy_from_buffer(sg, sg_nents, &rx_desc->data[0], imm_data_len); cmd->write_data_done += imm_data_len; if (cmd->write_data_done == cmd->se_cmd.data_length) { spin_lock_bh(&cmd->istate_lock); cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT; cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT; spin_unlock_bh(&cmd->istate_lock); } sequence_cmd: rc = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn); if (!rc && dump_payload == false && unsol_data) iscsit_set_unsoliticed_dataout(cmd); else if (dump_payload && imm_data) target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd); return 0; } static int isert_handle_iscsi_dataout(struct isert_conn *isert_conn, struct iser_rx_desc *rx_desc, unsigned char *buf) { struct scatterlist *sg_start; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_cmd *cmd = NULL; struct iscsi_data *hdr = (struct iscsi_data *)buf; u32 unsol_data_len = ntoh24(hdr->dlength); int rc, sg_nents, sg_off, page_off; rc = iscsit_check_dataout_hdr(conn, buf, &cmd); if (rc < 0) return rc; else if (!cmd) return 0; /* * FIXME: Unexpected unsolicited_data out */ if (!cmd->unsolicited_data) { pr_err("Received unexpected solicited data payload\n"); dump_stack(); return -1; } pr_debug("Unsolicited DataOut unsol_data_len: %u, write_data_done: %u, data_length: %u\n", unsol_data_len, cmd->write_data_done, cmd->se_cmd.data_length); sg_off = cmd->write_data_done / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; sg_nents = max(1UL, DIV_ROUND_UP(unsol_data_len, PAGE_SIZE)); page_off = cmd->write_data_done % PAGE_SIZE; /* * FIXME: Non page-aligned unsolicited_data out */ if (page_off) { pr_err("Received unexpected non-page aligned data payload\n"); dump_stack(); return -1; } pr_debug("Copying DataOut: sg_start: %p, sg_off: %u sg_nents: %u from %p %u\n", sg_start, sg_off, sg_nents, &rx_desc->data[0], unsol_data_len); sg_copy_from_buffer(sg_start, sg_nents, &rx_desc->data[0], unsol_data_len); rc = iscsit_check_dataout_payload(cmd, hdr, false); if (rc < 0) return rc; return 0; } static int isert_rx_opcode(struct isert_conn *isert_conn, struct iser_rx_desc *rx_desc, uint32_t read_stag, uint64_t read_va, uint32_t write_stag, uint64_t write_va) { struct iscsi_hdr *hdr = &rx_desc->iscsi_header; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_cmd *cmd; struct isert_cmd *isert_cmd; int ret = -EINVAL; u8 opcode = (hdr->opcode & ISCSI_OPCODE_MASK); switch (opcode) { case ISCSI_OP_SCSI_CMD: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); isert_cmd->read_stag = read_stag; isert_cmd->read_va = read_va; isert_cmd->write_stag = write_stag; isert_cmd->write_va = write_va; ret = isert_handle_scsi_cmd(isert_conn, isert_cmd, rx_desc, (unsigned char *)hdr); break; case ISCSI_OP_NOOP_OUT: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_nop_out(conn, cmd, (unsigned char *)hdr); break; case ISCSI_OP_SCSI_DATA_OUT: ret = isert_handle_iscsi_dataout(isert_conn, rx_desc, (unsigned char *)hdr); break; case ISCSI_OP_SCSI_TMFUNC: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_task_mgt_cmd(conn, cmd, (unsigned char *)hdr); break; case ISCSI_OP_LOGOUT: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_logout_cmd(conn, cmd, (unsigned char *)hdr); if (ret > 0) wait_for_completion_timeout(&conn->conn_logout_comp, SECONDS_FOR_LOGOUT_COMP * HZ); break; default: pr_err("Got unknown iSCSI OpCode: 0x%02x\n", opcode); dump_stack(); break; } return ret; } static void isert_rx_do_work(struct iser_rx_desc *rx_desc, struct isert_conn *isert_conn) { struct iser_hdr *iser_hdr = &rx_desc->iser_header; uint64_t read_va = 0, write_va = 0; uint32_t read_stag = 0, write_stag = 0; int rc; switch (iser_hdr->flags & 0xF0) { case ISCSI_CTRL: if (iser_hdr->flags & ISER_RSV) { read_stag = be32_to_cpu(iser_hdr->read_stag); read_va = be64_to_cpu(iser_hdr->read_va); pr_debug("ISER_RSV: read_stag: 0x%08x read_va: 0x%16llx\n", read_stag, (unsigned long long)read_va); } if (iser_hdr->flags & ISER_WSV) { write_stag = be32_to_cpu(iser_hdr->write_stag); write_va = be64_to_cpu(iser_hdr->write_va); pr_debug("ISER_WSV: write__stag: 0x%08x write_va: 0x%16llx\n", write_stag, (unsigned long long)write_va); } pr_debug("ISER ISCSI_CTRL PDU\n"); break; case ISER_HELLO: pr_err("iSER Hello message\n"); break; default: pr_warn("Unknown iSER hdr flags: 0x%02x\n", iser_hdr->flags); break; } rc = isert_rx_opcode(isert_conn, rx_desc, read_stag, read_va, write_stag, write_va); } static void isert_rx_completion(struct iser_rx_desc *desc, struct isert_conn *isert_conn, unsigned long xfer_len) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iscsi_hdr *hdr; u64 rx_dma; int rx_buflen, outstanding; if ((char *)desc == isert_conn->login_req_buf) { rx_dma = isert_conn->login_req_dma; rx_buflen = ISER_RX_LOGIN_SIZE; pr_debug("ISER login_buf: Using rx_dma: 0x%llx, rx_buflen: %d\n", rx_dma, rx_buflen); } else { rx_dma = desc->dma_addr; rx_buflen = ISER_RX_PAYLOAD_SIZE; pr_debug("ISER req_buf: Using rx_dma: 0x%llx, rx_buflen: %d\n", rx_dma, rx_buflen); } ib_dma_sync_single_for_cpu(ib_dev, rx_dma, rx_buflen, DMA_FROM_DEVICE); hdr = &desc->iscsi_header; pr_debug("iSCSI opcode: 0x%02x, ITT: 0x%08x, flags: 0x%02x dlen: %d\n", hdr->opcode, hdr->itt, hdr->flags, (int)(xfer_len - ISER_HEADERS_LEN)); if ((char *)desc == isert_conn->login_req_buf) isert_rx_login_req(desc, xfer_len - ISER_HEADERS_LEN, isert_conn); else isert_rx_do_work(desc, isert_conn); ib_dma_sync_single_for_device(ib_dev, rx_dma, rx_buflen, DMA_FROM_DEVICE); isert_conn->post_recv_buf_count--; pr_debug("iSERT: Decremented post_recv_buf_count: %d\n", isert_conn->post_recv_buf_count); if ((char *)desc == isert_conn->login_req_buf) return; outstanding = isert_conn->post_recv_buf_count; if (outstanding + ISERT_MIN_POSTED_RX <= ISERT_QP_MAX_RECV_DTOS) { int err, count = min(ISERT_QP_MAX_RECV_DTOS - outstanding, ISERT_MIN_POSTED_RX); err = isert_post_recv(isert_conn, count); if (err) { pr_err("isert_post_recv() count: %d failed, %d\n", count, err); } } } static void isert_unmap_cmd(struct isert_cmd *isert_cmd, struct isert_conn *isert_conn) { struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; pr_debug("isert_unmap_cmd >>>>>>>>>>>>>>>>>>>>>>>\n"); if (wr->sge) { ib_dma_unmap_sg(ib_dev, wr->sge, wr->num_sge, DMA_TO_DEVICE); wr->sge = NULL; } kfree(wr->send_wr); wr->send_wr = NULL; kfree(isert_cmd->ib_sge); isert_cmd->ib_sge = NULL; } static void isert_put_cmd(struct isert_cmd *isert_cmd, bool comp_err) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct isert_conn *isert_conn = isert_cmd->conn; struct iscsi_conn *conn = isert_conn->conn; pr_debug("Entering isert_put_cmd: %p\n", isert_cmd); switch (cmd->iscsi_opcode) { case ISCSI_OP_SCSI_CMD: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); if (cmd->data_direction == DMA_TO_DEVICE) { iscsit_stop_dataout_timer(cmd); /* * Check for special case during comp_err where * WRITE_PENDING has been handed off from core, * but requires an extra target_put_sess_cmd() * before transport_generic_free_cmd() below. */ if (comp_err && cmd->se_cmd.t_state == TRANSPORT_WRITE_PENDING) { struct se_cmd *se_cmd = &cmd->se_cmd; target_put_sess_cmd(se_cmd->se_sess, se_cmd); } } isert_unmap_cmd(isert_cmd, isert_conn); transport_generic_free_cmd(&cmd->se_cmd, 0); break; case ISCSI_OP_SCSI_TMFUNC: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); transport_generic_free_cmd(&cmd->se_cmd, 0); break; case ISCSI_OP_REJECT: case ISCSI_OP_NOOP_OUT: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); /* * Handle special case for REJECT when iscsi_add_reject*() has * overwritten the original iscsi_opcode assignment, and the * associated cmd->se_cmd needs to be released. */ if (cmd->se_cmd.se_tfo != NULL) { pr_debug("Calling transport_generic_free_cmd from" " isert_put_cmd for 0x%02x\n", cmd->iscsi_opcode); transport_generic_free_cmd(&cmd->se_cmd, 0); break; } /* * Fall-through */ default: isert_release_cmd(cmd); break; } } static void isert_unmap_tx_desc(struct iser_tx_desc *tx_desc, struct ib_device *ib_dev) { if (tx_desc->dma_addr != 0) { pr_debug("Calling ib_dma_unmap_single for tx_desc->dma_addr\n"); ib_dma_unmap_single(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); tx_desc->dma_addr = 0; } } static void isert_completion_put(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd, struct ib_device *ib_dev, bool comp_err) { if (isert_cmd->sense_buf_dma != 0) { pr_debug("Calling ib_dma_unmap_single for isert_cmd->sense_buf_dma\n"); ib_dma_unmap_single(ib_dev, isert_cmd->sense_buf_dma, isert_cmd->sense_buf_len, DMA_TO_DEVICE); isert_cmd->sense_buf_dma = 0; } isert_unmap_tx_desc(tx_desc, ib_dev); isert_put_cmd(isert_cmd, comp_err); } static void isert_completion_rdma_read(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd) { struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct se_cmd *se_cmd = &cmd->se_cmd; struct ib_device *ib_dev = isert_cmd->conn->conn_cm_id->device; iscsit_stop_dataout_timer(cmd); if (wr->sge) { pr_debug("isert_do_rdma_read_comp: Unmapping wr->sge from t_data_sg\n"); ib_dma_unmap_sg(ib_dev, wr->sge, wr->num_sge, DMA_TO_DEVICE); wr->sge = NULL; } if (isert_cmd->ib_sge) { pr_debug("isert_do_rdma_read_comp: Freeing isert_cmd->ib_sge\n"); kfree(isert_cmd->ib_sge); isert_cmd->ib_sge = NULL; } cmd->write_data_done = se_cmd->data_length; wr->send_wr_num = 0; pr_debug("isert_do_rdma_read_comp, calling target_execute_cmd\n"); spin_lock_bh(&cmd->istate_lock); cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT; cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT; spin_unlock_bh(&cmd->istate_lock); target_execute_cmd(se_cmd); } static void isert_do_control_comp(struct work_struct *work) { struct isert_cmd *isert_cmd = container_of(work, struct isert_cmd, comp_work); struct isert_conn *isert_conn = isert_cmd->conn; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; switch (cmd->i_state) { case ISTATE_SEND_TASKMGTRSP: pr_debug("Calling iscsit_tmr_post_handler >>>>>>>>>>>>>>>>>\n"); atomic_dec(&isert_conn->post_send_buf_count); iscsit_tmr_post_handler(cmd, cmd->conn); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(&isert_cmd->tx_desc, isert_cmd, ib_dev, false); break; case ISTATE_SEND_REJECT: pr_debug("Got isert_do_control_comp ISTATE_SEND_REJECT: >>>\n"); atomic_dec(&isert_conn->post_send_buf_count); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(&isert_cmd->tx_desc, isert_cmd, ib_dev, false); break; case ISTATE_SEND_LOGOUTRSP: pr_debug("Calling iscsit_logout_post_handler >>>>>>>>>>>>>>\n"); atomic_dec(&isert_conn->post_send_buf_count); iscsit_logout_post_handler(cmd, cmd->conn); break; default: pr_err("Unknown do_control_comp i_state %d\n", cmd->i_state); dump_stack(); break; } } static void isert_response_completion(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd, struct isert_conn *isert_conn, struct ib_device *ib_dev) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; if (cmd->i_state == ISTATE_SEND_TASKMGTRSP || cmd->i_state == ISTATE_SEND_LOGOUTRSP || cmd->i_state == ISTATE_SEND_REJECT) { isert_unmap_tx_desc(tx_desc, ib_dev); INIT_WORK(&isert_cmd->comp_work, isert_do_control_comp); queue_work(isert_comp_wq, &isert_cmd->comp_work); return; } atomic_sub(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(tx_desc, isert_cmd, ib_dev, false); } static void isert_send_completion(struct iser_tx_desc *tx_desc, struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_cmd *isert_cmd = tx_desc->isert_cmd; struct isert_rdma_wr *wr; if (!isert_cmd) { atomic_dec(&isert_conn->post_send_buf_count); isert_unmap_tx_desc(tx_desc, ib_dev); return; } wr = &isert_cmd->rdma_wr; switch (wr->iser_ib_op) { case ISER_IB_RECV: pr_err("isert_send_completion: Got ISER_IB_RECV\n"); dump_stack(); break; case ISER_IB_SEND: pr_debug("isert_send_completion: Got ISER_IB_SEND\n"); isert_response_completion(tx_desc, isert_cmd, isert_conn, ib_dev); break; case ISER_IB_RDMA_WRITE: pr_err("isert_send_completion: Got ISER_IB_RDMA_WRITE\n"); dump_stack(); break; case ISER_IB_RDMA_READ: pr_debug("isert_send_completion: Got ISER_IB_RDMA_READ:\n"); atomic_sub(wr->send_wr_num, &isert_conn->post_send_buf_count); isert_completion_rdma_read(tx_desc, isert_cmd); break; default: pr_err("Unknown wr->iser_ib_op: 0x%02x\n", wr->iser_ib_op); dump_stack(); break; } } static void isert_cq_tx_comp_err(struct iser_tx_desc *tx_desc, struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_cmd *isert_cmd = tx_desc->isert_cmd; if (!isert_cmd) isert_unmap_tx_desc(tx_desc, ib_dev); else isert_completion_put(tx_desc, isert_cmd, ib_dev, true); } static void isert_cq_rx_comp_err(struct isert_conn *isert_conn) { struct iscsi_conn *conn = isert_conn->conn; if (isert_conn->post_recv_buf_count) return; if (conn->sess) { target_sess_cmd_list_set_waiting(conn->sess->se_sess); target_wait_for_sess_cmds(conn->sess->se_sess); } while (atomic_read(&isert_conn->post_send_buf_count)) msleep(3000); mutex_lock(&isert_conn->conn_mutex); isert_conn->state = ISER_CONN_DOWN; mutex_unlock(&isert_conn->conn_mutex); iscsit_cause_connection_reinstatement(isert_conn->conn, 0); complete(&isert_conn->conn_wait_comp_err); } static void isert_cq_tx_work(struct work_struct *work) { struct isert_cq_desc *cq_desc = container_of(work, struct isert_cq_desc, cq_tx_work); struct isert_device *device = cq_desc->device; int cq_index = cq_desc->cq_index; struct ib_cq *tx_cq = device->dev_tx_cq[cq_index]; struct isert_conn *isert_conn; struct iser_tx_desc *tx_desc; struct ib_wc wc; while (ib_poll_cq(tx_cq, 1, &wc) == 1) { tx_desc = (struct iser_tx_desc *)(unsigned long)wc.wr_id; isert_conn = wc.qp->qp_context; if (wc.status == IB_WC_SUCCESS) { isert_send_completion(tx_desc, isert_conn); } else { pr_debug("TX wc.status != IB_WC_SUCCESS >>>>>>>>>>>>>>\n"); pr_debug("TX wc.status: 0x%08x\n", wc.status); atomic_dec(&isert_conn->post_send_buf_count); isert_cq_tx_comp_err(tx_desc, isert_conn); } } ib_req_notify_cq(tx_cq, IB_CQ_NEXT_COMP); } static void isert_cq_tx_callback(struct ib_cq *cq, void *context) { struct isert_cq_desc *cq_desc = (struct isert_cq_desc *)context; INIT_WORK(&cq_desc->cq_tx_work, isert_cq_tx_work); queue_work(isert_comp_wq, &cq_desc->cq_tx_work); } static void isert_cq_rx_work(struct work_struct *work) { struct isert_cq_desc *cq_desc = container_of(work, struct isert_cq_desc, cq_rx_work); struct isert_device *device = cq_desc->device; int cq_index = cq_desc->cq_index; struct ib_cq *rx_cq = device->dev_rx_cq[cq_index]; struct isert_conn *isert_conn; struct iser_rx_desc *rx_desc; struct ib_wc wc; unsigned long xfer_len; while (ib_poll_cq(rx_cq, 1, &wc) == 1) { rx_desc = (struct iser_rx_desc *)(unsigned long)wc.wr_id; isert_conn = wc.qp->qp_context; if (wc.status == IB_WC_SUCCESS) { xfer_len = (unsigned long)wc.byte_len; isert_rx_completion(rx_desc, isert_conn, xfer_len); } else { pr_debug("RX wc.status != IB_WC_SUCCESS >>>>>>>>>>>>>>\n"); if (wc.status != IB_WC_WR_FLUSH_ERR) pr_debug("RX wc.status: 0x%08x\n", wc.status); isert_conn->post_recv_buf_count--; isert_cq_rx_comp_err(isert_conn); } } ib_req_notify_cq(rx_cq, IB_CQ_NEXT_COMP); } static void isert_cq_rx_callback(struct ib_cq *cq, void *context) { struct isert_cq_desc *cq_desc = (struct isert_cq_desc *)context; INIT_WORK(&cq_desc->cq_rx_work, isert_cq_rx_work); queue_work(isert_rx_wq, &cq_desc->cq_rx_work); } static int isert_post_response(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd) { struct ib_send_wr *wr_failed; int ret; atomic_inc(&isert_conn->post_send_buf_count); ret = ib_post_send(isert_conn->conn_qp, &isert_cmd->tx_desc.send_wr, &wr_failed); if (ret) { pr_err("ib_post_send failed with %d\n", ret); atomic_dec(&isert_conn->post_send_buf_count); return ret; } return ret; } static int isert_put_response(struct iscsi_conn *conn, struct iscsi_cmd *cmd) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; struct iscsi_scsi_rsp *hdr = (struct iscsi_scsi_rsp *) &isert_cmd->tx_desc.iscsi_header; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_rsp_pdu(cmd, conn, true, hdr); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); /* * Attach SENSE DATA payload to iSCSI Response PDU */ if (cmd->se_cmd.sense_buffer && ((cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) || (cmd->se_cmd.se_cmd_flags & SCF_EMULATED_TASK_SENSE))) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *tx_dsg = &isert_cmd->tx_desc.tx_sg[1]; u32 padding, sense_len; put_unaligned_be16(cmd->se_cmd.scsi_sense_length, cmd->sense_buffer); cmd->se_cmd.scsi_sense_length += sizeof(__be16); padding = -(cmd->se_cmd.scsi_sense_length) & 3; hton24(hdr->dlength, (u32)cmd->se_cmd.scsi_sense_length); sense_len = cmd->se_cmd.scsi_sense_length + padding; isert_cmd->sense_buf_dma = ib_dma_map_single(ib_dev, (void *)cmd->sense_buffer, sense_len, DMA_TO_DEVICE); isert_cmd->sense_buf_len = sense_len; tx_dsg->addr = isert_cmd->sense_buf_dma; tx_dsg->length = sense_len; tx_dsg->lkey = isert_conn->conn_mr->lkey; isert_cmd->tx_desc.num_sge = 2; } isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting SCSI Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_nopin(struct iscsi_cmd *cmd, struct iscsi_conn *conn, bool nopout_response) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_nopin_rsp(cmd, conn, (struct iscsi_nopin *) &isert_cmd->tx_desc.iscsi_header, nopout_response); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting NOPIN Reponse IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_logout_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_logout_rsp(cmd, conn, (struct iscsi_logout_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Logout Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_tm_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_task_mgt_rsp(cmd, conn, (struct iscsi_tm_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Task Management Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_reject(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *tx_dsg = &isert_cmd->tx_desc.tx_sg[1]; struct iscsi_reject *hdr = (struct iscsi_reject *)&isert_cmd->tx_desc.iscsi_header; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_reject(cmd, conn, hdr); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); hton24(hdr->dlength, ISCSI_HDR_LEN); isert_cmd->sense_buf_dma = ib_dma_map_single(ib_dev, (void *)cmd->buf_ptr, ISCSI_HDR_LEN, DMA_TO_DEVICE); isert_cmd->sense_buf_len = ISCSI_HDR_LEN; tx_dsg->addr = isert_cmd->sense_buf_dma; tx_dsg->length = ISCSI_HDR_LEN; tx_dsg->lkey = isert_conn->conn_mr->lkey; isert_cmd->tx_desc.num_sge = 2; isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Reject IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_build_rdma_wr(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct ib_sge *ib_sge, struct ib_send_wr *send_wr, u32 data_left, u32 offset) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct scatterlist *sg_start, *tmp_sg; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; u32 sg_off, page_off; int i = 0, sg_nents; sg_off = offset / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; sg_nents = min(cmd->se_cmd.t_data_nents - sg_off, isert_conn->max_sge); page_off = offset % PAGE_SIZE; send_wr->sg_list = ib_sge; send_wr->num_sge = sg_nents; send_wr->wr_id = (unsigned long)&isert_cmd->tx_desc; /* * Perform mapping of TCM scatterlist memory ib_sge dma_addr. */ for_each_sg(sg_start, tmp_sg, sg_nents, i) { pr_debug("ISER RDMA from SGL dma_addr: 0x%16llx dma_len: %u, page_off: %u\n", (unsigned long long)tmp_sg->dma_address, tmp_sg->length, page_off); ib_sge->addr = ib_sg_dma_address(ib_dev, tmp_sg) + page_off; ib_sge->length = min_t(u32, data_left, ib_sg_dma_len(ib_dev, tmp_sg) - page_off); ib_sge->lkey = isert_conn->conn_mr->lkey; pr_debug("RDMA ib_sge: addr: 0x%16llx length: %u\n", ib_sge->addr, ib_sge->length); page_off = 0; data_left -= ib_sge->length; ib_sge++; pr_debug("Incrementing ib_sge pointer to %p\n", ib_sge); } pr_debug("Set outgoing sg_list: %p num_sg: %u from TCM SGLs\n", send_wr->sg_list, send_wr->num_sge); return sg_nents; } static int isert_put_datain(struct iscsi_conn *conn, struct iscsi_cmd *cmd) { struct se_cmd *se_cmd = &cmd->se_cmd; struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *wr_failed, *send_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *ib_sge; struct scatterlist *sg; u32 offset = 0, data_len, data_left, rdma_write_max; int rc, ret = 0, count, sg_nents, i, ib_sge_cnt; pr_debug("RDMA_WRITE: data_length: %u\n", se_cmd->data_length); sg = &se_cmd->t_data_sg[0]; sg_nents = se_cmd->t_data_nents; count = ib_dma_map_sg(ib_dev, sg, sg_nents, DMA_TO_DEVICE); if (unlikely(!count)) { pr_err("Unable to map put_datain SGs\n"); return -EINVAL; } wr->sge = sg; wr->num_sge = sg_nents; pr_debug("Mapped IB count: %u sg: %p sg_nents: %u for RDMA_WRITE\n", count, sg, sg_nents); ib_sge = kzalloc(sizeof(struct ib_sge) * sg_nents, GFP_KERNEL); if (!ib_sge) { pr_warn("Unable to allocate datain ib_sge\n"); ret = -ENOMEM; goto unmap_sg; } isert_cmd->ib_sge = ib_sge; pr_debug("Allocated ib_sge: %p from t_data_ents: %d for RDMA_WRITE\n", ib_sge, se_cmd->t_data_nents); wr->send_wr_num = DIV_ROUND_UP(sg_nents, isert_conn->max_sge); wr->send_wr = kzalloc(sizeof(struct ib_send_wr) * wr->send_wr_num, GFP_KERNEL); if (!wr->send_wr) { pr_err("Unable to allocate wr->send_wr\n"); ret = -ENOMEM; goto unmap_sg; } pr_debug("Allocated wr->send_wr: %p wr->send_wr_num: %u\n", wr->send_wr, wr->send_wr_num); iscsit_increment_maxcmdsn(cmd, conn->sess); cmd->stat_sn = conn->stat_sn++; wr->isert_cmd = isert_cmd; rdma_write_max = isert_conn->max_sge * PAGE_SIZE; data_left = se_cmd->data_length; for (i = 0; i < wr->send_wr_num; i++) { send_wr = &isert_cmd->rdma_wr.send_wr[i]; data_len = min(data_left, rdma_write_max); send_wr->opcode = IB_WR_RDMA_WRITE; send_wr->send_flags = 0; send_wr->wr.rdma.remote_addr = isert_cmd->read_va + offset; send_wr->wr.rdma.rkey = isert_cmd->read_stag; ib_sge_cnt = isert_build_rdma_wr(isert_conn, isert_cmd, ib_sge, send_wr, data_len, offset); ib_sge += ib_sge_cnt; if (i + 1 == wr->send_wr_num) send_wr->next = &isert_cmd->tx_desc.send_wr; else send_wr->next = &wr->send_wr[i + 1]; offset += data_len; data_left -= data_len; } /* * Build isert_conn->tx_desc for iSCSI response PDU and attach */ isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_rsp_pdu(cmd, conn, false, (struct iscsi_scsi_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, &isert_cmd->tx_desc.send_wr); atomic_add(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); rc = ib_post_send(isert_conn->conn_qp, wr->send_wr, &wr_failed); if (rc) { pr_warn("ib_post_send() failed for IB_WR_RDMA_WRITE\n"); atomic_sub(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); } pr_debug("Posted RDMA_WRITE + Response for iSER Data READ\n"); return 1; unmap_sg: ib_dma_unmap_sg(ib_dev, sg, sg_nents, DMA_TO_DEVICE); return ret; } static int isert_get_dataout(struct iscsi_conn *conn, struct iscsi_cmd *cmd, bool recovery) { struct se_cmd *se_cmd = &cmd->se_cmd; struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *wr_failed, *send_wr; struct ib_sge *ib_sge; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct scatterlist *sg_start; u32 sg_off, sg_nents, page_off, va_offset = 0; u32 offset = 0, data_len, data_left, rdma_write_max; int rc, ret = 0, count, i, ib_sge_cnt; pr_debug("RDMA_READ: data_length: %u write_data_done: %u\n", se_cmd->data_length, cmd->write_data_done); sg_off = cmd->write_data_done / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; page_off = cmd->write_data_done % PAGE_SIZE; pr_debug("RDMA_READ: sg_off: %d, sg_start: %p page_off: %d\n", sg_off, sg_start, page_off); data_left = se_cmd->data_length - cmd->write_data_done; sg_nents = se_cmd->t_data_nents - sg_off; pr_debug("RDMA_READ: data_left: %d, sg_nents: %d\n", data_left, sg_nents); count = ib_dma_map_sg(ib_dev, sg_start, sg_nents, DMA_FROM_DEVICE); if (unlikely(!count)) { pr_err("Unable to map get_dataout SGs\n"); return -EINVAL; } wr->sge = sg_start; wr->num_sge = sg_nents; pr_debug("Mapped IB count: %u sg_start: %p sg_nents: %u for RDMA_READ\n", count, sg_start, sg_nents); ib_sge = kzalloc(sizeof(struct ib_sge) * sg_nents, GFP_KERNEL); if (!ib_sge) { pr_warn("Unable to allocate dataout ib_sge\n"); ret = -ENOMEM; goto unmap_sg; } isert_cmd->ib_sge = ib_sge; pr_debug("Using ib_sge: %p from sg_ents: %d for RDMA_READ\n", ib_sge, sg_nents); wr->send_wr_num = DIV_ROUND_UP(sg_nents, isert_conn->max_sge); wr->send_wr = kzalloc(sizeof(struct ib_send_wr) * wr->send_wr_num, GFP_KERNEL); if (!wr->send_wr) { pr_debug("Unable to allocate wr->send_wr\n"); ret = -ENOMEM; goto unmap_sg; } pr_debug("Allocated wr->send_wr: %p wr->send_wr_num: %u\n", wr->send_wr, wr->send_wr_num); isert_cmd->tx_desc.isert_cmd = isert_cmd; wr->iser_ib_op = ISER_IB_RDMA_READ; wr->isert_cmd = isert_cmd; rdma_write_max = isert_conn->max_sge * PAGE_SIZE; offset = cmd->write_data_done; for (i = 0; i < wr->send_wr_num; i++) { send_wr = &isert_cmd->rdma_wr.send_wr[i]; data_len = min(data_left, rdma_write_max); send_wr->opcode = IB_WR_RDMA_READ; send_wr->wr.rdma.remote_addr = isert_cmd->write_va + va_offset; send_wr->wr.rdma.rkey = isert_cmd->write_stag; ib_sge_cnt = isert_build_rdma_wr(isert_conn, isert_cmd, ib_sge, send_wr, data_len, offset); ib_sge += ib_sge_cnt; if (i + 1 == wr->send_wr_num) send_wr->send_flags = IB_SEND_SIGNALED; else send_wr->next = &wr->send_wr[i + 1]; offset += data_len; va_offset += data_len; data_left -= data_len; } atomic_add(wr->send_wr_num, &isert_conn->post_send_buf_count); rc = ib_post_send(isert_conn->conn_qp, wr->send_wr, &wr_failed); if (rc) { pr_warn("ib_post_send() failed for IB_WR_RDMA_READ\n"); atomic_sub(wr->send_wr_num, &isert_conn->post_send_buf_count); } pr_debug("Posted RDMA_READ memory for ISER Data WRITE\n"); return 0; unmap_sg: ib_dma_unmap_sg(ib_dev, sg_start, sg_nents, DMA_FROM_DEVICE); return ret; } static int isert_immediate_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state) { int ret; switch (state) { case ISTATE_SEND_NOPIN_WANT_RESPONSE: ret = isert_put_nopin(cmd, conn, false); break; default: pr_err("Unknown immediate state: 0x%02x\n", state); ret = -EINVAL; break; } return ret; } static int isert_response_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state) { int ret; switch (state) { case ISTATE_SEND_LOGOUTRSP: ret = isert_put_logout_rsp(cmd, conn); if (!ret) { pr_debug("Returning iSER Logout -EAGAIN\n"); ret = -EAGAIN; } break; case ISTATE_SEND_NOPIN: ret = isert_put_nopin(cmd, conn, true); break; case ISTATE_SEND_TASKMGTRSP: ret = isert_put_tm_rsp(cmd, conn); break; case ISTATE_SEND_REJECT: ret = isert_put_reject(cmd, conn); break; case ISTATE_SEND_STATUS: /* * Special case for sending non GOOD SCSI status from TX thread * context during pre se_cmd excecution failure. */ ret = isert_put_response(conn, cmd); break; default: pr_err("Unknown response state: 0x%02x\n", state); ret = -EINVAL; break; } return ret; } struct rdma_cm_id * isert_setup_id(struct isert_np *isert_np) { struct iscsi_np *np = isert_np->np; struct rdma_cm_id *id; struct sockaddr *sa; int ret; sa = (struct sockaddr *)&np->np_sockaddr; pr_debug("ksockaddr: %p, sa: %p\n", &np->np_sockaddr, sa); id = rdma_create_id(isert_cma_handler, isert_np, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(id)) { pr_err("rdma_create_id() failed: %ld\n", PTR_ERR(id)); ret = PTR_ERR(id); goto out; } pr_debug("id %p context %p\n", id, id->context); ret = rdma_bind_addr(id, sa); if (ret) { pr_err("rdma_bind_addr() failed: %d\n", ret); goto out_id; } ret = rdma_listen(id, ISERT_RDMA_LISTEN_BACKLOG); if (ret) { pr_err("rdma_listen() failed: %d\n", ret); goto out_id; } return id; out_id: rdma_destroy_id(id); out: return ERR_PTR(ret); } static int isert_setup_np(struct iscsi_np *np, struct __kernel_sockaddr_storage *ksockaddr) { struct isert_np *isert_np; struct rdma_cm_id *isert_lid; int ret; isert_np = kzalloc(sizeof(struct isert_np), GFP_KERNEL); if (!isert_np) { pr_err("Unable to allocate struct isert_np\n"); return -ENOMEM; } init_waitqueue_head(&isert_np->np_accept_wq); mutex_init(&isert_np->np_accept_mutex); INIT_LIST_HEAD(&isert_np->np_accept_list); init_completion(&isert_np->np_login_comp); isert_np->np = np; /* * Setup the np->np_sockaddr from the passed sockaddr setup * in iscsi_target_configfs.c code.. */ memcpy(&np->np_sockaddr, ksockaddr, sizeof(struct __kernel_sockaddr_storage)); isert_lid = isert_setup_id(isert_np); if (IS_ERR(isert_lid)) { ret = PTR_ERR(isert_lid); goto out; } isert_np->np_cm_id = isert_lid; np->np_context = isert_np; return 0; out: kfree(isert_np); return ret; } static int isert_check_accept_queue(struct isert_np *isert_np) { int empty; mutex_lock(&isert_np->np_accept_mutex); empty = list_empty(&isert_np->np_accept_list); mutex_unlock(&isert_np->np_accept_mutex); return empty; } static int isert_rdma_accept(struct isert_conn *isert_conn) { struct rdma_cm_id *cm_id = isert_conn->conn_cm_id; struct rdma_conn_param cp; int ret; memset(&cp, 0, sizeof(struct rdma_conn_param)); cp.responder_resources = isert_conn->responder_resources; cp.initiator_depth = isert_conn->initiator_depth; cp.retry_count = 7; cp.rnr_retry_count = 7; pr_debug("Before rdma_accept >>>>>>>>>>>>>>>>>>>>.\n"); ret = rdma_accept(cm_id, &cp); if (ret) { pr_err("rdma_accept() failed with: %d\n", ret); return ret; } pr_debug("After rdma_accept >>>>>>>>>>>>>>>>>>>>>.\n"); return 0; } static int isert_get_login_rx(struct iscsi_conn *conn, struct iscsi_login *login) { struct isert_conn *isert_conn = (struct isert_conn *)conn->context; int ret; pr_debug("isert_get_login_rx before conn_login_comp conn: %p\n", conn); ret = wait_for_completion_interruptible(&isert_conn->conn_login_comp); if (ret) return ret; pr_debug("isert_get_login_rx processing login->req: %p\n", login->req); return 0; } static void isert_set_conn_info(struct iscsi_np *np, struct iscsi_conn *conn, struct isert_conn *isert_conn) { struct rdma_cm_id *cm_id = isert_conn->conn_cm_id; struct rdma_route *cm_route = &cm_id->route; struct sockaddr_in *sock_in; struct sockaddr_in6 *sock_in6; conn->login_family = np->np_sockaddr.ss_family; if (np->np_sockaddr.ss_family == AF_INET6) { sock_in6 = (struct sockaddr_in6 *)&cm_route->addr.dst_addr; snprintf(conn->login_ip, sizeof(conn->login_ip), "%pI6c", &sock_in6->sin6_addr.in6_u); conn->login_port = ntohs(sock_in6->sin6_port); sock_in6 = (struct sockaddr_in6 *)&cm_route->addr.src_addr; snprintf(conn->local_ip, sizeof(conn->local_ip), "%pI6c", &sock_in6->sin6_addr.in6_u); conn->local_port = ntohs(sock_in6->sin6_port); } else { sock_in = (struct sockaddr_in *)&cm_route->addr.dst_addr; sprintf(conn->login_ip, "%pI4", &sock_in->sin_addr.s_addr); conn->login_port = ntohs(sock_in->sin_port); sock_in = (struct sockaddr_in *)&cm_route->addr.src_addr; sprintf(conn->local_ip, "%pI4", &sock_in->sin_addr.s_addr); conn->local_port = ntohs(sock_in->sin_port); } } static int isert_accept_np(struct iscsi_np *np, struct iscsi_conn *conn) { struct isert_np *isert_np = (struct isert_np *)np->np_context; struct isert_conn *isert_conn; int max_accept = 0, ret; accept_wait: ret = wait_event_interruptible(isert_np->np_accept_wq, !isert_check_accept_queue(isert_np) || np->np_thread_state == ISCSI_NP_THREAD_RESET); if (max_accept > 5) return -ENODEV; spin_lock_bh(&np->np_thread_lock); if (np->np_thread_state >= ISCSI_NP_THREAD_RESET) { spin_unlock_bh(&np->np_thread_lock); pr_debug("np_thread_state %d for isert_accept_np\n", np->np_thread_state); /** * No point in stalling here when np_thread * is in state RESET/SHUTDOWN/EXIT - bail **/ return -ENODEV; } spin_unlock_bh(&np->np_thread_lock); mutex_lock(&isert_np->np_accept_mutex); if (list_empty(&isert_np->np_accept_list)) { mutex_unlock(&isert_np->np_accept_mutex); max_accept++; goto accept_wait; } isert_conn = list_first_entry(&isert_np->np_accept_list, struct isert_conn, conn_accept_node); list_del_init(&isert_conn->conn_accept_node); mutex_unlock(&isert_np->np_accept_mutex); conn->context = isert_conn; isert_conn->conn = conn; max_accept = 0; ret = isert_rdma_post_recvl(isert_conn); if (ret) return ret; ret = isert_rdma_accept(isert_conn); if (ret) return ret; isert_set_conn_info(np, conn, isert_conn); pr_debug("Processing isert_accept_np: isert_conn: %p\n", isert_conn); return 0; } static void isert_free_np(struct iscsi_np *np) { struct isert_np *isert_np = (struct isert_np *)np->np_context; if (isert_np->np_cm_id) rdma_destroy_id(isert_np->np_cm_id); np->np_context = NULL; kfree(isert_np); } static void isert_wait_conn(struct iscsi_conn *conn) { struct isert_conn *isert_conn = conn->context; pr_debug("isert_wait_conn: Starting \n"); mutex_lock(&isert_conn->conn_mutex); if (isert_conn->conn_cm_id) { pr_debug("Calling rdma_disconnect from isert_wait_conn\n"); rdma_disconnect(isert_conn->conn_cm_id); } /* * Only wait for conn_wait_comp_err if the isert_conn made it * into full feature phase.. */ if (isert_conn->state == ISER_CONN_INIT) { mutex_unlock(&isert_conn->conn_mutex); return; } if (isert_conn->state == ISER_CONN_UP) isert_conn->state = ISER_CONN_TERMINATING; mutex_unlock(&isert_conn->conn_mutex); wait_for_completion(&isert_conn->conn_wait_comp_err); wait_for_completion(&isert_conn->conn_wait); isert_put_conn(isert_conn); } static void isert_free_conn(struct iscsi_conn *conn) { struct isert_conn *isert_conn = conn->context; isert_put_conn(isert_conn); } static struct iscsit_transport iser_target_transport = { .name = "IB/iSER", .transport_type = ISCSI_INFINIBAND, .owner = THIS_MODULE, .iscsit_setup_np = isert_setup_np, .iscsit_accept_np = isert_accept_np, .iscsit_free_np = isert_free_np, .iscsit_wait_conn = isert_wait_conn, .iscsit_free_conn = isert_free_conn, .iscsit_alloc_cmd = isert_alloc_cmd, .iscsit_get_login_rx = isert_get_login_rx, .iscsit_put_login_tx = isert_put_login_tx, .iscsit_immediate_queue = isert_immediate_queue, .iscsit_response_queue = isert_response_queue, .iscsit_get_dataout = isert_get_dataout, .iscsit_queue_data_in = isert_put_datain, .iscsit_queue_status = isert_put_response, }; static int __init isert_init(void) { int ret; isert_rx_wq = alloc_workqueue("isert_rx_wq", 0, 0); if (!isert_rx_wq) { pr_err("Unable to allocate isert_rx_wq\n"); return -ENOMEM; } isert_comp_wq = alloc_workqueue("isert_comp_wq", 0, 0); if (!isert_comp_wq) { pr_err("Unable to allocate isert_comp_wq\n"); ret = -ENOMEM; goto destroy_rx_wq; } isert_cmd_cache = kmem_cache_create("isert_cmd_cache", sizeof(struct isert_cmd), __alignof__(struct isert_cmd), 0, NULL); if (!isert_cmd_cache) { pr_err("Unable to create isert_cmd_cache\n"); ret = -ENOMEM; goto destroy_tx_cq; } iscsit_register_transport(&iser_target_transport); pr_debug("iSER_TARGET[0] - Loaded iser_target_transport\n"); return 0; destroy_tx_cq: destroy_workqueue(isert_comp_wq); destroy_rx_wq: destroy_workqueue(isert_rx_wq); return ret; } static void __exit isert_exit(void) { flush_scheduled_work(); kmem_cache_destroy(isert_cmd_cache); destroy_workqueue(isert_comp_wq); destroy_workqueue(isert_rx_wq); iscsit_unregister_transport(&iser_target_transport); pr_debug("iSER_TARGET[0] - Released iser_target_transport\n"); } MODULE_DESCRIPTION("iSER-Target for mainline target infrastructure"); MODULE_VERSION("0.1"); MODULE_AUTHOR("nab@Linux-iSCSI.org"); MODULE_LICENSE("GPL"); module_init(isert_init); module_exit(isert_exit);
Java
// Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org) // // SPDX-License-Identifier: GPL-2.0-or-later #pragma once #include <string> #include <utility> /// Base class for controls with a tooltip class ctrlBaseTooltip { public: ctrlBaseTooltip(std::string tooltip = "") : tooltip_(std::move(tooltip)) {} virtual ~ctrlBaseTooltip(); void SetTooltip(const std::string& tooltip) { tooltip_ = tooltip; } const std::string& GetTooltip() const { return tooltip_; } /// Swap the tooltips of those controls void SwapTooltip(ctrlBaseTooltip& other); void ShowTooltip() const; /// Show a temporary tooltip void ShowTooltip(const std::string& tooltip) const; void HideTooltip() const; protected: std::string tooltip_; };
Java
// // Microsoft.VisualBasic.* Test Cases // // Authors: // Gert Driesen (drieseng@users.sourceforge.net) // // (c) 2006 Novell // using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Globalization; using System.IO; using System.Text; using NUnit.Framework; namespace MonoTests.Microsoft.VisualBasic { /// <summary> /// Test ICodeGenerator's GenerateCodeFromNamespace, along with a /// minimal set CodeDom components. /// </summary> [TestFixture] public class CodeGeneratorFromNamespaceTest : CodeGeneratorTestBase { CodeNamespace codeNamespace = null; [SetUp] public void Init () { InitBase (); codeNamespace = new CodeNamespace (); } protected override string Generate (CodeGeneratorOptions options) { StringWriter writer = new StringWriter (); writer.NewLine = NewLine; generator.GenerateCodeFromNamespace (codeNamespace, writer, options); writer.Close (); return writer.ToString (); } [Test] [ExpectedException (typeof (NullReferenceException))] public void NullNamespaceTest () { codeNamespace = null; Generate (); } [Test] public void NullNamespaceNameTest () { codeNamespace.Name = null; Assert.AreEqual ("\n", Generate ()); } [Test] public void DefaultNamespaceTest () { Assert.AreEqual ("\n", Generate ()); } [Test] public void SimpleNamespaceTest () { codeNamespace.Name = "A"; Assert.AreEqual ("\nNamespace A\nEnd Namespace\n", Generate ()); } [Test] public void InvalidNamespaceTest () { codeNamespace.Name = "A,B"; Assert.AreEqual ("\nNamespace A,B\nEnd Namespace\n", Generate ()); } [Test] public void CommentOnlyNamespaceTest () { CodeCommentStatement comment = new CodeCommentStatement ("a"); codeNamespace.Comments.Add (comment); Assert.AreEqual ("\n'a\n", Generate ()); } [Test] public void ImportsTest () { codeNamespace.Imports.Add (new CodeNamespaceImport ("System")); codeNamespace.Imports.Add (new CodeNamespaceImport ("System.Collections")); Assert.AreEqual (string.Format(CultureInfo.InvariantCulture, "Imports System{0}" + "Imports System.Collections{0}" + "{0}", NewLine), Generate (), "#1"); codeNamespace.Name = "A"; Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "Imports System{0}" + "Imports System.Collections{0}" + "{0}" + "Namespace A{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); codeNamespace.Name = null; codeNamespace.Comments.Add (new CodeCommentStatement ("a")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "Imports System{0}" + "Imports System.Collections{0}" + "{0}" + "'a{0}", NewLine), Generate (), "#3"); codeNamespace.Name = "A"; Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "Imports System{0}" + "Imports System.Collections{0}" + "{0}" + "'a{0}" + "Namespace A{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); } [Test] public void TypeTest () { codeNamespace.Types.Add (new CodeTypeDeclaration ("Person")); Assert.AreEqual (string.Format(CultureInfo.InvariantCulture, "{0}" + "{0}" + "Public Class Person{0}" + "End Class{0}", NewLine), Generate (), "#A1"); CodeGeneratorOptions options = new CodeGeneratorOptions (); options.BlankLinesBetweenMembers = false; Assert.AreEqual (string.Format(CultureInfo.InvariantCulture, "{0}" + "Public Class Person{0}" + "End Class{0}", NewLine), Generate (options), "#A2"); codeNamespace.Name = "A"; Assert.AreEqual (string.Format(CultureInfo.InvariantCulture, "{0}" + "Namespace A{0}" + " {0}" + " Public Class Person{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#B1"); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace A{0}" + " Public Class Person{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (options), "#B2"); } [Test] public void Type_TypeParameters () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); type.TypeParameters.Add (new CodeTypeParameter ("T")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#1"); type.TypeParameters.Add (new CodeTypeParameter ("As")); type.TypeParameters.Add (new CodeTypeParameter ("New")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T, As, New){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); CodeTypeParameter typeParamR = new CodeTypeParameter ("R"); typeParamR.Constraints.Add (new CodeTypeReference (typeof (IComparable))); type.TypeParameters.Add (typeParamR); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T, As, New, R As System.IComparable){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#3"); type.TypeParameters.Add (new CodeTypeParameter ("S")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T, As, New, R As System.IComparable, S){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); } [Test] public void Type_TypeParameters_Constraints () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeTypeParameter typeParamT = new CodeTypeParameter ("T"); typeParamT.Constraints.Add (new CodeTypeReference (typeof (IComparable))); type.TypeParameters.Add (typeParamT); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As System.IComparable){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#1"); typeParamT.Constraints.Add (new CodeTypeReference (typeof (ICloneable))); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable}}){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); typeParamT.HasConstructorConstraint = true; Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#3"); CodeTypeParameter typeParamS = new CodeTypeParameter ("S"); typeParamS.Constraints.Add (new CodeTypeReference (typeof (IDisposable))); type.TypeParameters.Add (typeParamS); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); CodeTypeParameter typeParamR = new CodeTypeParameter ("R"); typeParamR.HasConstructorConstraint = true; type.TypeParameters.Add (typeParamR); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#5"); } [Test] public void Type_TypeParameters_ConstructorConstraint () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeTypeParameter typeParam = new CodeTypeParameter ("T"); typeParam.HasConstructorConstraint = true; type.TypeParameters.Add (typeParam); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As New){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate ()); } [Test] public void Method_TypeParameters () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeMemberMethod method = new CodeMemberMethod (); method.Name = "SomeMethod"; type.Members.Add (method); method.TypeParameters.Add (new CodeTypeParameter ("T")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#1"); method.TypeParameters.Add (new CodeTypeParameter ("As")); method.TypeParameters.Add (new CodeTypeParameter ("New")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T, As, New)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); CodeTypeParameter typeParamR = new CodeTypeParameter ("R"); typeParamR.Constraints.Add (new CodeTypeReference (typeof (IComparable))); method.TypeParameters.Add (typeParamR); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T, As, New, R As System.IComparable)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#3"); method.TypeParameters.Add (new CodeTypeParameter ("S")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T, As, New, R As System.IComparable, S)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); } [Test] public void Method_TypeParameters_Constraints () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeMemberMethod method = new CodeMemberMethod (); method.Name = "SomeMethod"; type.Members.Add (method); CodeTypeParameter typeParamT = new CodeTypeParameter ("T"); typeParamT.Constraints.Add (new CodeTypeReference (typeof (IComparable))); method.TypeParameters.Add (typeParamT); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As System.IComparable)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#1"); typeParamT.Constraints.Add (new CodeTypeReference (typeof (ICloneable))); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable}})(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); typeParamT.HasConstructorConstraint = true; Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}})(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#3"); CodeTypeParameter typeParamS = new CodeTypeParameter ("S"); typeParamS.Constraints.Add (new CodeTypeReference (typeof (IDisposable))); method.TypeParameters.Add (typeParamS); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); CodeTypeParameter typeParamR = new CodeTypeParameter ("R"); typeParamR.HasConstructorConstraint = true; method.TypeParameters.Add (typeParamR); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#5"); } [Test] public void Method_TypeParameters_ConstructorConstraint () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeMemberMethod method = new CodeMemberMethod (); method.Name = "SomeMethod"; type.Members.Add (method); CodeTypeParameter typeParam = new CodeTypeParameter ("T"); typeParam.HasConstructorConstraint = true; method.TypeParameters.Add (typeParam); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As New)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate ()); } } }
Java
<div class="patient-details container ng-cloak" ng-cloak> <div ng-if="vm.patient == null"> Es wurde kein Patient ausgewählt! </div> <div ng-if="vm.patient != null"> <h1 class="header">Patient</h1> <div class="clearfix"> <div class="patient-personal patient-abstract"> <h2 class="sub-header">Persönliche Daten</h2> <span class="table list"> <span class="table-row"> <span class="table-cell">Vorname</span> <span class="table-cell">{{ vm.patient.firstname }}</span> </span> <span class="table-row"> <span class="table-cell">Nachname</span> <span class="table-cell">{{ vm.patient.lastname }}</span> </span> <span class="table-row"> <span class="table-cell">Straße</span> <span class="table-cell">{{ vm.patient.street }}</span> </span> <span class="table-row"> <span class="table-cell">PLZ / Ort</span> <span class="table-cell">{{ vm.patient.postal }} {{ vm.patient.city }}</span> </span> </span> <span class="table list"> <span class="table-row"> <span class="table-cell">Telefon</span> <span class="table-cell">{{ vm.patient.phone }}</span> </span> <span class="table-row"> <span class="table-cell">Geschäftlich</span> <span class="table-cell">{{ vm.patient.office }}</span> </span> <span class="table-row"> <span class="table-cell">Mobil</span> <span class="table-cell">{{ vm.patient.mobile }}</span> </span> </span> <a ng-click="vm.showPersonalDetails = !vm.showPersonalDetails" ng-hide="vm.showPersonalDetails" style="display: block; margin-bottom: 0.3em;">Details anzeigen</a> <a ng-click="vm.showPersonalDetails = !vm.showPersonalDetails" ng-show="vm.showPersonalDetails" style="display: block; margin-bottom: 0.3em;">Details verbergen</a> <span class="table list" ng-show="vm.showPersonalDetails"> <span class="table-row"> <span class="table-cell">Geburtstag</span> <span class="table-cell">{{ vm.patient.birthday }}</span> </span> <span class="table-row"> <span class="table-cell">Familienstatus</span> <span class="table-cell">{{ vm.patient.status }}</span> </span> <span class="table-row"> <span class="table-cell">Beruf</span> <span class="table-cell">{{ vm.patient.profession }}</span> </span> <span class="table-row"> <span class="table-cell">Versicherung</span> <span class="table-cell">{{ vm.patient.insurance.type }} {{ vm.patient.insurance.name }}</span> </span> <span class="table-row"> <span class="table-cell">Bemerkungen</span> <span class="table-cell">{{ vm.patient.notes }}</span> </span> </span> </div> <div class="patient-attributes patient-abstract"> <div class="patient-attention"> <h2 class="sub-header">Vermerk</h2> <span>{{ vm.patient.attention }}</span> </div> <span class="table list"> <span class="table-row"> <span class="table-cell">Referenz durch</span> <span class="table-cell">{{ vm.patient.reference }}</span> </span> <span class="table-row"> <span class="table-cell">Behandelnder Arzt</span> <span class="table-cell">{{ vm.patient.doctor }}</span> </span> <span class="table-row"> <span class="table-cell">Papierakte?</span> <span class="table-cell"> <span ng-if="vm.patient.paperfile">Ja</span> <span ng-if="!vm.patient.paperfile">Nein</span> </span> </span> </span> </div> </div> <div class="patient-abstract"> <h2 class="sub-header">Aktuelles</h2> <span class="table list"> <span class="table-row"> <span class="table-cell">Befunde</span> <span class="table-cell">{{ vm.patient.findings }}</span> </span> <span class="table-row"> <span class="table-cell">Therapie</span> <span class="table-cell">{{ vm.patient.therapy }}</span> </span> </span> </div> <div class="patient-abstract"> <h2 class="sub-header">Krankengeschichte</h2> <span class="table list"> <span class="table-row"> <span class="table-cell">Operationen </span> <span class="table-cell">{{ vm.patient.history.operations }}</span> </span> <span class="table-row"> <span class="table-cell">Unfälle</span> <span class="table-cell">{{ vm.patient.history.accidents }}</span> </span> <span class="table-row"> <span class="table-cell">Vorerkrankungen</span> <span class="table-cell">{{ vm.patient.history.disease }}</span> </span> </span> </div> <div class="patient-abstract"> <div class="patient-current"> <h2 class="sub-header">Risikofaktoren</h2> <span class="table list"> <span class="table-row"> <span class="table-cell">Allergien</span> <span class="table-cell">{{ vm.patient.risks.allergy }}</span> </span> <span class="table-row"> <span class="table-cell">Medikation</span> <span class="table-cell">{{ vm.patient.risks.medicine }}</span> </span> </span> </div> </div> </div> </div> <div class="footer"> <a class="button" ng-click="vm.goBack()">Zurück</a> <a class="button" ng-click="vm.editPatient()">Editieren</a> <a class="button" ng-click="vm.showTreatment()">Behandlungsakte</a> </div>
Java
/*CXXR $Id$ *CXXR *CXXR This file is part of CXXR, a project to refactor the R interpreter *CXXR into C++. It may consist in whole or in part of program code and *CXXR documentation taken from the R project itself, incorporated into *CXXR CXXR (and possibly MODIFIED) under the terms of the GNU General Public *CXXR Licence. *CXXR *CXXR CXXR is Copyright (C) 2008-14 Andrew R. Runnalls, subject to such other *CXXR copyrights and copyright restrictions as may be stated below. *CXXR *CXXR CXXR is not part of the R project, and bugs and other issues should *CXXR not be reported via r-bugs or other R project channels; instead refer *CXXR to the CXXR website. *CXXR */ /* * R : A Computer Language for Statistical Data Analysis * Copyright (C) 2001--2012 The R Core 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, a copy is available at * http://www.r-project.org/Licenses/ */ #include <R_ext/Complex.h> #include <R_ext/RS.h> /* use declarations in R_ext/Lapack.h (instead of having them there *and* here) but ``delete'' the 'extern' there : */ #define La_extern #define BLAS_extern #include <R_ext/Lapack.h> #undef La_extern #undef BLAS_extern
Java
/* $Id: tstCAPIGlue.c 109358 2016-07-31 17:11:31Z bird $ */ /** @file tstCAPIGlue.c * Demonstrator program to illustrate use of C bindings of Main API. * * It has sample code showing how to retrieve all available error information, * and how to handle active (event delivery through callbacks) or passive * (event delivery through a polling mechanism) event listeners. */ /* * Copyright (C) 2009-2016 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /** @todo * Our appologies for the 256+ missing return code checks in this sample file. * * We strongly recomment users of the VBoxCAPI to check all return codes! */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include "VBoxCAPIGlue.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef WIN32 # include <signal.h> # include <unistd.h> # include <sys/poll.h> #endif #ifdef ___iprt_cdefs_h # error "not supposed to involve any IPRT or VBox headers here." #endif /** * Select between active event listener (defined) and passive event listener * (undefined). The active event listener case needs much more code, and * additionally requires a lot more platform dependent code. */ #undef USE_ACTIVE_EVENT_LISTENER /********************************************************************************************************************************* * Global Variables * *********************************************************************************************************************************/ /** Set by Ctrl+C handler. */ static volatile int g_fStop = 0; #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 /** The COM type information for IEventListener, for implementing IDispatch. */ static ITypeInfo *g_pTInfoIEventListener = NULL; # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ static const char *GetStateName(MachineState_T machineState) { switch (machineState) { case MachineState_Null: return "<null>"; case MachineState_PoweredOff: return "PoweredOff"; case MachineState_Saved: return "Saved"; case MachineState_Teleported: return "Teleported"; case MachineState_Aborted: return "Aborted"; case MachineState_Running: return "Running"; case MachineState_Paused: return "Paused"; case MachineState_Stuck: return "Stuck"; case MachineState_Teleporting: return "Teleporting"; case MachineState_LiveSnapshotting: return "LiveSnapshotting"; case MachineState_Starting: return "Starting"; case MachineState_Stopping: return "Stopping"; case MachineState_Saving: return "Saving"; case MachineState_Restoring: return "Restoring"; case MachineState_TeleportingPausedVM: return "TeleportingPausedVM"; case MachineState_TeleportingIn: return "TeleportingIn"; case MachineState_FaultTolerantSyncing: return "FaultTolerantSyncing"; case MachineState_DeletingSnapshotOnline: return "DeletingSnapshotOnline"; case MachineState_DeletingSnapshotPaused: return "DeletingSnapshotPaused"; case MachineState_RestoringSnapshot: return "RestoringSnapshot"; case MachineState_DeletingSnapshot: return "DeletingSnapshot"; case MachineState_SettingUp: return "SettingUp"; default: return "no idea"; } } /** * Ctrl+C handler, terminate event listener. * * Remember that most function calls are not allowed in this context (including * printf!), so make sure that this does as little as possible. * * @param iInfo Platform dependent detail info (ignored). */ static BOOL VBOX_WINAPI ctrlCHandler(DWORD iInfo) { (void)iInfo; g_fStop = 1; return TRUE; } /** * Sample event processing function, dumping some event information. * Shared between active and passive event demo, to highlight that this part * is identical between the two. */ static HRESULT EventListenerDemoProcessEvent(IEvent *event) { VBoxEventType_T evType; HRESULT rc; if (!event) { printf("event null\n"); return S_OK; } evType = VBoxEventType_Invalid; rc = IEvent_get_Type(event, &evType); if (FAILED(rc)) { printf("cannot get event type, rc=%#x\n", rc); return S_OK; } switch (evType) { case VBoxEventType_OnMousePointerShapeChanged: printf("OnMousePointerShapeChanged\n"); break; case VBoxEventType_OnMouseCapabilityChanged: printf("OnMouseCapabilityChanged\n"); break; case VBoxEventType_OnKeyboardLedsChanged: printf("OnMouseCapabilityChanged\n"); break; case VBoxEventType_OnStateChanged: { IStateChangedEvent *ev = NULL; enum MachineState state; rc = IEvent_QueryInterface(event, &IID_IStateChangedEvent, (void **)&ev); if (FAILED(rc)) { printf("cannot get StateChangedEvent interface, rc=%#x\n", rc); return S_OK; } if (!ev) { printf("StateChangedEvent reference null\n"); return S_OK; } rc = IStateChangedEvent_get_State(ev, &state); if (FAILED(rc)) printf("warning: cannot get state, rc=%#x\n", rc); IStateChangedEvent_Release(ev); printf("OnStateChanged: %s\n", GetStateName(state)); fflush(stdout); if ( state == MachineState_PoweredOff || state == MachineState_Saved || state == MachineState_Teleported || state == MachineState_Aborted ) g_fStop = 1; break; } case VBoxEventType_OnAdditionsStateChanged: printf("OnAdditionsStateChanged\n"); break; case VBoxEventType_OnNetworkAdapterChanged: printf("OnNetworkAdapterChanged\n"); break; case VBoxEventType_OnSerialPortChanged: printf("OnSerialPortChanged\n"); break; case VBoxEventType_OnParallelPortChanged: printf("OnParallelPortChanged\n"); break; case VBoxEventType_OnStorageControllerChanged: printf("OnStorageControllerChanged\n"); break; case VBoxEventType_OnMediumChanged: printf("OnMediumChanged\n"); break; case VBoxEventType_OnVRDEServerChanged: printf("OnVRDEServerChanged\n"); break; case VBoxEventType_OnUSBControllerChanged: printf("OnUSBControllerChanged\n"); break; case VBoxEventType_OnUSBDeviceStateChanged: printf("OnUSBDeviceStateChanged\n"); break; case VBoxEventType_OnSharedFolderChanged: printf("OnSharedFolderChanged\n"); break; case VBoxEventType_OnRuntimeError: printf("OnRuntimeError\n"); break; case VBoxEventType_OnCanShowWindow: printf("OnCanShowWindow\n"); break; case VBoxEventType_OnShowWindow: printf("OnShowWindow\n"); break; default: printf("unknown event: %d\n", evType); } return S_OK; } #ifdef USE_ACTIVE_EVENT_LISTENER struct IEventListenerDemo; typedef struct IEventListenerDemo IEventListenerDemo; typedef struct IEventListenerDemoVtbl { HRESULT (*QueryInterface)(IEventListenerDemo *pThis, REFIID riid, void **ppvObject); ULONG (*AddRef)(IEventListenerDemo *pThis); ULONG (*Release)(IEventListenerDemo *pThis); #ifdef WIN32 HRESULT (*GetTypeInfoCount)(IEventListenerDemo *pThis, UINT *pctinfo); HRESULT (*GetTypeInfo)(IEventListenerDemo *pThis, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo); HRESULT (*GetIDsOfNames)(IEventListenerDemo *pThis, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); HRESULT (*Invoke)(IEventListenerDemo *pThis, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); #endif HRESULT (*HandleEvent)(IEventListenerDemo *pThis, IEvent *aEvent); } IEventListenerDemoVtbl; typedef struct IEventListenerDemo { struct IEventListenerDemoVtbl *lpVtbl; int cRef; #ifdef WIN32 /* Active event delivery needs a free threaded marshaler, as the default * proxy marshaling cannot deal correctly with this case. */ IUnknown *pUnkMarshaler; #endif } IEventListenerDemo; /* Defines for easily calling IEventListenerDemo functions. */ /* IUnknown functions. */ #define IEventListenerDemo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) ) #define IEventListenerDemo_AddRef(This) \ ( (This)->lpVtbl->AddRef(This) ) #define IEventListenerDemo_Release(This) \ ( (This)->lpVtbl->Release(This) ) #ifdef WIN32 /* IDispatch functions. */ #define IEventListenerDemo_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) ) #define IEventListenerDemo_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define IEventListenerDemo_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define IEventListenerDemo_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif /* IEventListener functions. */ #define IEventListenerDemo_HandleEvent(This,aEvent) \ ( (This)->lpVtbl->HandleEvent(This,aEvent) ) /** * Event handler function, for active event processing. */ static HRESULT IEventListenerDemoImpl_HandleEvent(IEventListenerDemo *pThis, IEvent *event) { return EventListenerDemoProcessEvent(event); } static HRESULT IEventListenerDemoImpl_QueryInterface(IEventListenerDemo *pThis, const IID *iid, void **resultp) { /* match iid */ if ( !memcmp(iid, &IID_IEventListener, sizeof(IID)) || !memcmp(iid, &IID_IDispatch, sizeof(IID)) || !memcmp(iid, &IID_IUnknown, sizeof(IID))) { IEventListenerDemo_AddRef(pThis); *resultp = pThis; return S_OK; } #ifdef WIN32 if (!memcmp(iid, &IID_IMarshal, sizeof(IID))) return IUnknown_QueryInterface(pThis->pUnkMarshaler, iid, resultp); #endif return E_NOINTERFACE; } static HRESULT IEventListenerDemoImpl_AddRef(IEventListenerDemo *pThis) { return ++(pThis->cRef); } static HRESULT IEventListenerDemoImpl_Release(IEventListenerDemo *pThis) { HRESULT c; c = --(pThis->cRef); if (!c) free(pThis); return c; } #ifdef WIN32 static HRESULT IEventListenerDemoImpl_GetTypeInfoCount(IEventListenerDemo *pThis, UINT *pctinfo) { if (!pctinfo) return E_POINTER; *pctinfo = 1; return S_OK; } static HRESULT IEventListenerDemoImpl_GetTypeInfo(IEventListenerDemo *pThis, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo) { if (!ppTInfo) return E_POINTER; ITypeInfo_AddRef(g_pTInfoIEventListener); *ppTInfo = g_pTInfoIEventListener; return S_OK; } static HRESULT IEventListenerDemoImpl_GetIDsOfNames(IEventListenerDemo *pThis, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { return ITypeInfo_GetIDsOfNames(g_pTInfoIEventListener, rgszNames, cNames, rgDispId); } static HRESULT IEventListenerDemoImpl_Invoke(IEventListenerDemo *pThis, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { return ITypeInfo_Invoke(g_pTInfoIEventListener, (IDispatch *)pThis, dispIdMember, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } static HRESULT LoadTypeInfo(REFIID riid, ITypeInfo **pTInfo) { HRESULT rc; ITypeLib *pTypeLib; rc = LoadRegTypeLib(&LIBID_VirtualBox, 1 /* major */, 0 /* minor */, 0 /* lcid */, &pTypeLib); if (FAILED(rc)) return rc; rc = ITypeLib_GetTypeInfoOfGuid(pTypeLib, riid, pTInfo); /* No longer need access to the type lib, release it. */ ITypeLib_Release(pTypeLib); return rc; } #endif #ifdef __GNUC__ typedef struct IEventListenerDemoVtblInt { ptrdiff_t offset_to_top; void *typeinfo; IEventListenerDemoVtbl lpVtbl; } IEventListenerDemoVtblInt; static IEventListenerDemoVtblInt g_IEventListenerDemoVtblInt = { 0, /* offset_to_top */ NULL, /* typeinfo, not vital */ { IEventListenerDemoImpl_QueryInterface, IEventListenerDemoImpl_AddRef, IEventListenerDemoImpl_Release, #ifdef WIN32 IEventListenerDemoImpl_GetTypeInfoCount, IEventListenerDemoImpl_GetTypeInfo, IEventListenerDemoImpl_GetIDsOfNames, IEventListenerDemoImpl_Invoke, #endif IEventListenerDemoImpl_HandleEvent } }; #elif defined(_MSC_VER) typedef struct IEventListenerDemoVtblInt { IEventListenerDemoVtbl lpVtbl; } IEventListenerDemoVtblInt; static IEventListenerDemoVtblInt g_IEventListenerDemoVtblInt = { { IEventListenerDemoImpl_QueryInterface, IEventListenerDemoImpl_AddRef, IEventListenerDemoImpl_Release, #ifdef WIN32 IEventListenerDemoImpl_GetTypeInfoCount, IEventListenerDemoImpl_GetTypeInfo, IEventListenerDemoImpl_GetIDsOfNames, IEventListenerDemoImpl_Invoke, #endif IEventListenerDemoImpl_HandleEvent } }; #else # error Port me! #endif /** * Register active event listener for the selected VM. * * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void registerActiveEventListener(IVirtualBox *virtualBox, ISession *session) { IConsole *console = NULL; HRESULT rc; rc = ISession_get_Console(session, &console); if ((SUCCEEDED(rc)) && console) { IEventSource *es = NULL; rc = IConsole_get_EventSource(console, &es); if (SUCCEEDED(rc) && es) { static const ULONG s_auInterestingEvents[] = { VBoxEventType_OnMousePointerShapeChanged, VBoxEventType_OnMouseCapabilityChanged, VBoxEventType_OnKeyboardLedsChanged, VBoxEventType_OnStateChanged, VBoxEventType_OnAdditionsStateChanged, VBoxEventType_OnNetworkAdapterChanged, VBoxEventType_OnSerialPortChanged, VBoxEventType_OnParallelPortChanged, VBoxEventType_OnStorageControllerChanged, VBoxEventType_OnMediumChanged, VBoxEventType_OnVRDEServerChanged, VBoxEventType_OnUSBControllerChanged, VBoxEventType_OnUSBDeviceStateChanged, VBoxEventType_OnSharedFolderChanged, VBoxEventType_OnRuntimeError, VBoxEventType_OnCanShowWindow, VBoxEventType_OnShowWindow }; SAFEARRAY *interestingEventsSA = NULL; IEventListenerDemo *consoleListener = NULL; /* The VirtualBox API expects enum values as VT_I4, which in the * future can be hopefully relaxed. */ interestingEventsSA = g_pVBoxFuncs->pfnSafeArrayCreateVector(VT_I4, 0, sizeof(s_auInterestingEvents) / sizeof(s_auInterestingEvents[0])); g_pVBoxFuncs->pfnSafeArrayCopyInParamHelper(interestingEventsSA, &s_auInterestingEvents, sizeof(s_auInterestingEvents)); consoleListener = calloc(1, sizeof(IEventListenerDemo)); if (consoleListener) { consoleListener->lpVtbl = &(g_IEventListenerDemoVtblInt.lpVtbl); #ifdef WIN32 CoCreateFreeThreadedMarshaler((IUnknown *)consoleListener, &consoleListener->pUnkMarshaler); #endif IEventListenerDemo_AddRef(consoleListener); rc = IEventSource_RegisterListener(es, (IEventListener *)consoleListener, ComSafeArrayAsInParam(interestingEventsSA), 1 /* active */); if (SUCCEEDED(rc)) { /* Just wait here for events, no easy way to do this better * as there's not much to do after this completes. */ printf("Entering event loop, PowerOff the machine to exit or press Ctrl-C to terminate\n"); fflush(stdout); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, TRUE); #else signal(SIGINT, (void (*)(int))ctrlCHandler); #endif while (!g_fStop) g_pVBoxFuncs->pfnProcessEventQueue(250); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, FALSE); #else signal(SIGINT, SIG_DFL); #endif } else printf("Failed to register event listener.\n"); IEventSource_UnregisterListener(es, (IEventListener *)consoleListener); #ifdef WIN32 if (consoleListener->pUnkMarshaler) IUnknown_Release(consoleListener->pUnkMarshaler); #endif IEventListenerDemo_Release(consoleListener); } else printf("Failed while allocating memory for console event listener.\n"); g_pVBoxFuncs->pfnSafeArrayDestroy(interestingEventsSA); IEventSource_Release(es); } else printf("Failed to get the event source instance.\n"); IConsole_Release(console); } } #else /* !USE_ACTIVE_EVENT_LISTENER */ /** * Register passive event listener for the selected VM. * * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void registerPassiveEventListener(ISession *session) { IConsole *console = NULL; HRESULT rc; rc = ISession_get_Console(session, &console); if (SUCCEEDED(rc) && console) { IEventSource *es = NULL; rc = IConsole_get_EventSource(console, &es); if (SUCCEEDED(rc) && es) { static const ULONG s_auInterestingEvents[] = { VBoxEventType_OnMousePointerShapeChanged, VBoxEventType_OnMouseCapabilityChanged, VBoxEventType_OnKeyboardLedsChanged, VBoxEventType_OnStateChanged, VBoxEventType_OnAdditionsStateChanged, VBoxEventType_OnNetworkAdapterChanged, VBoxEventType_OnSerialPortChanged, VBoxEventType_OnParallelPortChanged, VBoxEventType_OnStorageControllerChanged, VBoxEventType_OnMediumChanged, VBoxEventType_OnVRDEServerChanged, VBoxEventType_OnUSBControllerChanged, VBoxEventType_OnUSBDeviceStateChanged, VBoxEventType_OnSharedFolderChanged, VBoxEventType_OnRuntimeError, VBoxEventType_OnCanShowWindow, VBoxEventType_OnShowWindow }; SAFEARRAY *interestingEventsSA = NULL; IEventListener *consoleListener = NULL; /* The VirtualBox API expects enum values as VT_I4, which in the * future can be hopefully relaxed. */ interestingEventsSA = g_pVBoxFuncs->pfnSafeArrayCreateVector(VT_I4, 0, sizeof(s_auInterestingEvents) / sizeof(s_auInterestingEvents[0])); g_pVBoxFuncs->pfnSafeArrayCopyInParamHelper(interestingEventsSA, &s_auInterestingEvents, sizeof(s_auInterestingEvents)); rc = IEventSource_CreateListener(es, &consoleListener); if (SUCCEEDED(rc) && consoleListener) { rc = IEventSource_RegisterListener(es, consoleListener, ComSafeArrayAsInParam(interestingEventsSA), 0 /* passive */); if (SUCCEEDED(rc)) { /* Just wait here for events, no easy way to do this better * as there's not much to do after this completes. */ printf("Entering event loop, PowerOff the machine to exit or press Ctrl-C to terminate\n"); fflush(stdout); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, TRUE); #else signal(SIGINT, (void (*)(int))ctrlCHandler); #endif while (!g_fStop) { IEvent *ev = NULL; rc = IEventSource_GetEvent(es, consoleListener, 250, &ev); if (FAILED(rc)) { printf("Failed getting event: %#x\n", rc); g_fStop = 1; continue; } /* handle timeouts, resulting in NULL events */ if (!ev) continue; rc = EventListenerDemoProcessEvent(ev); if (FAILED(rc)) { printf("Failed processing event: %#x\n", rc); g_fStop = 1; /* finish processing the event */ } rc = IEventSource_EventProcessed(es, consoleListener, ev); if (FAILED(rc)) { printf("Failed to mark event as processed: %#x\n", rc); g_fStop = 1; /* continue with event release */ } if (ev) { IEvent_Release(ev); ev = NULL; } } #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, FALSE); #else signal(SIGINT, SIG_DFL); #endif } else printf("Failed to register event listener.\n"); IEventSource_UnregisterListener(es, (IEventListener *)consoleListener); IEventListener_Release(consoleListener); } else printf("Failed to create an event listener instance.\n"); g_pVBoxFuncs->pfnSafeArrayDestroy(interestingEventsSA); IEventSource_Release(es); } else printf("Failed to get the event source instance.\n"); IConsole_Release(console); } } #endif /* !USE_ACTIVE_EVENT_LISTENER */ /** * Print detailed error information if available. * @param pszExecutable string with the executable name * @param pszErrorMsg string containing the code location specific error message * @param rc COM/XPCOM result code */ static void PrintErrorInfo(const char *pszExecutable, const char *pszErrorMsg, HRESULT rc) { IErrorInfo *ex; HRESULT rc2; fprintf(stderr, "%s: %s (rc=%#010x)\n", pszExecutable, pszErrorMsg, (unsigned)rc); rc2 = g_pVBoxFuncs->pfnGetException(&ex); if (SUCCEEDED(rc2) && ex) { IVirtualBoxErrorInfo *ei; rc2 = IErrorInfo_QueryInterface(ex, &IID_IVirtualBoxErrorInfo, (void **)&ei); if (SUCCEEDED(rc2) && ei != NULL) { /* got extended error info, maybe multiple infos */ do { LONG resultCode = S_OK; BSTR componentUtf16 = NULL; char *component = NULL; BSTR textUtf16 = NULL; char *text = NULL; IVirtualBoxErrorInfo *ei_next = NULL; fprintf(stderr, "Extended error info (IVirtualBoxErrorInfo):\n"); IVirtualBoxErrorInfo_get_ResultCode(ei, &resultCode); fprintf(stderr, " resultCode=%#010x\n", (unsigned)resultCode); IVirtualBoxErrorInfo_get_Component(ei, &componentUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(componentUtf16, &component); g_pVBoxFuncs->pfnComUnallocString(componentUtf16); fprintf(stderr, " component=%s\n", component); g_pVBoxFuncs->pfnUtf8Free(component); IVirtualBoxErrorInfo_get_Text(ei, &textUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(textUtf16, &text); g_pVBoxFuncs->pfnComUnallocString(textUtf16); fprintf(stderr, " text=%s\n", text); g_pVBoxFuncs->pfnUtf8Free(text); rc2 = IVirtualBoxErrorInfo_get_Next(ei, &ei_next); if (FAILED(rc2)) ei_next = NULL; IVirtualBoxErrorInfo_Release(ei); ei = ei_next; } while (ei); } IErrorInfo_Release(ex); g_pVBoxFuncs->pfnClearException(); } } /** * Start a VM. * * @param argv0 executable name * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object * @param id identifies the machine to start */ static void startVM(const char *argv0, IVirtualBox *virtualBox, ISession *session, BSTR id) { HRESULT rc; IMachine *machine = NULL; IProgress *progress = NULL; BSTR env = NULL; BSTR sessionType; SAFEARRAY *groupsSA = g_pVBoxFuncs->pfnSafeArrayOutParamAlloc(); rc = IVirtualBox_FindMachine(virtualBox, id, &machine); if (FAILED(rc) || !machine) { PrintErrorInfo(argv0, "Error: Couldn't get the Machine reference", rc); return; } rc = IMachine_get_Groups(machine, ComSafeArrayAsOutTypeParam(groupsSA, BSTR)); if (SUCCEEDED(rc)) { BSTR *groups = NULL; ULONG cbGroups = 0; ULONG i, cGroups; g_pVBoxFuncs->pfnSafeArrayCopyOutParamHelper((void **)&groups, &cbGroups, VT_BSTR, groupsSA); g_pVBoxFuncs->pfnSafeArrayDestroy(groupsSA); cGroups = cbGroups / sizeof(groups[0]); for (i = 0; i < cGroups; ++i) { /* Note that the use of %S might be tempting, but it is not * available on all platforms, and even where it is usable it * may depend on correct compiler options to make wchar_t a * 16 bit number. So better play safe and use UTF-8. */ char *group; g_pVBoxFuncs->pfnUtf16ToUtf8(groups[i], &group); printf("Groups[%d]: %s\n", i, group); g_pVBoxFuncs->pfnUtf8Free(group); } for (i = 0; i < cGroups; ++i) g_pVBoxFuncs->pfnComUnallocString(groups[i]); g_pVBoxFuncs->pfnArrayOutFree(groups); } g_pVBoxFuncs->pfnUtf8ToUtf16("gui", &sessionType); rc = IMachine_LaunchVMProcess(machine, session, sessionType, env, &progress); g_pVBoxFuncs->pfnUtf16Free(sessionType); if (SUCCEEDED(rc)) { BOOL completed; LONG resultCode; printf("Waiting for the remote session to open...\n"); IProgress_WaitForCompletion(progress, -1); rc = IProgress_get_Completed(progress, &completed); if (FAILED(rc)) fprintf(stderr, "Error: GetCompleted status failed\n"); IProgress_get_ResultCode(progress, &resultCode); if (FAILED(resultCode)) { IVirtualBoxErrorInfo *errorInfo; BSTR textUtf16; char *text; IProgress_get_ErrorInfo(progress, &errorInfo); IVirtualBoxErrorInfo_get_Text(errorInfo, &textUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(textUtf16, &text); printf("Error: %s\n", text); g_pVBoxFuncs->pfnComUnallocString(textUtf16); g_pVBoxFuncs->pfnUtf8Free(text); IVirtualBoxErrorInfo_Release(errorInfo); } else { fprintf(stderr, "VM process has been successfully started\n"); /* Kick off the event listener demo part, which is quite separate. * Ignore it if you need a more basic sample. */ #ifdef USE_ACTIVE_EVENT_LISTENER registerActiveEventListener(virtualBox, session); #else registerPassiveEventListener(session); #endif } IProgress_Release(progress); } else PrintErrorInfo(argv0, "Error: LaunchVMProcess failed", rc); /* It's important to always release resources. */ IMachine_Release(machine); } /** * List the registered VMs. * * @param argv0 executable name * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void listVMs(const char *argv0, IVirtualBox *virtualBox, ISession *session) { HRESULT rc; SAFEARRAY *machinesSA = g_pVBoxFuncs->pfnSafeArrayOutParamAlloc(); IMachine **machines = NULL; ULONG machineCnt = 0; ULONG i; unsigned start_id; /* * Get the list of all registered VMs. */ rc = IVirtualBox_get_Machines(virtualBox, ComSafeArrayAsOutIfaceParam(machinesSA, IMachine *)); if (FAILED(rc)) { PrintErrorInfo(argv0, "could not get list of machines", rc); return; } /* * Extract interface pointers from machinesSA, and update the reference * counter of each object, as destroying machinesSA would call Release. */ g_pVBoxFuncs->pfnSafeArrayCopyOutIfaceParamHelper((IUnknown ***)&machines, &machineCnt, machinesSA); g_pVBoxFuncs->pfnSafeArrayDestroy(machinesSA); if (!machineCnt) { g_pVBoxFuncs->pfnArrayOutFree(machines); printf("\tNo VMs\n"); return; } printf("VM List:\n\n"); /* * Iterate through the collection. */ for (i = 0; i < machineCnt; ++i) { IMachine *machine = machines[i]; BOOL isAccessible = FALSE; printf("\tMachine #%u\n", (unsigned)i); if (!machine) { printf("\t(skipped, NULL)\n"); continue; } IMachine_get_Accessible(machine, &isAccessible); if (isAccessible) { BSTR machineNameUtf16; char *machineName; IMachine_get_Name(machine, &machineNameUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(machineNameUtf16,&machineName); g_pVBoxFuncs->pfnComUnallocString(machineNameUtf16); printf("\tName: %s\n", machineName); g_pVBoxFuncs->pfnUtf8Free(machineName); } else printf("\tName: <inaccessible>\n"); { BSTR uuidUtf16; char *uuidUtf8; IMachine_get_Id(machine, &uuidUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(uuidUtf16, &uuidUtf8); g_pVBoxFuncs->pfnComUnallocString(uuidUtf16); printf("\tUUID: %s\n", uuidUtf8); g_pVBoxFuncs->pfnUtf8Free(uuidUtf8); } if (isAccessible) { { BSTR configFileUtf16; char *configFileUtf8; IMachine_get_SettingsFilePath(machine, &configFileUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(configFileUtf16, &configFileUtf8); g_pVBoxFuncs->pfnComUnallocString(configFileUtf16); printf("\tConfig file: %s\n", configFileUtf8); g_pVBoxFuncs->pfnUtf8Free(configFileUtf8); } { ULONG memorySize; IMachine_get_MemorySize(machine, &memorySize); printf("\tMemory size: %uMB\n", memorySize); } { BSTR typeId; BSTR osNameUtf16; char *osName; IGuestOSType *osType = NULL; IMachine_get_OSTypeId(machine, &typeId); IVirtualBox_GetGuestOSType(virtualBox, typeId, &osType); g_pVBoxFuncs->pfnComUnallocString(typeId); IGuestOSType_get_Description(osType, &osNameUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(osNameUtf16,&osName); g_pVBoxFuncs->pfnComUnallocString(osNameUtf16); printf("\tGuest OS: %s\n\n", osName); g_pVBoxFuncs->pfnUtf8Free(osName); IGuestOSType_Release(osType); } } } /* * Let the user chose a machine to start. */ printf("Type Machine# to start (0 - %u) or 'quit' to do nothing: ", (unsigned)(machineCnt - 1)); fflush(stdout); if (scanf("%u", &start_id) == 1 && start_id < machineCnt) { IMachine *machine = machines[start_id]; if (machine) { BSTR uuidUtf16 = NULL; IMachine_get_Id(machine, &uuidUtf16); startVM(argv0, virtualBox, session, uuidUtf16); g_pVBoxFuncs->pfnComUnallocString(uuidUtf16); } } /* * Don't forget to release the objects in the array. */ for (i = 0; i < machineCnt; ++i) { IMachine *machine = machines[i]; if (machine) IMachine_Release(machine); } g_pVBoxFuncs->pfnArrayOutFree(machines); } /* Main - Start the ball rolling. */ int main(int argc, char **argv) { IVirtualBoxClient *vboxclient = NULL; IVirtualBox *vbox = NULL; ISession *session = NULL; ULONG revision = 0; BSTR versionUtf16 = NULL; BSTR homefolderUtf16 = NULL; HRESULT rc; /* Result code of various function (method) calls. */ (void)argc; printf("Starting main()\n"); if (VBoxCGlueInit()) { fprintf(stderr, "%s: FATAL: VBoxCGlueInit failed: %s\n", argv[0], g_szVBoxErrMsg); return EXIT_FAILURE; } { unsigned ver = g_pVBoxFuncs->pfnGetVersion(); printf("VirtualBox version: %u.%u.%u\n", ver / 1000000, ver / 1000 % 1000, ver % 1000); ver = g_pVBoxFuncs->pfnGetAPIVersion(); printf("VirtualBox API version: %u.%u\n", ver / 1000, ver % 1000); } g_pVBoxFuncs->pfnClientInitialize(NULL, &vboxclient); if (!vboxclient) { fprintf(stderr, "%s: FATAL: could not get VirtualBoxClient reference\n", argv[0]); return EXIT_FAILURE; } printf("----------------------------------------------------\n"); rc = IVirtualBoxClient_get_VirtualBox(vboxclient, &vbox); if (FAILED(rc) || !vbox) { PrintErrorInfo(argv[0], "FATAL: could not get VirtualBox reference", rc); return EXIT_FAILURE; } rc = IVirtualBoxClient_get_Session(vboxclient, &session); if (FAILED(rc) || !session) { PrintErrorInfo(argv[0], "FATAL: could not get Session reference", rc); return EXIT_FAILURE; } #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 rc = LoadTypeInfo(&IID_IEventListener, &g_pTInfoIEventListener); if (FAILED(rc) || !g_pTInfoIEventListener) { PrintErrorInfo(argv[0], "FATAL: could not get type information for IEventListener", rc); return EXIT_FAILURE; } # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ /* * Now ask for revision, version and home folder information of * this vbox. Were not using fancy macros here so it * remains easy to see how we access C++'s vtable. */ /* 1. Revision */ rc = IVirtualBox_get_Revision(vbox, &revision); if (SUCCEEDED(rc)) printf("\tRevision: %u\n", revision); else PrintErrorInfo(argv[0], "GetRevision() failed", rc); /* 2. Version */ rc = IVirtualBox_get_Version(vbox, &versionUtf16); if (SUCCEEDED(rc)) { char *version = NULL; g_pVBoxFuncs->pfnUtf16ToUtf8(versionUtf16, &version); printf("\tVersion: %s\n", version); g_pVBoxFuncs->pfnUtf8Free(version); g_pVBoxFuncs->pfnComUnallocString(versionUtf16); } else PrintErrorInfo(argv[0], "GetVersion() failed", rc); /* 3. Home Folder */ rc = IVirtualBox_get_HomeFolder(vbox, &homefolderUtf16); if (SUCCEEDED(rc)) { char *homefolder = NULL; g_pVBoxFuncs->pfnUtf16ToUtf8(homefolderUtf16, &homefolder); printf("\tHomeFolder: %s\n", homefolder); g_pVBoxFuncs->pfnUtf8Free(homefolder); g_pVBoxFuncs->pfnComUnallocString(homefolderUtf16); } else PrintErrorInfo(argv[0], "GetHomeFolder() failed", rc); listVMs(argv[0], vbox, session); ISession_UnlockMachine(session); printf("----------------------------------------------------\n"); /* * Do as mom told us: always clean up after yourself. */ #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 if (g_pTInfoIEventListener) { ITypeInfo_Release(g_pTInfoIEventListener); g_pTInfoIEventListener = NULL; } # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ if (session) { ISession_Release(session); session = NULL; } if (vbox) { IVirtualBox_Release(vbox); vbox = NULL; } if (vboxclient) { IVirtualBoxClient_Release(vboxclient); vboxclient = NULL; } g_pVBoxFuncs->pfnClientUninitialize(); VBoxCGlueTerm(); printf("Finished main()\n"); return 0; } /* vim: set ts=4 sw=4 et: */
Java
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>schrodinger.graphics3d.polyhedron.MaestroIcosahedron</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="schrodinger-module.html">Package&nbsp;schrodinger</a> :: <a href="schrodinger.graphics3d-module.html">Package&nbsp;graphics3d</a> :: <a href="schrodinger.graphics3d.polyhedron-module.html">Module&nbsp;polyhedron</a> :: Class&nbsp;MaestroIcosahedron </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class MaestroIcosahedron</h1><p class="nomargin-top"></p> <pre class="base-tree"> <a href="object-class.html">object</a> --+ | <a href="schrodinger.graphics3d.common.Primitive-class.html">common.Primitive</a> --+ | <a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a> --+ | <a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html">MaestroPolyhedronCore</a> --+ | <strong class="uidshort">MaestroIcosahedron</strong> </pre> <dl><dt>Known Subclasses:</dt> <dd> <ul class="subclass-list"> <li><a href="schrodinger.graphics3d.polyhedron.Icosahedron-class.html">Icosahedron</a></li> </ul> </dd></dl> <hr /> <p>Class to draw a 3D icosahedron in Maestro's Workspace.</p> <p>See <a href="schrodinger.graphics3d.polyhedron.Tetrahedron-class.html" class="link">Tetrahedron</a> doc string for more details.</p> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">center</span>, <span class="summary-sig-arg">mode</span>, <span class="summary-sig-arg">length</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">radius</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">volume</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">color</span>=<span class="summary-sig-default"><code class="variable-quote">'</code><code class="variable-string">red</code><code class="variable-quote">'</code></span>, <span class="summary-sig-arg">opacity</span>=<span class="summary-sig-default">1.0</span>, <span class="summary-sig-arg">style</span>=<span class="summary-sig-default">1</span>)</span><br /> Create a polyhedron centered at <code>center</code>.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html#getVertices" class="summary-sig-name">getVertices</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">center</span>, <span class="summary-sig-arg">length</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">radius</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">volume</span>=<span class="summary-sig-default">None</span>)</span><br /> Get a list of vertices.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html#getIndices" class="summary-sig-name">getIndices</a>(<span class="summary-sig-arg">self</span>)</span><br /> @return The indices of the faces</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html">MaestroPolyhedronCore</a></code></b>: <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#getFaces">getFaces</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#updateVertices">updateVertices</a></code> </p> <div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html">MaestroPolyhedronCore</a></code></b> (private): <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#_checkSizeArgs" onclick="show_private();">_checkSizeArgs</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#_handleOpenGLLevelChange" onclick="show_private();">_handleOpenGLLevelChange</a></code> </p></div> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b>: <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#setStyle">setStyle</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#update">update</a></code> </p> <div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private): <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_calculateBoundingBox" onclick="show_private();">_calculateBoundingBox</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_draw" onclick="show_private();">_draw</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_setNormals" onclick="show_private();">_setNormals</a></code> </p></div> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.common.Primitive-class.html">common.Primitive</a></code></b>: <code><a href="schrodinger.graphics3d.common.Primitive-class.html#__del__">__del__</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#groupHidden">groupHidden</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#groupShown">groupShown</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#hide">hide</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#isGroupShown">isGroupShown</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#isShown">isShown</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#setEntryID">setEntryID</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#show">show</a></code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__delattr__">__delattr__</a></code>, <code><a href="object-class.html#__format__">__format__</a></code>, <code><a href="object-class.html#__getattribute__">__getattribute__</a></code>, <code><a href="object-class.html#__hash__">__hash__</a></code>, <code><a href="object-class.html#__new__">__new__</a></code>, <code><a href="object-class.html#__reduce__">__reduce__</a></code>, <code><a href="object-class.html#__reduce_ex__">__reduce_ex__</a></code>, <code><a href="object-class.html#__repr__">__repr__</a></code>, <code><a href="object-class.html#__setattr__">__setattr__</a></code>, <code><a href="object-class.html#__sizeof__">__sizeof__</a></code>, <code><a href="object-class.html#__str__">__str__</a></code>, <code><a href="object-class.html#__subclasshook__">__subclasshook__</a></code> </p> </td> </tr> </table> <!-- ==================== STATIC METHODS ==================== --> <a name="section-StaticMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Static Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-StaticMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private): <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_glReset" onclick="show_private();">_glReset</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_glSetup" onclick="show_private();">_glSetup</a></code> </p></div> </td> </tr> </table> <!-- ==================== CLASS VARIABLES ==================== --> <a name="section-ClassVariables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Class Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-ClassVariables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private): <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_blend" onclick="show_private();">_blend</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_cull" onclick="show_private();">_cull</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_lighting" onclick="show_private();">_lighting</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_lighting_model" onclick="show_private();">_lighting_model</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_polygon_mode" onclick="show_private();">_polygon_mode</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_shading_model" onclick="show_private();">_shading_model</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_smooth_point" onclick="show_private();">_smooth_point</a></code> </p></div> </td> </tr> </table> <!-- ==================== INSTANCE VARIABLES ==================== --> <a name="section-InstanceVariables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceVariables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b>: <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#faces">faces</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#normals">normals</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#vertices">vertices</a></code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__class__">__class__</a></code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">center</span>, <span class="sig-arg">mode</span>, <span class="sig-arg">length</span>=<span class="sig-default">None</span>, <span class="sig-arg">radius</span>=<span class="sig-default">None</span>, <span class="sig-arg">volume</span>=<span class="sig-default">None</span>, <span class="sig-arg">color</span>=<span class="sig-default"><code class="variable-quote">'</code><code class="variable-string">red</code><code class="variable-quote">'</code></span>, <span class="sig-arg">opacity</span>=<span class="sig-default">1.0</span>, <span class="sig-arg">style</span>=<span class="sig-default">1</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Create a polyhedron centered at <code>center</code>. Note that one of <code>length</code>, <code>radius</code>, <code>volume</code> is needed to create the shape.</p> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>center</code></strong> - List of 3 Angstrom values indicating the center coordinate of the tetrahedron.</li> <li><strong class="pname"><code>length</code></strong> - Length in Angstroms of each of the edges of the tetrahedron.</li> <li><strong class="pname"><code>radius</code></strong> - Circumsphere radius in Angstroms from center of tetrahedron.</li> <li><strong class="pname"><code>volume</code></strong> - Volume in cubed Angstroms of the object.</li> <li><strong class="pname"><code>color</code></strong> - One of - Color object, Color name (string), or Tuple of (R, G, B) (each 0.0-1.0)</li> <li><strong class="pname"><code>opacity</code></strong> - 0.0 (invisible) through 1.0 (opaque). Defaults to 1.0</li> <li><strong class="pname"><code>style</code></strong> - LINE or FILL. Default is FILL.</li> </ul></dd> <dt>Raises:</dt> <dd><ul class="nomargin-top"> <li><code><strong class='fraise'>RuntimeError</strong></code> - If a single option from <code>length</code>, <code>radius</code>, and <code>volume</code> does not have a value.</li> <li><code><strong class='fraise'>ValueError</strong></code> - If the size parameter (<code>length</code>, <code>radius</code>, or <code>volume</code>) is not a float.</li> <li><code><strong class='fraise'>NotImplementedError</strong></code> - If the initiating subclass does not have a <code>getVertices</code> or <code>getFaces</code> method.</li> </ul></dd> <dt>Overrides: object.__init__ </dt> </dl> <div class="fields"> <p><strong>See Also:</strong> <a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#__init__" class="link">MaestroPolyhedronCore.__init__</a> </p> </div></td></tr></table> </div> <a name="getVertices"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">getVertices</span>(<span class="sig-arg">self</span>, <span class="sig-arg">center</span>, <span class="sig-arg">length</span>=<span class="sig-default">None</span>, <span class="sig-arg">radius</span>=<span class="sig-default">None</span>, <span class="sig-arg">volume</span>=<span class="sig-default">None</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Get a list of vertices. If the center coordinates are considered the origin the vertices will have a base on the y-plane, a vertex on the x-axis and a vertex directly in the +z-axis from the <code>center</code>.</p> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>center</code></strong> (List) - List of 3 Angstrom values indicating the center coordinate of the icosahedron.</li> <li><strong class="pname"><code>length</code></strong> (float) - Length in Angstroms of each of the sides of the icosahedron. Note: <code>length</code> or <code>radius</code> must be specified to create icosahedron.</li> <li><strong class="pname"><code>radius</code></strong> (float) - Circumsphere radius in Angstroms from center of icosahedron. Note: <code>length</code> or <code>radius</code> must be specified to create icosahedron.</li> <li><strong class="pname"><code>volume</code></strong> (float) - Volume in cubed Angstroms of the object.</li> </ul></dd> <dt>Overrides: <a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#getVertices">MaestroPolyhedronCore.getVertices</a> </dt> </dl> </td></tr></table> </div> <a name="getIndices"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">getIndices</span>(<span class="sig-arg">self</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>@return The indices of the faces</p> <dl class="fields"> <dt>Overrides: <a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#getIndices">MaestroPolyhedronCore.getIndices</a> </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sat May 9 06:31:22 2015 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
Java
#!/usr/bin/env python """ Grid time ============= """ from datetime import timedelta import numpy as np from opendrift.readers import reader_global_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.oceandrift import OceanDrift # Seeding at a grid at regular interval o = OceanDrift(loglevel=20) # Set loglevel to 0 for debug information reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') #%% # Landmask reader_landmask = reader_global_landmask.Reader( extent=[4.0, 5.5, 59.9, 61.2]) o.add_reader([reader_landmask, reader_norkyst]) #%% # Seeding some particles lons = np.linspace(4.4, 4.6, 10) lats = np.linspace(60.0, 60.1, 10) lons, lats = np.meshgrid(lons, lats) lons = lons.ravel() lats = lats.ravel() #%% # Seed oil elements on a grid at regular time interval start_time = reader_norkyst.start_time time_step = timedelta(hours=6) num_steps = 10 for i in range(num_steps+1): o.seed_elements(lons, lats, radius=0, number=100, time=start_time + i*time_step) #%% # Running model for 60 hours o.run(steps=60*4, time_step=900, time_step_output=3600) #%% # Print and plot results print(o) o.animation(fast=True) #%% # .. image:: /gallery/animations/example_grid_time_0.gif
Java
/* * setting.h * * Created on: 2015. 2. 3. * Author: asran */ #ifndef INCLUDE_SETTING_H_ #define INCLUDE_SETTING_H_ //#define MATRIX //#define MATRIX_CSR //#define MATRIX_VECTOR #define MATRIX_MAP #define COL_SIZE (1000) #define ROW_SIZE (1000) #define VAL_RANGE_START (1) #define VAL_RANGE_END (10) #define VAL_PER_COL (6) #ifdef MATRIX #include <matrix.h> typedef matrix::Matrix matrix_t; #define TEST_MULTI_THREAD (0) #endif #ifdef MATRIX_CSR #include <matrix_csr.h> typedef matrix::MatrixCSR matrix_t; #define TEST_MULTI_THREAD (0) #endif #ifdef MATRIX_MAP #include <sparse_matrix2.h> typedef matrix::SparseMatrix2 matrix_t; #define TEST_MULTI_THREAD (1) #endif #ifdef MATRIX_VECTOR #include <sparse_matrix.h> typedef matrix::SparseMatrix matrix_t; #define TEST_MULTI_THREAD (1) #endif #include "matrix_error.h" #endif /* INCLUDE_SETTING_H_ */
Java
/* * Copyright (C) 1997 by Stephan Kulow <coolo@kde.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 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. * */ #ifndef KTIMETRACKER_TASK_H #define KTIMETRACKER_TASK_H #include "desktoplist.h" // Required b/c DesktopList is a typedef not a class. #include "taskview.h" // Required b/c of static cast below. #include <KCalCore/Todo> #include <QDateTime> #include <QPixmap> #include <QVector> class QObject; class QPixmap; class QString; class timetrackerstorage; /** \brief A class representing a task * * A "Task" object stores information about a task such as it's name, * total and session times. * * It can log when the task is started, stoped or deleted. * * If a task is associated with some desktop's activity it can remember that * too. * * It can also contain subtasks - these are managed using the * QListViewItem class. */ class Task : public QObject, public QTreeWidgetItem { Q_OBJECT public: Task( const QString& taskname, const QString& taskdescription, long minutes, long sessionTime, DesktopList desktops, TaskView* parent = 0, bool konsolemode=false ); Task( const QString& taskname, const QString& taskdescription, long minutes, long sessionTime, DesktopList desktops, Task* parent = 0); Task( const KCalCore::Todo::Ptr &incident, TaskView* parent, bool konsolemode=false ); /* destructor */ ~Task(); /** return parent Task or null in case of TaskView. * same as QListViewItem::parent() */ Task* parent() const { return (Task*)QTreeWidgetItem::parent(); } /** Return task view for this task */ TaskView* taskView() const { return static_cast<TaskView *>( treeWidget() ); } /** Return unique iCalendar Todo ID for this task. */ QString uid() const; int depth(); void delete_recursive(); /** * Set unique id for the task. * * The uid is the key used to update the storage. * * @param uid The new unique id. */ void setUid( const QString &uid ); /** cut Task out of parent Task or the TaskView */ void cut(); /** cut Task out of parent Task or the TaskView and into the * destination Task */ void move(Task* destination); /** insert Task into the destination Task */ void paste(Task* destination); //@{ timing related functions /** * Change task time. Adds minutes to both total time and session time by adding an event. * * @param minutes minutes to add to - may be negative * @param storage Pointer to timetrackerstorage instance. * If zero, don't save changes. */ void changeTime( long minutes, timetrackerstorage* storage ); /** * Add minutes to time and session time by adding an event, and write to storage. * * @param minutesSession minutes to add to task session time * @param minutes minutes to add to task time * @param storage Pointer to timetrackerstorage instance. * If zero, don't save changes. */ void changeTimes ( long minutesSession, long minutes, timetrackerstorage* storage=0 ); /** adds minutes to total and session time by adding an event * * @param minutesSession minutes to add to task total session time * @param minutes minutes to add to task total time */ void changeTotalTimes( long minutesSession, long minutes ); /** Adds minutes to the time of the task and the total time of its supertasks. This does not add an event. * * @param minutes minutes to add to the time * @returns A QString with the error message, in case of no error an empty QString. * */ QString addTime( long minutes ); /** Adds minutes to the total time of the task and its supertasks. This does not add an event. * * @param minutes minutes to add to the time * @returns A QString with the error message, in case of no error an empty QString. * */ QString addTotalTime( long minutes ); /** Adds minutes to the task's session time and its supertasks' total session time. This does not add an event. * * @param minutes minutes to add to the session time * @returns A QString with the error message, in case of no error an empty QString. * */ QString addSessionTime( long minutes ); /** Adds minutes to the task's and its supertasks' total session time. This does not add an event. * * @param minutes minutes to add to the session time * @returns A QString with the error message, in case of no error an empty QString. * */ QString addTotalSessionTime( long minutes ); /** Sets the time (not session time). This does not add an event. * * @param minutes minutes to set time to * */ QString setTime( long minutes ); /** Sets the total time, does not change the parent's total time. This means the parent's total time can run out of sync. */ void setTotalTime( long minutes ) { mTotalTime=minutes; }; /** Sets the total session time, does not change the parent's total session time. This means the parent's total session time can run out of sync. */ void setTotalSessionTime( long minutes ) { mTotalSessionTime=minutes; }; /** A recursive function to calculate the total time of a task. */ QString recalculatetotaltime(); /** A recursive function to calculate the total session time of a task. */ QString recalculatetotalsessiontime(); /** Sets the session time. * Set the session time without changing totalTime nor sessionTime. * Do not change the parent's totalTime. * Do not add an event. * See also: changeTimes(long, long) and resetTimes * * @param minutes minutes to set session time to * */ QString setSessionTime( long minutes ); /** * Reset all times to 0 and adjust parent task's totalTiMes. */ void resetTimes(); /** @return time in minutes */ long time() const; /** @return total time in minutes */ long totalTime() const { return mTotalTime; }; long sessionTime() const; long totalSessionTime() const { return mTotalSessionTime; }; KDateTime sessionStartTiMe() const; /** * Return time the task was started. */ QDateTime startTime() const; /** sets session time to zero. */ void startNewSession(); //@} //@{ desktop related functions void setDesktopList ( DesktopList dl ); DesktopList desktops() const; QString getDesktopStr() const; //@} //@{ name related functions /** sets the name of the task * @param name a pointer to the name. A deep copy will be made. * @param storage a pointer to a timetrackerstorage object. */ void setName( const QString& name, timetrackerstorage* storage ); /** sets the description of the task */ void setDescription( const QString& description); /** returns the name of this task. * @return a pointer to the name. */ QString name() const; /** returns the description of this task. * @return a pointer to the description. */ QString description() const; /** * Returns that task name, prefixed by parent tree up to root. * * Task names are separated by a forward slash: / */ QString fullName() const; //@} /** Update the display of the task (all columns) in the UI. */ void update(); //@{ the state of a Task - stopped, running /** starts or stops a task * @param on true or false for starting or stopping a task * @param storage a pointer to a timetrackerstorage object. * @param when time when the task was started or stopped. Normally QDateTime::currentDateTime, but if calendar has been changed by another program and being reloaded the task is set to running with another start date */ void setRunning( bool on, timetrackerstorage* storage, const QDateTime &when = QDateTime::currentDateTime() ); /** Resume the running state of a task. * This is the same as setrunning, but the storage is not modified. */ void resumeRunning(); /** return the state of a task - if it's running or not * @return true or false depending on whether the task is running */ bool isRunning() const; //@} /** * Parses an incidence. This is needed e.g. when you create a task out of a todo. * You read the todo, extract its custom properties (like session time) * and use these data to initialize the task. */ bool parseIncidence( const KCalCore::Incidence::Ptr &, long& sessionMinutes); /** * Load the todo passed in with this tasks info. */ KCalCore::Todo::Ptr asTodo(KCalCore::Todo::Ptr &calendar) const; /** * Set a task's description * A description is a comment. */ void setDescription( QString desc, timetrackerstorage* storage ); /** * Add a comment to this task. * A comment is called "description" in the context of KCalCore::ToDo */ void addComment( const QString &comment, timetrackerstorage* storage ); /** Retrieve the entire comment for the task. */ QString comment() const; /** tells you whether this task is the root of the task tree */ bool isRoot() const { return parent() == 0; } /** remove Task with all it's children * @param storage a pointer to a timetrackerstorage object. */ bool remove( timetrackerstorage* storage ); /** * Update percent complete for this task. * * Tasks that are complete (i.e., percent = 100) do not show up in * taskview. If percent NULL, set to zero. If greater than 100, set to * 100. If less than zero, set to zero. */ void setPercentComplete(const int percent, timetrackerstorage *storage); int percentComplete() const; /** * Update priority for this task. * * Priority is allowed from 0 to 9. 0 unspecified, 1 highest and 9 lowest. */ void setPriority( int priority ); int priority() const; /** Sets an appropriate icon for this task based on its level of * completion */ void setPixmapProgress(); /** Return true if task is complete (percent complete equals 100). */ bool isComplete(); protected: void changeParentTotalTimes( long minutesSession, long minutes ); Q_SIGNALS: void totalTimesChanged( long minutesSession, long minutes); /** signal that we're about to delete a task */ void deletingTask(Task* thisTask); protected Q_SLOTS: /** animate the active icon */ void updateActiveIcon(); private: // Original KCalCore::Todo object KCalCore::Todo::Ptr taskTodo; /** if the time or session time is negative set them to zero */ void noNegativeTimes(); /** populate a ToDo with provided data */ void populateTodo(const QString& taskName, const QString& taskDescription, long minutes, long sessionTime, DesktopList desktops); /** initialize a task */ void init(bool konsolemode=false); static QVector<QPixmap*> *icons; /** Last time this task was started. */ QDateTime mLastStart; /** totals of the whole subtree including self */ long mTotalTime; long mTotalSessionTime; QTimer *mTimer; int mCurrentPic; /** Don't need to update storage when deleting task from list. */ bool mRemoving; }; #endif // KTIMETRACKER_TASK_H
Java
# ###### # CONFIG ROOTPWD="1234" USERNAME="cubie" USERPASS="1234" ########################### #Main Section ########################### if [[ $EUID -ne 0 ]]; then echo "You must be a root user" 2>&1 exit 1 fi useradd -m -U -d /home/$USERNAME -s /bin/bash $USERNAME # set User password to 1234 (echo $USERPASS;echo $USERPASS;) | passwd $USERNAME # Do NOT force password change upon first login as it will prevent autologin :( adduser $USERNAME sudo DEST_LANG="en_US" DEST_LANGUAGE="en" echo -e $DEST_LANG'.UTF-8 UTF-8\n' >> /etc/locale.gen echo -e 'fr_FR.UTF-8 UTF-8\n' >> /etc/locale.gen echo -e 'LANG="'$DEST_LANG'.UTF-8"\nLANGUAGE="'$DEST_LANG':'$DEST_LANGUAGE'"\n' > /etc/default/locale dpkg-reconfigure -f noninteractive locales update-locale # Setup apt-sources sourcesFile="/etc/apt/sources.list" rm $sourcesFile touch $sourcesFile #Get all info running : sudo netselect-apt -a armhf -n -s -c fr jessie # Or : sudo netselect-apt -a armhf -n -s -c fr wheezy #Edit output file to add wheezy updates and uncomment security + backports #Jessie echo "# Debian packages for Jessie" >> $sourcesFile echo "deb http://debian.mirrors.ovh.net/debian/ jessie main contrib non-free" >> $sourcesFile echo "deb http://debian.mirrors.ovh.net/debian/ jessie-updates main contrib non-free" >> $sourcesFile echo "#Security updates for stable" >> $sourcesFile echo "deb http://security.debian.org/ stable/updates main contrib non-free" >> $sourcesFile echo "deb http://ftp.debian.org/debian/ jessie-backports main contrib non-free" >> $sourcesFile # Wheezy echo "# Debian packages for wheezy" >> $sourcesFile echo "deb http://debian.mirrors.ovh.net/debian/ wheezy main contrib non-free" >> $sourcesFile echo "deb http://debian.mirrors.ovh.net/debian/ wheezy-updates main contrib non-free" >> $sourcesFile echo "#Security updates for stable" >> $sourcesFile echo "deb http://security.debian.org/ stable/updates main contrib non-free" >> $sourcesFile echo "deb http://ftp.debian.org/debian/ wheezy-backports main contrib non-free" >> $sourcesFile apt-get update #Change Timezones echo "Europe/Paris" > /etc/timezone dpkg-reconfigure -f noninteractive tzdata #UnusedTo configure keyboard : #apt-get install console-data # Install packages #Put all packages here :) INSTPKG="hdparm hddtemp console-setup console-data netselect-apt" INSTPKG+=" bash-completion parted cpufrequtils unzip mosh" INSTPKG+=" vim tmux htop sudo locate tree ncdu toilet figlet git mosh" INSTPKG+=" xorg ttf-mscorefonts-installer openbox xterm xinit obconf xscreensaver xscreensaver-gl menu obmenu" INSTPKG+=" lightdm iceweasel x11vnc" echo $INSTPKG apt-get -y upgrade export DEBIAN_FRONTEND=noninteractive; apt-get -y install $INSTPKG #For wheezy only export DEBIAN_FRONTEND=noninteractive; apt-get -y install -t wheezy-backports $INSTPKG #Disable Sshd root login #sed -e "s/PermitRootLogin no/PermitRootLogin yes/g" -i /etc/ssh/sshd_config # Overclock - DANGER #sudo sed -i "s/echo -n 1100000/echo -n 1008000/g" /etc/init.d/cpufrequtils # Install RAMLOG - No ramlog in Jessie #dpkg -i /tmp/ramlog_2.0.0_all.deb #if ! grep -q "TMPFS_RAMFS_SIZE=256m" /etc/default/ramlog; then # sed -e 's/TMPFS_RAMFS_SIZE=/TMPFS_RAMFS_SIZE=256m/g' -i /etc/default/ramlog # sed -e 's/# Required-Start: $remote_fs $time/# Required-Start: $remote_fs $time ramlog/g' -i /etc/init.d/rsyslog # sed -e 's/# Required-Stop: umountnfs $time/# Required-Stop: umountnfs $time ramlog/g' -i /etc/init.d/rsyslog #fi #rm /tmp/ramlog_2.0.0_all.deb #insserv # Cleanup APT apt-get -y clean # set root password to 1234 (echo $ROOTPWD;echo $ROOTPWD;) | passwd root # force password change upon first login chage -d 0 root #Configure Xserver autostart dpkg-reconfigure keyboard-configuration adduser $USERNAME video if ! grep -q $USERNAME /etc/lightdm/lightdm.conf; then sed -i "s/#autologin-user=/autologin-user=$USERNAME/g" /etc/lightdm/lightdm.conf sed -i "s/#autologin-user-timeout=0/autologin-user-timeout=0/g" /etc/lightdm/lightdm.conf fi #To enable connexion using crontab on DISPLAY :0.0 sed -i "s/xserver-allow-tcp=false/xserver-allow-tcp=true/g" /etc/lightdm/lightdm.conf mkdir -p /home/$USERNAME/.config/openbox echo "xhost +localhost &" > /home/$USERNAME/.config/openbox/autostart echo "setxkbmap fr &" >> /home/$USERNAME/.config/openbox/autostart echo "xterm -e '/sbin/ifconfig eth0 && read a' &" >> /home/$USERNAME/.config/openbox/autostart echo "xset -dpms &" >> /home/$USERNAME/.config/openbox/autostart echo "xset s noblank;xset s 0 0;xset s off" >> /home/$USERNAME/.config/openbox/autostart chown -R $USERNAME:$USERNAME /home/$USERNAME/.config/openbox/autostart chmod 755 /home/$USERNAME/.config/openbox/autostart #Setup tmpfs for firefox profiles - All profiles will be in RAMDISK mkdir -p /home/$USERNAME/.mozilla/firefox/ chown -R $USERNAME:$USERNAME /home/cubie/.mozilla/firefox mkdir -p /media/ramdrive if ! grep -q ramdrive /etc/fstab then echo "adding line to fstab" echo 'ramdrive /media/ramdrive tmpfs size=225M,user,auto,exec,rw 0 0' | tee -a /etc/fstab mount -a fi #Screensaver & Screen blanking stuff #export DISPLAY=":0.0" #xset -dpms xset s noblank;xset s 0 0;xset s off #xset + dpms #A inverser pour les xset s #xset s activate #xset s reset #xset dpms force on off suspend standby #For Cubie2 Jessie #Config export DISPLAY=":0.0" xhost +localhost & xset s off xset -dpms #Turn Off xset dpms force off #Turn On reboot #For rpi2 (some commands need root others don't) #https://www.freshrelevance.com/blog/server-monitoring-with-a-raspberry-pi-and-graphite #config export DISPLAY=":0.0" xhost +localhost & xset s off xset -dpms #Turn off tvservice --off > /dev/null #Turn on tvservice --preferred > /dev/null fbset -depth 8; fbset -depth 16; xrefresh
Java
// // C++ Implementation: Audio::OggStream // #include "config.h" #ifdef HAVE_OGG #include "OggStream.h" #include "OggData.h" #include "config.h" #include <utility> #include <limits> #include <stdlib.h> #include <vorbis/vorbisfile.h> #include "vsfilesystem.h" #ifndef OGG_BUFFER_SIZE #define OGG_BUFFER_SIZE 4096*2*2 #endif namespace Audio { OggStream::OggStream(const std::string& path, VSFileSystem::VSFileType type) throw(Exception) : Stream(path) { if ( file.OpenReadOnly(path, type) <= VSFileSystem::Ok ) throw FileOpenException("Error opening file \"" + path + "\""); oggData = new __impl::OggData(file, getFormatInternal(), 0); // Cache duration in case ov_time_total gets expensive duration = ov_time_total( &oggData->vorbisFile, oggData->streamIndex ); // Allocate read buffer readBufferSize = OGG_BUFFER_SIZE; readBufferAvail = 0; readBuffer = malloc(readBufferSize); } OggStream::~OggStream() { // destructor closes the file already delete oggData; } double OggStream::getLengthImpl() const throw(Exception) { return duration; } double OggStream::getPositionImpl() const throw() { return ov_time_tell( &oggData->vorbisFile ); } void OggStream::seekImpl(double position) throw(Exception) { if (position >= duration) throw EndOfStreamException(); readBufferAvail = 0; switch (ov_time_seek(&oggData->vorbisFile, position)) { case 0: break; case OV_ENOSEEK: throw Exception("Stream not seekable"); case OV_EINVAL: throw Exception("Invalid argument or state"); case OV_EREAD: throw Exception("Read error"); case OV_EFAULT: throw Exception("Internal logic fault, bug or heap/stack corruption"); case OV_EBADLINK:throw CorruptStreamException(false); default: throw Exception("Unidentified error code"); } } void OggStream::getBufferImpl(void *&buffer, unsigned int &bufferSize) throw(Exception) { if (readBufferAvail == 0) throw NoBufferException(); buffer = readBuffer; bufferSize = readBufferAvail; } void OggStream::nextBufferImpl() throw(Exception) { int curStream = oggData->streamIndex; long ovr; switch( ovr = ov_read(&oggData->vorbisFile, (char*)readBuffer, readBufferSize, 0, 2, 1, &curStream) ) { case OV_HOLE: throw CorruptStreamException(false); case OV_EBADLINK: throw CorruptStreamException(false); case 0: throw EndOfStreamException(); default: readBufferSize = ovr; } } }; #endif // HAVE_OGG
Java
angular.module('component').component('getGit', { template: ` <section> <h1>GIT : Repro</h1> <div class="controller" > <div git-repro="user : 'gaetanV',repositories :'angular_directive',branch:'master',path:'angular1/directive/gitRepro.directive.js'" > </div> </div> </section> `, });
Java
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="Generator" content="ReWorX 1.1 (021204) - http://www.republico.com" /> <meta name="Originator" content="Microsoft Word 9" /> <title>N_int32</title> <link rel="StyleSheet" type="text/css" href="SNAP%20Graphics%20Architecture.css" /> <script language="JavaScript" src="RePublicoToolbar.js"> </script> <script type="text/javascript" src="RePublico.js"> </script> </head> <body style="tab-interval:.5in;" lang="EN-US" link="blue" vlink="purple" class="rpomain" onbeforeprint="JavaScript:RePublicoOnBeforePrint();" onafterprint="JavaScript:RePublicoOnAfterPrint();" onload="JavaScript:RePublicoTrack('index.html','toc',true);RePublicoShowHide();RePublicoBanner(2);"> <table class="RpoToolbar" cellpadding="0" cellspacing="0" onselectstart="javascript:return false;"> <tr valign="middle"> <td> <table title="Supported Browsers" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('SupportedBrowsers.html','');" onimage="./Images/RpoButtonHomeOn.gif" offimage="./Images/RpoButtonHomeOff.gif"> <tr valign="middle"> <td class="buttonText"> <img hspace="1" height="16" width="16" border="0" alt="Supported Browsers" src="./Images/RpoButtonHomeOff.gif" /> </td> <td class="buttonText"> Home&nbsp;&nbsp;&nbsp; </td> </tr> </table> </td> <td> <table title="N_int16" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('N_int16.html','');" onimage="./Images/RpoButtonPreviousOn.gif" offimage="./Images/RpoButtonPreviousOff.gif"> <tr valign="middle"> <td class="buttonText"> <img hspace="1" height="16" width="16" border="0" alt="N_int16" src="./Images/RpoButtonPreviousOff.gif" /> </td> <td class="buttonText"> Previous&nbsp;&nbsp;&nbsp; </td> </tr> </table> </td> <td> <table title="N_int8" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('N_int8.html','');" onimage="./Images/RpoButtonNextOn.gif" offimage="./Images/RpoButtonNextOff.gif"> <tr valign="middle"> <td class="buttonText"> <img hspace="1" height="16" width="16" border="0" alt="N_int8" src="./Images/RpoButtonNextOff.gif" /> </td> <td class="buttonText"> Next&nbsp;&nbsp;&nbsp; </td> </tr> </table> </td> <td> <table title="Type Definitions" class="buttonOff" cellpadding="0" cellspacing="0" onmouseover="javascript:mouseoverButton(this);" onmouseout="javascript:mouseoutButton(this);" onmousedown="javascript:mousedownButton(this);" onmouseup="javascript:mouseupButton(this);" href="JavaScript:executeButton('TypeDefinitions.html','');" onimage="./Images/RpoButtonUpOn.gif" offimage="./Images/RpoButtonUpOff.gif"> <tr valign="middle"> <td class="buttonText"> <img hspace="1" height="16" width="16" border="0" alt="Type Definitions" src="./Images/RpoButtonUpOff.gif" /> </td> <td class="buttonText"> Up&nbsp;&nbsp;&nbsp; </td> </tr> </table> </td> <td width="100%"> </td> </tr> </table> <div class="Section3"> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="FuncHeading3"> N_int32 </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection"> Declaration </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="Preformatted"> typedef long N_int32 </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection"> Prototype In </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MsoBodyText"> snap/common.h </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MethodSection"> Description </p> <p style="tab-stops:'.45in .7in .95in 1.2in';" class="MsoBodyText"> Fundamental type definition for a 32-bit signed value. </p> </div> <p class="CitationBody"> Copyright &#169; 2002 SciTech Software, Inc. Visit our web site at <a href="http://www.scitechsoft.com" target="_top">http://www.scitechsoft.com<a> </p> </body> </html>
Java
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Universal Flash Storage Host controller driver * Copyright (C) 2011-2013 Samsung India Software Operations * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved. * * Authors: * Santosh Yaraganavi <santosh.sy@samsung.com> * Vinayak Holikatti <h.vinayak@samsung.com> */ #ifndef _UFSHCD_H #define _UFSHCD_H #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/rwsem.h> #include <linux/workqueue.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/wait.h> #include <linux/bitops.h> #include <linux/pm_runtime.h> #include <linux/clk.h> #include <linux/completion.h> #include <linux/regulator/consumer.h> #include <linux/bitfield.h> #include <linux/devfreq.h> #include <linux/blk-crypto-profile.h> #include "unipro.h" #include <asm/irq.h> #include <asm/byteorder.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_host.h> #include <scsi/scsi_tcq.h> #include <scsi/scsi_dbg.h> #include <scsi/scsi_eh.h> #include "ufs.h" #include "ufs_quirks.h" #include "ufshci.h" #define UFSHCD "ufshcd" #define UFSHCD_DRIVER_VERSION "0.2" struct ufs_hba; enum dev_cmd_type { DEV_CMD_TYPE_NOP = 0x0, DEV_CMD_TYPE_QUERY = 0x1, }; enum ufs_event_type { /* uic specific errors */ UFS_EVT_PA_ERR = 0, UFS_EVT_DL_ERR, UFS_EVT_NL_ERR, UFS_EVT_TL_ERR, UFS_EVT_DME_ERR, /* fatal errors */ UFS_EVT_AUTO_HIBERN8_ERR, UFS_EVT_FATAL_ERR, UFS_EVT_LINK_STARTUP_FAIL, UFS_EVT_RESUME_ERR, UFS_EVT_SUSPEND_ERR, UFS_EVT_WL_SUSP_ERR, UFS_EVT_WL_RES_ERR, /* abnormal events */ UFS_EVT_DEV_RESET, UFS_EVT_HOST_RESET, UFS_EVT_ABORT, UFS_EVT_CNT, }; /** * struct uic_command - UIC command structure * @command: UIC command * @argument1: UIC command argument 1 * @argument2: UIC command argument 2 * @argument3: UIC command argument 3 * @cmd_active: Indicate if UIC command is outstanding * @done: UIC command completion */ struct uic_command { u32 command; u32 argument1; u32 argument2; u32 argument3; int cmd_active; struct completion done; }; /* Used to differentiate the power management options */ enum ufs_pm_op { UFS_RUNTIME_PM, UFS_SYSTEM_PM, UFS_SHUTDOWN_PM, }; /* Host <-> Device UniPro Link state */ enum uic_link_state { UIC_LINK_OFF_STATE = 0, /* Link powered down or disabled */ UIC_LINK_ACTIVE_STATE = 1, /* Link is in Fast/Slow/Sleep state */ UIC_LINK_HIBERN8_STATE = 2, /* Link is in Hibernate state */ UIC_LINK_BROKEN_STATE = 3, /* Link is in broken state */ }; #define ufshcd_is_link_off(hba) ((hba)->uic_link_state == UIC_LINK_OFF_STATE) #define ufshcd_is_link_active(hba) ((hba)->uic_link_state == \ UIC_LINK_ACTIVE_STATE) #define ufshcd_is_link_hibern8(hba) ((hba)->uic_link_state == \ UIC_LINK_HIBERN8_STATE) #define ufshcd_is_link_broken(hba) ((hba)->uic_link_state == \ UIC_LINK_BROKEN_STATE) #define ufshcd_set_link_off(hba) ((hba)->uic_link_state = UIC_LINK_OFF_STATE) #define ufshcd_set_link_active(hba) ((hba)->uic_link_state = \ UIC_LINK_ACTIVE_STATE) #define ufshcd_set_link_hibern8(hba) ((hba)->uic_link_state = \ UIC_LINK_HIBERN8_STATE) #define ufshcd_set_link_broken(hba) ((hba)->uic_link_state = \ UIC_LINK_BROKEN_STATE) #define ufshcd_set_ufs_dev_active(h) \ ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE) #define ufshcd_set_ufs_dev_sleep(h) \ ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE) #define ufshcd_set_ufs_dev_poweroff(h) \ ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE) #define ufshcd_set_ufs_dev_deepsleep(h) \ ((h)->curr_dev_pwr_mode = UFS_DEEPSLEEP_PWR_MODE) #define ufshcd_is_ufs_dev_active(h) \ ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE) #define ufshcd_is_ufs_dev_sleep(h) \ ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE) #define ufshcd_is_ufs_dev_poweroff(h) \ ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE) #define ufshcd_is_ufs_dev_deepsleep(h) \ ((h)->curr_dev_pwr_mode == UFS_DEEPSLEEP_PWR_MODE) /* * UFS Power management levels. * Each level is in increasing order of power savings, except DeepSleep * which is lower than PowerDown with power on but not PowerDown with * power off. */ enum ufs_pm_level { UFS_PM_LVL_0, UFS_PM_LVL_1, UFS_PM_LVL_2, UFS_PM_LVL_3, UFS_PM_LVL_4, UFS_PM_LVL_5, UFS_PM_LVL_6, UFS_PM_LVL_MAX }; struct ufs_pm_lvl_states { enum ufs_dev_pwr_mode dev_state; enum uic_link_state link_state; }; /** * struct ufshcd_lrb - local reference block * @utr_descriptor_ptr: UTRD address of the command * @ucd_req_ptr: UCD address of the command * @ucd_rsp_ptr: Response UPIU address for this command * @ucd_prdt_ptr: PRDT address of the command * @utrd_dma_addr: UTRD dma address for debug * @ucd_prdt_dma_addr: PRDT dma address for debug * @ucd_rsp_dma_addr: UPIU response dma address for debug * @ucd_req_dma_addr: UPIU request dma address for debug * @cmd: pointer to SCSI command * @sense_buffer: pointer to sense buffer address of the SCSI command * @sense_bufflen: Length of the sense buffer * @scsi_status: SCSI status of the command * @command_type: SCSI, UFS, Query. * @task_tag: Task tag of the command * @lun: LUN of the command * @intr_cmd: Interrupt command (doesn't participate in interrupt aggregation) * @issue_time_stamp: time stamp for debug purposes * @compl_time_stamp: time stamp for statistics * @crypto_key_slot: the key slot to use for inline crypto (-1 if none) * @data_unit_num: the data unit number for the first block for inline crypto * @req_abort_skip: skip request abort task flag */ struct ufshcd_lrb { struct utp_transfer_req_desc *utr_descriptor_ptr; struct utp_upiu_req *ucd_req_ptr; struct utp_upiu_rsp *ucd_rsp_ptr; struct ufshcd_sg_entry *ucd_prdt_ptr; dma_addr_t utrd_dma_addr; dma_addr_t ucd_req_dma_addr; dma_addr_t ucd_rsp_dma_addr; dma_addr_t ucd_prdt_dma_addr; struct scsi_cmnd *cmd; u8 *sense_buffer; unsigned int sense_bufflen; int scsi_status; int command_type; int task_tag; u8 lun; /* UPIU LUN id field is only 8-bit wide */ bool intr_cmd; ktime_t issue_time_stamp; ktime_t compl_time_stamp; #ifdef CONFIG_SCSI_UFS_CRYPTO int crypto_key_slot; u64 data_unit_num; #endif bool req_abort_skip; }; /** * struct ufs_query - holds relevant data structures for query request * @request: request upiu and function * @descriptor: buffer for sending/receiving descriptor * @response: response upiu and response */ struct ufs_query { struct ufs_query_req request; u8 *descriptor; struct ufs_query_res response; }; /** * struct ufs_dev_cmd - all assosiated fields with device management commands * @type: device management command type - Query, NOP OUT * @lock: lock to allow one command at a time * @complete: internal commands completion */ struct ufs_dev_cmd { enum dev_cmd_type type; struct mutex lock; struct completion *complete; struct ufs_query query; }; /** * struct ufs_clk_info - UFS clock related info * @list: list headed by hba->clk_list_head * @clk: clock node * @name: clock name * @max_freq: maximum frequency supported by the clock * @min_freq: min frequency that can be used for clock scaling * @curr_freq: indicates the current frequency that it is set to * @keep_link_active: indicates that the clk should not be disabled if link is active * @enabled: variable to check against multiple enable/disable */ struct ufs_clk_info { struct list_head list; struct clk *clk; const char *name; u32 max_freq; u32 min_freq; u32 curr_freq; bool keep_link_active; bool enabled; }; enum ufs_notify_change_status { PRE_CHANGE, POST_CHANGE, }; struct ufs_pa_layer_attr { u32 gear_rx; u32 gear_tx; u32 lane_rx; u32 lane_tx; u32 pwr_rx; u32 pwr_tx; u32 hs_rate; }; struct ufs_pwr_mode_info { bool is_valid; struct ufs_pa_layer_attr info; }; /** * struct ufs_hba_variant_ops - variant specific callbacks * @name: variant name * @init: called when the driver is initialized * @exit: called to cleanup everything done in init * @get_ufs_hci_version: called to get UFS HCI version * @clk_scale_notify: notifies that clks are scaled up/down * @setup_clocks: called before touching any of the controller registers * @hce_enable_notify: called before and after HCE enable bit is set to allow * variant specific Uni-Pro initialization. * @link_startup_notify: called before and after Link startup is carried out * to allow variant specific Uni-Pro initialization. * @pwr_change_notify: called before and after a power mode change * is carried out to allow vendor spesific capabilities * to be set. * @setup_xfer_req: called before any transfer request is issued * to set some things * @setup_task_mgmt: called before any task management request is issued * to set some things * @hibern8_notify: called around hibern8 enter/exit * @apply_dev_quirks: called to apply device specific quirks * @suspend: called during host controller PM callback * @resume: called during host controller PM callback * @dbg_register_dump: used to dump controller debug information * @phy_initialization: used to initialize phys * @device_reset: called to issue a reset pulse on the UFS device * @program_key: program or evict an inline encryption key * @event_notify: called to notify important events */ struct ufs_hba_variant_ops { const char *name; int (*init)(struct ufs_hba *); void (*exit)(struct ufs_hba *); u32 (*get_ufs_hci_version)(struct ufs_hba *); int (*clk_scale_notify)(struct ufs_hba *, bool, enum ufs_notify_change_status); int (*setup_clocks)(struct ufs_hba *, bool, enum ufs_notify_change_status); int (*hce_enable_notify)(struct ufs_hba *, enum ufs_notify_change_status); int (*link_startup_notify)(struct ufs_hba *, enum ufs_notify_change_status); int (*pwr_change_notify)(struct ufs_hba *, enum ufs_notify_change_status status, struct ufs_pa_layer_attr *, struct ufs_pa_layer_attr *); void (*setup_xfer_req)(struct ufs_hba *, int, bool); void (*setup_task_mgmt)(struct ufs_hba *, int, u8); void (*hibern8_notify)(struct ufs_hba *, enum uic_cmd_dme, enum ufs_notify_change_status); int (*apply_dev_quirks)(struct ufs_hba *hba); void (*fixup_dev_quirks)(struct ufs_hba *hba); int (*suspend)(struct ufs_hba *, enum ufs_pm_op, enum ufs_notify_change_status); int (*resume)(struct ufs_hba *, enum ufs_pm_op); void (*dbg_register_dump)(struct ufs_hba *hba); int (*phy_initialization)(struct ufs_hba *); int (*device_reset)(struct ufs_hba *hba); void (*config_scaling_param)(struct ufs_hba *hba, struct devfreq_dev_profile *profile, void *data); int (*program_key)(struct ufs_hba *hba, const union ufs_crypto_cfg_entry *cfg, int slot); void (*event_notify)(struct ufs_hba *hba, enum ufs_event_type evt, void *data); }; /* clock gating state */ enum clk_gating_state { CLKS_OFF, CLKS_ON, REQ_CLKS_OFF, REQ_CLKS_ON, }; /** * struct ufs_clk_gating - UFS clock gating related info * @gate_work: worker to turn off clocks after some delay as specified in * delay_ms * @ungate_work: worker to turn on clocks that will be used in case of * interrupt context * @state: the current clocks state * @delay_ms: gating delay in ms * @is_suspended: clk gating is suspended when set to 1 which can be used * during suspend/resume * @delay_attr: sysfs attribute to control delay_attr * @enable_attr: sysfs attribute to enable/disable clock gating * @is_enabled: Indicates the current status of clock gating * @is_initialized: Indicates whether clock gating is initialized or not * @active_reqs: number of requests that are pending and should be waited for * completion before gating clocks. */ struct ufs_clk_gating { struct delayed_work gate_work; struct work_struct ungate_work; enum clk_gating_state state; unsigned long delay_ms; bool is_suspended; struct device_attribute delay_attr; struct device_attribute enable_attr; bool is_enabled; bool is_initialized; int active_reqs; struct workqueue_struct *clk_gating_workq; }; struct ufs_saved_pwr_info { struct ufs_pa_layer_attr info; bool is_valid; }; /** * struct ufs_clk_scaling - UFS clock scaling related data * @active_reqs: number of requests that are pending. If this is zero when * devfreq ->target() function is called then schedule "suspend_work" to * suspend devfreq. * @tot_busy_t: Total busy time in current polling window * @window_start_t: Start time (in jiffies) of the current polling window * @busy_start_t: Start time of current busy period * @enable_attr: sysfs attribute to enable/disable clock scaling * @saved_pwr_info: UFS power mode may also be changed during scaling and this * one keeps track of previous power mode. * @workq: workqueue to schedule devfreq suspend/resume work * @suspend_work: worker to suspend devfreq * @resume_work: worker to resume devfreq * @min_gear: lowest HS gear to scale down to * @is_enabled: tracks if scaling is currently enabled or not, controlled by clkscale_enable sysfs node * @is_allowed: tracks if scaling is currently allowed or not, used to block clock scaling which is not invoked from devfreq governor * @is_initialized: Indicates whether clock scaling is initialized or not * @is_busy_started: tracks if busy period has started or not * @is_suspended: tracks if devfreq is suspended or not */ struct ufs_clk_scaling { int active_reqs; unsigned long tot_busy_t; ktime_t window_start_t; ktime_t busy_start_t; struct device_attribute enable_attr; struct ufs_saved_pwr_info saved_pwr_info; struct workqueue_struct *workq; struct work_struct suspend_work; struct work_struct resume_work; u32 min_gear; bool is_enabled; bool is_allowed; bool is_initialized; bool is_busy_started; bool is_suspended; }; #define UFS_EVENT_HIST_LENGTH 8 /** * struct ufs_event_hist - keeps history of errors * @pos: index to indicate cyclic buffer position * @reg: cyclic buffer for registers value * @tstamp: cyclic buffer for time stamp * @cnt: error counter */ struct ufs_event_hist { int pos; u32 val[UFS_EVENT_HIST_LENGTH]; ktime_t tstamp[UFS_EVENT_HIST_LENGTH]; unsigned long long cnt; }; /** * struct ufs_stats - keeps usage/err statistics * @last_intr_status: record the last interrupt status. * @last_intr_ts: record the last interrupt timestamp. * @hibern8_exit_cnt: Counter to keep track of number of exits, * reset this after link-startup. * @last_hibern8_exit_tstamp: Set time after the hibern8 exit. * Clear after the first successful command completion. */ struct ufs_stats { u32 last_intr_status; ktime_t last_intr_ts; u32 hibern8_exit_cnt; ktime_t last_hibern8_exit_tstamp; struct ufs_event_hist event[UFS_EVT_CNT]; }; /** * enum ufshcd_state - UFS host controller state * @UFSHCD_STATE_RESET: Link is not operational. Postpone SCSI command * processing. * @UFSHCD_STATE_OPERATIONAL: The host controller is operational and can process * SCSI commands. * @UFSHCD_STATE_EH_SCHEDULED_NON_FATAL: The error handler has been scheduled. * SCSI commands may be submitted to the controller. * @UFSHCD_STATE_EH_SCHEDULED_FATAL: The error handler has been scheduled. Fail * newly submitted SCSI commands with error code DID_BAD_TARGET. * @UFSHCD_STATE_ERROR: An unrecoverable error occurred, e.g. link recovery * failed. Fail all SCSI commands with error code DID_ERROR. */ enum ufshcd_state { UFSHCD_STATE_RESET, UFSHCD_STATE_OPERATIONAL, UFSHCD_STATE_EH_SCHEDULED_NON_FATAL, UFSHCD_STATE_EH_SCHEDULED_FATAL, UFSHCD_STATE_ERROR, }; enum ufshcd_quirks { /* Interrupt aggregation support is broken */ UFSHCD_QUIRK_BROKEN_INTR_AGGR = 1 << 0, /* * delay before each dme command is required as the unipro * layer has shown instabilities */ UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS = 1 << 1, /* * If UFS host controller is having issue in processing LCC (Line * Control Command) coming from device then enable this quirk. * When this quirk is enabled, host controller driver should disable * the LCC transmission on UFS device (by clearing TX_LCC_ENABLE * attribute of device to 0). */ UFSHCD_QUIRK_BROKEN_LCC = 1 << 2, /* * The attribute PA_RXHSUNTERMCAP specifies whether or not the * inbound Link supports unterminated line in HS mode. Setting this * attribute to 1 fixes moving to HS gear. */ UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP = 1 << 3, /* * This quirk needs to be enabled if the host controller only allows * accessing the peer dme attributes in AUTO mode (FAST AUTO or * SLOW AUTO). */ UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE = 1 << 4, /* * This quirk needs to be enabled if the host controller doesn't * advertise the correct version in UFS_VER register. If this quirk * is enabled, standard UFS host driver will call the vendor specific * ops (get_ufs_hci_version) to get the correct version. */ UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION = 1 << 5, /* * Clear handling for transfer/task request list is just opposite. */ UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR = 1 << 6, /* * This quirk needs to be enabled if host controller doesn't allow * that the interrupt aggregation timer and counter are reset by s/w. */ UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR = 1 << 7, /* * This quirks needs to be enabled if host controller cannot be * enabled via HCE register. */ UFSHCI_QUIRK_BROKEN_HCE = 1 << 8, /* * This quirk needs to be enabled if the host controller regards * resolution of the values of PRDTO and PRDTL in UTRD as byte. */ UFSHCD_QUIRK_PRDT_BYTE_GRAN = 1 << 9, /* * This quirk needs to be enabled if the host controller reports * OCS FATAL ERROR with device error through sense data */ UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR = 1 << 10, /* * This quirk needs to be enabled if the host controller has * auto-hibernate capability but it doesn't work. */ UFSHCD_QUIRK_BROKEN_AUTO_HIBERN8 = 1 << 11, /* * This quirk needs to disable manual flush for write booster */ UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL = 1 << 12, /* * This quirk needs to disable unipro timeout values * before power mode change */ UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING = 1 << 13, /* * This quirk allows only sg entries aligned with page size. */ UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE = 1 << 14, }; enum ufshcd_caps { /* Allow dynamic clk gating */ UFSHCD_CAP_CLK_GATING = 1 << 0, /* Allow hiberb8 with clk gating */ UFSHCD_CAP_HIBERN8_WITH_CLK_GATING = 1 << 1, /* Allow dynamic clk scaling */ UFSHCD_CAP_CLK_SCALING = 1 << 2, /* Allow auto bkops to enabled during runtime suspend */ UFSHCD_CAP_AUTO_BKOPS_SUSPEND = 1 << 3, /* * This capability allows host controller driver to use the UFS HCI's * interrupt aggregation capability. * CAUTION: Enabling this might reduce overall UFS throughput. */ UFSHCD_CAP_INTR_AGGR = 1 << 4, /* * This capability allows the device auto-bkops to be always enabled * except during suspend (both runtime and suspend). * Enabling this capability means that device will always be allowed * to do background operation when it's active but it might degrade * the performance of ongoing read/write operations. */ UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND = 1 << 5, /* * This capability allows host controller driver to automatically * enable runtime power management by itself instead of waiting * for userspace to control the power management. */ UFSHCD_CAP_RPM_AUTOSUSPEND = 1 << 6, /* * This capability allows the host controller driver to turn-on * WriteBooster, if the underlying device supports it and is * provisioned to be used. This would increase the write performance. */ UFSHCD_CAP_WB_EN = 1 << 7, /* * This capability allows the host controller driver to use the * inline crypto engine, if it is present */ UFSHCD_CAP_CRYPTO = 1 << 8, /* * This capability allows the controller regulators to be put into * lpm mode aggressively during clock gating. * This would increase power savings. */ UFSHCD_CAP_AGGR_POWER_COLLAPSE = 1 << 9, /* * This capability allows the host controller driver to use DeepSleep, * if it is supported by the UFS device. The host controller driver must * support device hardware reset via the hba->device_reset() callback, * in order to exit DeepSleep state. */ UFSHCD_CAP_DEEPSLEEP = 1 << 10, /* * This capability allows the host controller driver to use temperature * notification if it is supported by the UFS device. */ UFSHCD_CAP_TEMP_NOTIF = 1 << 11, }; struct ufs_hba_variant_params { struct devfreq_dev_profile devfreq_profile; struct devfreq_simple_ondemand_data ondemand_data; u16 hba_enable_delay_us; u32 wb_flush_threshold; }; #ifdef CONFIG_SCSI_UFS_HPB /** * struct ufshpb_dev_info - UFSHPB device related info * @num_lu: the number of user logical unit to check whether all lu finished * initialization * @rgn_size: device reported HPB region size * @srgn_size: device reported HPB sub-region size * @slave_conf_cnt: counter to check all lu finished initialization * @hpb_disabled: flag to check if HPB is disabled * @max_hpb_single_cmd: device reported bMAX_DATA_SIZE_FOR_SINGLE_CMD value * @is_legacy: flag to check HPB 1.0 * @control_mode: either host or device */ struct ufshpb_dev_info { int num_lu; int rgn_size; int srgn_size; atomic_t slave_conf_cnt; bool hpb_disabled; u8 max_hpb_single_cmd; bool is_legacy; u8 control_mode; }; #endif struct ufs_hba_monitor { unsigned long chunk_size; unsigned long nr_sec_rw[2]; ktime_t total_busy[2]; unsigned long nr_req[2]; /* latencies*/ ktime_t lat_sum[2]; ktime_t lat_max[2]; ktime_t lat_min[2]; u32 nr_queued[2]; ktime_t busy_start_ts[2]; ktime_t enabled_ts; bool enabled; }; /** * struct ufs_hba - per adapter private structure * @mmio_base: UFSHCI base register address * @ucdl_base_addr: UFS Command Descriptor base address * @utrdl_base_addr: UTP Transfer Request Descriptor base address * @utmrdl_base_addr: UTP Task Management Descriptor base address * @ucdl_dma_addr: UFS Command Descriptor DMA address * @utrdl_dma_addr: UTRDL DMA address * @utmrdl_dma_addr: UTMRDL DMA address * @host: Scsi_Host instance of the driver * @dev: device handle * @lrb: local reference block * @cmd_queue: Used to allocate command tags from hba->host->tag_set. * @outstanding_tasks: Bits representing outstanding task requests * @outstanding_lock: Protects @outstanding_reqs. * @outstanding_reqs: Bits representing outstanding transfer requests * @capabilities: UFS Controller Capabilities * @nutrs: Transfer Request Queue depth supported by controller * @nutmrs: Task Management Queue depth supported by controller * @ufs_version: UFS Version to which controller complies * @vops: pointer to variant specific operations * @priv: pointer to variant specific private data * @irq: Irq number of the controller * @active_uic_cmd: handle of active UIC command * @uic_cmd_mutex: mutex for UIC command * @tmf_tag_set: TMF tag set. * @tmf_queue: Used to allocate TMF tags. * @pwr_done: completion for power mode change * @ufshcd_state: UFSHCD state * @eh_flags: Error handling flags * @intr_mask: Interrupt Mask Bits * @ee_ctrl_mask: Exception event control mask * @is_powered: flag to check if HBA is powered * @shutting_down: flag to check if shutdown has been invoked * @host_sem: semaphore used to serialize concurrent contexts * @eh_wq: Workqueue that eh_work works on * @eh_work: Worker to handle UFS errors that require s/w attention * @eeh_work: Worker to handle exception events * @errors: HBA errors * @uic_error: UFS interconnect layer error status * @saved_err: sticky error mask * @saved_uic_err: sticky UIC error mask * @force_reset: flag to force eh_work perform a full reset * @force_pmc: flag to force a power mode change * @silence_err_logs: flag to silence error logs * @dev_cmd: ufs device management command information * @last_dme_cmd_tstamp: time stamp of the last completed DME command * @auto_bkops_enabled: to track whether bkops is enabled in device * @vreg_info: UFS device voltage regulator information * @clk_list_head: UFS host controller clocks list node head * @pwr_info: holds current power mode * @max_pwr_info: keeps the device max valid pwm * @desc_size: descriptor sizes reported by device * @urgent_bkops_lvl: keeps track of urgent bkops level for device * @is_urgent_bkops_lvl_checked: keeps track if the urgent bkops level for * device is known or not. * @scsi_block_reqs_cnt: reference counting for scsi block requests * @crypto_capabilities: Content of crypto capabilities register (0x100) * @crypto_cap_array: Array of crypto capabilities * @crypto_cfg_register: Start of the crypto cfg array * @crypto_profile: the crypto profile of this hba (if applicable) */ struct ufs_hba { void __iomem *mmio_base; /* Virtual memory reference */ struct utp_transfer_cmd_desc *ucdl_base_addr; struct utp_transfer_req_desc *utrdl_base_addr; struct utp_task_req_desc *utmrdl_base_addr; /* DMA memory reference */ dma_addr_t ucdl_dma_addr; dma_addr_t utrdl_dma_addr; dma_addr_t utmrdl_dma_addr; struct Scsi_Host *host; struct device *dev; struct request_queue *cmd_queue; /* * This field is to keep a reference to "scsi_device" corresponding to * "UFS device" W-LU. */ struct scsi_device *sdev_ufs_device; struct scsi_device *sdev_rpmb; #ifdef CONFIG_SCSI_UFS_HWMON struct device *hwmon_device; #endif enum ufs_dev_pwr_mode curr_dev_pwr_mode; enum uic_link_state uic_link_state; /* Desired UFS power management level during runtime PM */ enum ufs_pm_level rpm_lvl; /* Desired UFS power management level during system PM */ enum ufs_pm_level spm_lvl; struct device_attribute rpm_lvl_attr; struct device_attribute spm_lvl_attr; int pm_op_in_progress; /* Auto-Hibernate Idle Timer register value */ u32 ahit; struct ufshcd_lrb *lrb; unsigned long outstanding_tasks; spinlock_t outstanding_lock; unsigned long outstanding_reqs; u32 capabilities; int nutrs; int nutmrs; u32 ufs_version; const struct ufs_hba_variant_ops *vops; struct ufs_hba_variant_params *vps; void *priv; unsigned int irq; bool is_irq_enabled; enum ufs_ref_clk_freq dev_ref_clk_freq; unsigned int quirks; /* Deviations from standard UFSHCI spec. */ /* Device deviations from standard UFS device spec. */ unsigned int dev_quirks; struct blk_mq_tag_set tmf_tag_set; struct request_queue *tmf_queue; struct request **tmf_rqs; struct uic_command *active_uic_cmd; struct mutex uic_cmd_mutex; struct completion *uic_async_done; enum ufshcd_state ufshcd_state; u32 eh_flags; u32 intr_mask; u16 ee_ctrl_mask; /* Exception event mask */ u16 ee_drv_mask; /* Exception event mask for driver */ u16 ee_usr_mask; /* Exception event mask for user (via debugfs) */ struct mutex ee_ctrl_mutex; bool is_powered; bool shutting_down; struct semaphore host_sem; /* Work Queues */ struct workqueue_struct *eh_wq; struct work_struct eh_work; struct work_struct eeh_work; /* HBA Errors */ u32 errors; u32 uic_error; u32 saved_err; u32 saved_uic_err; struct ufs_stats ufs_stats; bool force_reset; bool force_pmc; bool silence_err_logs; /* Device management request data */ struct ufs_dev_cmd dev_cmd; ktime_t last_dme_cmd_tstamp; int nop_out_timeout; /* Keeps information of the UFS device connected to this host */ struct ufs_dev_info dev_info; bool auto_bkops_enabled; struct ufs_vreg_info vreg_info; struct list_head clk_list_head; /* Number of requests aborts */ int req_abort_count; /* Number of lanes available (1 or 2) for Rx/Tx */ u32 lanes_per_direction; struct ufs_pa_layer_attr pwr_info; struct ufs_pwr_mode_info max_pwr_info; struct ufs_clk_gating clk_gating; /* Control to enable/disable host capabilities */ u32 caps; struct devfreq *devfreq; struct ufs_clk_scaling clk_scaling; bool is_sys_suspended; enum bkops_status urgent_bkops_lvl; bool is_urgent_bkops_lvl_checked; struct rw_semaphore clk_scaling_lock; unsigned char desc_size[QUERY_DESC_IDN_MAX]; atomic_t scsi_block_reqs_cnt; struct device bsg_dev; struct request_queue *bsg_queue; struct delayed_work rpm_dev_flush_recheck_work; #ifdef CONFIG_SCSI_UFS_HPB struct ufshpb_dev_info ufshpb_dev; #endif struct ufs_hba_monitor monitor; #ifdef CONFIG_SCSI_UFS_CRYPTO union ufs_crypto_capabilities crypto_capabilities; union ufs_crypto_cap_entry *crypto_cap_array; u32 crypto_cfg_register; struct blk_crypto_profile crypto_profile; #endif #ifdef CONFIG_DEBUG_FS struct dentry *debugfs_root; struct delayed_work debugfs_ee_work; u32 debugfs_ee_rate_limit_ms; #endif u32 luns_avail; bool complete_put; }; /* Returns true if clocks can be gated. Otherwise false */ static inline bool ufshcd_is_clkgating_allowed(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_CLK_GATING; } static inline bool ufshcd_can_hibern8_during_gating(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_HIBERN8_WITH_CLK_GATING; } static inline int ufshcd_is_clkscaling_supported(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_CLK_SCALING; } static inline bool ufshcd_can_autobkops_during_suspend(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_AUTO_BKOPS_SUSPEND; } static inline bool ufshcd_is_rpm_autosuspend_allowed(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_RPM_AUTOSUSPEND; } static inline bool ufshcd_is_intr_aggr_allowed(struct ufs_hba *hba) { return (hba->caps & UFSHCD_CAP_INTR_AGGR) && !(hba->quirks & UFSHCD_QUIRK_BROKEN_INTR_AGGR); } static inline bool ufshcd_can_aggressive_pc(struct ufs_hba *hba) { return !!(ufshcd_is_link_hibern8(hba) && (hba->caps & UFSHCD_CAP_AGGR_POWER_COLLAPSE)); } static inline bool ufshcd_is_auto_hibern8_supported(struct ufs_hba *hba) { return (hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) && !(hba->quirks & UFSHCD_QUIRK_BROKEN_AUTO_HIBERN8); } static inline bool ufshcd_is_auto_hibern8_enabled(struct ufs_hba *hba) { return FIELD_GET(UFSHCI_AHIBERN8_TIMER_MASK, hba->ahit) ? true : false; } static inline bool ufshcd_is_wb_allowed(struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_WB_EN; } static inline bool ufshcd_is_user_access_allowed(struct ufs_hba *hba) { return !hba->shutting_down; } #define ufshcd_writel(hba, val, reg) \ writel((val), (hba)->mmio_base + (reg)) #define ufshcd_readl(hba, reg) \ readl((hba)->mmio_base + (reg)) /** * ufshcd_rmwl - read modify write into a register * @hba - per adapter instance * @mask - mask to apply on read value * @val - actual value to write * @reg - register address */ static inline void ufshcd_rmwl(struct ufs_hba *hba, u32 mask, u32 val, u32 reg) { u32 tmp; tmp = ufshcd_readl(hba, reg); tmp &= ~mask; tmp |= (val & mask); ufshcd_writel(hba, tmp, reg); } int ufshcd_alloc_host(struct device *, struct ufs_hba **); void ufshcd_dealloc_host(struct ufs_hba *); int ufshcd_hba_enable(struct ufs_hba *hba); int ufshcd_init(struct ufs_hba *, void __iomem *, unsigned int); int ufshcd_link_recovery(struct ufs_hba *hba); int ufshcd_make_hba_operational(struct ufs_hba *hba); void ufshcd_remove(struct ufs_hba *); int ufshcd_uic_hibern8_enter(struct ufs_hba *hba); int ufshcd_uic_hibern8_exit(struct ufs_hba *hba); void ufshcd_delay_us(unsigned long us, unsigned long tolerance); int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask, u32 val, unsigned long interval_us, unsigned long timeout_ms); void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk); void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val); void ufshcd_hba_stop(struct ufs_hba *hba); static inline void check_upiu_size(void) { BUILD_BUG_ON(ALIGNED_UPIU_SIZE < GENERAL_UPIU_REQUEST_SIZE + QUERY_DESC_MAX_SIZE); } /** * ufshcd_set_variant - set variant specific data to the hba * @hba - per adapter instance * @variant - pointer to variant specific data */ static inline void ufshcd_set_variant(struct ufs_hba *hba, void *variant) { BUG_ON(!hba); hba->priv = variant; } /** * ufshcd_get_variant - get variant specific data from the hba * @hba - per adapter instance */ static inline void *ufshcd_get_variant(struct ufs_hba *hba) { BUG_ON(!hba); return hba->priv; } static inline bool ufshcd_keep_autobkops_enabled_except_suspend( struct ufs_hba *hba) { return hba->caps & UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND; } static inline u8 ufshcd_wb_get_query_index(struct ufs_hba *hba) { if (hba->dev_info.wb_buffer_type == WB_BUF_MODE_LU_DEDICATED) return hba->dev_info.wb_dedicated_lu; return 0; } #ifdef CONFIG_SCSI_UFS_HWMON void ufs_hwmon_probe(struct ufs_hba *hba, u8 mask); void ufs_hwmon_remove(struct ufs_hba *hba); void ufs_hwmon_notify_event(struct ufs_hba *hba, u8 ee_mask); #else static inline void ufs_hwmon_probe(struct ufs_hba *hba, u8 mask) {} static inline void ufs_hwmon_remove(struct ufs_hba *hba) {} static inline void ufs_hwmon_notify_event(struct ufs_hba *hba, u8 ee_mask) {} #endif #ifdef CONFIG_PM extern int ufshcd_runtime_suspend(struct device *dev); extern int ufshcd_runtime_resume(struct device *dev); #endif #ifdef CONFIG_PM_SLEEP extern int ufshcd_system_suspend(struct device *dev); extern int ufshcd_system_resume(struct device *dev); #endif extern int ufshcd_shutdown(struct ufs_hba *hba); extern int ufshcd_dme_configure_adapt(struct ufs_hba *hba, int agreed_gear, int adapt_val); extern int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel, u8 attr_set, u32 mib_val, u8 peer); extern int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel, u32 *mib_val, u8 peer); extern int ufshcd_config_pwr_mode(struct ufs_hba *hba, struct ufs_pa_layer_attr *desired_pwr_mode); /* UIC command interfaces for DME primitives */ #define DME_LOCAL 0 #define DME_PEER 1 #define ATTR_SET_NOR 0 /* NORMAL */ #define ATTR_SET_ST 1 /* STATIC */ static inline int ufshcd_dme_set(struct ufs_hba *hba, u32 attr_sel, u32 mib_val) { return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_NOR, mib_val, DME_LOCAL); } static inline int ufshcd_dme_st_set(struct ufs_hba *hba, u32 attr_sel, u32 mib_val) { return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_ST, mib_val, DME_LOCAL); } static inline int ufshcd_dme_peer_set(struct ufs_hba *hba, u32 attr_sel, u32 mib_val) { return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_NOR, mib_val, DME_PEER); } static inline int ufshcd_dme_peer_st_set(struct ufs_hba *hba, u32 attr_sel, u32 mib_val) { return ufshcd_dme_set_attr(hba, attr_sel, ATTR_SET_ST, mib_val, DME_PEER); } static inline int ufshcd_dme_get(struct ufs_hba *hba, u32 attr_sel, u32 *mib_val) { return ufshcd_dme_get_attr(hba, attr_sel, mib_val, DME_LOCAL); } static inline int ufshcd_dme_peer_get(struct ufs_hba *hba, u32 attr_sel, u32 *mib_val) { return ufshcd_dme_get_attr(hba, attr_sel, mib_val, DME_PEER); } static inline bool ufshcd_is_hs_mode(struct ufs_pa_layer_attr *pwr_info) { return (pwr_info->pwr_rx == FAST_MODE || pwr_info->pwr_rx == FASTAUTO_MODE) && (pwr_info->pwr_tx == FAST_MODE || pwr_info->pwr_tx == FASTAUTO_MODE); } static inline int ufshcd_disable_host_tx_lcc(struct ufs_hba *hba) { return ufshcd_dme_set(hba, UIC_ARG_MIB(PA_LOCAL_TX_LCC_ENABLE), 0); } /* Expose Query-Request API */ int ufshcd_query_descriptor_retry(struct ufs_hba *hba, enum query_opcode opcode, enum desc_idn idn, u8 index, u8 selector, u8 *desc_buf, int *buf_len); int ufshcd_read_desc_param(struct ufs_hba *hba, enum desc_idn desc_id, int desc_index, u8 param_offset, u8 *param_read_buf, u8 param_size); int ufshcd_query_attr_retry(struct ufs_hba *hba, enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector, u32 *attr_val); int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector, u32 *attr_val); int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res); void ufshcd_auto_hibern8_enable(struct ufs_hba *hba); void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit); void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups); #define SD_ASCII_STD true #define SD_RAW false int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index, u8 **buf, bool ascii); int ufshcd_hold(struct ufs_hba *hba, bool async); void ufshcd_release(struct ufs_hba *hba); void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id, int *desc_length); u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba); int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd); int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba, struct utp_upiu_req *req_upiu, struct utp_upiu_req *rsp_upiu, int msgcode, u8 *desc_buff, int *buff_len, enum query_opcode desc_op); int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable); int ufshcd_suspend_prepare(struct device *dev); void ufshcd_resume_complete(struct device *dev); /* Wrapper functions for safely calling variant operations */ static inline const char *ufshcd_get_var_name(struct ufs_hba *hba) { if (hba->vops) return hba->vops->name; return ""; } static inline int ufshcd_vops_init(struct ufs_hba *hba) { if (hba->vops && hba->vops->init) return hba->vops->init(hba); return 0; } static inline void ufshcd_vops_exit(struct ufs_hba *hba) { if (hba->vops && hba->vops->exit) return hba->vops->exit(hba); } static inline u32 ufshcd_vops_get_ufs_hci_version(struct ufs_hba *hba) { if (hba->vops && hba->vops->get_ufs_hci_version) return hba->vops->get_ufs_hci_version(hba); return ufshcd_readl(hba, REG_UFS_VERSION); } static inline int ufshcd_vops_clk_scale_notify(struct ufs_hba *hba, bool up, enum ufs_notify_change_status status) { if (hba->vops && hba->vops->clk_scale_notify) return hba->vops->clk_scale_notify(hba, up, status); return 0; } static inline void ufshcd_vops_event_notify(struct ufs_hba *hba, enum ufs_event_type evt, void *data) { if (hba->vops && hba->vops->event_notify) hba->vops->event_notify(hba, evt, data); } static inline int ufshcd_vops_setup_clocks(struct ufs_hba *hba, bool on, enum ufs_notify_change_status status) { if (hba->vops && hba->vops->setup_clocks) return hba->vops->setup_clocks(hba, on, status); return 0; } static inline int ufshcd_vops_hce_enable_notify(struct ufs_hba *hba, bool status) { if (hba->vops && hba->vops->hce_enable_notify) return hba->vops->hce_enable_notify(hba, status); return 0; } static inline int ufshcd_vops_link_startup_notify(struct ufs_hba *hba, bool status) { if (hba->vops && hba->vops->link_startup_notify) return hba->vops->link_startup_notify(hba, status); return 0; } static inline int ufshcd_vops_phy_initialization(struct ufs_hba *hba) { if (hba->vops && hba->vops->phy_initialization) return hba->vops->phy_initialization(hba); return 0; } static inline int ufshcd_vops_pwr_change_notify(struct ufs_hba *hba, enum ufs_notify_change_status status, struct ufs_pa_layer_attr *dev_max_params, struct ufs_pa_layer_attr *dev_req_params) { if (hba->vops && hba->vops->pwr_change_notify) return hba->vops->pwr_change_notify(hba, status, dev_max_params, dev_req_params); return -ENOTSUPP; } static inline void ufshcd_vops_setup_task_mgmt(struct ufs_hba *hba, int tag, u8 tm_function) { if (hba->vops && hba->vops->setup_task_mgmt) return hba->vops->setup_task_mgmt(hba, tag, tm_function); } static inline void ufshcd_vops_hibern8_notify(struct ufs_hba *hba, enum uic_cmd_dme cmd, enum ufs_notify_change_status status) { if (hba->vops && hba->vops->hibern8_notify) return hba->vops->hibern8_notify(hba, cmd, status); } static inline int ufshcd_vops_apply_dev_quirks(struct ufs_hba *hba) { if (hba->vops && hba->vops->apply_dev_quirks) return hba->vops->apply_dev_quirks(hba); return 0; } static inline void ufshcd_vops_fixup_dev_quirks(struct ufs_hba *hba) { if (hba->vops && hba->vops->fixup_dev_quirks) hba->vops->fixup_dev_quirks(hba); } static inline int ufshcd_vops_suspend(struct ufs_hba *hba, enum ufs_pm_op op, enum ufs_notify_change_status status) { if (hba->vops && hba->vops->suspend) return hba->vops->suspend(hba, op, status); return 0; } static inline int ufshcd_vops_resume(struct ufs_hba *hba, enum ufs_pm_op op) { if (hba->vops && hba->vops->resume) return hba->vops->resume(hba, op); return 0; } static inline void ufshcd_vops_dbg_register_dump(struct ufs_hba *hba) { if (hba->vops && hba->vops->dbg_register_dump) hba->vops->dbg_register_dump(hba); } static inline int ufshcd_vops_device_reset(struct ufs_hba *hba) { if (hba->vops && hba->vops->device_reset) return hba->vops->device_reset(hba); return -EOPNOTSUPP; } static inline void ufshcd_vops_config_scaling_param(struct ufs_hba *hba, struct devfreq_dev_profile *profile, void *data) { if (hba->vops && hba->vops->config_scaling_param) hba->vops->config_scaling_param(hba, profile, data); } extern struct ufs_pm_lvl_states ufs_pm_lvl_states[]; /* * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN * @scsi_lun: scsi LUN id * * Returns UPIU LUN id */ static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun) { if (scsi_is_wlun(scsi_lun)) return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID) | UFS_UPIU_WLUN_ID; else return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID; } int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len, const char *prefix); int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask); int ufshcd_write_ee_control(struct ufs_hba *hba); int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask, u16 set, u16 clr); static inline int ufshcd_update_ee_drv_mask(struct ufs_hba *hba, u16 set, u16 clr) { return ufshcd_update_ee_control(hba, &hba->ee_drv_mask, &hba->ee_usr_mask, set, clr); } static inline int ufshcd_update_ee_usr_mask(struct ufs_hba *hba, u16 set, u16 clr) { return ufshcd_update_ee_control(hba, &hba->ee_usr_mask, &hba->ee_drv_mask, set, clr); } static inline int ufshcd_rpm_get_sync(struct ufs_hba *hba) { return pm_runtime_get_sync(&hba->sdev_ufs_device->sdev_gendev); } static inline int ufshcd_rpm_put_sync(struct ufs_hba *hba) { return pm_runtime_put_sync(&hba->sdev_ufs_device->sdev_gendev); } static inline int ufshcd_rpm_put(struct ufs_hba *hba) { return pm_runtime_put(&hba->sdev_ufs_device->sdev_gendev); } #endif /* End of Header */
Java
// // begin license header // // This file is part of Pixy CMUcam5 or "Pixy" for short // // All Pixy source code is provided under the terms of the // GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html). // Those wishing to use Pixy source code, software and/or // technologies under different licensing terms should contact us at // cmucam@cs.cmu.edu. Such licensing terms are available for // all portions of the Pixy codebase presented here. // // end license header // #include <math.h> #include "pixy_init.h" #include "misc.h" #include "power.h" static const ProcModule g_module[] = { { "pwr_getVin", (ProcPtr)pwr_getVin, {END}, "Get Vin (JP1) voltage" "@r voltage in millivolts" }, { "pwr_get5V", (ProcPtr)pwr_get5v, {END}, "Get 5V voltage" "@r voltage in millivolts" }, { "pwr_getVbus", (ProcPtr)pwr_getVbus, {END}, "Get USB VBUS voltage" "@r voltage in millivolts" }, { "pwr_USBpowered", (ProcPtr)pwr_USBpowered, {END}, "Determine if camera power is from USB host." "@r 0 if power is from Vin (JP1), nonzero if power is from USB" }, END }; uint32_t pwr_getVin() { uint32_t vin; vin = adc_get(VIN_ADCCHAN)*10560/1024 + 330; // 10560 = 3.3*3.2*1000, 330 is diode drop return vin; } uint32_t pwr_get5v() { uint32_t v5; v5 = adc_get(V5_ADCCHAN)*5293/1024; // 5293=3.3*1.604*1000 return v5; } uint32_t pwr_getVbus() { uint32_t vbus; vbus = adc_get(VBUS_ADCCHAN)*5293/1024; // 5293=3.3*1.604*1000 return vbus; } uint32_t pwr_USBpowered() { if (LPC_GPIO_PORT->PIN[5]&0x0100) return 1; else return 0; } void pwr_init() { LPC_GPIO_PORT->DIR[5] |= 0x0100; // choose USB power or vin if (pwr_getVin()>6430) // 6430=5000+1100(ldo)+330(diode) LPC_GPIO_PORT->PIN[5] &= ~0x0100; else // switch usb on LPC_GPIO_PORT->PIN[5] |= 0x0100; #if 0 // Undergrad robotics mod, no need for usb shit fuck my ass nigga please g_chirpUsb->registerModule(g_module); #endif }
Java
// Copyright 2014 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "VideoCommon/GeometryShaderGen.h" #include <cmath> #include <cstring> #include "Common/CommonTypes.h" #include "VideoCommon/DriverDetails.h" #include "VideoCommon/LightingShaderGen.h" #include "VideoCommon/VideoCommon.h" #include "VideoCommon/VideoConfig.h" #include "VideoCommon/XFMemory.h" constexpr std::array<const char*, 4> primitives_ogl = { {"points", "lines", "triangles", "triangles"}}; constexpr std::array<const char*, 4> primitives_d3d = {{"point", "line", "triangle", "triangle"}}; bool geometry_shader_uid_data::IsPassthrough() const { const bool stereo = g_ActiveConfig.iStereoMode > 0; const bool wireframe = g_ActiveConfig.bWireFrame; return primitive_type >= static_cast<u32>(PrimitiveType::Triangles) && !stereo && !wireframe; } GeometryShaderUid GetGeometryShaderUid(PrimitiveType primitive_type) { ShaderUid<geometry_shader_uid_data> out; geometry_shader_uid_data* uid_data = out.GetUidData<geometry_shader_uid_data>(); memset(uid_data, 0, sizeof(geometry_shader_uid_data)); uid_data->primitive_type = static_cast<u32>(primitive_type); uid_data->numTexGens = xfmem.numTexGen.numTexGens; return out; } static void EmitVertex(ShaderCode& out, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data, const char* vertex, APIType ApiType, bool wireframe, bool pixel_lighting, bool first_vertex = false); static void EndPrimitive(ShaderCode& out, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data, APIType ApiType, bool wireframe, bool pixel_lighting); ShaderCode GenerateGeometryShaderCode(APIType ApiType, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data) { ShaderCode out; // Non-uid template parameters will write to the dummy data (=> gets optimized out) const bool wireframe = host_config.wireframe; const bool pixel_lighting = g_ActiveConfig.bEnablePixelLighting; const bool msaa = host_config.msaa; const bool ssaa = host_config.ssaa; const bool stereo = host_config.stereo; const PrimitiveType primitive_type = static_cast<PrimitiveType>(uid_data->primitive_type); const unsigned primitive_type_index = static_cast<unsigned>(uid_data->primitive_type); const unsigned vertex_in = std::min(static_cast<unsigned>(primitive_type_index) + 1, 3u); unsigned vertex_out = primitive_type == PrimitiveType::TriangleStrip ? 3 : 4; const unsigned int layers = host_config.more_layers * 2 + (int)(stereo) + 1; if (wireframe) vertex_out++; if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { // Insert layout parameters if (host_config.backend_gs_instancing) { out.Write("layout(%s, invocations = %d) in;\n", primitives_ogl[primitive_type_index], layers); out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle", vertex_out); } else { out.Write("layout(%s) in;\n", primitives_ogl[primitive_type_index]); out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle", vertex_out * layers); } } out.Write("%s", s_lighting_struct); // uniforms if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) out.Write("UBO_BINDING(std140, 3) uniform GSBlock {\n"); else out.Write("cbuffer GSBlock {\n"); out.Write("\tfloat4 " I_STEREOPARAMS ";\n" "\tfloat4 " I_LINEPTPARAMS ";\n" "\tint4 " I_TEXOFFSET ";\n" "};\n"); out.Write("struct VS_OUTPUT {\n"); GenerateVSOutputMembers<ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting, ""); out.Write("};\n"); if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { if (host_config.backend_gs_instancing) out.Write("#define InstanceID gl_InvocationID\n"); out.Write("VARYING_LOCATION(0) in VertexData {\n"); GenerateVSOutputMembers<ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting, GetInterpolationQualifier(msaa, ssaa, true, true)); out.Write("} vs[%d];\n", vertex_in); out.Write("VARYING_LOCATION(0) out VertexData {\n"); GenerateVSOutputMembers<ShaderCode>(out, ApiType, uid_data->numTexGens, pixel_lighting, GetInterpolationQualifier(msaa, ssaa, true, false)); if (stereo || host_config.more_layers) out.Write("\tflat int layer;\n"); out.Write("} ps;\n"); out.Write("void main()\n{\n"); } else // D3D { out.Write("struct VertexData {\n"); out.Write("\tVS_OUTPUT o;\n"); if (stereo || host_config.more_layers) out.Write("\tuint layer : SV_RenderTargetArrayIndex;\n"); out.Write("};\n"); if (host_config.backend_gs_instancing) { out.Write("[maxvertexcount(%d)]\n[instance(%d)]\n", vertex_out, layers); out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output, in uint " "InstanceID : SV_GSInstanceID)\n{\n", primitives_d3d[primitive_type_index], vertex_in, wireframe ? "Line" : "Triangle"); } else { out.Write("[maxvertexcount(%d)]\n", vertex_out * layers); out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output)\n{\n", primitives_d3d[primitive_type_index], vertex_in, wireframe ? "Line" : "Triangle"); } out.Write("\tVertexData ps;\n"); } if (primitive_type == PrimitiveType::Lines) { if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { out.Write("\tVS_OUTPUT start, end;\n"); AssignVSOutputMembers(out, "start", "vs[0]", uid_data->numTexGens, pixel_lighting); AssignVSOutputMembers(out, "end", "vs[1]", uid_data->numTexGens, pixel_lighting); } else { out.Write("\tVS_OUTPUT start = o[0];\n"); out.Write("\tVS_OUTPUT end = o[1];\n"); } // GameCube/Wii's line drawing algorithm is a little quirky. It does not // use the correct line caps. Instead, the line caps are vertical or // horizontal depending the slope of the line. out.Write("\tfloat2 offset;\n" "\tfloat2 to = abs(end.pos.xy / end.pos.w - start.pos.xy / start.pos.w);\n" // FIXME: What does real hardware do when line is at a 45-degree angle? // FIXME: Lines aren't drawn at the correct width. See Twilight Princess map. "\tif (" I_LINEPTPARAMS ".y * to.y > " I_LINEPTPARAMS ".x * to.x) {\n" // Line is more tall. Extend geometry left and right. // Lerp LineWidth/2 from [0..VpWidth] to [-1..1] "\t\toffset = float2(" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".x, 0);\n" "\t} else {\n" // Line is more wide. Extend geometry up and down. // Lerp LineWidth/2 from [0..VpHeight] to [1..-1] "\t\toffset = float2(0, -" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".y);\n" "\t}\n"); } else if (primitive_type == PrimitiveType::Points) { if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { out.Write("\tVS_OUTPUT center;\n"); AssignVSOutputMembers(out, "center", "vs[0]", uid_data->numTexGens, pixel_lighting); } else { out.Write("\tVS_OUTPUT center = o[0];\n"); } // Offset from center to upper right vertex // Lerp PointSize/2 from [0,0..VpWidth,VpHeight] to [-1,1..1,-1] out.Write("\tfloat2 offset = float2(" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".x, -" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".y) * center.pos.w;\n"); } if (stereo || host_config.more_layers) { // If the GPU supports invocation we don't need a for loop and can simply use the // invocation identifier to determine which layer we're rendering. if (host_config.backend_gs_instancing) out.Write("\tint eye = InstanceID;\n"); else out.Write("\tfor (int eye = 0; eye < %d; ++eye) {\n", layers); } if (wireframe) out.Write("\tVS_OUTPUT first;\n"); out.Write("\tfor (int i = 0; i < %d; ++i) {\n", vertex_in); if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) { out.Write("\tVS_OUTPUT f;\n"); AssignVSOutputMembers(out, "f", "vs[i]", uid_data->numTexGens, pixel_lighting); if (host_config.backend_depth_clamp && DriverDetails::HasBug(DriverDetails::BUG_BROKEN_CLIP_DISTANCE)) { // On certain GPUs we have to consume the clip distance from the vertex shader // or else the other vertex shader outputs will get corrupted. out.Write("\tf.clipDist0 = gl_in[i].gl_ClipDistance[0];\n"); out.Write("\tf.clipDist1 = gl_in[i].gl_ClipDistance[1];\n"); } } else { out.Write("\tVS_OUTPUT f = o[i];\n"); } if (host_config.vr) { // Select the output layer out.Write("\tps.layer = eye;\n"); if (ApiType == APIType::OpenGL) out.Write("\tgl_Layer = eye;\n"); // StereoParams[eye] = camera shift in game units * projection[0][0] // StereoParams[eye+2] = offaxis shift from Oculus projection[0][2] out.Write("\tf.clipPos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS "[eye+2] * f.clipPos.w;\n"); out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS "[eye+2] * f.pos.w;\n"); } else if (stereo || host_config.more_layers) { // Select the output layer out.Write("\tps.layer = eye;\n"); if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) out.Write("\tgl_Layer = eye;\n"); // For stereoscopy add a small horizontal offset in Normalized Device Coordinates proportional // to the depth of the vertex. We retrieve the depth value from the w-component of the projected // vertex which contains the negated z-component of the original vertex. // For negative parallax (out-of-screen effects) we subtract a convergence value from // the depth value. This results in objects at a distance smaller than the convergence // distance to seemingly appear in front of the screen. // This formula is based on page 13 of the "Nvidia 3D Vision Automatic, Best Practices Guide" out.Write("\tfloat hoffset = (eye == 0) ? " I_STEREOPARAMS ".x : " I_STEREOPARAMS ".y;\n"); out.Write("\tf.pos.x += hoffset * (f.pos.w - " I_STEREOPARAMS ".z);\n"); } if (primitive_type == PrimitiveType::Lines) { out.Write("\tVS_OUTPUT l = f;\n" "\tVS_OUTPUT r = f;\n"); out.Write("\tl.pos.xy -= offset * l.pos.w;\n" "\tr.pos.xy += offset * r.pos.w;\n"); out.Write("\tif (" I_TEXOFFSET "[2] != 0) {\n"); out.Write("\tfloat texOffset = 1.0 / float(" I_TEXOFFSET "[2]);\n"); for (unsigned int i = 0; i < uid_data->numTexGens; ++i) { out.Write("\tif (((" I_TEXOFFSET "[0] >> %d) & 0x1) != 0)\n", i); out.Write("\t\tr.tex%d.x += texOffset;\n", i); } out.Write("\t}\n"); EmitVertex(out, host_config, uid_data, "l", ApiType, wireframe, pixel_lighting, true); EmitVertex(out, host_config, uid_data, "r", ApiType, wireframe, pixel_lighting); } else if (primitive_type == PrimitiveType::Points) { out.Write("\tVS_OUTPUT ll = f;\n" "\tVS_OUTPUT lr = f;\n" "\tVS_OUTPUT ul = f;\n" "\tVS_OUTPUT ur = f;\n"); out.Write("\tll.pos.xy += float2(-1,-1) * offset;\n" "\tlr.pos.xy += float2(1,-1) * offset;\n" "\tul.pos.xy += float2(-1,1) * offset;\n" "\tur.pos.xy += offset;\n"); out.Write("\tif (" I_TEXOFFSET "[3] != 0) {\n"); out.Write("\tfloat2 texOffset = float2(1.0 / float(" I_TEXOFFSET "[3]), 1.0 / float(" I_TEXOFFSET "[3]));\n"); for (unsigned int i = 0; i < uid_data->numTexGens; ++i) { out.Write("\tif (((" I_TEXOFFSET "[1] >> %d) & 0x1) != 0) {\n", i); out.Write("\t\tul.tex%d.xy += float2(0,1) * texOffset;\n", i); out.Write("\t\tur.tex%d.xy += texOffset;\n", i); out.Write("\t\tlr.tex%d.xy += float2(1,0) * texOffset;\n", i); out.Write("\t}\n"); } out.Write("\t}\n"); EmitVertex(out, host_config, uid_data, "ll", ApiType, wireframe, pixel_lighting, true); EmitVertex(out, host_config, uid_data, "lr", ApiType, wireframe, pixel_lighting); EmitVertex(out, host_config, uid_data, "ul", ApiType, wireframe, pixel_lighting); EmitVertex(out, host_config, uid_data, "ur", ApiType, wireframe, pixel_lighting); } else { EmitVertex(out, host_config, uid_data, "f", ApiType, wireframe, pixel_lighting, true); } out.Write("\t}\n"); EndPrimitive(out, host_config, uid_data, ApiType, wireframe, pixel_lighting); if ((stereo || host_config.more_layers) && !host_config.backend_gs_instancing) out.Write("\t}\n"); out.Write("}\n"); return out; } static void EmitVertex(ShaderCode& out, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data, const char* vertex, APIType ApiType, bool wireframe, bool pixel_lighting, bool first_vertex) { if (wireframe && first_vertex) out.Write("\tif (i == 0) first = %s;\n", vertex); if (ApiType == APIType::OpenGL) { out.Write("\tgl_Position = %s.pos;\n", vertex); if (host_config.backend_depth_clamp) { out.Write("\tgl_ClipDistance[0] = %s.clipDist0;\n", vertex); out.Write("\tgl_ClipDistance[1] = %s.clipDist1;\n", vertex); } AssignVSOutputMembers(out, "ps", vertex, uid_data->numTexGens, pixel_lighting); } else if (ApiType == APIType::Vulkan) { // Vulkan NDC space has Y pointing down (right-handed NDC space). out.Write("\tgl_Position = %s.pos;\n", vertex); out.Write("\tgl_Position.y = -gl_Position.y;\n"); AssignVSOutputMembers(out, "ps", vertex, uid_data->numTexGens, pixel_lighting); } else { out.Write("\tps.o = %s;\n", vertex); } if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) out.Write("\tEmitVertex();\n"); else out.Write("\toutput.Append(ps);\n"); } static void EndPrimitive(ShaderCode& out, const ShaderHostConfig& host_config, const geometry_shader_uid_data* uid_data, APIType ApiType, bool wireframe, bool pixel_lighting) { if (wireframe) EmitVertex(out, host_config, uid_data, "first", ApiType, wireframe, pixel_lighting); if (ApiType == APIType::OpenGL || ApiType == APIType::Vulkan) out.Write("\tEndPrimitive();\n"); else out.Write("\toutput.RestartStrip();\n"); } void EnumerateGeometryShaderUids(const std::function<void(const GeometryShaderUid&)>& callback) { GeometryShaderUid uid; std::memset(&uid, 0, sizeof(uid)); const std::array<PrimitiveType, 3> primitive_lut = { {g_ActiveConfig.backend_info.bSupportsPrimitiveRestart ? PrimitiveType::TriangleStrip : PrimitiveType::Triangles, PrimitiveType::Lines, PrimitiveType::Points}}; for (PrimitiveType primitive : primitive_lut) { auto* guid = uid.GetUidData<geometry_shader_uid_data>(); guid->primitive_type = static_cast<u32>(primitive); for (u32 texgens = 0; texgens <= 8; texgens++) { guid->numTexGens = texgens; callback(uid); } } } template <class T> static T GenerateAvatarGeometryShader(PrimitiveType primitive_type, APIType ApiType, const ShaderHostConfig& host_config) { T out; const bool wireframe = host_config.wireframe; const bool pixel_lighting = g_ActiveConfig.bEnablePixelLighting; const bool stereo = host_config.stereo; // Non-uid template parameters will write to the dummy data (=> gets optimized out) geometry_shader_uid_data dummy_data; geometry_shader_uid_data* uid_data = out.template GetUidData<geometry_shader_uid_data>(); if (uid_data == nullptr) uid_data = &dummy_data; const unsigned primitive_type_index = static_cast<unsigned>(primitive_type); uid_data->primitive_type = primitive_type_index; const unsigned vertex_in = std::min(static_cast<unsigned>(primitive_type_index) + 1, 3u); unsigned vertex_out = primitive_type == PrimitiveType::TriangleStrip ? 3 : 4; const unsigned int layers = host_config.more_layers * 2 + host_config.stereo + 1; if (wireframe) vertex_out++; if (ApiType == APIType::OpenGL) { // Insert layout parameters if (host_config.backend_gs_instancing) { out.Write("layout(%s, invocations = %d) in;\n", primitives_ogl[primitive_type_index], layers); out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle", vertex_out); } else { out.Write("layout(%s) in;\n", primitives_ogl[primitive_type_index]); out.Write("layout(%s_strip, max_vertices = %d) out;\n", wireframe ? "line" : "triangle", vertex_out * layers); } } // uniforms if (ApiType == APIType::OpenGL) out.Write("layout(std140%s) uniform GSBlock {\n", g_ActiveConfig.backend_info.bSupportsBindingLayout ? ", binding = 3" : ""); else out.Write("cbuffer GSBlock {\n"); out.Write("\tfloat4 " I_STEREOPARAMS ";\n" "\tfloat4 " I_LINEPTPARAMS ";\n" "\tint4 " I_TEXOFFSET ";\n" "};\n"); uid_data->numTexGens = 1; const char* qualifier = ""; out.Write("struct VS_OUTPUT {\n"); DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION"); DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0); DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0); out.Write("};\n"); if (ApiType == APIType::OpenGL) { if (host_config.backend_gs_instancing) out.Write("#define InstanceID gl_InvocationID\n"); out.Write("in VertexData {\n"); qualifier = g_ActiveConfig.backend_info.bSupportsBindingLayout ? "centroid" : "centroid in"; DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION"); DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0); DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0); out.Write("} vs[%d];\n", vertex_in); out.Write("out VertexData {\n"); qualifier = g_ActiveConfig.backend_info.bSupportsBindingLayout ? "centroid" : "centroid out"; DefineOutputMember(out, ApiType, qualifier, "float4", "pos", -1, "POSITION"); DefineOutputMember(out, ApiType, qualifier, "float4", "colors_", 0, "COLOR", 0); DefineOutputMember(out, ApiType, qualifier, "float3", "tex", 0, "TEXCOORD", 0); if (stereo || host_config.more_layers) out.Write("\tflat int layer;\n"); out.Write("} ps;\n"); out.Write("void main()\n{\n"); } else // D3D { out.Write("struct VertexData {\n"); out.Write("\tVS_OUTPUT o;\n"); if (stereo || host_config.more_layers) out.Write("\tuint layer : SV_RenderTargetArrayIndex;\n"); out.Write("};\n"); if (host_config.backend_gs_instancing) { out.Write("[maxvertexcount(%d)]\n[instance(%d)]\n", vertex_out, layers); out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output, in uint " "InstanceID : SV_GSInstanceID)\n{\n", primitives_d3d[primitive_type_index], vertex_in, wireframe ? "Line" : "Triangle"); } else { out.Write("[maxvertexcount(%d)]\n", vertex_out * layers); out.Write("void main(%s VS_OUTPUT o[%d], inout %sStream<VertexData> output)\n{\n", primitives_d3d[primitive_type_index], vertex_in, wireframe ? "Line" : "Triangle"); } out.Write("\tVertexData ps;\n"); } if (primitive_type == PrimitiveType::Lines) { if (ApiType == APIType::OpenGL) { out.Write("\tVS_OUTPUT start, end;\n"); const char* a = "start"; const char* b = "vs[0]"; out.Write("\t%s.pos = %s.pos;\n", a, b); out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b); out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0); a = "end"; b = "vs[1]"; out.Write("\t%s.pos = %s.pos;\n", a, b); out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b); out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0); } else { out.Write("\tVS_OUTPUT start = o[0];\n"); out.Write("\tVS_OUTPUT end = o[1];\n"); } // GameCube/Wii's line drawing algorithm is a little quirky. It does not // use the correct line caps. Instead, the line caps are vertical or // horizontal depending the slope of the line. out.Write("\tfloat2 offset;\n" "\tfloat2 to = abs(end.pos.xy - start.pos.xy);\n" // FIXME: What does real hardware do when line is at a 45-degree angle? // FIXME: Lines aren't drawn at the correct width. See Twilight Princess map. "\tif (" I_LINEPTPARAMS ".y * to.y > " I_LINEPTPARAMS ".x * to.x) {\n" // Line is more tall. Extend geometry left and right. // Lerp LineWidth/2 from [0..VpWidth] to [-1..1] "\t\toffset = float2(" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".x, 0);\n" "\t} else {\n" // Line is more wide. Extend geometry up and down. // Lerp LineWidth/2 from [0..VpHeight] to [1..-1] "\t\toffset = float2(0, -" I_LINEPTPARAMS ".z / " I_LINEPTPARAMS ".y);\n" "\t}\n"); } else if (primitive_type == PrimitiveType::Points) { if (ApiType == APIType::OpenGL) { const char* a = "center"; const char* b = "vs[0]"; out.Write("\tVS_OUTPUT center;\n"); out.Write("\t%s.pos = %s.pos;\n", a, b); out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b); out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0); } else { out.Write("\tVS_OUTPUT center = o[0];\n"); } // Offset from center to upper right vertex // Lerp PointSize/2 from [0,0..VpWidth,VpHeight] to [-1,1..1,-1] out.Write("\tfloat2 offset = float2(" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".x, -" I_LINEPTPARAMS ".w / " I_LINEPTPARAMS ".y) * center.pos.w;\n"); } if (stereo || host_config.more_layers) { // If the GPU supports invocation we don't need a for loop and can simply use the // invocation identifier to determine which layer we're rendering. if (host_config.backend_gs_instancing) out.Write("\tint eye = InstanceID;\n"); else out.Write("\tfor (int eye = 0; eye < 2; ++eye) {\n"); } if (wireframe) out.Write("\tVS_OUTPUT first;\n"); out.Write("\tfor (int i = 0; i < %d; ++i) {\n", vertex_in); if (ApiType == APIType::OpenGL) { out.Write("\tVS_OUTPUT f;\n"); const char* a = "f"; const char* b = "vs[i]"; out.Write("\t%s.pos = %s.pos;\n", a, b); out.Write("\t%s.colors_0 = %s.colors_0;\n", a, b); out.Write("\t%s.tex%d = %s.tex%d;\n", a, 0, b, 0); } else { out.Write("\tVS_OUTPUT f = o[i];\n"); } if (host_config.vr) { // Select the output layer out.Write("\tps.layer = eye;\n"); if (ApiType == APIType::OpenGL) out.Write("\tgl_Layer = eye;\n"); // StereoParams[eye] = camera shift in game units * projection[0][0] // StereoParams[eye+2] = offaxis shift from Oculus projection[0][2] // out.Write("\tf.clipPos.x += " I_STEREOPARAMS"[eye] - " I_STEREOPARAMS"[eye+2] * // f.clipPos.w;\n"); out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] - " I_STEREOPARAMS "[eye+2] * f.pos.w;\n"); } else if (stereo || host_config.more_layers) { // Select the output layer out.Write("\tps.layer = eye;\n"); if (ApiType == APIType::OpenGL) out.Write("\tgl_Layer = eye;\n"); // For stereoscopy add a small horizontal offset in Normalized Device Coordinates proportional // to the depth of the vertex. We retrieve the depth value from the w-component of the projected // vertex which contains the negated z-component of the original vertex. // For negative parallax (out-of-screen effects) we subtract a convergence value from // the depth value. This results in objects at a distance smaller than the convergence // distance to seemingly appear in front of the screen. // This formula is based on page 13 of the "Nvidia 3D Vision Automatic, Best Practices Guide" // out.Write("\tf.clipPos.x += " I_STEREOPARAMS"[eye] * (f.clipPos.w - " // I_STEREOPARAMS"[2]);\n"); out.Write("\tf.pos.x += " I_STEREOPARAMS "[eye] * (f.pos.w - " I_STEREOPARAMS "[2]);\n"); } if (primitive_type == PrimitiveType::Lines) { out.Write("\tVS_OUTPUT l = f;\n" "\tVS_OUTPUT r = f;\n"); out.Write("\tl.pos.xy -= offset * l.pos.w;\n" "\tr.pos.xy += offset * r.pos.w;\n"); out.Write("\tif (" I_TEXOFFSET "[2] != 0) {\n"); out.Write("\tfloat texOffset = 1.0 / float(" I_TEXOFFSET "[2]);\n"); for (unsigned int i = 0; i < uid_data->numTexGens; ++i) { out.Write("\tif (((" I_TEXOFFSET "[0] >> %d) & 0x1) != 0)\n", i); out.Write("\t\tr.tex%d.x += texOffset;\n", i); } out.Write("\t}\n"); EmitVertex(out, host_config, uid_data, "l", ApiType, wireframe, pixel_lighting, true); EmitVertex(out, host_config, uid_data, "r", ApiType, wireframe, pixel_lighting); } else if (primitive_type == PrimitiveType::Points) { out.Write("\tVS_OUTPUT ll = f;\n" "\tVS_OUTPUT lr = f;\n" "\tVS_OUTPUT ul = f;\n" "\tVS_OUTPUT ur = f;\n"); out.Write("\tll.pos.xy += float2(-1,-1) * offset;\n" "\tlr.pos.xy += float2(1,-1) * offset;\n" "\tul.pos.xy += float2(-1,1) * offset;\n" "\tur.pos.xy += offset;\n"); out.Write("\tif (" I_TEXOFFSET "[3] != 0) {\n"); out.Write("\tfloat2 texOffset = float2(1.0 / float(" I_TEXOFFSET "[3]), 1.0 / float(" I_TEXOFFSET "[3]));\n"); for (unsigned int i = 0; i < 1; ++i) { out.Write("\tif (((" I_TEXOFFSET "[1] >> %d) & 0x1) != 0) {\n", i); out.Write("\t\tll.tex%d.xy += float2(0,1) * texOffset;\n", i); out.Write("\t\tlr.tex%d.xy += texOffset;\n", i); out.Write("\t\tur.tex%d.xy += float2(1,0) * texOffset;\n", i); out.Write("\t}\n"); } out.Write("\t}\n"); EmitVertex(out, host_config, uid_data, "ll", ApiType, wireframe, pixel_lighting, true); EmitVertex(out, host_config, uid_data, "lr", ApiType, wireframe, pixel_lighting); EmitVertex(out, host_config, uid_data, "ul", ApiType, wireframe, pixel_lighting); EmitVertex(out, host_config, uid_data, "ur", ApiType, wireframe, pixel_lighting); } else { EmitVertex(out, host_config, uid_data, "f", ApiType, wireframe, pixel_lighting, true); } out.Write("\t}\n"); EndPrimitive(out, host_config, uid_data, ApiType, wireframe, pixel_lighting); if ((stereo || host_config.more_layers) && !host_config.backend_gs_instancing) out.Write("\t}\n"); out.Write("}\n"); return out; } ShaderCode GenerateAvatarGeometryShaderCode(PrimitiveType primitive_type, APIType ApiType, const ShaderHostConfig& host_config) { return GenerateAvatarGeometryShader<ShaderCode>(primitive_type, ApiType, host_config); }
Java
# lastDate A minimal modular date picker with different calendar support
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CryptoMethods")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP")] [assembly: AssemblyProduct("CryptoMethods")] [assembly: AssemblyCopyright("Copyright © HP 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6eb617c1-11a2-4074-91bc-b4687444cebf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
--[[ # # @hunter18k # @Dragon_Born # ]] local access_token = "3084249803.280d5d7.999310365c8248f8948ee0f6929c2f02" -- your api key local function instagramUser(msg, query) local receiver = get_receiver(msg) local url = "https://api.instagram.com/v1/users/search?q="..URL.escape(query).."&access_token="..access_token local jstr, res = https.request(url) if res ~= 200 then return "No Connection" end local jdat = json:decode(jstr) if #jdat.data == 0 then send_msg(receiver,"#Error\nUsername not found",ok_cb,false) end if jdat.meta.error_message then send_msg(receiver,"#Error\n"..jdat.meta.error_message,ok_cb,false) end local id = jdat.data[1].id local gurl = "https://api.instagram.com/v1/users/"..id.."/?access_token="..access_token local ress = https.request(gurl) local user = json:decode(ress) if user.meta.error_message then send_msg(receiver,"#Error\n"..user.meta.error_message,ok_cb,false) end local text = '' if user.data.bio ~= '' then text = text.."Username: "..user.data.username:upper().."\n\n" else text = text.."المعرف : "..user.data.username:upper().."\n" end if user.data.bio ~= '' then text = text..user.data.bio.."\n\n" end if user.data.full_name ~= '' then text = text.."الاسم : "..user.data.full_name.."\n" end text = text.."النغمات : "..user.data.counts.media.."\n" text = text.."متابع لهم : "..user.data.counts.follows.."\n" text = text.."متابعينك : "..user.data.counts.followed_by.."\n" if user.data.website ~= '' then text = text.."Website: "..user.data.website.."\n" end text = text.."\n" local file_path = download_to_file(user.data.profile_picture,"insta.png") -- disable this line if you want to send profile photo as sticker --local file_path = download_to_file(user.data.profile_picture,"insta.webp") -- enable this line if you want to send profile photo as sticker local cb_extra = {file_path=file_path} local mime_type = mimetype.get_content_type_no_sub(ext) send_photo(receiver, file_path, rmtmp_cb, cb_extra) -- disable this line if you want to send profile photo as sticker --send_document(receiver, file_path, rmtmp_cb, cb_extra) -- enable this line if you want to send profile photo as sticker send_msg(receiver,text,ok_cb,false) end local function instagramMedia(msg, query) local receiver = get_receiver(msg) local url = "https://api.instagram.com/v1/media/shortcode/"..URL.escape(query).."?access_token="..access_token local jstr, res = https.request(url) if res ~= 200 then return "No Connection" end local jdat = json:decode(jstr) if jdat.meta.error_message then send_msg(receiver,"#Error\n"..jdat.meta.error_type.."\n"..jdat.meta.error_message,ok_cb,false) end local text = '' local data = '' if jdat.data.caption then data = jdat.data.caption text = text.."Username: "..data.from.username:upper().."\n\n" text = text..data.from.full_name.."\n\n" text = text..data.text.."\n\n" text = text.."Like Count: "..jdat.data.likes.count.."\n" else text = text.."Username: "..jdat.data.user.username:upper().."\n" text = text.."Name: "..jdat.data.user.full_name.."\n" text = text.."Like Count: "..jdat.data.likes.count.."\n" end text = text.."\n" send_msg(receiver,text,ok_cb,false) end local function run(msg, matches) if matches[1] == "insta" and not matches[3] then return instagramUser(msg,matches[2]) end if matches[1] == "insta" and matches[3] then local media = matches[3] if string.match(media , '/') then media = media:gsub("/", "") end return instagramMedia(msg,media) end end return { patterns = { "^([Ii]nsta) ([Hh]ttps://www.instagram.com/p/)([^%s]+)$", "^([Ii]nsta) ([Hh]ttps://instagram.com/p/)([^%s]+)$", "^([Ii]nsta) ([Hh]ttp://www.instagram.com/p/)([^%s]+)$", "^([Ii]nsta) ([Hh]ttp://instagram.com/p/)([^%s]+)$", "^([Ii]nsta) ([^%s]+)$", }, run = run }
Java
/* * Copyright (c) 2013, 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. * * 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. */ /** * @test * @summary Spliterator traversing and splitting tests * @library ../stream/bootlib * @build java.base/java.util.SpliteratorOfIntDataBuilder * java.base/java.util.SpliteratorTestHelper * @run testng SpliteratorTraversingAndSplittingTest * @bug 8020016 8071477 8072784 8169838 */ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.nio.CharBuffer; import java.util.AbstractCollection; import java.util.AbstractList; import java.util.AbstractSet; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.PriorityQueue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedSet; import java.util.Spliterator; import java.util.SpliteratorOfIntDataBuilder; import java.util.SpliteratorTestHelper; import java.util.Spliterators; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import java.util.WeakHashMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.Function; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; public class SpliteratorTraversingAndSplittingTest extends SpliteratorTestHelper { private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 42); private static final String LOW = new String(new char[] {Character.MIN_LOW_SURROGATE}); private static final String HIGH = new String(new char[] {Character.MIN_HIGH_SURROGATE}); private static final String HIGH_LOW = HIGH + LOW; private static final String CHAR_HIGH_LOW = "A" + HIGH_LOW; private static final String HIGH_LOW_CHAR = HIGH_LOW + "A"; private static final String CHAR_HIGH_LOW_CHAR = "A" + HIGH_LOW + "A"; private static final List<String> STRINGS = generateTestStrings(); private static List<String> generateTestStrings() { List<String> strings = new ArrayList<>(); for (int n : Arrays.asList(1, 2, 3, 16, 17)) { strings.add(generate("A", n)); strings.add(generate(LOW, n)); strings.add(generate(HIGH, n)); strings.add(generate(HIGH_LOW, n)); strings.add(generate(CHAR_HIGH_LOW, n)); strings.add(generate(HIGH_LOW_CHAR, n)); strings.add(generate(CHAR_HIGH_LOW_CHAR, n)); } return strings; } private static String generate(String s, int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(s); } return sb.toString(); } private static class SpliteratorDataBuilder<T> { List<Object[]> data; List<T> exp; Map<T, T> mExp; SpliteratorDataBuilder(List<Object[]> data, List<T> exp) { this.data = data; this.exp = exp; this.mExp = createMap(exp); } Map<T, T> createMap(List<T> l) { Map<T, T> m = new LinkedHashMap<>(); for (T t : l) { m.put(t, t); } return m; } void add(String description, Collection<?> expected, Supplier<Spliterator<?>> s) { description = joiner(description).toString(); data.add(new Object[]{description, expected, s}); } void add(String description, Supplier<Spliterator<?>> s) { add(description, exp, s); } void addCollection(Function<Collection<T>, ? extends Collection<T>> c) { add("new " + c.apply(Collections.<T>emptyList()).getClass().getName() + ".spliterator()", () -> c.apply(exp).spliterator()); } void addList(Function<Collection<T>, ? extends List<T>> l) { addCollection(l); addCollection(l.andThen(list -> list.subList(0, list.size()))); } void addMap(Function<Map<T, T>, ? extends Map<T, T>> m) { String description = "new " + m.apply(Collections.<T, T>emptyMap()).getClass().getName(); addMap(m, description); } void addMap(Function<Map<T, T>, ? extends Map<T, T>> m, String description) { add(description + ".keySet().spliterator()", () -> m.apply(mExp).keySet().spliterator()); add(description + ".values().spliterator()", () -> m.apply(mExp).values().spliterator()); add(description + ".entrySet().spliterator()", mExp.entrySet(), () -> m.apply(mExp).entrySet().spliterator()); } StringBuilder joiner(String description) { return new StringBuilder(description). append(" {"). append("size=").append(exp.size()). append("}"); } } static Object[][] spliteratorDataProvider; @DataProvider(name = "Spliterator<Integer>") public static Object[][] spliteratorDataProvider() { if (spliteratorDataProvider != null) { return spliteratorDataProvider; } List<Object[]> data = new ArrayList<>(); for (int size : SIZES) { List<Integer> exp = listIntRange(size); SpliteratorDataBuilder<Integer> db = new SpliteratorDataBuilder<>(data, exp); // Direct spliterator methods db.add("Spliterators.spliterator(Collection, ...)", () -> Spliterators.spliterator(exp, 0)); db.add("Spliterators.spliterator(Iterator, ...)", () -> Spliterators.spliterator(exp.iterator(), exp.size(), 0)); db.add("Spliterators.spliteratorUnknownSize(Iterator, ...)", () -> Spliterators.spliteratorUnknownSize(exp.iterator(), 0)); db.add("Spliterators.spliterator(Spliterators.iteratorFromSpliterator(Spliterator ), ...)", () -> Spliterators.spliterator(Spliterators.iterator(exp.spliterator()), exp.size(), 0)); db.add("Spliterators.spliterator(T[], ...)", () -> Spliterators.spliterator(exp.toArray(new Integer[0]), 0)); db.add("Arrays.spliterator(T[], ...)", () -> Arrays.spliterator(exp.toArray(new Integer[0]))); class SpliteratorFromIterator extends Spliterators.AbstractSpliterator<Integer> { Iterator<Integer> it; SpliteratorFromIterator(Iterator<Integer> it, long est) { super(est, Spliterator.SIZED); this.it = it; } @Override public boolean tryAdvance(Consumer<? super Integer> action) { if (action == null) throw new NullPointerException(); if (it.hasNext()) { action.accept(it.next()); return true; } else { return false; } } } db.add("new Spliterators.AbstractSpliterator()", () -> new SpliteratorFromIterator(exp.iterator(), exp.size())); // Collections // default method implementations class AbstractCollectionImpl extends AbstractCollection<Integer> { Collection<Integer> c; AbstractCollectionImpl(Collection<Integer> c) { this.c = c; } @Override public Iterator<Integer> iterator() { return c.iterator(); } @Override public int size() { return c.size(); } } db.addCollection( c -> new AbstractCollectionImpl(c)); class AbstractListImpl extends AbstractList<Integer> { List<Integer> l; AbstractListImpl(Collection<Integer> c) { this.l = new ArrayList<>(c); } @Override public Integer get(int index) { return l.get(index); } @Override public int size() { return l.size(); } } db.addCollection( c -> new AbstractListImpl(c)); class AbstractSetImpl extends AbstractSet<Integer> { Set<Integer> s; AbstractSetImpl(Collection<Integer> c) { this.s = new HashSet<>(c); } @Override public Iterator<Integer> iterator() { return s.iterator(); } @Override public int size() { return s.size(); } } db.addCollection( c -> new AbstractSetImpl(c)); class AbstractSortedSetImpl extends AbstractSet<Integer> implements SortedSet<Integer> { SortedSet<Integer> s; AbstractSortedSetImpl(Collection<Integer> c) { this.s = new TreeSet<>(c); } @Override public Iterator<Integer> iterator() { return s.iterator(); } @Override public int size() { return s.size(); } @Override public Comparator<? super Integer> comparator() { return s.comparator(); } @Override public SortedSet<Integer> subSet(Integer fromElement, Integer toElement) { return s.subSet(fromElement, toElement); } @Override public SortedSet<Integer> headSet(Integer toElement) { return s.headSet(toElement); } @Override public SortedSet<Integer> tailSet(Integer fromElement) { return s.tailSet(fromElement); } @Override public Integer first() { return s.first(); } @Override public Integer last() { return s.last(); } @Override public Spliterator<Integer> spliterator() { return SortedSet.super.spliterator(); } } db.addCollection( c -> new AbstractSortedSetImpl(c)); class IterableWrapper implements Iterable<Integer> { final Iterable<Integer> it; IterableWrapper(Iterable<Integer> it) { this.it = it; } @Override public Iterator<Integer> iterator() { return it.iterator(); } } db.add("new Iterable.spliterator()", () -> new IterableWrapper(exp).spliterator()); // db.add("Arrays.asList().spliterator()", () -> Spliterators.spliterator(Arrays.asList(exp.toArray(new Integer[0])), 0)); db.addList(ArrayList::new); db.addList(LinkedList::new); db.addList(Vector::new); class AbstractRandomAccessListImpl extends AbstractList<Integer> implements RandomAccess { Integer[] ia; AbstractRandomAccessListImpl(Collection<Integer> c) { this.ia = c.toArray(new Integer[c.size()]); } @Override public Integer get(int index) { return ia[index]; } @Override public int size() { return ia.length; } } db.addList(AbstractRandomAccessListImpl::new); class RandomAccessListImpl implements List<Integer>, RandomAccess { Integer[] ia; List<Integer> l; RandomAccessListImpl(Collection<Integer> c) { this.ia = c.toArray(new Integer[c.size()]); this.l = Arrays.asList(ia); } @Override public Integer get(int index) { return ia[index]; } @Override public Integer set(int index, Integer element) { throw new UnsupportedOperationException(); } @Override public void add(int index, Integer element) { throw new UnsupportedOperationException(); } @Override public Integer remove(int index) { throw new UnsupportedOperationException(); } @Override public int indexOf(Object o) { return l.indexOf(o); } @Override public int lastIndexOf(Object o) { return Arrays.asList(ia).lastIndexOf(o); } @Override public ListIterator<Integer> listIterator() { return l.listIterator(); } @Override public ListIterator<Integer> listIterator(int index) { return l.listIterator(index); } @Override public List<Integer> subList(int fromIndex, int toIndex) { return l.subList(fromIndex, toIndex); } @Override public int size() { return ia.length; } @Override public boolean isEmpty() { return size() != 0; } @Override public boolean contains(Object o) { return l.contains(o); } @Override public Iterator<Integer> iterator() { return l.iterator(); } @Override public Object[] toArray() { return l.toArray(); } @Override public <T> T[] toArray(T[] a) { return l.toArray(a); } @Override public boolean add(Integer integer) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> c) { return l.containsAll(c); } @Override public boolean addAll(Collection<? extends Integer> c) { throw new UnsupportedOperationException(); } @Override public boolean addAll(int index, Collection<? extends Integer> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } } db.addList(RandomAccessListImpl::new); db.addCollection(HashSet::new); db.addCollection(LinkedHashSet::new); db.addCollection(TreeSet::new); db.addCollection(c -> { Stack<Integer> s = new Stack<>(); s.addAll(c); return s;}); db.addCollection(PriorityQueue::new); db.addCollection(ArrayDeque::new); db.addCollection(ConcurrentSkipListSet::new); if (size > 0) { db.addCollection(c -> { ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(size); abq.addAll(c); return abq; }); } db.addCollection(PriorityBlockingQueue::new); db.addCollection(LinkedBlockingQueue::new); db.addCollection(LinkedTransferQueue::new); db.addCollection(ConcurrentLinkedQueue::new); db.addCollection(LinkedBlockingDeque::new); db.addCollection(CopyOnWriteArrayList::new); db.addCollection(CopyOnWriteArraySet::new); if (size == 0) { db.addCollection(c -> Collections.<Integer>emptySet()); db.addList(c -> Collections.<Integer>emptyList()); } else if (size == 1) { db.addCollection(c -> Collections.singleton(exp.get(0))); db.addCollection(c -> Collections.singletonList(exp.get(0))); } { Integer[] ai = new Integer[size]; Arrays.fill(ai, 1); db.add(String.format("Collections.nCopies(%d, 1)", exp.size()), Arrays.asList(ai), () -> Collections.nCopies(exp.size(), 1).spliterator()); } // Collections.synchronized/unmodifiable/checked wrappers db.addCollection(Collections::unmodifiableCollection); db.addCollection(c -> Collections.unmodifiableSet(new HashSet<>(c))); db.addCollection(c -> Collections.unmodifiableSortedSet(new TreeSet<>(c))); db.addList(c -> Collections.unmodifiableList(new ArrayList<>(c))); db.addMap(Collections::unmodifiableMap); db.addMap(m -> Collections.unmodifiableSortedMap(new TreeMap<>(m))); db.addCollection(Collections::synchronizedCollection); db.addCollection(c -> Collections.synchronizedSet(new HashSet<>(c))); db.addCollection(c -> Collections.synchronizedSortedSet(new TreeSet<>(c))); db.addList(c -> Collections.synchronizedList(new ArrayList<>(c))); db.addMap(Collections::synchronizedMap); db.addMap(m -> Collections.synchronizedSortedMap(new TreeMap<>(m))); db.addCollection(c -> Collections.checkedCollection(c, Integer.class)); db.addCollection(c -> Collections.checkedQueue(new ArrayDeque<>(c), Integer.class)); db.addCollection(c -> Collections.checkedSet(new HashSet<>(c), Integer.class)); db.addCollection(c -> Collections.checkedSortedSet(new TreeSet<>(c), Integer.class)); db.addList(c -> Collections.checkedList(new ArrayList<>(c), Integer.class)); db.addMap(c -> Collections.checkedMap(c, Integer.class, Integer.class)); db.addMap(m -> Collections.checkedSortedMap(new TreeMap<>(m), Integer.class, Integer.class)); // Maps db.addMap(HashMap::new); db.addMap(m -> { // Create a Map ensuring that for large sizes // buckets will contain 2 or more entries HashMap<Integer, Integer> cm = new HashMap<>(1, m.size() + 1); // Don't use putAll which inflates the table by // m.size() * loadFactor, thus creating a very sparse // map for 1000 entries defeating the purpose of this test, // in addition it will cause the split until null test to fail // because the number of valid splits is larger than the // threshold for (Map.Entry<Integer, Integer> e : m.entrySet()) cm.put(e.getKey(), e.getValue()); return cm; }, "new java.util.HashMap(1, size + 1)"); db.addMap(LinkedHashMap::new); db.addMap(IdentityHashMap::new); db.addMap(WeakHashMap::new); db.addMap(m -> { // Create a Map ensuring that for large sizes // buckets will be consist of 2 or more entries WeakHashMap<Integer, Integer> cm = new WeakHashMap<>(1, m.size() + 1); for (Map.Entry<Integer, Integer> e : m.entrySet()) cm.put(e.getKey(), e.getValue()); return cm; }, "new java.util.WeakHashMap(1, size + 1)"); // @@@ Descending maps etc db.addMap(TreeMap::new); db.addMap(ConcurrentHashMap::new); db.addMap(ConcurrentSkipListMap::new); if (size == 0) { db.addMap(m -> Collections.<Integer, Integer>emptyMap()); } else if (size == 1) { db.addMap(m -> Collections.singletonMap(exp.get(0), exp.get(0))); } } return spliteratorDataProvider = data.toArray(new Object[0][]); } private static List<Integer> listIntRange(int upTo) { List<Integer> exp = new ArrayList<>(); for (int i = 0; i < upTo; i++) exp.add(i); return Collections.unmodifiableList(exp); } @Test(dataProvider = "Spliterator<Integer>") public void testNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining(null)); executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance(null)); } @Test(dataProvider = "Spliterator<Integer>") public void testForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testForEach(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testTryAdvance(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testMixedTryAdvanceForEach(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testMixedTraverseAndSplit(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testSplitAfterFullTraversal(s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testSplitOnce(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testSplitSixDeep(exp, s, UnaryOperator.identity()); } @Test(dataProvider = "Spliterator<Integer>") public void testSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) { testSplitUntilNull(exp, s, UnaryOperator.identity()); } // private static class SpliteratorOfIntCharDataBuilder { List<Object[]> data; String s; List<Integer> expChars; List<Integer> expCodePoints; SpliteratorOfIntCharDataBuilder(List<Object[]> data, String s) { this.data = data; this.s = s; this.expChars = transform(s, false); this.expCodePoints = transform(s, true); } static List<Integer> transform(String s, boolean toCodePoints) { List<Integer> l = new ArrayList<>(); if (!toCodePoints) { for (int i = 0; i < s.length(); i++) { l.add((int) s.charAt(i)); } } else { for (int i = 0; i < s.length();) { char c1 = s.charAt(i++); int cp = c1; if (Character.isHighSurrogate(c1) && i < s.length()) { char c2 = s.charAt(i); if (Character.isLowSurrogate(c2)) { i++; cp = Character.toCodePoint(c1, c2); } } l.add(cp); } } return l; } void add(String description, Function<String, CharSequence> f) { description = description.replace("%s", s); { Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).chars().spliterator(); data.add(new Object[]{description + ".chars().spliterator()", expChars, supplier}); } { Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).codePoints().spliterator(); data.add(new Object[]{description + ".codePoints().spliterator()", expCodePoints, supplier}); } } } static Object[][] spliteratorOfIntDataProvider; @DataProvider(name = "Spliterator.OfInt") public static Object[][] spliteratorOfIntDataProvider() { if (spliteratorOfIntDataProvider != null) { return spliteratorOfIntDataProvider; } List<Object[]> data = new ArrayList<>(); for (int size : SIZES) { int exp[] = arrayIntRange(size); SpliteratorOfIntDataBuilder db = new SpliteratorOfIntDataBuilder(data, listIntRange(size)); db.add("Spliterators.spliterator(int[], ...)", () -> Spliterators.spliterator(exp, 0)); db.add("Arrays.spliterator(int[], ...)", () -> Arrays.spliterator(exp)); db.add("Spliterators.spliterator(PrimitiveIterator.OfInt, ...)", () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0)); db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfInt, ...)", () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0)); class IntSpliteratorFromArray extends Spliterators.AbstractIntSpliterator { int[] a; int index = 0; IntSpliteratorFromArray(int[] a) { super(a.length, Spliterator.SIZED); this.a = a; } @Override public boolean tryAdvance(IntConsumer action) { if (action == null) throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; } else { return false; } } } db.add("new Spliterators.AbstractIntAdvancingSpliterator()", () -> new IntSpliteratorFromArray(exp)); } // Class for testing default methods class CharSequenceImpl implements CharSequence { final String s; public CharSequenceImpl(String s) { this.s = s; } @Override public int length() { return s.length(); } @Override public char charAt(int index) { return s.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return s.subSequence(start, end); } @Override public String toString() { return s; } } for (String string : STRINGS) { SpliteratorOfIntCharDataBuilder cdb = new SpliteratorOfIntCharDataBuilder(data, string); cdb.add("\"%s\"", s -> s); cdb.add("new CharSequenceImpl(\"%s\")", CharSequenceImpl::new); cdb.add("new StringBuilder(\"%s\")", StringBuilder::new); cdb.add("new StringBuffer(\"%s\")", StringBuffer::new); cdb.add("CharBuffer.wrap(\"%s\".toCharArray())", s -> CharBuffer.wrap(s.toCharArray())); } return spliteratorOfIntDataProvider = data.toArray(new Object[0][]); } private static int[] arrayIntRange(int upTo) { int[] exp = new int[upTo]; for (int i = 0; i < upTo; i++) exp[i] = i; return exp; } @Test(dataProvider = "Spliterator.OfInt") public void testIntNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((IntConsumer) null)); executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((IntConsumer) null)); } @Test(dataProvider = "Spliterator.OfInt") public void testIntForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testForEach(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testTryAdvance(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testMixedTryAdvanceForEach(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testMixedTraverseAndSplit(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testSplitAfterFullTraversal(s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testSplitOnce(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testSplitSixDeep(exp, s, intBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfInt") public void testIntSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) { testSplitUntilNull(exp, s, intBoxingConsumer()); } // private static class SpliteratorOfLongDataBuilder { List<Object[]> data; List<Long> exp; SpliteratorOfLongDataBuilder(List<Object[]> data, List<Long> exp) { this.data = data; this.exp = exp; } void add(String description, List<Long> expected, Supplier<Spliterator.OfLong> s) { description = joiner(description).toString(); data.add(new Object[]{description, expected, s}); } void add(String description, Supplier<Spliterator.OfLong> s) { add(description, exp, s); } StringBuilder joiner(String description) { return new StringBuilder(description). append(" {"). append("size=").append(exp.size()). append("}"); } } static Object[][] spliteratorOfLongDataProvider; @DataProvider(name = "Spliterator.OfLong") public static Object[][] spliteratorOfLongDataProvider() { if (spliteratorOfLongDataProvider != null) { return spliteratorOfLongDataProvider; } List<Object[]> data = new ArrayList<>(); for (int size : SIZES) { long exp[] = arrayLongRange(size); SpliteratorOfLongDataBuilder db = new SpliteratorOfLongDataBuilder(data, listLongRange(size)); db.add("Spliterators.spliterator(long[], ...)", () -> Spliterators.spliterator(exp, 0)); db.add("Arrays.spliterator(long[], ...)", () -> Arrays.spliterator(exp)); db.add("Spliterators.spliterator(PrimitiveIterator.OfLong, ...)", () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0)); db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfLong, ...)", () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0)); class LongSpliteratorFromArray extends Spliterators.AbstractLongSpliterator { long[] a; int index = 0; LongSpliteratorFromArray(long[] a) { super(a.length, Spliterator.SIZED); this.a = a; } @Override public boolean tryAdvance(LongConsumer action) { if (action == null) throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; } else { return false; } } } db.add("new Spliterators.AbstractLongAdvancingSpliterator()", () -> new LongSpliteratorFromArray(exp)); } return spliteratorOfLongDataProvider = data.toArray(new Object[0][]); } private static List<Long> listLongRange(int upTo) { List<Long> exp = new ArrayList<>(); for (long i = 0; i < upTo; i++) exp.add(i); return Collections.unmodifiableList(exp); } private static long[] arrayLongRange(int upTo) { long[] exp = new long[upTo]; for (int i = 0; i < upTo; i++) exp[i] = i; return exp; } @Test(dataProvider = "Spliterator.OfLong") public void testLongNullPointerException(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((LongConsumer) null)); executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((LongConsumer) null)); } @Test(dataProvider = "Spliterator.OfLong") public void testLongForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testForEach(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongTryAdvance(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testTryAdvance(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongMixedTryAdvanceForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testMixedTryAdvanceForEach(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongMixedTraverseAndSplit(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testMixedTraverseAndSplit(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongSplitAfterFullTraversal(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testSplitAfterFullTraversal(s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongSplitOnce(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testSplitOnce(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongSplitSixDeep(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testSplitSixDeep(exp, s, longBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfLong") public void testLongSplitUntilNull(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) { testSplitUntilNull(exp, s, longBoxingConsumer()); } // private static class SpliteratorOfDoubleDataBuilder { List<Object[]> data; List<Double> exp; SpliteratorOfDoubleDataBuilder(List<Object[]> data, List<Double> exp) { this.data = data; this.exp = exp; } void add(String description, List<Double> expected, Supplier<Spliterator.OfDouble> s) { description = joiner(description).toString(); data.add(new Object[]{description, expected, s}); } void add(String description, Supplier<Spliterator.OfDouble> s) { add(description, exp, s); } StringBuilder joiner(String description) { return new StringBuilder(description). append(" {"). append("size=").append(exp.size()). append("}"); } } static Object[][] spliteratorOfDoubleDataProvider; @DataProvider(name = "Spliterator.OfDouble") public static Object[][] spliteratorOfDoubleDataProvider() { if (spliteratorOfDoubleDataProvider != null) { return spliteratorOfDoubleDataProvider; } List<Object[]> data = new ArrayList<>(); for (int size : SIZES) { double exp[] = arrayDoubleRange(size); SpliteratorOfDoubleDataBuilder db = new SpliteratorOfDoubleDataBuilder(data, listDoubleRange(size)); db.add("Spliterators.spliterator(double[], ...)", () -> Spliterators.spliterator(exp, 0)); db.add("Arrays.spliterator(double[], ...)", () -> Arrays.spliterator(exp)); db.add("Spliterators.spliterator(PrimitiveIterator.OfDouble, ...)", () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0)); db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfDouble, ...)", () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0)); class DoubleSpliteratorFromArray extends Spliterators.AbstractDoubleSpliterator { double[] a; int index = 0; DoubleSpliteratorFromArray(double[] a) { super(a.length, Spliterator.SIZED); this.a = a; } @Override public boolean tryAdvance(DoubleConsumer action) { if (action == null) throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; } else { return false; } } } db.add("new Spliterators.AbstractDoubleAdvancingSpliterator()", () -> new DoubleSpliteratorFromArray(exp)); } return spliteratorOfDoubleDataProvider = data.toArray(new Object[0][]); } private static List<Double> listDoubleRange(int upTo) { List<Double> exp = new ArrayList<>(); for (double i = 0; i < upTo; i++) exp.add(i); return Collections.unmodifiableList(exp); } private static double[] arrayDoubleRange(int upTo) { double[] exp = new double[upTo]; for (int i = 0; i < upTo; i++) exp[i] = i; return exp; } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleNullPointerException(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((DoubleConsumer) null)); executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((DoubleConsumer) null)); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testForEach(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleTryAdvance(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testTryAdvance(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleMixedTryAdvanceForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testMixedTryAdvanceForEach(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleMixedTraverseAndSplit(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testMixedTraverseAndSplit(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleSplitAfterFullTraversal(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testSplitAfterFullTraversal(s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleSplitOnce(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testSplitOnce(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleSplitSixDeep(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testSplitSixDeep(exp, s, doubleBoxingConsumer()); } @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleSplitUntilNull(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) { testSplitUntilNull(exp, s, doubleBoxingConsumer()); } }
Java
<template name="recipeContext"> <span class="menu-header"> Options <i class="pull-right icon icon-vert-dots"></i> </span> <div class="menu"> {{#each settings}} <label class="menu-row"> <input type="checkbox" data-key={{key}} checked="{{#if value}}checked{{/if}}" class="change-setting checkbox"> {{_ label}} </label> {{/each}} </div> </template>
Java
<!-- BEGINS HERO IMAGE --> <!-- build:remove --> <div class="hero"> <img class="img-responsive" src='images/two_col_sample_content/1.png' alt='This is a typical header image' /> </div> <!-- /build --> <t4 type="navigation" id="106" /> <!-- ENDS HERO IMAGE -->
Java
/* * The ManaPlus Client * Copyright (C) 2004-2009 The Mana World Development Team * Copyright (C) 2009-2010 The Mana Developers * Copyright (C) 2011-2018 The ManaPlus Developers * * This file is part of The ManaPlus Client. * * 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 * 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/>. */ #include "net/eathena/itemrecv.h" #include "actormanager.h" #include "itemcolormanager.h" #include "logger.h" #include "const/resources/item/cards.h" #include "net/messagein.h" #include "debug.h" extern int packetVersion; extern bool packets_zero; namespace EAthena { void ItemRecv::processItemDropped(Net::MessageIn &msg) { const BeingId id = msg.readBeingId("id"); const int itemId = msg.readItemId("item id"); ItemTypeT itemType = ItemType::Unknown; if (msg.getVersion() >= 20130000) itemType = static_cast<ItemTypeT>(msg.readInt16("type")); const Identified identified = fromInt( msg.readUInt8("identify"), Identified); const int x = msg.readInt16("x"); const int y = msg.readInt16("y"); const int subX = CAST_S32(msg.readInt8("subx")); const int subY = CAST_S32(msg.readInt8("suby")); const int amount = msg.readInt16("count"); if (packets_zero || packetVersion >= 20180418) { msg.readUInt8("show drop effect"); msg.readInt16("show effect mode"); } if (actorManager != nullptr) { actorManager->createItem(id, itemId, x, y, itemType, amount, 0, ItemColor_one, identified, Damaged_false, subX, subY, nullptr); } } void ItemRecv::processItemDropped2(Net::MessageIn &msg) { const BeingId id = msg.readBeingId("id"); const int itemId = msg.readInt16("item id"); // +++ need use int32 const ItemTypeT itemType = static_cast<ItemTypeT>(msg.readUInt8("type")); const Identified identified = fromInt( msg.readUInt8("identify"), Identified); const Damaged damaged = fromBool(msg.readUInt8("attribute"), Damaged); const uint8_t refine = msg.readUInt8("refine"); int cards[maxCards]; for (int f = 0; f < maxCards; f++) cards[f] = msg.readUInt16("card"); // ++ need use int32 const int x = msg.readInt16("x"); const int y = msg.readInt16("y"); const int amount = msg.readInt16("amount"); const int subX = CAST_S32(msg.readInt8("subx")); const int subY = CAST_S32(msg.readInt8("suby")); // +++ probably need add drop effect fields? if (actorManager != nullptr) { actorManager->createItem(id, itemId, x, y, itemType, amount, refine, ItemColorManager::getColorFromCards(&cards[0]), identified, damaged, subX, subY, &cards[0]); } } void ItemRecv::processItemMvpDropped(Net::MessageIn &msg) { UNIMPLEMENTEDPACKET; msg.readInt16("len"); msg.readUInt8("type"); msg.readItemId("item id"); msg.readUInt8("len"); msg.readString(24, "name"); msg.readUInt8("monster name len"); msg.readString(24, "monster name"); } void ItemRecv::processItemVisible(Net::MessageIn &msg) { const BeingId id = msg.readBeingId("item object id"); const int itemId = msg.readItemId("item id"); const Identified identified = fromInt( msg.readUInt8("identify"), Identified); const int x = msg.readInt16("x"); const int y = msg.readInt16("y"); const int amount = msg.readInt16("amount"); const int subX = CAST_S32(msg.readInt8("sub x")); const int subY = CAST_S32(msg.readInt8("sub y")); if (actorManager != nullptr) { actorManager->createItem(id, itemId, x, y, ItemType::Unknown, amount, 0, ItemColor_one, identified, Damaged_false, subX, subY, nullptr); } } void ItemRecv::processItemVisible2(Net::MessageIn &msg) { const BeingId id = msg.readBeingId("item object id"); const int itemId = msg.readInt16("item id"); // +++ need use int32 const ItemTypeT itemType = static_cast<ItemTypeT>( msg.readUInt8("type")); const Identified identified = fromInt( msg.readUInt8("identify"), Identified); const Damaged damaged = fromBool(msg.readUInt8("attribute"), Damaged); const uint8_t refine = msg.readUInt8("refine"); int cards[maxCards]; for (int f = 0; f < maxCards; f++) cards[f] = msg.readUInt16("card"); // +++ need use int32 const int x = msg.readInt16("x"); const int y = msg.readInt16("y"); const int amount = msg.readInt16("amount"); const int subX = CAST_S32(msg.readInt8("sub x")); const int subY = CAST_S32(msg.readInt8("sub y")); if (actorManager != nullptr) { actorManager->createItem(id, itemId, x, y, itemType, amount, refine, ItemColorManager::getColorFromCards(&cards[0]), identified, damaged, subX, subY, &cards[0]); } } } // namespace EAthena
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_07) on Tue Sep 12 14:14:15 CEST 2006 --> <TITLE> PTEventTestASubClass </TITLE> <META NAME="keywords" CONTENT="test.org.peertrust.event.PTEventTestASubClass class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="PTEventTestASubClass"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PTEventTestASubClass.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../test/org/peertrust/event/PTEventTestB.html" title="class in test.org.peertrust.event"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?test/org/peertrust/event/PTEventTestASubClass.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PTEventTestASubClass.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_org.peertrust.event.PTEvent">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> test.org.peertrust.event</FONT> <BR> Class PTEventTestASubClass</H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../org/peertrust/event/PTEvent.html" title="class in org.peertrust.event">org.peertrust.event.PTEvent</A> <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event">test.org.peertrust.event.PTEventTestA</A> <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>test.org.peertrust.event.PTEventTestASubClass</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>java.lang.Cloneable</DD> </DL> <HR> <DL> <DT><PRE>public class <B>PTEventTestASubClass</B><DT>extends <A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event">PTEventTestA</A></DL> </PRE> <P> $Id: PTEventTestASubClass.html,v 1.1 2006/09/20 15:25:16 jldecoi Exp $ <P> <P> <DL> <DT><B>Author:</B></DT> <DD>olmedilla</DD> </DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../test/org/peertrust/event/PTEventTestASubClass.html#PTEventTestASubClass(java.lang.Object)">PTEventTestASubClass</A></B>(java.lang.Object&nbsp;source)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.peertrust.event.PTEvent"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class org.peertrust.event.<A HREF="../../../../org/peertrust/event/PTEvent.html" title="class in org.peertrust.event">PTEvent</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../org/peertrust/event/PTEvent.html#getSource()">getSource</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="PTEventTestASubClass(java.lang.Object)"><!-- --></A><H3> PTEventTestASubClass</H3> <PRE> public <B>PTEventTestASubClass</B>(java.lang.Object&nbsp;source)</PRE> <DL> <DL> <DT><B>Parameters:</B><DD><CODE>source</CODE> - </DL> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PTEventTestASubClass.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../test/org/peertrust/event/PTEventTestA.html" title="class in test.org.peertrust.event"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../test/org/peertrust/event/PTEventTestB.html" title="class in test.org.peertrust.event"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?test/org/peertrust/event/PTEventTestASubClass.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PTEventTestASubClass.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_org.peertrust.event.PTEvent">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
/** * ownCloud Android client application * * @author Mario Danic * Copyright (C) 2017 Mario Danic * Copyright (C) 2012 Bartek Przybylski * Copyright (C) 2012-2016 ownCloud Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * 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, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.fragment; import android.animation.LayoutTransition; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.resources.files.SearchOperation; import com.owncloud.android.ui.ExtendedListView; import com.owncloud.android.ui.activity.FileDisplayActivity; import com.owncloud.android.ui.activity.FolderPickerActivity; import com.owncloud.android.ui.activity.OnEnforceableRefreshListener; import com.owncloud.android.ui.activity.UploadFilesActivity; import com.owncloud.android.ui.adapter.FileListListAdapter; import com.owncloud.android.ui.adapter.LocalFileListAdapter; import com.owncloud.android.ui.events.SearchEvent; import org.greenrobot.eventbus.EventBus; import org.parceler.Parcel; import java.util.ArrayList; import third_parties.in.srain.cube.GridViewWithHeaderAndFooter; import static android.content.res.Configuration.ORIENTATION_LANDSCAPE; public class ExtendedListFragment extends Fragment implements OnItemClickListener, OnEnforceableRefreshListener, SearchView.OnQueryTextListener { protected static final String TAG = ExtendedListFragment.class.getSimpleName(); protected static final String KEY_SAVED_LIST_POSITION = "SAVED_LIST_POSITION"; private static final String KEY_INDEXES = "INDEXES"; private static final String KEY_FIRST_POSITIONS = "FIRST_POSITIONS"; private static final String KEY_TOPS = "TOPS"; private static final String KEY_HEIGHT_CELL = "HEIGHT_CELL"; private static final String KEY_EMPTY_LIST_MESSAGE = "EMPTY_LIST_MESSAGE"; private static final String KEY_IS_GRID_VISIBLE = "IS_GRID_VISIBLE"; protected SwipeRefreshLayout mRefreshListLayout; private SwipeRefreshLayout mRefreshGridLayout; protected SwipeRefreshLayout mRefreshEmptyLayout; protected LinearLayout mEmptyListContainer; protected TextView mEmptyListMessage; protected TextView mEmptyListHeadline; protected ImageView mEmptyListIcon; protected ProgressBar mEmptyListProgress; private FloatingActionsMenu mFabMain; private FloatingActionButton mFabUpload; private FloatingActionButton mFabMkdir; private FloatingActionButton mFabUploadFromApp; // Save the state of the scroll in browsing private ArrayList<Integer> mIndexes; private ArrayList<Integer> mFirstPositions; private ArrayList<Integer> mTops; private int mHeightCell = 0; private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null; protected AbsListView mCurrentListView; private ExtendedListView mListView; private View mListFooterView; private GridViewWithHeaderAndFooter mGridView; private View mGridFooterView; private BaseAdapter mAdapter; protected SearchView searchView; private Handler handler = new Handler(); @Parcel public enum SearchType { NO_SEARCH, REGULAR_FILTER, FILE_SEARCH, FAVORITE_SEARCH, FAVORITE_SEARCH_FILTER, VIDEO_SEARCH, VIDEO_SEARCH_FILTER, PHOTO_SEARCH, PHOTOS_SEARCH_FILTER, RECENTLY_MODIFIED_SEARCH, RECENTLY_MODIFIED_SEARCH_FILTER, RECENTLY_ADDED_SEARCH, RECENTLY_ADDED_SEARCH_FILTER, // not a real filter, but nevertheless SHARED_FILTER } protected void setListAdapter(BaseAdapter listAdapter) { mAdapter = listAdapter; mCurrentListView.setAdapter(listAdapter); mCurrentListView.invalidateViews(); } protected AbsListView getListView() { return mCurrentListView; } public FloatingActionButton getFabUpload() { return mFabUpload; } public FloatingActionButton getFabUploadFromApp() { return mFabUploadFromApp; } public FloatingActionButton getFabMkdir() { return mFabMkdir; } public FloatingActionsMenu getFabMain() { return mFabMain; } public void switchToGridView() { if (!isGridEnabled()) { mListView.setAdapter(null); mRefreshListLayout.setVisibility(View.GONE); mRefreshGridLayout.setVisibility(View.VISIBLE); mCurrentListView = mGridView; setListAdapter(mAdapter); } } public void switchToListView() { if (isGridEnabled()) { mGridView.setAdapter(null); mRefreshGridLayout.setVisibility(View.GONE); mRefreshListLayout.setVisibility(View.VISIBLE); mCurrentListView = mListView; setListAdapter(mAdapter); } } public boolean isGridEnabled() { return (mCurrentListView != null && mCurrentListView.equals(mGridView)); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { final MenuItem item = menu.findItem(R.id.action_search); searchView = (SearchView) MenuItemCompat.getActionView(item); searchView.setOnQueryTextListener(this); final Handler handler = new Handler(); DisplayMetrics displaymetrics = new DisplayMetrics(); Activity activity; if ((activity = getActivity()) != null) { activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int width = displaymetrics.widthPixels; if (getResources().getConfiguration().orientation == ORIENTATION_LANDSCAPE) { searchView.setMaxWidth((int) (width * 0.4)); } else { if (activity instanceof FolderPickerActivity) { searchView.setMaxWidth((int) (width * 0.8)); } else { searchView.setMaxWidth((int) (width * 0.7)); } } } searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { if (hasFocus) { mFabMain.collapse(); } handler.postDelayed(new Runnable() { @Override public void run() { if (getActivity() != null && !(getActivity() instanceof FolderPickerActivity)) { setFabEnabled(!hasFocus); boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext())); if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) { BottomNavigationView bottomNavigationView = (BottomNavigationView) getActivity(). findViewById(R.id.bottom_navigation_view); if (hasFocus) { bottomNavigationView.setVisibility(View.GONE); } else { bottomNavigationView.setVisibility(View.VISIBLE); } } } } }, 100); } }); final View mSearchEditFrame = searchView .findViewById(android.support.v7.appcompat.R.id.search_edit_frame); ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { int oldVisibility = -1; @Override public void onGlobalLayout() { int currentVisibility = mSearchEditFrame.getVisibility(); if (currentVisibility != oldVisibility) { if (currentVisibility == View.VISIBLE) { setEmptyListMessage(SearchType.REGULAR_FILTER); } else { setEmptyListMessage(SearchType.NO_SEARCH); } oldVisibility = currentVisibility; } } }); LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar); searchBar.setLayoutTransition(new LayoutTransition()); } public boolean onQueryTextChange(final String query) { if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT) instanceof ExtendedListFragment){ performSearch(query, false); return true; } else { return false; } } @Override public boolean onQueryTextSubmit(String query) { if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT) instanceof ExtendedListFragment){ performSearch(query, true); return true; } else { return false; } } private void performSearch(final String query, boolean isSubmit) { handler.removeCallbacksAndMessages(null); if (!TextUtils.isEmpty(query)) { int delay = 500; if (isSubmit) { delay = 0; } if (mAdapter != null && mAdapter instanceof FileListListAdapter) { handler.postDelayed(new Runnable() { @Override public void run() { if (AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext()))) { EventBus.getDefault().post(new SearchEvent(query, SearchOperation.SearchType.FILE_SEARCH, SearchEvent.UnsetType.NO_UNSET)); } else { FileListListAdapter fileListListAdapter = (FileListListAdapter) mAdapter; fileListListAdapter.getFilter().filter(query); } } }, delay); } else if (mAdapter != null && mAdapter instanceof LocalFileListAdapter) { handler.postDelayed(new Runnable() { @Override public void run() { LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter; localFileListAdapter.filter(query); } }, delay); } if (searchView != null && delay == 0) { searchView.clearFocus(); } } else { Activity activity; if ((activity = getActivity()) != null) { if (activity instanceof FileDisplayActivity) { ((FileDisplayActivity) activity).refreshListOfFilesFragment(true); } else if (activity instanceof UploadFilesActivity) { LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter; localFileListAdapter.filter(query); } else if (activity instanceof FolderPickerActivity) { ((FolderPickerActivity) activity).refreshListOfFilesFragment(true); } } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log_OC.d(TAG, "onCreateView"); View v = inflater.inflate(R.layout.list_fragment, null); setupEmptyList(v); mListView = (ExtendedListView) (v.findViewById(R.id.list_root)); mListView.setOnItemClickListener(this); mListFooterView = inflater.inflate(R.layout.list_footer, null, false); mGridView = (GridViewWithHeaderAndFooter) (v.findViewById(R.id.grid_root)); mGridView.setNumColumns(GridView.AUTO_FIT); mGridView.setOnItemClickListener(this); mGridFooterView = inflater.inflate(R.layout.list_footer, null, false); // Pull-down to refresh layout mRefreshListLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_list); mRefreshGridLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_grid); mRefreshEmptyLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_empty); onCreateSwipeToRefresh(mRefreshListLayout); onCreateSwipeToRefresh(mRefreshGridLayout); onCreateSwipeToRefresh(mRefreshEmptyLayout); mListView.setEmptyView(mRefreshEmptyLayout); mGridView.setEmptyView(mRefreshEmptyLayout); mFabMain = (FloatingActionsMenu) v.findViewById(R.id.fab_main); mFabUpload = (FloatingActionButton) v.findViewById(R.id.fab_upload); mFabMkdir = (FloatingActionButton) v.findViewById(R.id.fab_mkdir); mFabUploadFromApp = (FloatingActionButton) v.findViewById(R.id.fab_upload_from_app); boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext())); if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) { RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFabMain.getLayoutParams(); final float scale = v.getResources().getDisplayMetrics().density; BottomNavigationView bottomNavigationView = (BottomNavigationView) v.findViewById(R.id.bottom_navigation_view); // convert the DP into pixel int pixel = (int) (32 * scale + 0.5f); layoutParams.setMargins(0, 0, pixel / 2, bottomNavigationView.getMeasuredHeight() + pixel * 2); } mCurrentListView = mListView; // list by default if (savedInstanceState != null) { if (savedInstanceState.getBoolean(KEY_IS_GRID_VISIBLE, false)) { switchToGridView(); } int referencePosition = savedInstanceState.getInt(KEY_SAVED_LIST_POSITION); if (isGridEnabled()) { Log_OC.v(TAG, "Setting grid position " + referencePosition); mGridView.setSelection(referencePosition); } else { Log_OC.v(TAG, "Setting and centering around list position " + referencePosition); mListView.setAndCenterSelection(referencePosition); } } return v; } protected void setupEmptyList(View view) { mEmptyListContainer = (LinearLayout) view.findViewById(R.id.empty_list_view); mEmptyListMessage = (TextView) view.findViewById(R.id.empty_list_view_text); mEmptyListHeadline = (TextView) view.findViewById(R.id.empty_list_view_headline); mEmptyListIcon = (ImageView) view.findViewById(R.id.empty_list_icon); mEmptyListProgress = (ProgressBar) view.findViewById(R.id.empty_list_progress); } /** * {@inheritDoc} */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { mIndexes = savedInstanceState.getIntegerArrayList(KEY_INDEXES); mFirstPositions = savedInstanceState.getIntegerArrayList(KEY_FIRST_POSITIONS); mTops = savedInstanceState.getIntegerArrayList(KEY_TOPS); mHeightCell = savedInstanceState.getInt(KEY_HEIGHT_CELL); setMessageForEmptyList(savedInstanceState.getString(KEY_EMPTY_LIST_MESSAGE)); } else { mIndexes = new ArrayList<>(); mFirstPositions = new ArrayList<>(); mTops = new ArrayList<>(); mHeightCell = 0; } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); Log_OC.d(TAG, "onSaveInstanceState()"); savedInstanceState.putBoolean(KEY_IS_GRID_VISIBLE, isGridEnabled()); savedInstanceState.putInt(KEY_SAVED_LIST_POSITION, getReferencePosition()); savedInstanceState.putIntegerArrayList(KEY_INDEXES, mIndexes); savedInstanceState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions); savedInstanceState.putIntegerArrayList(KEY_TOPS, mTops); savedInstanceState.putInt(KEY_HEIGHT_CELL, mHeightCell); savedInstanceState.putString(KEY_EMPTY_LIST_MESSAGE, getEmptyViewText()); } /** * Calculates the position of the item that will be used as a reference to * reposition the visible items in the list when the device is turned to * other position. * * The current policy is take as a reference the visible item in the center * of the screen. * * @return The position in the list of the visible item in the center of the * screen. */ protected int getReferencePosition() { if (mCurrentListView != null) { return (mCurrentListView.getFirstVisiblePosition() + mCurrentListView.getLastVisiblePosition()) / 2; } else { return 0; } } /* * Restore index and position */ protected void restoreIndexAndTopPosition() { if (mIndexes.size() > 0) { // needs to be checked; not every browse-up had a browse-down before int index = mIndexes.remove(mIndexes.size() - 1); final int firstPosition = mFirstPositions.remove(mFirstPositions.size() - 1); int top = mTops.remove(mTops.size() - 1); Log_OC.v(TAG, "Setting selection to position: " + firstPosition + "; top: " + top + "; index: " + index); if (mCurrentListView != null && mCurrentListView.equals(mListView)) { if (mHeightCell * index <= mListView.getHeight()) { mListView.setSelectionFromTop(firstPosition, top); } else { mListView.setSelectionFromTop(index, 0); } } else { if (mHeightCell * index <= mGridView.getHeight()) { mGridView.setSelection(firstPosition); //mGridView.smoothScrollToPosition(firstPosition); } else { mGridView.setSelection(index); //mGridView.smoothScrollToPosition(index); } } } } /* * Save index and top position */ protected void saveIndexAndTopPosition(int index) { mIndexes.add(index); int firstPosition = mCurrentListView.getFirstVisiblePosition(); mFirstPositions.add(firstPosition); View view = mCurrentListView.getChildAt(0); int top = (view == null) ? 0 : view.getTop(); mTops.add(top); // Save the height of a cell mHeightCell = (view == null || mHeightCell != 0) ? mHeightCell : view.getHeight(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // to be @overriden } @Override public void onRefresh() { if (searchView != null) { searchView.onActionViewCollapsed(); Activity activity; if ((activity = getActivity()) != null && activity instanceof FileDisplayActivity) { FileDisplayActivity fileDisplayActivity = (FileDisplayActivity) activity; fileDisplayActivity.setDrawerIndicatorEnabled(fileDisplayActivity.isDrawerIndicatorAvailable()); } } mRefreshListLayout.setRefreshing(false); mRefreshGridLayout.setRefreshing(false); mRefreshEmptyLayout.setRefreshing(false); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } public void setOnRefreshListener(OnEnforceableRefreshListener listener) { mOnRefreshListener = listener; } /** * Disables swipe gesture. * * Sets the 'enabled' state of the refresh layouts contained in the fragment. * * When 'false' is set, prevents user gestures but keeps the option to refresh programatically, * * @param enabled Desired state for capturing swipe gesture. */ public void setSwipeEnabled(boolean enabled) { mRefreshListLayout.setEnabled(enabled); mRefreshGridLayout.setEnabled(enabled); mRefreshEmptyLayout.setEnabled(enabled); } /** * Sets the 'visibility' state of the FAB contained in the fragment. * * When 'false' is set, FAB visibility is set to View.GONE programmatically, * * @param enabled Desired visibility for the FAB. */ public void setFabEnabled(boolean enabled) { if (enabled) { mFabMain.setVisibility(View.VISIBLE); } else { mFabMain.setVisibility(View.GONE); } } /** * Set message for empty list view. */ public void setMessageForEmptyList(String message) { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListMessage.setText(message); } } /** * displays an empty list information with a headline, a message and an icon. * * @param headline the headline * @param message the message * @param icon the icon to be shown */ public void setMessageForEmptyList(@StringRes final int headline, @StringRes final int message, @DrawableRes final int icon) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListHeadline.setText(headline); mEmptyListMessage.setText(message); mEmptyListIcon.setImageResource(icon); mEmptyListIcon.setVisibility(View.VISIBLE); mEmptyListProgress.setVisibility(View.GONE); } } }); } public void setEmptyListMessage(final SearchType searchType) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (searchType == SearchType.NO_SEARCH) { setMessageForEmptyList( R.string.file_list_empty_headline, R.string.file_list_empty, R.drawable.ic_list_empty_folder ); } else if (searchType == SearchType.FILE_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty, R.drawable.ic_search_light_grey); } else if (searchType == SearchType.FAVORITE_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_favorite_headline, R.string.file_list_empty_favorites_filter_list, R.drawable.ic_star_light_grey); } else if (searchType == SearchType.VIDEO_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos, R.string.file_list_empty_text_videos, R.drawable.ic_list_empty_video); } else if (searchType == SearchType.PHOTO_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos, R.string.file_list_empty_text_photos, R.drawable.ic_list_empty_image); } else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_modified, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.RECENTLY_ADDED_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_added, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.REGULAR_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_search, R.string.file_list_empty_search, R.drawable.ic_search_light_grey); } else if (searchType == SearchType.FAVORITE_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_favorites_filter, R.drawable.ic_star_light_grey); } else if (searchType == SearchType.VIDEO_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos, R.string.file_list_empty_text_videos_filter, R.drawable.ic_list_empty_video); } else if (searchType == SearchType.PHOTOS_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos, R.string.file_list_empty_text_photos_filter, R.drawable.ic_list_empty_image); } else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_modified_filter, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.RECENTLY_ADDED_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_added_filter, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.SHARED_FILTER) { setMessageForEmptyList(R.string.file_list_empty_shared_headline, R.string.file_list_empty_shared, R.drawable.ic_list_empty_shared); } } }); } /** * Set message for empty list view. */ public void setEmptyListLoadingMessage() { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListHeadline.setText(R.string.file_list_loading); mEmptyListMessage.setText(""); mEmptyListIcon.setVisibility(View.GONE); mEmptyListProgress.setVisibility(View.VISIBLE); } } }); } /** * Get the text of EmptyListMessage TextView. * * @return String empty text view text-value */ public String getEmptyViewText() { return (mEmptyListContainer != null && mEmptyListMessage != null) ? mEmptyListMessage.getText().toString() : ""; } protected void onCreateSwipeToRefresh(SwipeRefreshLayout refreshLayout) { // Colors in animations refreshLayout.setColorSchemeResources(R.color.color_accent, R.color.primary, R.color.primary_dark); refreshLayout.setOnRefreshListener(this); } @Override public void onRefresh(boolean ignoreETag) { mRefreshListLayout.setRefreshing(false); mRefreshGridLayout.setRefreshing(false); mRefreshEmptyLayout.setRefreshing(false); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } protected void setChoiceMode(int choiceMode) { mListView.setChoiceMode(choiceMode); mGridView.setChoiceMode(choiceMode); } protected void setMultiChoiceModeListener(AbsListView.MultiChoiceModeListener listener) { mListView.setMultiChoiceModeListener(listener); mGridView.setMultiChoiceModeListener(listener); } /** * TODO doc * To be called before setAdapter, or GridViewWithHeaderAndFooter will throw an exception * * @param enabled flag if footer should be shown/calculated */ protected void setFooterEnabled(boolean enabled) { if (enabled) { if (mGridView.getFooterViewCount() == 0 && mGridView.isCorrectAdapter()) { if (mGridFooterView.getParent() != null) { ((ViewGroup) mGridFooterView.getParent()).removeView(mGridFooterView); } mGridView.addFooterView(mGridFooterView, null, false); } mGridFooterView.invalidate(); if (mListView.getFooterViewsCount() == 0) { if (mListFooterView.getParent() != null) { ((ViewGroup) mListFooterView.getParent()).removeView(mListFooterView); } mListView.addFooterView(mListFooterView, null, false); } mListFooterView.invalidate(); } else { mGridView.removeFooterView(mGridFooterView); mListView.removeFooterView(mListFooterView); } } /** * set the list/grid footer text. * * @param text the footer text */ protected void setFooterText(String text) { if (text != null && text.length() > 0) { ((TextView) mListFooterView.findViewById(R.id.footerText)).setText(text); ((TextView) mGridFooterView.findViewById(R.id.footerText)).setText(text); setFooterEnabled(true); } else { setFooterEnabled(false); } } }
Java
/* * Copyright (C) 2001-2006 Jacek Sieka, arnetheduck on gmail point 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "stdinc.h" #include "DCPlusPlus.h" #include "ZUtils.h" #include "Exception.h" #include "ResourceManager.h" const double ZFilter::MIN_COMPRESSION_LEVEL = 0.9; ZFilter::ZFilter() : totalIn(0), totalOut(0), compressing(true) { memset(&zs, 0, sizeof(zs)); if(deflateInit(&zs, 3) != Z_OK) { throw Exception(STRING(COMPRESSION_ERROR)); } } ZFilter::~ZFilter() { dcdebug("ZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1)); deflateEnd(&zs); } bool ZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) { if(outsize == 0) return false; zs.next_in = (Bytef*)in; zs.next_out = (Bytef*)out; // Check if there's any use compressing; if not, save some cpu... if(compressing && insize > 0 && outsize > 16 && (totalIn > (64*1024)) && ((static_cast<double>(totalOut) / totalIn) > 0.95)) { zs.avail_in = 0; zs.avail_out = outsize; if(deflateParams(&zs, 0, Z_DEFAULT_STRATEGY) != Z_OK) { throw Exception(STRING(COMPRESSION_ERROR)); } zs.avail_in = insize; compressing = false; dcdebug("Dynamically disabled compression"); // Check if we ate all space already... if(zs.avail_out == 0) { outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return true; } } else { zs.avail_in = insize; zs.avail_out = outsize; } if(insize == 0) { int err = ::deflate(&zs, Z_FINISH); if(err != Z_OK && err != Z_STREAM_END) throw Exception(STRING(COMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return err == Z_OK; } else { int err = ::deflate(&zs, Z_NO_FLUSH); if(err != Z_OK) throw Exception(STRING(COMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return true; } } UnZFilter::UnZFilter() { memset(&zs, 0, sizeof(zs)); if(inflateInit(&zs) != Z_OK) throw Exception(STRING(DECOMPRESSION_ERROR)); } UnZFilter::~UnZFilter() { dcdebug("UnZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1)); inflateEnd(&zs); } bool UnZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) { if(outsize == 0) return 0; zs.avail_in = insize; zs.next_in = (Bytef*)in; zs.avail_out = outsize; zs.next_out = (Bytef*)out; int err = ::inflate(&zs, Z_NO_FLUSH); // see zlib/contrib/minizip/unzip.c, Z_BUF_ERROR means we should have padded // with a dummy byte if at end of stream - since we don't do this it's not a real // error if(!(err == Z_OK || err == Z_STREAM_END || (err == Z_BUF_ERROR && in == NULL))) throw Exception(STRING(DECOMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; return err == Z_OK; }
Java
/* Copyright (C) 2007 The SpringLobby Team. All rights reserved. */ // #ifndef NO_TORRENT_SYSTEM #ifdef _MSC_VER #ifndef NOMINMAX #define NOMINMAX #endif // NOMINMAX #include <winsock2.h> #endif // _MSC_VER #include <wx/stattext.h> #include <wx/sizer.h> #include <wx/textctrl.h> #include <wx/intl.h> #include <wx/choice.h> #include <wx/statbox.h> #include <wx/event.h> #include <wx/regex.h> #include <wx/checkbox.h> #include "filelistfilter.h" #include "filelistctrl.h" #include "filelistdialog.h" #include "../uiutils.h" #include "../utils/downloader.h" #include "../torrentwrapper.h" /////////////////////////////////////////////////////////////////////////// BEGIN_EVENT_TABLE( FileListFilter, wxPanel ) EVT_CHOICE( FILE_FILTER_TYPE_CHOICE, FileListFilter::OnChangeType ) EVT_TEXT( FILE_FILTER_NAME_EDIT , FileListFilter::OnChangeName ) EVT_CHECKBOX( FILE_FILTER_ONDISK , FileListFilter::OnChangeOndisk ) END_EVENT_TABLE() FileListFilter::FileListFilter( wxWindow* parent, wxWindowID id, FileListDialog* parentBattleListTab, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ), m_parent_filelistdialog( parentBattleListTab ) { wxBoxSizer* m_filter_sizer; m_filter_sizer = new wxBoxSizer( wxVERTICAL ); wxStaticBoxSizer* m_filter_body_sizer; m_filter_body_sizer = new wxStaticBoxSizer( new wxStaticBox( this, -1, wxEmptyString ), wxVERTICAL ); wxBoxSizer* m_filter_body_row1_sizer; m_filter_body_row1_sizer = new wxBoxSizer( wxHORIZONTAL ); m_filter_name_text = new wxStaticText( this, wxID_ANY, _( "Filename:" ), wxDefaultPosition, wxSize( -1,-1 ), 0 ); m_filter_name_text->Wrap( -1 ); m_filter_name_text->SetMinSize( wxSize( 90,-1 ) ); m_filter_body_row1_sizer->Add( m_filter_name_text, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_filter_name_edit = new wxTextCtrl( this, FILE_FILTER_NAME_EDIT, _T( "" ), wxDefaultPosition, wxSize( -1,-1 ), 0|wxSIMPLE_BORDER ); m_filter_name_edit->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) ); m_filter_name_edit->SetMinSize( wxSize( 220,-1 ) ); m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE ); m_filter_body_row1_sizer->Add( m_filter_name_edit, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); wxBoxSizer* m_filter_type_sizer; m_filter_type_sizer = new wxBoxSizer( wxHORIZONTAL ); m_filter_type_text = new wxStaticText( this, wxID_ANY, _( "Filetype:" ), wxDefaultPosition, wxDefaultSize, 0 ); m_filter_type_text->Wrap( -1 ); m_filter_type_sizer->Add( m_filter_type_text, 0, wxALIGN_RIGHT|wxALL|wxALIGN_CENTER_VERTICAL, 5 ); wxBoxSizer* m_filter_ondisk_sizer; m_filter_ondisk_sizer = new wxBoxSizer( wxHORIZONTAL ); m_filter_ondisk = new wxCheckBox( this, FILE_FILTER_ONDISK, _T( "Filter files already on disk" ) ); m_filter_ondisk_sizer->Add( m_filter_ondisk, 0, wxALIGN_CENTER_VERTICAL ); wxString firstChoice = _T( "Any" ); wxArrayString m_filter_type_choiceChoices; m_filter_type_choiceChoices.Add( firstChoice ); m_filter_type_choiceChoices.Add( _( "Map" ) ); m_filter_type_choiceChoices.Add( _( "Game" ) ); m_filter_type_choice = new wxChoice( this, FILE_FILTER_TYPE_CHOICE, wxDefaultPosition, wxDefaultSize, m_filter_type_choiceChoices, wxSIMPLE_BORDER ); m_filter_type_sizer->Add( m_filter_type_choice, 0, wxALIGN_RIGHT|wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_filter_body_row1_sizer->Add( m_filter_type_sizer, 0, wxEXPAND, 5 ); m_filter_body_row1_sizer->Add( m_filter_ondisk_sizer, 0, wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); m_filter_body_sizer->Add( m_filter_body_row1_sizer, 1, wxEXPAND, 5 ); m_filter_sizer->Add( m_filter_body_sizer, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL, 5 ); this->SetSizer( m_filter_sizer ); this->Layout(); m_filter_sizer->Fit( this ); delete m_filter_name_expression; m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE ); m_filter_type_choice_value = -1; wxCommandEvent dummy; OnChange( dummy ); } bool FileListFilter::DoFilterResource( const PlasmaResourceInfo& /*info*/ ) { // if(!data.ok())return false; // if ( data->name.Upper().Find( m_filter_name_edit->GetValue().Upper() ) == wxNOT_FOUND // && !m_filter_name_expression->Matches( data->name ) ) // return false; // if ( m_filter_type_choice_value == 0 && data->type != SpringUnitSync::map ) return false; // // if ( m_filter_type_choice_value == 1 && data->type != SpringUnitSync::mod ) return false; // // if ( m_filter_ondisk->IsChecked() && data->HasFullFileLocal() ) // return false; return false; } void FileListFilter::OnChange( wxCommandEvent& ) { //needs dummy event data m_parent_filelistdialog->UpdateList( GlobalEvents::GlobalEventData() ); } void FileListFilter::OnChangeName( wxCommandEvent& event ) { delete m_filter_name_expression; m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE ); OnChange( event ); } void FileListFilter::OnChangeType( wxCommandEvent& event ) { m_filter_type_choice_value = m_filter_type_choice->GetSelection()-1; OnChange( event ); } void FileListFilter::OnChangeOndisk( wxCommandEvent& event ) { OnChange( event ); } #endif
Java
#ifndef TOUCHPANEL_H__ #define TOUCHPANEL_H__ /* Pre-defined definition */ /* Register */ #define FD_ADDR_MAX 0xE9 #define FD_ADDR_MIN 0xDD #define FD_BYTE_COUNT 6 #define CUSTOM_MAX_WIDTH (720) #define CUSTOM_MAX_HEIGHT (1280) //#define TPD_UPDATE_FIRMWARE #define TPD_HAVE_BUTTON #define TPD_BUTTON_HEIGH (100) #define TPD_KEY_COUNT 3 #define TPD_KEYS { KEY_MENU, KEY_HOMEPAGE, KEY_BACK} #define TPD_KEYS_DIM {{145,1330,120,TPD_BUTTON_HEIGH},\ {360,1330,120,TPD_BUTTON_HEIGH},\ {600,1330,120,TPD_BUTTON_HEIGH}} #define TPD_POWER_SOURCE_CUSTOM MT65XX_POWER_LDO_VGP5 //#define TPD_HAVE_CALIBRATION //#define TPD_CALIBRATION_MATRIX {2680,0,0,0,2760,0,0,0}; //#define TPD_WARP_START //#define TPD_WARP_END //#define TPD_RESET_ISSUE_WORKAROUND //#define TPD_MAX_RESET_COUNT 3 //#define TPD_WARP_Y(y) ( TPD_Y_RES - 1 - y ) //#define TPD_WARP_X(x) ( x ) #endif /* TOUCHPANEL_H__ */
Java
<?php //add a button to the content editor, next to the media button //this button will show a popup that contains inline content add_action('media_buttons_context', 'add_my_custom_button'); //add some content to the bottom of the page //This will be shown in the inline modal if(is_admin()){ add_action('admin_footer', 'add_inline_popup_content'); } //action to add a custom button to the content editor function add_my_custom_button($context) { //path to my icon $img = get_template_directory_uri() .'/images/shortcode_button.png'; //our popup's title $title = __('Cosmone Shortcodes','cosmone'); //append the icon $context .= "<a class='cosmone_shortcodes' title='{$title}'><img src='{$img}' /></a>"; return $context; } function add_inline_popup_content() { global $cosmone_shortcodes ; ?> <div class="white-popup cosmone_shortcodes_container mfp-with-anim mfp-hide" id="cosmone_shortcodes_container" style="" > <form> <h4><?php _e("MageeWP Shortcodes Generator",'cosmone');?></h4> <ul class="cosmone_shortcodes_list"> <?php if(is_array($cosmone_shortcodes )):foreach($cosmone_shortcodes as $key => $val){ if(in_array($key ,array("testimonial_item","pricing_row",'tab','accordion'))){continue;} ?> <li><a class='cosmone_shortcode_item <?php echo $key;?>' title='<?php echo ucwords(str_replace("_"," ",$key));?>' data-shortcode="<?php echo $key;?>" href="javascript:;"><?php echo ucwords(str_replace("_"," ",$key));?></a></li> <?php } ?> <?php endif;?> </ul> <div id="cosmone-shortcodes-settings"> <div id="cosmone-generator-breadcrumbs"> <a title="Click to return to the shortcodes list" class="cosmone-shortcodes-home" href="javascript:void(0);"><?php _e("All shortcodes",'cosmone');?></a> &rarr; <span class="current_shortcode"></span> <div class="clear"></div> </div> <div id="cosmone-shortcodes-settings-inner"></div> <input name="cosmone-shortcode" type="hidden" id="cosmone-shortcode" value="" /> <input name="cosmone-shortcode-textarea" type="hidden" id="cosmone-shortcode-textarea" value="" /> <div class="cosmone-shortcode-actions cosmone-shortcode-clearfix"> <!--<a class="button button-secondary button-large cosmone-shortcode-preview " href="javascript:void(0);"><?php _e("Preview shortcode",'cosmone');?></a>--> <a class="button button-primary button-large cosmone-shortcode-insert " href="javascript:void(0);"><?php _e("Insert shortcode",'cosmone');?></a> </div> <div class="clear"></div> </div></form> <div class="clear"></div> </div> <div id="cosmone-shortcode-preview" style="display:none;"> </div> <?php } ?>
Java
/* * Copyright (c) 2013, 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. * * 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. */ /* * @test SetDontInlineMethodTest * @compile -J-XX:+UnlockDiagnosticVMOptions -J-XX:+WhiteBoxAPI CompilerWhiteBoxTest.java * @compile -J-XX:+UnlockDiagnosticVMOptions -J-XX:+WhiteBoxAPI SetDontInlineMethodTest.java * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI SetDontInlineMethodTest * @author igor.ignatyev@oracle.com */ public class SetDontInlineMethodTest extends CompilerWhiteBoxTest { public static void main(String[] args) throws Exception { new SetDontInlineMethodTest().runTest(); } protected void test() throws Exception { if (WHITE_BOX.setDontInlineMethod(METHOD, true)) { throw new RuntimeException("on start " + METHOD + " must be inlineable"); } if (!WHITE_BOX.setDontInlineMethod(METHOD, true)) { throw new RuntimeException("after first change to true " + METHOD + " must be not inlineable"); } if (!WHITE_BOX.setDontInlineMethod(METHOD, false)) { throw new RuntimeException("after second change to true " + METHOD + " must be still not inlineable"); } if (WHITE_BOX.setDontInlineMethod(METHOD, false)) { throw new RuntimeException("after first change to false" + METHOD + " must be inlineable"); } if (WHITE_BOX.setDontInlineMethod(METHOD, false)) { throw new RuntimeException("after second change to false " + METHOD + " must be inlineable"); } } }
Java
/* Copyright (C) 2013 Stephen Robinson This file is part of HDMI-Light HDMI-Light 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. HDMI-Light 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 code (see the file names COPING). If not, see <http://www.gnu.org/licenses/>. */ struct ConfigTable { unsigned char address; unsigned char subaddress; unsigned char data; }; static const struct ConfigTable g_configTablePreEdid[] PROGMEM = { { 0x98, 0xF4, 0x80 }, // CEC { 0x98, 0xF5, 0x7C }, // INFOFRAME { 0x98, 0xF8, 0x4C }, // DPLL { 0x98, 0xF9, 0x64 }, // KSV { 0x98, 0xFA, 0x6C }, // EDID { 0x98, 0xFB, 0x68 }, // HDMI { 0x98, 0xFD, 0x44 }, // CP { 0x64, 0x77, 0x00 }, // Disable the Internal EDID { 0x00 } }; static const struct ConfigTable g_configTablePostEdid[] PROGMEM = { { 0x64, 0x77, 0x00 }, // Set the Most Significant Bit of the SPA location to 0 { 0x64, 0x52, 0x20 }, // Set the SPA for port B. { 0x64, 0x53, 0x00 }, // Set the SPA for port B. { 0x64, 0x70, 0x9E }, // Set the Least Significant Byte of the SPA location { 0x64, 0x74, 0x03 }, // Enable the Internal EDID for Ports { 0x98, 0x01, 0x06 }, // Prim_Mode =110b HDMI-GR { 0x98, 0x02, 0xF2 }, // Auto CSC, YCrCb out, Set op_656 bit { 0x98, 0x03, 0x40 }, // 24 bit SDR 444 Mode 0 { 0x98, 0x05, 0x28 }, // AV Codes Off { 0x98, 0x0B, 0x44 }, // Power up part { 0x98, 0x0C, 0x42 }, // Power up part { 0x98, 0x14, 0x55 }, // Min Drive Strength { 0x98, 0x15, 0x80 }, // Disable Tristate of Pins { 0x98, 0x19, 0x85 }, // LLC DLL phase { 0x98, 0x33, 0x40 }, // LLC DLL enable { 0x44, 0xBA, 0x01 }, // Set HDMI FreeRun { 0x64, 0x40, 0x81 }, // Disable HDCP 1.1 features { 0x68, 0x9B, 0x03 }, // ADI recommended setting { 0x68, 0xC1, 0x01 }, // ADI recommended setting { 0x68, 0xC2, 0x01 }, // ADI recommended setting { 0x68, 0xC3, 0x01 }, // ADI recommended setting { 0x68, 0xC4, 0x01 }, // ADI recommended setting { 0x68, 0xC5, 0x01 }, // ADI recommended setting { 0x68, 0xC6, 0x01 }, // ADI recommended setting { 0x68, 0xC7, 0x01 }, // ADI recommended setting { 0x68, 0xC8, 0x01 }, // ADI recommended setting { 0x68, 0xC9, 0x01 }, // ADI recommended setting { 0x68, 0xCA, 0x01 }, // ADI recommended setting { 0x68, 0xCB, 0x01 }, // ADI recommended setting { 0x68, 0xCC, 0x01 }, // ADI recommended setting { 0x68, 0x00, 0x00 }, // Set HDMI Input Port A { 0x68, 0x83, 0xFE }, // Enable clock terminator for port A { 0x68, 0x6F, 0x0C }, // ADI recommended setting { 0x68, 0x85, 0x1F }, // ADI recommended setting { 0x68, 0x87, 0x70 }, // ADI recommended setting { 0x68, 0x8D, 0x04 }, // LFG { 0x68, 0x8E, 0x1E }, // HFG { 0x68, 0x1A, 0x8A }, // unmute audio { 0x68, 0x57, 0xDA }, // ADI recommended setting { 0x68, 0x58, 0x01 }, // ADI recommended setting { 0x68, 0x75, 0x10 }, // DDC drive strength { 0x98, 0x40, 0xE2 }, // INT1 active high, active until cleared { 0x00 } };
Java
<!DOCTYPE html><html lang="en-us" > <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="generator" content="Source Themes Academic 4.8.0"> <meta name="author" content="Isabela Le Bras"> <meta name="description" content="Assistant Scientist&lt;br /&gt;Physical Oceanography Department"> <link rel="alternate" hreflang="en-us" href="https://ilebras.github.io/author/m-s-lozier/"> <meta name="theme-color" content="#2962ff"> <script src="/js/mathjax-config.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-1/css/all.min.css" integrity="sha256-4w9DunooKSr3MFXHXWyFER38WmPdm361bQS/2KUWZbU=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/github.min.css" crossorigin="anonymous" title="hl-light"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled> <script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.1.2/lazysizes.min.js" integrity="sha256-Md1qLToewPeKjfAHU1zyPwOutccPAm5tahnaw7Osw0A=" crossorigin="anonymous" async></script> <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" integrity="" crossorigin="anonymous" async></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CRoboto:400,400italic,700%7CRoboto+Mono&display=swap"> <link rel="stylesheet" href="/css/academic.css"> <link rel="alternate" href="/author/m-s-lozier/index.xml" type="application/rss+xml" title="Isabela Le Bras @ WHOI"> <link rel="manifest" href="/index.webmanifest"> <link rel="icon" type="image/png" href="/images/icon_hu7732e1026a0bb9a199bd2a822c780345_104731_32x32_fill_lanczos_center_2.png"> <link rel="apple-touch-icon" type="image/png" href="/images/icon_hu7732e1026a0bb9a199bd2a822c780345_104731_192x192_fill_lanczos_center_2.png"> <link rel="canonical" href="https://ilebras.github.io/author/m-s-lozier/"> <meta property="twitter:card" content="summary"> <meta property="og:site_name" content="Isabela Le Bras @ WHOI"> <meta property="og:url" content="https://ilebras.github.io/author/m-s-lozier/"> <meta property="og:title" content="M S Lozier | Isabela Le Bras @ WHOI"> <meta property="og:description" content="Assistant Scientist&lt;br /&gt;Physical Oceanography Department"><meta property="og:image" content="https://ilebras.github.io/images/icon_hu7732e1026a0bb9a199bd2a822c780345_104731_512x512_fill_lanczos_center_2.png"> <meta property="twitter:image" content="https://ilebras.github.io/images/icon_hu7732e1026a0bb9a199bd2a822c780345_104731_512x512_fill_lanczos_center_2.png"><meta property="og:locale" content="en-us"> <meta property="og:updated_time" content="2019-02-01T00:00:00&#43;00:00"> <title>M S Lozier | Isabela Le Bras @ WHOI</title> </head> <body id="top" data-spy="scroll" data-offset="70" data-target="#TableOfContents" > <aside class="search-results" id="search"> <div class="container"> <section class="search-header"> <div class="row no-gutters justify-content-between mb-3"> <div class="col-6"> <h1>Search</h1> </div> <div class="col-6 col-search-close"> <a class="js-search" href="#"><i class="fas fa-times-circle text-muted" aria-hidden="true"></i></a> </div> </div> <div id="search-box"> <input name="q" id="search-query" placeholder="Search..." autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" type="search" class="form-control"> </div> </section> <section class="section-search-results"> <div id="search-hits"> </div> </section> </div> </aside> <nav class="navbar navbar-expand-lg navbar-light compensate-for-scrollbar" id="navbar-main"> <div class="container"> <div class="d-none d-lg-inline-flex"> <a class="navbar-brand" href="/">Isabela Le Bras @ WHOI</a> </div> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbar-content" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation"> <span><i class="fas fa-bars"></i></span> </button> <div class="navbar-brand-mobile-wrapper d-inline-flex d-lg-none"> <a class="navbar-brand" href="/">Isabela Le Bras @ WHOI</a> </div> <div class="navbar-collapse main-menu-item collapse justify-content-end" id="navbar-content"> <ul class="navbar-nav d-md-inline-flex"> <li class="nav-item"> <a class="nav-link " href="/#about"><span>Home</span></a> </li> <li class="nav-item"> <a class="nav-link " href="/#projects"><span>Research</span></a> </li> <li class="nav-item"> <a class="nav-link " href="/#publications"><span>Publications</span></a> </li> <li class="nav-item"> <a class="nav-link " href="/join"><span>Join</span></a> </li> <li class="nav-item"> <a class="nav-link " href="/#contact"><span>Contact</span></a> </li> </ul> </div> <ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2"> <li class="nav-item"> <a class="nav-link js-search" href="#" aria-label="Search"><i class="fas fa-search" aria-hidden="true"></i></a> </li> <li class="nav-item dropdown theme-dropdown"> <a href="#" class="nav-link js-theme-selector" data-toggle="dropdown" aria-haspopup="true"> <i class="fas fa-palette" aria-hidden="true"></i> </a> <div class="dropdown-menu"> <a href="#" class="dropdown-item js-set-theme-light"> <span>Light</span> </a> <a href="#" class="dropdown-item js-set-theme-dark"> <span>Dark</span> </a> <a href="#" class="dropdown-item js-set-theme-auto"> <span>Automatic</span> </a> </div> </li> </ul> </div> </nav> <div class="universal-wrapper pt-3"> <h1>M S Lozier</h1> </div> <section id="profile-page" class="pt-5"> <div class="container"> <div class="article-widget content-widget-hr"> <h3>Latest</h3> <ul> <li> <a href="/publication/lozier-2019/">A sea change in our view of overturning in the subpolar North Atlantic.</a> </li> </ul> </div> </div> </section> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js" integrity="sha256-lqvxZrPLtfffUl2G/e7szqSvPBILGbwmsGE1MKlOi0Q=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js" integrity="sha256-CBrpuqrMhXwcLLUd5tvQ4euBHCdh7wGlDfNz8vbu/iI=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/instant.page/5.1.0/instantpage.min.js" integrity="sha512-1+qUtKoh9XZW7j+6LhRMAyOrgSQKenQ4mluTR+cvxXjP1Z54RxZuzstR/H9kgPXQsVB8IW7DMDFUJpzLjvhGSQ==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js" integrity="sha256-eOgo0OtLL4cdq7RdwRUiGKLX9XsIJ7nGhWEKbohmVAQ=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/languages/r.min.js"></script> <script async defer src="https://maps.googleapis.com/maps/api/js?key="></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.25/gmaps.min.js" integrity="sha256-7vjlAeb8OaTrCXZkCNun9djzuB2owUsaO72kXaFDBJs=" crossorigin="anonymous"></script> <script>const code_highlighting = true;</script> <script>const isSiteThemeDark = false;</script> <script> const search_config = {"indexURI":"/index.json","minLength":1,"threshold":0.3}; const i18n = {"no_results":"No results found","placeholder":"Search...","results":"results found"}; const content_type = { 'post': "Posts", 'project': "Projects", 'publication' : "Publications", 'talk' : "Talks", 'slides' : "Slides" }; </script> <script id="search-hit-fuse-template" type="text/x-template"> <div class="search-hit" id="summary-{{key}}"> <div class="search-hit-content"> <div class="search-hit-name"> <a href="{{relpermalink}}">{{title}}</a> <div class="article-metadata search-hit-type">{{type}}</div> <p class="search-hit-description">{{snippet}}</p> </div> </div> </div> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js" integrity="sha256-VzgmKYmhsGNNN4Ph1kMW+BjoYJM2jV5i4IlFoeZA9XI=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin="anonymous"></script> <script src="/js/academic.min.66c553246b0f279a03be6e5597f72b52.js"></script> <div class="container"> <footer class="site-footer"> <p class="powered-by"> © 2020 </p> <p class="powered-by"> Published with <a href="https://sourcethemes.com/academic/" target="_blank" rel="noopener">Academic Website Builder</a> <span class="float-right" aria-hidden="true"> <a href="#" class="back-to-top"> <span class="button_icon"> <i class="fas fa-chevron-up fa-2x"></i> </span> </a> </span> </p> </footer> </div> <div id="modal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Cite</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <pre><code class="tex hljs"></code></pre> </div> <div class="modal-footer"> <a class="btn btn-outline-primary my-1 js-copy-cite" href="#" target="_blank"> <i class="fas fa-copy"></i> Copy </a> <a class="btn btn-outline-primary my-1 js-download-cite" href="#" target="_blank"> <i class="fas fa-download"></i> Download </a> <div id="modal-error"></div> </div> </div> </div> </div> </body> </html>
Java
/* * UAE - The Un*x Amiga Emulator * * Sound emulation stuff * * Copyright 1995, 1996, 1997 Bernd Schmidt */ #ifndef UAE_AUDIO_H #define UAE_AUDIO_H #define PERIOD_MAX ULONG_MAX extern void aud0_handler (void); extern void aud1_handler (void); extern void aud2_handler (void); extern void aud3_handler (void); extern void AUDxDAT (int nr, uae_u16 value); extern void AUDxDAT_addr (int nr, uae_u16 value, uaecptr addr); extern void AUDxVOL (int nr, uae_u16 value); extern void AUDxPER (int nr, uae_u16 value); extern void AUDxLCH (int nr, uae_u16 value); extern void AUDxLCL (int nr, uae_u16 value); extern void AUDxLEN (int nr, uae_u16 value); extern uae_u16 audio_dmal (void); extern void audio_state_machine (void); extern uaecptr audio_getpt (int nr, bool reset); extern int init_audio (void); extern void ahi_install (void); extern void audio_reset (void); extern void update_audio (void); extern void audio_evhandler (void); extern void audio_hsync (void); extern void audio_update_adkmasks (void); extern void update_sound (double freq, int longframe, int linetoggle); extern void led_filter_audio (void); extern void set_audio (void); extern int audio_activate (void); extern void audio_vsync (void); void switch_audio_interpol (void); extern int sound_available; extern void audio_sampleripper(int); extern int sampleripper_enabled; //extern void write_wavheader (struct zfile *wavfile, uae_u32 size, uae_u32 freq); enum { SND_MONO, SND_STEREO, SND_4CH_CLONEDSTEREO, SND_4CH, SND_6CH_CLONEDSTEREO, SND_6CH, SND_NONE }; STATIC_INLINE int get_audio_stereomode (int channels) { switch (channels) { case 1: return SND_MONO; case 2: return SND_STEREO; case 4: return SND_4CH; case 6: return SND_6CH; } return SND_STEREO; } STATIC_INLINE int get_audio_nativechannels (int stereomode) { int ch[] = { 1, 2, 4, 4, 6, 6, 0 }; return ch[stereomode]; } STATIC_INLINE int get_audio_amigachannels (int stereomode) { int ch[] = { 1, 2, 2, 4, 2, 4, 0 }; return ch[stereomode]; } STATIC_INLINE int get_audio_ismono (int stereomode) { if (stereomode == 0) return 1; return 0; } #define SOUND_MAX_DELAY_BUFFER 1024 #define SOUND_MAX_LOG_DELAY 10 #define MIXED_STEREO_MAX 16 #define MIXED_STEREO_SCALE 32 #endif /* UAE_AUDIO_H */
Java
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero> * * 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 */ #include "MapManager.h" #include "Log.h" #include "GridStates.h" #include "CellImpl.h" #include "Map.h" #include "DBCEnums.h" #include "DBCStores.h" #include "GridMap.h" #include "VMapFactory.h" #include "World.h" #include "Policies/SingletonImp.h" #include "Util.h" char const* MAP_MAGIC = "MAPS"; char const* MAP_VERSION_MAGIC = "10.1"; char const* MAP_AREA_MAGIC = "AREA"; char const* MAP_HEIGHT_MAGIC = "MHGT"; char const* MAP_LIQUID_MAGIC = "MLIQ"; GridMap::GridMap() { m_flags = 0; // Area data m_gridArea = 0; m_area_map = NULL; // Height level data m_gridHeight = INVALID_HEIGHT_VALUE; m_gridGetHeight = &GridMap::getHeightFromFlat; m_V9 = NULL; m_V8 = NULL; // Liquid data m_liquidType = 0; m_liquid_offX = 0; m_liquid_offY = 0; m_liquid_width = 0; m_liquid_height = 0; m_liquidLevel = INVALID_HEIGHT_VALUE; m_liquid_type = NULL; m_liquid_map = NULL; } GridMap::~GridMap() { unloadData(); } bool GridMap::loadData(char *filename) { // Unload old data if exist unloadData(); GridMapFileHeader header; // Not return error if file not found FILE *in = fopen(filename, "rb"); if (!in) return true; fread(&header, sizeof(header),1,in); if (header.mapMagic == *((uint32 const*)(MAP_MAGIC)) && header.versionMagic == *((uint32 const*)(MAP_VERSION_MAGIC))) { // loadup area data if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize)) { sLog.outError("Error loading map area data\n"); fclose(in); return false; } // loadup height data if (header.heightMapOffset && !loadHeightData(in, header.heightMapOffset, header.heightMapSize)) { sLog.outError("Error loading map height data\n"); fclose(in); return false; } // loadup liquid data if (header.liquidMapOffset && !loadGridMapLiquidData(in, header.liquidMapOffset, header.liquidMapSize)) { sLog.outError("Error loading map liquids data\n"); fclose(in); return false; } fclose(in); return true; } sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename); fclose(in); return false; } void GridMap::unloadData() { if (m_area_map) delete[] m_area_map; if (m_V9) delete[] m_V9; if (m_V8) delete[] m_V8; if (m_liquid_type) delete[] m_liquid_type; if (m_liquid_map) delete[] m_liquid_map; m_area_map = NULL; m_V9 = NULL; m_V8 = NULL; m_liquid_type = NULL; m_liquid_map = NULL; m_gridGetHeight = &GridMap::getHeightFromFlat; } bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 /*size*/) { GridMapAreaHeader header; fseek(in, offset, SEEK_SET); fread(&header, sizeof(header), 1, in); if (header.fourcc != *((uint32 const*)(MAP_AREA_MAGIC))) return false; m_gridArea = header.gridArea; if (!(header.flags & MAP_AREA_NO_AREA)) { m_area_map = new uint16 [16*16]; fread(m_area_map, sizeof(uint16), 16*16, in); } return true; } bool GridMap::loadHeightData(FILE *in, uint32 offset, uint32 /*size*/) { GridMapHeightHeader header; fseek(in, offset, SEEK_SET); fread(&header, sizeof(header), 1, in); if (header.fourcc != *((uint32 const*)(MAP_HEIGHT_MAGIC))) return false; m_gridHeight = header.gridHeight; if (!(header.flags & MAP_HEIGHT_NO_HEIGHT)) { if ((header.flags & MAP_HEIGHT_AS_INT16)) { m_uint16_V9 = new uint16 [129*129]; m_uint16_V8 = new uint16 [128*128]; fread(m_uint16_V9, sizeof(uint16), 129*129, in); fread(m_uint16_V8, sizeof(uint16), 128*128, in); m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535; m_gridGetHeight = &GridMap::getHeightFromUint16; } else if ((header.flags & MAP_HEIGHT_AS_INT8)) { m_uint8_V9 = new uint8 [129*129]; m_uint8_V8 = new uint8 [128*128]; fread(m_uint8_V9, sizeof(uint8), 129*129, in); fread(m_uint8_V8, sizeof(uint8), 128*128, in); m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255; m_gridGetHeight = &GridMap::getHeightFromUint8; } else { m_V9 = new float [129*129]; m_V8 = new float [128*128]; fread(m_V9, sizeof(float), 129*129, in); fread(m_V8, sizeof(float), 128*128, in); m_gridGetHeight = &GridMap::getHeightFromFloat; } } else m_gridGetHeight = &GridMap::getHeightFromFlat; return true; } bool GridMap::loadGridMapLiquidData(FILE *in, uint32 offset, uint32 /*size*/) { GridMapLiquidHeader header; fseek(in, offset, SEEK_SET); fread(&header, sizeof(header), 1, in); if (header.fourcc != *((uint32 const*)(MAP_LIQUID_MAGIC))) return false; m_liquidType = header.liquidType; m_liquid_offX = header.offsetX; m_liquid_offY = header.offsetY; m_liquid_width = header.width; m_liquid_height = header.height; m_liquidLevel = header.liquidLevel; if (!(header.flags & MAP_LIQUID_NO_TYPE)) { m_liquid_type = new uint8 [16*16]; fread(m_liquid_type, sizeof(uint8), 16*16, in); } if (!(header.flags & MAP_LIQUID_NO_HEIGHT)) { m_liquid_map = new float [m_liquid_width*m_liquid_height]; fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in); } return true; } uint16 GridMap::getArea(float x, float y) { if (!m_area_map) return m_gridArea; x = 16 * (32 - x/SIZE_OF_GRIDS); y = 16 * (32 - y/SIZE_OF_GRIDS); int lx = (int)x & 15; int ly = (int)y & 15; return m_area_map[lx*16 + ly]; } float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const { return m_gridHeight; } float GridMap::getHeightFromFloat(float x, float y) const { if (!m_V8 || !m_V9) return m_gridHeight; x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; x_int &= (MAP_RESOLUTION - 1); y_int &= (MAP_RESOLUTION - 1); // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid // +--------------> X // | h1-------h2 Coordinates is: // | | \ 1 / | h1 0,0 // | | \ / | h2 0,1 // | | 2 h5 3 | h3 1,0 // | | / \ | h4 1,1 // | | / 4 \ | h5 1/2,1/2 // | h3-------h4 // V Y // For find height need // 1 - detect triangle // 2 - solve linear equation from triangle points // Calculate coefficients for solve h = a*x + b*y + c float a,b,c; // Select triangle: if (x+y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) float h1 = m_V9[(x_int )*129 + y_int]; float h2 = m_V9[(x_int+1)*129 + y_int]; float h5 = 2 * m_V8[x_int*128 + y_int]; a = h2-h1; b = h5-h1-h2; c = h1; } else { // 2 triangle (h1, h3, h5 points) float h1 = m_V9[x_int*129 + y_int ]; float h3 = m_V9[x_int*129 + y_int+1]; float h5 = 2 * m_V8[x_int*128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; } } else { if (x > y) { // 3 triangle (h2, h4, h5 points) float h2 = m_V9[(x_int+1)*129 + y_int ]; float h4 = m_V9[(x_int+1)*129 + y_int+1]; float h5 = 2 * m_V8[x_int*128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; } else { // 4 triangle (h3, h4, h5 points) float h3 = m_V9[(x_int )*129 + y_int+1]; float h4 = m_V9[(x_int+1)*129 + y_int+1]; float h5 = 2 * m_V8[x_int*128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; } } // Calculate height return a * x + b * y + c; } float GridMap::getHeightFromUint8(float x, float y) const { if (!m_uint8_V8 || !m_uint8_V9) return m_gridHeight; x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; x_int &= (MAP_RESOLUTION - 1); y_int &= (MAP_RESOLUTION - 1); int32 a, b, c; uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int]; if (x+y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) int32 h1 = V9_h1_ptr[ 0]; int32 h2 = V9_h1_ptr[129]; int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; a = h2-h1; b = h5-h1-h2; c = h1; } else { // 2 triangle (h1, h3, h5 points) int32 h1 = V9_h1_ptr[0]; int32 h3 = V9_h1_ptr[1]; int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; } } else { if (x > y) { // 3 triangle (h2, h4, h5 points) int32 h2 = V9_h1_ptr[129]; int32 h4 = V9_h1_ptr[130]; int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; } else { // 4 triangle (h3, h4, h5 points) int32 h3 = V9_h1_ptr[ 1]; int32 h4 = V9_h1_ptr[130]; int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; } } // Calculate height return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight; } float GridMap::getHeightFromUint16(float x, float y) const { if (!m_uint16_V8 || !m_uint16_V9) return m_gridHeight; x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int x_int = (int)x; int y_int = (int)y; x -= x_int; y -= y_int; x_int &= (MAP_RESOLUTION - 1); y_int &= (MAP_RESOLUTION - 1); int32 a, b, c; uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int]; if (x+y < 1) { if (x > y) { // 1 triangle (h1, h2, h5 points) int32 h1 = V9_h1_ptr[ 0]; int32 h2 = V9_h1_ptr[129]; int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; a = h2-h1; b = h5-h1-h2; c = h1; } else { // 2 triangle (h1, h3, h5 points) int32 h1 = V9_h1_ptr[0]; int32 h3 = V9_h1_ptr[1]; int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; a = h5 - h1 - h3; b = h3 - h1; c = h1; } } else { if (x > y) { // 3 triangle (h2, h4, h5 points) int32 h2 = V9_h1_ptr[129]; int32 h4 = V9_h1_ptr[130]; int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; a = h2 + h4 - h5; b = h4 - h2; c = h5 - h4; } else { // 4 triangle (h3, h4, h5 points) int32 h3 = V9_h1_ptr[ 1]; int32 h4 = V9_h1_ptr[130]; int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int]; a = h4 - h3; b = h3 + h4 - h5; c = h5 - h4; } } // Calculate height return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight; } float GridMap::getLiquidLevel(float x, float y) { if (!m_liquid_map) return m_liquidLevel; x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY; int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX; if (cx_int < 0 || cx_int >=m_liquid_height) return INVALID_HEIGHT_VALUE; if (cy_int < 0 || cy_int >=m_liquid_width ) return INVALID_HEIGHT_VALUE; return m_liquid_map[cx_int*m_liquid_width + cy_int]; } uint8 GridMap::getTerrainType(float x, float y) { if (!m_liquid_type) return (uint8)m_liquidType; x = 16 * (32 - x/SIZE_OF_GRIDS); y = 16 * (32 - y/SIZE_OF_GRIDS); int lx = (int)x & 15; int ly = (int)y & 15; return m_liquid_type[lx*16 + ly]; } // Get water state on map GridMapLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, GridMapLiquidData *data) { // Check water type (if no water return) if (!m_liquid_type && !m_liquidType) return LIQUID_MAP_NO_WATER; // Get cell float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS); float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS); int x_int = (int)cx & (MAP_RESOLUTION-1); int y_int = (int)cy & (MAP_RESOLUTION-1); // Check water type in cell uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType; if (type == 0) return LIQUID_MAP_NO_WATER; // Check req liquid type mask if (ReqLiquidType && !(ReqLiquidType&type)) return LIQUID_MAP_NO_WATER; // Check water level: // Check water height map int lx_int = x_int - m_liquid_offY; if (lx_int < 0 || lx_int >=m_liquid_height) return LIQUID_MAP_NO_WATER; int ly_int = y_int - m_liquid_offX; if (ly_int < 0 || ly_int >=m_liquid_width ) return LIQUID_MAP_NO_WATER; // Get water level float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel; // Get ground level (sub 0.2 for fix some errors) float ground_level = getHeight(x, y); // Check water level and ground level if (liquid_level < ground_level || z < ground_level - 2) return LIQUID_MAP_NO_WATER; // All ok in water -> store data if (data) { data->type = type; data->level = liquid_level; data->depth_level = ground_level; } // For speed check as int values int delta = int((liquid_level - z) * 10); // Get position delta if (delta > 20) // Under water return LIQUID_MAP_UNDER_WATER; if (delta > 0 ) // In water return LIQUID_MAP_IN_WATER; if (delta > -1) // Walk on water return LIQUID_MAP_WATER_WALK; // Above water return LIQUID_MAP_ABOVE_WATER; } bool GridMap::ExistMap(uint32 mapid,int gx,int gy) { int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1; char* tmp = new char[len]; snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy); FILE *pf=fopen(tmp,"rb"); if(!pf) { sLog.outError("Check existing of map file '%s': not exist!",tmp); delete[] tmp; return false; } GridMapFileHeader header; fread(&header, sizeof(header), 1, pf); if (header.mapMagic != *((uint32 const*)(MAP_MAGIC)) || header.versionMagic != *((uint32 const*)(MAP_VERSION_MAGIC))) { sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp); delete [] tmp; fclose(pf); //close file before return return false; } delete [] tmp; fclose(pf); return true; } bool GridMap::ExistVMap(uint32 mapid,int gx,int gy) { if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager()) { if(vmgr->isMapLoadingEnabled()) { // x and y are swapped !! => fixed now bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy); if(!exists) { std::string name = vmgr->getDirFileName(mapid,gx,gy); sLog.outError("VMap file '%s' is missing or point to wrong version vmap file, redo vmaps with latest vmap_assembler.exe program", (sWorld.GetDataPath()+"vmaps/"+name).c_str()); return false; } } } return true; } ////////////////////////////////////////////////////////////////////////// TerrainInfo::TerrainInfo(uint32 mapid) : m_mapId(mapid) { for (int k = 0; k < MAX_NUMBER_OF_GRIDS; ++k) { for (int i = 0; i < MAX_NUMBER_OF_GRIDS; ++i) { m_GridMaps[i][k] = NULL; m_GridRef[i][k] = 0; } } //clean up GridMap objects every minute const uint32 iCleanUpInterval = 60; //schedule start randlomly const uint32 iRandomStart = urand(20, 40); i_timer.SetInterval(iCleanUpInterval * 1000); i_timer.SetCurrent(iRandomStart * 1000); } TerrainInfo::~TerrainInfo() { for (int k = 0; k < MAX_NUMBER_OF_GRIDS; ++k) for (int i = 0; i < MAX_NUMBER_OF_GRIDS; ++i) delete m_GridMaps[i][k]; VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(m_mapId); } GridMap * TerrainInfo::Load(const uint32 x, const uint32 y) { MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS); MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS); //reference grid as a first step RefGrid(x, y); //quick check if GridMap already loaded GridMap * pMap = m_GridMaps[x][y]; if(!pMap) pMap = LoadMapAndVMap(x, y); return pMap; } //schedule lazy GridMap object cleanup void TerrainInfo::Unload(const uint32 x, const uint32 y) { MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS); MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS); if(m_GridMaps[x][y]) { //decrease grid reference count... if(UnrefGrid(x, y) == 0) { //TODO: add your additional logic here } } } //call this method only void TerrainInfo::CleanUpGrids(const uint32 diff) { i_timer.Update(diff); if( !i_timer.Passed() ) return; for (int y = 0; y < MAX_NUMBER_OF_GRIDS; ++y) { for (int x = 0; x < MAX_NUMBER_OF_GRIDS; ++x) { const int16& iRef = m_GridRef[x][y]; GridMap * pMap = m_GridMaps[x][y]; //delete those GridMap objects which have refcount = 0 if(pMap && iRef == 0 ) { m_GridMaps[x][y] = NULL; //delete grid data if reference count == 0 pMap->unloadData(); delete pMap; //unload VMAPS... VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(m_mapId, x, y); } } } i_timer.Reset(); } int TerrainInfo::RefGrid(const uint32& x, const uint32& y) { MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS); MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS); LOCK_GUARD _lock(m_refMutex); return (m_GridRef[x][y] += 1); } int TerrainInfo::UnrefGrid(const uint32& x, const uint32& y) { MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS); MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS); int16& iRef = m_GridRef[x][y]; LOCK_GUARD _lock(m_refMutex); if(iRef > 0) return (iRef -= 1); return 0; } float TerrainInfo::GetHeight(float x, float y, float z, bool pUseVmaps, float maxSearchDist) const { // find raw .map surface under Z coordinates float mapHeight; float z2 = z + 2.f; if (GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { float _mapheight = gmap->getHeight(x,y); // look from a bit higher pos to find the floor, ignore under surface case if (z2 > _mapheight) mapHeight = _mapheight; else mapHeight = VMAP_INVALID_HEIGHT_VALUE; } else mapHeight = VMAP_INVALID_HEIGHT_VALUE; float vmapHeight; if (pUseVmaps) { VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); if (vmgr->isHeightCalcEnabled()) { // if mapHeight has been found search vmap height at least until mapHeight point // this prevent case when original Z "too high above ground and vmap height search fail" // this will not affect most normal cases (no map in instance, or stay at ground at continent) if (mapHeight > INVALID_HEIGHT && z2 - mapHeight > maxSearchDist) maxSearchDist = z2 - mapHeight + 1.0f; // 1.0 make sure that we not fail for case when map height near but above for vamp height // look from a bit higher pos to find the floor vmapHeight = vmgr->getHeight(GetMapId(), x, y, z2, maxSearchDist); } else vmapHeight = VMAP_INVALID_HEIGHT_VALUE; } else vmapHeight = VMAP_INVALID_HEIGHT_VALUE; // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT // vmapheight set for any under Z value or <= INVALID_HEIGHT if (vmapHeight > INVALID_HEIGHT) { if (mapHeight > INVALID_HEIGHT) { // we have mapheight and vmapheight and must select more appropriate // we are already under the surface or vmap height above map heigt // or if the distance of the vmap height is less the land height distance if (z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z)) return vmapHeight; else return mapHeight; // better use .map surface height } else return vmapHeight; // we have only vmapHeight (if have) } return mapHeight; } inline bool IsOutdoorWMO(uint32 mogpFlags) { return mogpFlags & 0x8008; } bool TerrainInfo::IsOutdoors(float x, float y, float z) const { uint32 mogpFlags; int32 adtId, rootId, groupId; // no wmo found? -> outside by default if(!GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId)) return true; return IsOutdoorWMO(mogpFlags); } bool TerrainInfo::GetAreaInfo(float x, float y, float z, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const { float vmap_z = z; VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); if (vmgr->getAreaInfo(GetMapId(), x, y, vmap_z, flags, adtId, rootId, groupId)) { // check if there's terrain between player height and object height if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { float _mapheight = gmap->getHeight(x,y); // z + 2.0f condition taken from GetHeight(), not sure if it's such a great choice... if(z + 2.0f > _mapheight && _mapheight > vmap_z) return false; } return true; } return false; } uint16 TerrainInfo::GetAreaFlag(float x, float y, float z, bool *isOutdoors) const { uint32 mogpFlags; int32 adtId, rootId, groupId; WMOAreaTableEntry const* wmoEntry = 0; AreaTableEntry const* atEntry = 0; bool haveAreaInfo = false; if(GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId)) { haveAreaInfo = true; wmoEntry = GetWMOAreaTableEntryByTripple(rootId, adtId, groupId); if(wmoEntry) atEntry = GetAreaEntryByAreaID(wmoEntry->areaId); } uint16 areaflag; if (atEntry) areaflag = atEntry->exploreFlag; else { if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) areaflag = gmap->getArea(x, y); // this used while not all *.map files generated (instances) else areaflag = GetAreaFlagByMapId(GetMapId()); } if (isOutdoors) { if (haveAreaInfo) *isOutdoors = IsOutdoorWMO(mogpFlags); else *isOutdoors = true; } return areaflag; } uint8 TerrainInfo::GetTerrainType(float x, float y ) const { if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) return gmap->getTerrainType(x, y); else return 0; } uint32 TerrainInfo::GetAreaId(float x, float y, float z) const { return TerrainManager::GetAreaIdByAreaFlag(GetAreaFlag(x,y,z),m_mapId); } uint32 TerrainInfo::GetZoneId(float x, float y, float z) const { return TerrainManager::GetZoneIdByAreaFlag(GetAreaFlag(x,y,z),m_mapId); } void TerrainInfo::GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, float z) const { TerrainManager::GetZoneAndAreaIdByAreaFlag(zoneid,areaid,GetAreaFlag(x,y,z),m_mapId); } GridMapLiquidStatus TerrainInfo::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, GridMapLiquidData *data) const { GridMapLiquidStatus result = LIQUID_MAP_NO_WATER; VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); float liquid_level, ground_level = INVALID_HEIGHT_VALUE; uint32 liquid_type; if (vmgr->GetLiquidLevel(GetMapId(), x, y, z, ReqLiquidType, liquid_level, ground_level, liquid_type)) { DEBUG_LOG("getLiquidStatus(): vmap liquid level: %f ground: %f type: %u", liquid_level, ground_level, liquid_type); // Check water level and ground level if (liquid_level > ground_level && z > ground_level - 2) { // All ok in water -> store data if (data) { data->type = liquid_type; data->level = liquid_level; data->depth_level = ground_level; } // For speed check as int values int delta = int((liquid_level - z) * 10); // Get position delta if (delta > 20) // Under water return LIQUID_MAP_UNDER_WATER; if (delta > 0 ) // In water return LIQUID_MAP_IN_WATER; if (delta > -1) // Walk on water return LIQUID_MAP_WATER_WALK; result = LIQUID_MAP_ABOVE_WATER; } } if(GridMap* gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { GridMapLiquidData map_data; GridMapLiquidStatus map_result = gmap->getLiquidStatus(x, y, z, ReqLiquidType, &map_data); // Not override LIQUID_MAP_ABOVE_WATER with LIQUID_MAP_NO_WATER: if (map_result != LIQUID_MAP_NO_WATER && (map_data.level > ground_level)) { if (data) *data = map_data; return map_result; } } return result; } bool TerrainInfo::IsInWater(float x, float y, float pZ, GridMapLiquidData *data) const { // Check surface in x, y point for liquid if (const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { GridMapLiquidData liquid_status; GridMapLiquidData *liquid_ptr = data ? data : &liquid_status; if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, liquid_ptr)) { //if (liquid_prt->level - liquid_prt->depth_level > 2) //??? return true; } } return false; } bool TerrainInfo::IsUnderWater(float x, float y, float z) const { if (const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER) return true; } return false; } /** * Function find higher form water or ground height for current floor * * @param x, y, z Coordinates original point at floor level * * @param pGround optional arg for retrun calculated by function work ground height, it let avoid in caller code recalculate height for point if it need * * @param swim z coordinate can be calculated for select above/at or under z coordinate (for fly or swim/walking by bottom) * in last cases for in water returned under water height for avoid client set swimming unit as saty at water. * * @return calculated z coordinate */ float TerrainInfo::GetWaterOrGroundLevel(float x, float y, float z, float* pGround /*= NULL*/, bool swim /*= false*/) const { if (const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { // we need ground level (including grid height version) for proper return water level in point float ground_z = GetHeight(x, y, z, true, DEFAULT_WATER_SEARCH); if (pGround) *pGround = ground_z + 0.05f; GridMapLiquidData liquid_status; GridMapLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status); return res ? ( swim ? liquid_status.level - 2.0f : liquid_status.level) : ground_z + 0.05f; } return VMAP_INVALID_HEIGHT_VALUE; } GridMap * TerrainInfo::GetGrid( const float x, const float y ) { // half opt method int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y //quick check if GridMap already loaded GridMap * pMap = m_GridMaps[gx][gy]; if(!pMap) pMap = LoadMapAndVMap(gx, gy); return pMap; } GridMap * TerrainInfo::LoadMapAndVMap( const uint32 x, const uint32 y ) { //double checked lock pattern if(!m_GridMaps[x][y]) { LOCK_GUARD lock(m_mutex); if(!m_GridMaps[x][y]) { GridMap * map = new GridMap(); // map file name char *tmp=NULL; int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1; tmp = new char[len]; snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),m_mapId, x, y); sLog.outDetail("Loading map %s",tmp); if(!map->loadData(tmp)) { sLog.outError("Error load map file: \n %s\n", tmp); //ASSERT(false); } delete [] tmp; m_GridMaps[x][y] = map; //load VMAPs for current map/grid... const MapEntry * i_mapEntry = sMapStore.LookupEntry(m_mapId); const char* mapName = i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0"; int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), m_mapId, x, y); switch(vmapLoadResult) { case VMAP::VMAP_LOAD_RESULT_OK: sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y); break; case VMAP::VMAP_LOAD_RESULT_ERROR: sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y); break; case VMAP::VMAP_LOAD_RESULT_IGNORED: DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y); break; } } } return m_GridMaps[x][y]; } float TerrainInfo::GetWaterLevel(float x, float y, float z, float* pGround /*= NULL*/) const { if (const_cast<TerrainInfo*>(this)->GetGrid(x, y)) { // we need ground level (including grid height version) for proper return water level in point float ground_z = GetHeight(x, y, z, true, DEFAULT_WATER_SEARCH); if (pGround) *pGround = ground_z; GridMapLiquidData liquid_status; GridMapLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status); if (!res) return VMAP_INVALID_HEIGHT_VALUE; return liquid_status.level; } return VMAP_INVALID_HEIGHT_VALUE; } ////////////////////////////////////////////////////////////////////////// #define CLASS_LOCK MaNGOS::ClassLevelLockable<TerrainManager, ACE_Thread_Mutex> INSTANTIATE_SINGLETON_2(TerrainManager, CLASS_LOCK); INSTANTIATE_CLASS_MUTEX(TerrainManager, ACE_Thread_Mutex); TerrainManager::TerrainManager() { } TerrainManager::~TerrainManager() { for (TerrainDataMap::iterator it = i_TerrainMap.begin(); it != i_TerrainMap.end(); ++it) delete it->second; } TerrainInfo * TerrainManager::LoadTerrain(const uint32 mapId) { Guard _guard(*this); TerrainInfo * ptr = NULL; TerrainDataMap::const_iterator iter = i_TerrainMap.find(mapId); if(iter == i_TerrainMap.end()) { ptr = new TerrainInfo(mapId); i_TerrainMap[mapId] = ptr; } else ptr = (*iter).second; return ptr; } void TerrainManager::UnloadTerrain(const uint32 mapId) { if(sWorld.getConfig(CONFIG_BOOL_GRID_UNLOAD) == 0) return; Guard _guard(*this); TerrainDataMap::iterator iter = i_TerrainMap.find(mapId); if(iter != i_TerrainMap.end()) { TerrainInfo * ptr = (*iter).second; //lets check if this object can be actually freed if(ptr->IsReferenced() == false) { i_TerrainMap.erase(iter); delete ptr; } } } void TerrainManager::Update(const uint32 diff) { //global garbage collection for GridMap objects and VMaps for (TerrainDataMap::iterator iter = i_TerrainMap.begin(); iter != i_TerrainMap.end(); ++iter) iter->second->CleanUpGrids(diff); } void TerrainManager::UnloadAll() { for (TerrainDataMap::iterator it = i_TerrainMap.begin(); it != i_TerrainMap.end(); ++it) delete it->second; i_TerrainMap.clear(); } uint32 TerrainManager::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id) { AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id); if (entry) return entry->ID; else return 0; } uint32 TerrainManager::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id) { AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id); if( entry ) return ( entry->zone != 0 ) ? entry->zone : entry->ID; else return 0; } void TerrainManager::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id) { AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id); areaid = entry ? entry->ID : 0; zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0; }
Java
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta name="HandheldFriendly" content="true"/> <!--<meta name="MobileOptimized" content="320"/>--> <title>Hello H5+</title> <script type="text/javascript" src="../js/common.js"></script> <script type="text/javascript"> var auths={}; function plusReady(){ // 获取登录认证通道 plus.oauth.getServices(function(services){ var content=document.getElementById('dcontent'); var info=document.getElementById("info"); var txt="登录认证通道信息:"; for(var i in services){ var service=services[i]; console.log(service.id+": "+service.authResult+", "+service.userInfo); auths[service.id]=service; txt += "id:"+service.id+", "; txt += "description:"+service.description+", "; var de=document.createElement('div'); de.setAttribute('class','button'); de.setAttribute('onclick','login(this.id)'); de.id=service.id; de.innerText=service.description+"登录"; oauth.appendChild(de); } info.innerText=txt; },function(e){ outLine("获取登录认证失败:"+e.message); }); } document.addEventListener('plusready',plusReady,false); // 登录认证 function login(id){ outSet("----- 登录认证 -----"); var auth=auths[id]; if(auth){ var w=null; if(plus.os.name=="Android"){ w=plus.nativeUI.showWaiting(); } document.addEventListener("pause",function(){ setTimeout(function(){ w&&w.close();w=null; },2000); }, false ); auth.login(function(){ w&&w.close();w=null; outLine("登录认证成功:"); outLine(JSON.stringify(auth.authResult)); userinfo(auth); },function(e){ w&&w.close();w=null; outLine("登录认证失败:"); outLine("["+e.code+"]:"+e.message); plus.nativeUI.alert("详情错误信息请参考授权登录(OAuth)规范文档:http://www.html5plus.org/#specification#/specification/OAuth.html",null,"登录失败["+e.code+"]:"+e.message); }); }else{ outLine("无效的登录认证通道!"); plus.nativeUI.alert("无效的登录认证通道!",null,"登录"); } } // 获取用户信息 function userinfo(a){ outLine("----- 获取用户信息 -----"); a.getUserInfo(function(){ outLine("获取用户信息成功:"); outLine(JSON.stringify(a.userInfo)); var nickname=a.userInfo.nickname||a.userInfo.name; plus.nativeUI.alert("欢迎“"+nickname+"”登录!"); },function(e){ outLine("获取用户信息失败:"); outLine("["+e.code+"]:"+e.message); plus.nativeUI.alert("获取用户信息失败!",null,"登录"); }); } // 注销登录 function logoutAll(){ outSet("----- 注销登录认证 -----"); for(var i in auths){ logout(auths[i]); } } function logout(auth){ auth.logout(function(){ outLine("注销\""+auth.description+"\"成功"); },function(e){ outLine("注销\""+auth.description+"\"失败:"+e.message); }); } </script> <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8"/> <style type="text/css"> #total{ -webkit-user-select:text; text-align:right; padding:0 1em; border: 0px; border-bottom:1px solid #ECB100; border-radius: 0; font-size:16px; width:30%; outline:none; } </style> </head> <body> <header id="header"> <div class="nvbt iback" onclick="back()"></div> <div class="nvtt">OAuth</div> <div class="nvbt idoc" onclick="openDoc('OAuth Document','/doc/oauth.html')"></div> </header> <div id="dcontent" class="dcontent"> <br/> <p id="info" style="padding: 0 1em;text-align:left;">登录认证通道信息:</p> <div style="padding: 0.5em 1em;"><hr color="#EEE"/></div> <br/> <div id="oauth"></div> <br/> <div class="button button-waring" onclick="logoutAll()">注销登录</div> </div> <div id="output"> OAuth模块管理客户端的用户授权登录验证功能,允许应用访问第三方平台的资源。 </div> </body> <script type="text/javascript" src="../js/immersed.js" ></script> </html>
Java
<?php declare(strict_types=1); namespace mglaman\PHPStanDrupal\Rules\Drupal; use Drupal\Core\Extension\ModuleHandlerInterface; use PhpParser\Node; use PHPStan\Analyser\Scope; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\ShouldNotHappenException; use PHPStan\Type\ObjectType; class LoadIncludes extends LoadIncludeBase { public function getNodeType(): string { return Node\Expr\MethodCall::class; } public function processNode(Node $node, Scope $scope): array { assert($node instanceof Node\Expr\MethodCall); if (!$node->name instanceof Node\Identifier) { return []; } $method_name = $node->name->toString(); if ($method_name !== 'loadInclude') { return []; } $args = $node->getArgs(); if (\count($args) < 2) { return []; } $variable = $node->var; if (!$variable instanceof Node\Expr\Variable) { return []; } $var_name = $variable->name; if (!is_string($var_name)) { throw new ShouldNotHappenException(sprintf('Expected string for variable in %s, please open an issue on GitHub https://github.com/mglaman/phpstan-drupal/issues', static::class)); } $moduleHandlerInterfaceType = new ObjectType(ModuleHandlerInterface::class); $variableType = $scope->getVariableType($var_name); if (!$variableType->isSuperTypeOf($moduleHandlerInterfaceType)->yes()) { return []; } try { // Try to invoke it similarly as the module handler itself. [$moduleName, $filename] = $this->parseLoadIncludeArgs($args[0], $args[1], $args[2] ?? null, $scope); $module = $this->extensionMap->getModule($moduleName); if ($module === null) { return [ RuleErrorBuilder::message(sprintf( 'File %s could not be loaded from %s::loadInclude because %s module is not found.', $filename, ModuleHandlerInterface::class, $moduleName )) ->line($node->getLine()) ->build() ]; } $file = $module->getAbsolutePath() . DIRECTORY_SEPARATOR . $filename; if (is_file($file)) { require_once $file; return []; } return [ RuleErrorBuilder::message(sprintf( 'File %s could not be loaded from %s::loadInclude', $module->getPath() . DIRECTORY_SEPARATOR . $filename, ModuleHandlerInterface::class )) ->line($node->getLine()) ->build() ]; } catch (\Throwable $e) { return [ RuleErrorBuilder::message(sprintf( 'A file could not be loaded from %s::loadInclude', ModuleHandlerInterface::class )) ->line($node->getLine()) ->build() ]; } } }
Java
# # linux/arch/arm/boot/compressed/Makefile # # create a compressed vmlinuz image from the original vmlinux # OBJS = plus_sec := $(call as-instr,.arch_extension sec,+sec) # Ensure that MMCIF loader code appears early in the image # to minimise that number of bocks that have to be read in # order to load it. ifeq ($(CONFIG_ZBOOT_ROM_MMCIF),y) OBJS += mmcif-sh7372.o endif # Ensure that SDHI loader code appears early in the image # to minimise that number of bocks that have to be read in # order to load it. ifeq ($(CONFIG_ZBOOT_ROM_SH_MOBILE_SDHI),y) OBJS += sdhi-shmobile.o OBJS += sdhi-sh7372.o endif AFLAGS_head.o += -DTEXT_OFFSET=$(TEXT_OFFSET) AFLAGS_head.o += -Wa,-march=armv7-a$(plus_sec) AFLAGS_misc.o += -Wa,-march=armv7-a$(plus_sec) AFLAGS_decompress.o += -Wa,-march=armv7-a$(plus_sec) AFLAGS_lib1funcs.o += -Wa,-march=armv7-a$(plus_sec) AFLAGS_ashldi3.o += -Wa,-march=armv7-a$(plus_sec) # Make sure we can use these during final link CFLAGS_misc.o += -ffat-lto-objects CFLAGS_decompress.o += -ffat-lto-objects CFLAGS_string.o += -ffat-lto-objects HEAD = head.o OBJS += misc.o decompress.o ifeq ($(CONFIG_KERNEL_LZ4),y) CFLAGS_decompress.o := -Os endif FONTC = $(srctree)/drivers/video/console/font_acorn_8x8.c # string library code (-Os is enforced to keep it much smaller) OBJS += string.o CFLAGS_string.o += -Os # # Architecture dependencies # ifeq ($(CONFIG_ARCH_ACORN),y) OBJS += ll_char_wr.o font.o endif ifeq ($(CONFIG_ARCH_SHARK),y) OBJS += head-shark.o ofw-shark.o endif ifeq ($(CONFIG_ARCH_P720T),y) # Borrow this code from SA1100 OBJS += head-sa1100.o endif ifeq ($(CONFIG_ARCH_SA1100),y) OBJS += head-sa1100.o endif ifeq ($(CONFIG_ARCH_VT8500),y) OBJS += head-vt8500.o endif ifeq ($(CONFIG_CPU_XSCALE),y) OBJS += head-xscale.o endif ifeq ($(CONFIG_PXA_SHARPSL_DETECT_MACH_ID),y) OBJS += head-sharpsl.o endif ifeq ($(CONFIG_CPU_ENDIAN_BE32),y) ifeq ($(CONFIG_CPU_CP15),y) OBJS += big-endian.o else # The endian should be set by h/w design. endif endif ifeq ($(CONFIG_ARCH_SHMOBILE),y) OBJS += head-shmobile.o endif # # We now have a PIC decompressor implementation. Decompressors running # from RAM should not define ZTEXTADDR. Decompressors running directly # from ROM or Flash must define ZTEXTADDR (preferably via the config) # FIXME: Previous assignment to ztextaddr-y is lost here. See SHARK ifeq ($(CONFIG_ZBOOT_ROM),y) ZTEXTADDR := $(CONFIG_ZBOOT_ROM_TEXT) ZBSSADDR := $(CONFIG_ZBOOT_ROM_BSS) else ZTEXTADDR := 0 ZBSSADDR := ALIGN(8) endif SEDFLAGS = s/TEXT_START/$(ZTEXTADDR)/;s/BSS_START/$(ZBSSADDR)/ suffix_$(CONFIG_KERNEL_GZIP) = gzip suffix_$(CONFIG_KERNEL_LZO) = lzo suffix_$(CONFIG_KERNEL_LZMA) = lzma suffix_$(CONFIG_KERNEL_XZ) = xzkern suffix_$(CONFIG_KERNEL_LZ4) = lz4 AFLAGS_piggy.$(suffix_y).o += -Wa,-march=armv7-a$(plus_sec) # Borrowed libfdt files for the ATAG compatibility mode libfdt := fdt_rw.c fdt_ro.c fdt_wip.c fdt.c libfdt_hdrs := fdt.h libfdt.h libfdt_internal.h libfdt_objs := $(addsuffix .o, $(basename $(libfdt))) $(addprefix $(obj)/,$(libfdt) $(libfdt_hdrs)): $(obj)/%: $(srctree)/scripts/dtc/libfdt/% $(call cmd,shipped) $(addprefix $(obj)/,$(libfdt_objs) atags_to_fdt.o): \ $(addprefix $(obj)/,$(libfdt_hdrs)) ifeq ($(CONFIG_ARM_ATAG_DTB_COMPAT),y) OBJS += $(libfdt_objs) atags_to_fdt.o endif targets := vmlinux vmlinux.lds \ piggy.$(suffix_y) piggy.$(suffix_y).o \ lib1funcs.o lib1funcs.S ashldi3.o ashldi3.S \ font.o font.c head.o misc.o $(OBJS) # Make sure files are removed during clean extra-y += piggy.gzip piggy.lzo piggy.lzma piggy.xzkern piggy.lz4 \ lib1funcs.S ashldi3.S $(libfdt) $(libfdt_hdrs) ifeq ($(CONFIG_FUNCTION_TRACER),y) ORIG_CFLAGS := $(KBUILD_CFLAGS) KBUILD_CFLAGS = $(subst -pg, , $(ORIG_CFLAGS)) endif ccflags-y := -fpic -fno-builtin -I$(obj) asflags-y := # Supply kernel BSS size to the decompressor via a linker symbol. KBSS_SZ = $(shell $(CROSS_COMPILE)size $(obj)/../../../../vmlinux | \ awk 'END{print $$3}') LDFLAGS_vmlinux = --defsym _kernel_bss_size=$(KBSS_SZ) # Supply ZRELADDR to the decompressor via a linker symbol. ifneq ($(CONFIG_AUTO_ZRELADDR),y) LDFLAGS_vmlinux += --defsym zreladdr=$(ZRELADDR) endif ifeq ($(CONFIG_CPU_ENDIAN_BE8),y) LDFLAGS_vmlinux += --be8 endif ifneq ($(PARAMS_PHYS),) LDFLAGS_vmlinux += --defsym params_phys=$(PARAMS_PHYS) endif # ? LDFLAGS_vmlinux += -p # Report unresolved symbol references LDFLAGS_vmlinux += --no-undefined # Delete all temporary local symbols LDFLAGS_vmlinux += -X # Next argument is a linker script LDFLAGS_vmlinux += -T # For __aeabi_uidivmod lib1funcs = $(obj)/lib1funcs.o $(obj)/lib1funcs.S: $(srctree)/arch/$(SRCARCH)/lib/lib1funcs.S $(call cmd,shipped) # For __aeabi_llsl ashldi3 = $(obj)/ashldi3.o $(obj)/ashldi3.S: $(srctree)/arch/$(SRCARCH)/lib/ashldi3.S $(call cmd,shipped) # We need to prevent any GOTOFF relocs being used with references # to symbols in the .bss section since we cannot relocate them # independently from the rest at run time. This can be achieved by # ensuring that no private .bss symbols exist, as global symbols # always have a GOT entry which is what we need. # The .data section is already discarded by the linker script so no need # to bother about it here. check_for_bad_syms = \ bad_syms=$$($(CROSS_COMPILE)nm $@ | sed -n 's/^.\{8\} [bc] \(.*\)/\1/p') && \ [ -z "$$bad_syms" ] || \ ( echo "following symbols must have non local/private scope:" >&2; \ echo "$$bad_syms" >&2; rm -f $@; false ) check_for_multiple_zreladdr = \ if [ $(words $(ZRELADDR)) -gt 1 -a "$(CONFIG_AUTO_ZRELADDR)" = "" ]; then \ echo 'multiple zreladdrs: $(ZRELADDR)'; \ echo 'This needs CONFIG_AUTO_ZRELADDR to be set'; \ false; \ fi $(obj)/vmlinux: $(obj)/vmlinux.lds $(obj)/$(HEAD) $(obj)/piggy.$(suffix_y).o \ $(addprefix $(obj)/, $(OBJS)) $(lib1funcs) $(ashldi3) FORCE @$(check_for_multiple_zreladdr) $(call if_changed,ld) @$(check_for_bad_syms) $(obj)/piggy.$(suffix_y): $(obj)/../Image FORCE $(call if_changed,$(suffix_y)) $(obj)/piggy.$(suffix_y).o: $(obj)/piggy.$(suffix_y) FORCE CFLAGS_font.o := -Dstatic= $(obj)/font.c: $(FONTC) $(call cmd,shipped) $(obj)/vmlinux.lds: $(obj)/vmlinux.lds.in arch/arm/boot/Makefile $(KCONFIG_CONFIG) @sed "$(SEDFLAGS)" < $< > $@
Java
convert images/OCS-755.png -crop 1665x5086+0+0 +repage images/OCS-755-A.png convert images/OCS-755.png -crop 1665x5086+1665+0 +repage images/OCS-755-B.png #/OCS-755.png # # #
Java
/* * $Id$ */ package edu.jas.gbufd; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.List; //import junit.framework.Test; //import junit.framework.TestCase; //import junit.framework.TestSuite; import edu.jas.arith.BigRational; import edu.jas.arith.ModInteger; import edu.jas.arith.ModIntegerRing; import edu.jas.gb.GroebnerBase; import edu.jas.poly.ExpVector; import edu.jas.poly.GenPolynomial; import edu.jas.poly.GenPolynomialTokenizer; import edu.jas.poly.Monomial; import edu.jas.poly.OrderedPolynomialList; import edu.jas.poly.PolyUtil; import edu.jas.poly.PolynomialList; /** * Groebner base FGLM examples. Without JUnit. * @author Jan Suess. */ public class GroebnerBaseFGLMExamples /*extends TestCase*/ { /** * main */ public static void main(String[] args) { //BasicConfigurator.configure(); //junit.textui.TestRunner.run(suite()); GroebnerBaseFGLMExamples ex = new GroebnerBaseFGLMExamples(); ex.testC5(); /* ex.xtestFiveVarsOrder(); ex.xtestCAP(); ex.xtestAUX(); ex.xtestModC5(); ex.xtestC6(); ex.xtestIsaac(); ex.xtestNiermann(); ex.ytestWalkS7(); ex.ytestCassouMod1(); ex.ytestOmdi1(); ex.ytestLamm1(); ex.xtestEquilibrium(); ex.xtestTrinks2(); ex.xtestHairerRungeKutta_1(); */ } /* * Constructs a <CODE>GroebnerBaseFGLMExamples</CODE> object. * @param name String. public GroebnerBaseFGLMExamples(String name) { super(name); } */ /* * suite. public static Test suite() { TestSuite suite = new TestSuite(GroebnerBaseFGLMExamples.class); return suite; } */ //field Q String all = "Zahlbereich | Ordnung | Elements G | Elements L | bitHeight G | bitHeight L | Deg G | Deg L | Time G | Time FGLM | Time L"; String grad = "Zahlbereich | Ordnung | Elements G | bitHeight G | Deg G | Time G | vDim"; String lex = "Zahlbereich | Ordnung | Elements L | bitHeight L | Deg L | Time L"; String fglm = "Zahlbereich | Ordnung | Elements G | Elements L | bitHeight G | bitHeight L | Deg G | Deg L | Time G | Time FGLM"; //MOD 1831 String modAll = "Zahlbereich | Ordnung | Elements G | Elements L | Deg G | Deg L | Time G | Time FGLM | Time L"; String modGrad = "Zahlbereich | Ordnung | Elements G | Deg G | Time G"; String modfglm = "Zahlbereich | Ordnung | Elements G | Elements L | Deg G | Deg L | Time G | Time FGLM"; /* @Override protected void setUp() { System.out.println("Setup"); } @Override protected void tearDown() { System.out.println("Tear Down"); } */ //Test with five variables and different variable orders public void xtestFiveVarsOrder() { String polynomials = "( " + " (v^8*x*y*z), ( w^3*x - 2*v), ( 4*x*y - 2 + y), ( 3*y^5 - 3 + z ), ( 8*y^2*z^2 + x * y^6 )" + ") "; String[] order = new String[] { "v", "w", "x", "y", "z" }; //String order1 = shuffle(order); String order2 = shuffle(order); //String order3 = shuffle(order); //String order4 = shuffle(order); //String order5 = shuffle(order); //String order6 = "(z,w,v,y,x)"; //langsam //String order7 = "(v,z,w,y,x)"; //langsam //String order8 = "(w,z,v,x,y)"; //langsam /* String erg1 = testGeneral(order1, polynomials); String erg2 = testGeneral(order2, polynomials); String erg3 = testGeneral(order3, polynomials); String erg4 = testGeneral(order4, polynomials); String erg5 = testGeneral(order5, polynomials); */ String ergM13 = modAll(order2, polynomials, 13); String ergM7 = modAll(order2, polynomials, 7); /* String ergOnlyL_1 = testOnlyLex(order1, polynomials); String ergOnlyL_2 = testOnlyLex(order2, polynomials); String ergOnlyL_3 = testOnlyLex(order3, polynomials); String ergOnlyL_4 = testOnlyLex(order4, polynomials); String ergOnlyL_5 = testOnlyLex(order5, polynomials); String erg6 = testGeneral(order6, polynomials); String erg7 = testGeneral(order7, polynomials); String erg8 = testGeneral(order8, polynomials); */ //langsam: (z,w,v,y,x), (v,z,w,y,x) /* System.out.println(categoryLex); System.out.println(ergOnlyL_1); System.out.println(ergOnlyL_2); System.out.println(ergOnlyL_3); System.out.println(ergOnlyL_4); System.out.println(ergOnlyL_5); System.out.println(category); System.out.println(erg6); System.out.println(erg7); System.out.println(erg8); System.out.println(erg1); System.out.println(erg2); System.out.println(erg3); System.out.println(erg4); System.out.println(erg5); */ System.out.println(all); System.out.println("Mod 13"); System.out.println(ergM13); System.out.println("Mod 7"); System.out.println(ergM7); } //=================================================================== //Examples taken from "Efficient Computation of Zero-Dimensional Gröbner Bases by Change of Ordering", // 1994, Faugere, Gianni, Lazard, Mora (FGLM) //=================================================================== public void xtestCAP() { String polynomials = "( " + " (y^2*z + 2*x*y*t - 2*x - z)," + "(-x^3*z + 4*x*y^2*z + 4*x^2*y*t + 2*y^3*t + 4*x^2 - 10*y^2 + 4*x*z - 10*y*t + 2)," + "(2*y*z*t + x*t^2 - x - 2*z)," + "(-x*z^3 + 4*y*z^2*t + 4*x*z*t^2 + 2*y*t^3 + 4*x*z + 4*z^2 - 10*y*t -10*t^2 + 2)" + ") "; String orderINV = "(x,y,z,t)"; String orderL = "(t,z,y,x)"; //Tests String erg_deg = grad(orderINV, polynomials); System.out.println(grad); System.out.println(erg_deg); String erg1 = all(orderINV, polynomials); String erg2 = all(orderL, polynomials); String ergMod1 = modAll(orderINV, polynomials, 1831); String ergMod2 = modAll(orderL, polynomials, 1831); System.out.println(all); System.out.println(erg1); System.out.println(erg2); System.out.println("\n"); System.out.println(modAll); System.out.println(ergMod1); System.out.println(ergMod2); } public void xtestAUX() { String polynomials = "( " + " (a^2*b*c + a*b^2*c + a*b*c^2 + a*b*c + a*b + a*c + b*c)," + "(a^2*b^2*c + a*b^2*c^2 + a^2*b*c + a*b*c + b*c + a + c )," + "(a^2*b^2*c^2 + a^2*b^2*c + a*b^2*c + a*b*c + a*c + c + 1)" + ") "; String orderINV = "(a,b,c)"; String orderL = "(c,b,a)"; //Tests String erg_deg = grad(orderINV, polynomials); System.out.println(grad); System.out.println(erg_deg); String erg1 = all(orderINV, polynomials); String erg2 = all(orderL, polynomials); String ergMod1 = modAll(orderINV, polynomials, 1831); String ergMod2 = modAll(orderL, polynomials, 1831); System.out.println(all); System.out.println(erg1); System.out.println(erg2); System.out.println("\n"); System.out.println(modAll); System.out.println(ergMod1); System.out.println(ergMod2); } public void testC5() { String polynomials = "( " + " (a + b + c + d + e)," + "(a*b + b*c + c*d + a*e + d*e)," + "(a*b*c + b*c*d + a*b*e + a*d*e + c*d*e)," + "(a*b*c*d + a*b*c*e + a*b*d*e + a*c*d*e + b*c*d*e)," + "(a*b*c*d*e -1)" + ") "; String orderINV = "(a,b,c,d,e)"; String orderL = "(e,d,c,b,a)"; //Tests String erg_deg = grad(orderINV, polynomials); //System.out.println(grad); //System.out.println(erg_deg); String erg1 = all(orderINV, polynomials); String erg2 = all(orderL, polynomials); String ergMod1 = modAll(orderINV, polynomials, 1831); String ergMod2 = modAll(orderL, polynomials, 1831); System.out.println(grad); System.out.println(erg_deg); System.out.println(""); System.out.println(all); System.out.println(erg1); System.out.println(erg2); System.out.println("\n"); System.out.println(modAll); System.out.println(ergMod1); System.out.println(ergMod2); } public void xtestModC5() { String polynomials = "( " + " (a + b + c + d + e)," + "(a*b + b*c + c*d + a*e + d*e)," + "(a*b*c + b*c*d + a*b*e + a*d*e + c*d*e)," + "(b*c*d + a*b*c*e + a*b*d*e + a*c*d*e + b*c*d*e)," + "(a*b*c*d*e -1)" + ") "; String orderINV = "(a,b,c,d,e)"; String orderL = "(e,d,c,b,a)"; //Tests String erg_deg = grad(orderL, polynomials); System.out.println(grad); System.out.println(erg_deg); /* String ergOnlyFGLM_1 = fglm(orderINV, polynomials); System.out.println(fglm); System.out.println(ergOnlyFGLM_1); //Tests MODULO String ergOnlyG_1 = modGrad(orderINV, polynomials, 1831); System.out.println(modGrad); System.out.println(ergOnlyG_1); String erg1 = modfglm(orderINV, polynomials, 1831); System.out.println(modfglm); System.out.println(erg1); */ } public void xtestC6() { String polynomials = "( " + " (a + b + c + d + e + f)," + "(a*b + b*c + c*d + d*e + e*f + a*f)," + "(a*b*c + b*c*d + c*d*e + d*e*f + a*e*f + a*b*f)," + "(a*b*c*d + b*c*d*e + c*d*e*f + a*d*e*f + a*b*e*f + a*b*c*f)," + "(a*b*c*d*e + b*c*d*e*f + a*c*d*e*f + a*b*d*e*f + a*b*c*e*f + a*b*c*d*f)," + "(a*b*c*d*e*f - 1)" + ") "; String orderINV = "(a,b,c,d,e,f)"; String orderL = "(f,e,d,c,b,a)"; //Tests /* String erg2 = modAll(orderINV, polynomials, 1831); System.out.println(modAll); System.out.println(erg2); String ergOnlyG_1 = modGrad(orderINV, polynomials, 1831); System.out.println(modGrad); System.out.println(ergOnlyG_1); String erg1 = modfglm(orderINV, polynomials, 1831); System.out.println(modfglm); System.out.println(erg1); */ } //=================================================================== //Examples taken from "Der FGLM-Algorithmus: verallgemeinert und implementiert in SINGULAR", 1997, Wichmann //=================================================================== public void xtestIsaac() { String polynomials = "( " + " (8*w^2 + 5*w*x - 4*w*y + 2*w*z + 3*w + 5*x^2 + 2*x*y - 7*x*z - 7*x + 7*y^2 -8*y*z - 7*y + 7*z^2 - 8*z + 8)," + "(3*w^2 - 5*w*x - 3*w*y - 6*w*z + 9*w + 4*x^2 + 2*x*y - 2*x*z + 7*x + 9*y^2 + 6*y*z + 5*y + 7*z^2 + 7*z + 5)," + "(-2*w^2 + 9*w*x + 9*w*y - 7*w*z - 4*w + 8*x^2 + 9*x*y - 3*x*z + 8*x + 6*y^2 - 7*y*z + 4*y - 6*z^2 + 8*z + 2)," + "(7*w^2 + 5*w*x + 3*w*y - 5*w*z - 5*w + 2*x^2 + 9*x*y - 7*x*z + 4*x -4*y^2 - 5*y*z + 6*y - 4*z^2 - 9*z + 2)" + ") "; String orderINV = "(w,x,y,z)"; String orderL = "(z,y,x,w)"; //Tests String erg_deg = grad(orderL, polynomials); System.out.println(grad); System.out.println(erg_deg); /* String erg3 = all(orderINV, polynomials); System.out.println(all); System.out.println(erg3); String ergOnlyLex_1 = lex(orderINV, polynomials); String ergOnlyLex_2 = lex(orderL, polynomials); System.out.println(lex); System.out.println(ergOnlyLex_1); System.out.println(ergOnlyLex_2); String ergOnlyFGLM_1 = fglm(orderINV, polynomials); String ergOnlyFGLM_2 = fglm(orderL, polynomials); System.out.println(fglm); System.out.println(ergOnlyFGLM_1); System.out.println(ergOnlyFGLM_2); String ergm1 = modAll(orderINV, polynomials, 2147464751); String ergm2 = modAll(orderL, polynomials, 2147464751); System.out.println(modAll); System.out.println(ergm1); System.out.println(ergm2); */ } public void xtestNiermann() { String polynomials = "( " + " (x^2 + x*y^2*z - 2*x*y + y^4 + y^2 + z^2)," + "(-x^3*y^2 + x*y^2*z + x*y*z^3 - 2*x*y + y^4)," + "(-2*x^2*y + x*y^4 + y*z^4 - 3)" + ") "; String orderINV = "(x,y,z)"; String orderL = "(z,y,x)"; //Tests String erg_deg = grad(orderINV, polynomials); System.out.println(grad); System.out.println(erg_deg); /* String erg1 = fglm(orderINV, polynomials); String erg2 = fglm(orderL, polynomials); System.out.println(fglm); System.out.println(erg1); System.out.println(erg2); */ String ergm1 = modfglm(orderINV, polynomials, 1831); String ergm2 = modfglm(orderL, polynomials, 2147464751); System.out.println(modfglm); System.out.println(ergm1); System.out.println(ergm2); } public void ytestWalkS7() { String polynomials = "( " + " (2*g*b + 2*f*c + 2*e*d + a^2 + a)," + "(2*g*c + 2*f*d + e^2 + 2*b*a + b)," + "(2*g*d + 2*f*e + 2*c*a + c + b^2)," + "(2*g*e + f^2 + 2*d*a + d + 2*c*b)," + "(2*g*f + 2*e*a + e + 2*d*b + c^2)," + "(g^2 + 2*f*a + f + 2*e*b + 2*d*c)," + "(2*g*a + g + 2*f*b + 2*e*c + d^2)" + ") "; String orderINV = "(a,b,c,d,e,f,g)"; String orderL = "(g,f,e,d,c,b,a)"; //Tests //String ergm1 = modAll(orderINV, polynomials, 2147464751); //String ergm2 = modfglm(orderL, polynomials, 1831); //System.out.println(modfglm); //System.out.println(ergm1); //System.out.println(ergm2); String erg2 = fglm(orderL, polynomials); System.out.println(fglm); System.out.println(erg2); } public void ytestCassouMod1() { String polynomials = "( " + " (15*a^4*b*c^2 + 6*a^4*b^3 + 21*a^4*b^2*c - 144*a^2*b - 8*a^2*b^2*d - 28*a^2*b*c*d - 648*a^2*c + 36*c^2*d + 9*a^4*c^3 - 120)," + "(30*b^3*a^4*c - 32*c*d^2*b - 720*c*a^2*b - 24*b^3*a^2*d - 432*b^2*a^2 + 576*d*b - 576*c*d + 16*b*a^2*c^2*d + 16*c^2*d^2 + 16*d^2*b^2 + 9*b^4*a^4 + 5184 + 39*c^2*a^4*b^2 + 18*c^3*a^4*b - 432*c^2*a^2 + 24*c^3*a^2*d - 16*b^2*a^2*c*d - 240*b)," + "(216*c*a^2*b - 162*c^2*a^2 - 81*b^2*a^2 + 5184 + 1008*d*b - 1008*c*d + 15*b^2*a^2*c*d - 15*b^3*a^2*d - 80*c*d^2*b + 40*c^2*d^2 + 40*d^2*b^2)," + "(261 + 4*c*a^2*b - 3*c^2*a^2 - 4*b^2*a^2 + 22*d*b - 22*c*d)" + ") "; String orderINV = "(a,b,c,d)"; String orderL = "(d,c,b,a)"; //Tests String ergm1 = modfglm(orderL, polynomials, 1831); String ergm2 = modfglm(orderINV, polynomials, 1831); System.out.println(modfglm); System.out.println(ergm1); System.out.println(ergm2); } public void ytestOmdi1() { String polynomials = "( " + " (a + c + v + 2*x - 1)," + "(a*b + c*u + 2*v*w + 2*x*y + 2*x*z -2/3)," + "(a*b^2 + c*u^2 + 2*v*w^2 + 2*x*y^2 + 2*x*z^2 - 2/5)," + "(a*b^3 + c*u^3 + 2*v*w^3 + 2*x*y^3 + 2*x*z^3 - 2/7)," + "(a*b^4 + c*u^4 + 2*v*w^4 + 2*x*y^4 + 2*x*z^4 - 2/9)," + "(v*w^2 + 2*x*y*z - 1/9)," + "(v*w^4 + 2*x*y^2*z^2 - 1/25)," + "(v*w^3 + 2*x*y*z^2 + x*y^2*z - 1/15)," + "(v*w^4 + x*y*z^3 + x*y^3*z -1/21)" + ") "; String orderINV = "(a,b,c,u,v,w,x,y,z)"; String orderL = "(z,y,x,w,v,u,c,b,a)"; //Tests String erg_deg = grad(orderL, polynomials); System.out.println(grad); System.out.println(erg_deg); /* String ergm1 = modfglm(orderL, polynomials, 1831); String ergm2 = modfglm(orderINV, polynomials, 1831); System.out.println(modfglm); System.out.println(ergm1); System.out.println(ergm2); */ } public void ytestLamm1() { String polynomials = "( " + " (45*x^8 + 3*x^7 + 39*x^6 + 30*x^5 + 13*x^4 + 41*x^3 + 5*x^2 + 46*x + 7)," + "(49*x^7*y + 35*x*y^7 + 37*x*y^6 + 9*y^7 + 4*x^6 + 6*y^6 + 27*x^3*y^2 + 20*x*y^4 + 31*x^4 + 33*x^2*y + 24*x^2 + 49*y + 43)" + ") "; String orderINV = "(x,y)"; String orderL = "(y,x)"; //Tests String erg_deg = grad(orderINV, polynomials); System.out.println(grad); System.out.println(erg_deg); String erg1 = all(orderINV, polynomials); String erg2 = all(orderL, polynomials); String ergMod1 = modAll(orderINV, polynomials, 1831); String ergMod2 = modAll(orderL, polynomials, 1831); System.out.println(all); System.out.println(erg1); System.out.println(erg2); System.out.println("\n"); System.out.println(modAll); System.out.println(ergMod1); System.out.println(ergMod2); } //=================================================================== //Examples taken from "Some Examples for Solving Systems of Algebraic Equations by Calculating Gröbner Bases", 1984, Boege, Gebauer, Kredel //=================================================================== public void xtestEquilibrium() { String polynomials = "( " + " (y^4 - 20/7*z^2)," + "(z^2*x^4 + 7/10*z*x^4 + 7/48*x^4 - 50/27*z^2 - 35/27*z - 49/216)," + "(x^5*y^3 + 7/5*z^4*y^3 + 609/1000 *z^3*y^3 + 49/1250*z^2*y^3 - 27391/800000*z*y^3 - 1029/160000*y^3 + 3/7*z^5*x*y^2 +" + "3/5*z^6*x*y^2 + 63/200*z^3*x*y^2 + 147/2000*z^2*x*y^2 + 4137/800000*z*x*y^2 - 7/20*z^4*x^2*y - 77/125*z^3*x^2*y" + "- 23863/60000*z^2*x^2*y - 1078/9375*z*x^2*y - 24353/1920000*x^2*y - 3/20*z^4*x^3 - 21/100*z^3*x^3" + "- 91/800*z^2*x^3 - 5887/200000*z*x^3 - 343/128000*x^3)" + ") "; String order = "(x,y,z)"; //Tests String ergOnlyG_1 = grad(order, polynomials); System.out.println(grad); System.out.println(ergOnlyG_1); } public void xtestTrinks2() { String polynomials = "( " + " (45*p + 35*s - 165*b - 36)," + "(35*p + 40*z + 25*t - 27*s)," + "(15*w + 25*p*s + 30*z - 18*t - 165*b^2)," + "(-9*w + 15*p*t + 20*z*s)," + "(w*p + 2*z*t - 11*b^3)," + "(99*w - 11*s*b + 3*b^2)," + "(b^2 + 33/50*b + 2673/10000)" + ") "; String order1 = "(b,s,t,z,p,w)"; String order2 = "(s,b,t,z,p,w)"; String order3 = "(s,t,b,z,p,w)"; String order4 = "(s,t,z,p,b,w)"; String order5 = "(s,t,z,p,w,b)"; String order6 = "(s,z,p,w,b,t)"; String order7 = "(p,w,b,t,s,z)"; String order8 = "(z,w,b,s,t,p)"; String order9 = "(t,z,p,w,b,s)"; String order10 = "(z,p,w,b,s,t)"; String order11 = "(p,w,b,s,t,z)"; String order12 = "(w,b,s,t,z,p)"; //Tests String erg_1 = all(order1, polynomials); String erg_2 = all(order2, polynomials); String erg_3 = all(order3, polynomials); String erg_4 = all(order4, polynomials); String erg_5 = all(order5, polynomials); String erg_6 = all(order6, polynomials); String erg_7 = all(order7, polynomials); String erg_8 = all(order8, polynomials); String erg_9 = all(order9, polynomials); String erg_10 = all(order10, polynomials); String erg_11 = all(order11, polynomials); String erg_12 = all(order12, polynomials); System.out.println(all); System.out.println(erg_1); System.out.println(erg_2); System.out.println(erg_3); System.out.println(erg_4); System.out.println(erg_5); System.out.println(erg_6); System.out.println(erg_7); System.out.println(erg_8); System.out.println(erg_9); System.out.println(erg_10); System.out.println(erg_11); System.out.println(erg_12); } public void xtestHairerRungeKutta_1() { String polynomials = "( " + " (a-f),(b-h-g),(e+d+c-1),(d*a+c*b-1/2),(d*a^2+c*b^2-1/3),(c*g*a-1/6)" + ") "; String[] order = new String[] { "a", "b", "c", "d", "e", "f", "g", "h" }; String order1 = shuffle(order); String order2 = shuffle(order); String order3 = shuffle(order); String order4 = shuffle(order); String order5 = shuffle(order); // langsam (e,d,h,c,g,a,f,b), (h,d,b,e,c,g,a,f) um die 120 // sehr langsam (e,h,d,c,g,b,a,f) um die 1000 // sehr schnell (g,b,f,h,c,d,a,e), (h,c,a,g,d,f,e,b) 1 millisec String ergOnlyG_1 = grad(order1, polynomials); System.out.println(grad); System.out.println(ergOnlyG_1); String ergOnlyL_1 = lex(order1, polynomials); String ergOnlyL_2 = lex(order2, polynomials); String ergOnlyL_3 = lex(order3, polynomials); String ergOnlyL_4 = lex(order4, polynomials); String ergOnlyL_5 = lex(order5, polynomials); System.out.println(lex); System.out.println(ergOnlyL_1); System.out.println(ergOnlyL_2); System.out.println(ergOnlyL_3); System.out.println(ergOnlyL_4); System.out.println(ergOnlyL_5); //String ergGeneral = all(order, polynomials); //System.out.println(all); //System.out.println(ergGeneral); } //================================================================================================= //Internal methods //================================================================================================= @SuppressWarnings("unchecked") public String all(String order, String polynomials) { GroebnerBaseFGLM<BigRational> IdealObjectFGLM; BigRational coeff = new BigRational(); GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff); String polynomials_Grad = order + " G " + polynomials; String polynomials_Lex = order + " L " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<BigRational> G = null; Reader sourceL = new StringReader(polynomials_Lex); GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL); PolynomialList<BigRational> L = null; try { G = (PolynomialList<BigRational>) parserG.nextPolynomialSet(); L = (PolynomialList<BigRational>) parserL.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("Input " + G); System.out.println("Input " + L); //Computation of the Groebnerbase with Buchberger w.r.t INVLEX long buchberger_Lex = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GL = gb.GB(L.list); buchberger_Lex = System.currentTimeMillis() - buchberger_Lex; //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG); //PolynomialList<BigRational> GLL = new PolynomialList<BigRational>(L.ring, GL); IdealObjectFGLM = new GroebnerBaseFGLM<BigRational>(); //GGG); //IdealObjectLex = new GroebnerBaseSeq<BigRational>(GLL); long tconv = System.currentTimeMillis(); List<GenPolynomial<BigRational>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG); tconv = System.currentTimeMillis() - tconv; OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG); OrderedPolynomialList<BigRational> o2 = new OrderedPolynomialList<BigRational>( resultFGLM.get(0).ring, resultFGLM); //List<GenPolynomial<BigRational>> resultBuchberger = GL; OrderedPolynomialList<BigRational> o3 = new OrderedPolynomialList<BigRational>(GL.get(0).ring, GL); int grad_numberOfElements = GG.size(); int lex_numberOfElements = resultFGLM.size(); long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); // IdealObjectFGLM.maxDegreeOfGB(); long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GL); // IdealObjectLex.maxDegreeOfGB(); int grad_height = bitHeight(GG); int lex_height = bitHeight(resultFGLM); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2); System.out.println("Groebnerbase Buchberger (INVLEX) " + o3); String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |" + lex_numberOfElements + " |" + grad_height + " |" + lex_height + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv + " |" + buchberger_Lex; //assertEquals(o2, o3); if (! o2.equals(o3) ) { throw new RuntimeException("FGLM != GB: " + o2 + " != " + o3); } return erg; } @SuppressWarnings("unchecked") public String fglm(String order, String polynomials) { GroebnerBaseFGLM<BigRational> IdealObjectGrad; //GroebnerBaseAbstract<BigRational> IdealObjectLex; BigRational coeff = new BigRational(); GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff); String polynomials_Grad = order + " G " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<BigRational> G = null; try { G = (PolynomialList<BigRational>) parserG.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("Input " + G); //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG); IdealObjectGrad = new GroebnerBaseFGLM<BigRational>(); //GGG); long tconv = System.currentTimeMillis(); List<GenPolynomial<BigRational>> resultFGLM = IdealObjectGrad.convGroebnerToLex(GG); tconv = System.currentTimeMillis() - tconv; //PolynomialList<BigRational> LLL = new PolynomialList<BigRational>(G.ring, resultFGLM); //IdealObjectLex = new GroebnerBaseSeq<BigRational>(); //LLL); OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG); OrderedPolynomialList<BigRational> o2 = new OrderedPolynomialList<BigRational>( resultFGLM.get(0).ring, resultFGLM); int grad_numberOfElements = GG.size(); int lex_numberOfElements = resultFGLM.size(); long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); //IdealObjectGrad.maxDegreeOfGB(); long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(resultFGLM); //IdealObjectLex.maxDegreeOfGB(); int grad_height = bitHeight(GG); int lex_height = bitHeight(resultFGLM); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2); String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |" + lex_numberOfElements + " |" + grad_height + " |" + lex_height + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv; return erg; } @SuppressWarnings("unchecked") public String grad(String order, String polynomials) { BigRational coeff = new BigRational(); GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff); String polynomials_Grad = order + " G " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<BigRational> G = null; try { G = (PolynomialList<BigRational>) parserG.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("Input " + G); //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<BigRational> GGG = new PolynomialList<BigRational>(G.ring, GG); OrderedPolynomialList<BigRational> o1 = new OrderedPolynomialList<BigRational>(GG.get(0).ring, GG); GroebnerBaseFGLM<BigRational> IdealObjectGrad; IdealObjectGrad = new GroebnerBaseFGLM<BigRational>(); //GGG); long grad_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GG); //IdealObjectGrad.maxDegreeOfGB(); List<GenPolynomial<BigRational>> reducedTerms = IdealObjectGrad.redTerms(GG); OrderedPolynomialList<BigRational> o4 = new OrderedPolynomialList<BigRational>( reducedTerms.get(0).ring, reducedTerms); int grad_numberOfReducedElements = reducedTerms.size(); int grad_numberOfElements = GG.size(); int grad_height = bitHeight(GG); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Reduced Terms" + o4); String erg = "BigRational |" + order + " |" + grad_numberOfElements + " |" + grad_height + " |" + grad_maxPolyGrad + " |" + buchberger_Grad + " |" + grad_numberOfReducedElements; return erg; } @SuppressWarnings("unchecked") public String lex(String order, String polynomials) { //GroebnerBaseAbstract<BigRational> IdealObjectLex; BigRational coeff = new BigRational(); GroebnerBase<BigRational> gb = GBFactory.getImplementation(coeff); String polynomials_Lex = order + " L " + polynomials; Reader sourceL = new StringReader(polynomials_Lex); GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL); PolynomialList<BigRational> L = null; try { L = (PolynomialList<BigRational>) parserL.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("Input " + L); //Computation of the Groebnerbase with Buchberger w.r.t INVLEX long buchberger_Lex = System.currentTimeMillis(); List<GenPolynomial<BigRational>> GL = gb.GB(L.list); buchberger_Lex = System.currentTimeMillis() - buchberger_Lex; //PolynomialList<BigRational> GLL = new PolynomialList<BigRational>(L.ring, GL); //IdealObjectLex = new GroebnerBaseAbstract<BigRational>(GLL); OrderedPolynomialList<BigRational> o3 = new OrderedPolynomialList<BigRational>(GL.get(0).ring, GL); int lex_numberOfElements = GL.size(); long lex_maxPolyGrad = PolyUtil.<BigRational> totalDegreeLeadingTerm(GL); //IdealObjectLex.maxDegreeOfGB(); int lexHeigth = bitHeight(GL); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbase Buchberger (INVLEX) " + o3); String erg = "BigRational" + order + "|" + lex_numberOfElements + " |" + lexHeigth + " |" + lex_maxPolyGrad + " |" + buchberger_Lex; return erg; } @SuppressWarnings("unchecked") public String modAll(String order, String polynomials, Integer m) { GroebnerBaseFGLM<ModInteger> IdealObjectFGLM; //GroebnerBaseAbstract<ModInteger> IdealObjectLex; ModIntegerRing ring = new ModIntegerRing(m); GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring); String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials; String polynomials_Lex = "Mod " + ring.modul + " " + order + " L " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<ModInteger> G = null; Reader sourceL = new StringReader(polynomials_Lex); GenPolynomialTokenizer parserL = new GenPolynomialTokenizer(sourceL); PolynomialList<ModInteger> L = null; try { G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet(); L = (PolynomialList<ModInteger>) parserL.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("G= " + G); System.out.println("L= " + L); //Computation of the Groebnerbase with Buchberger w.r.t INVLEX long buchberger_Lex = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> GL = gb.GB(L.list); buchberger_Lex = System.currentTimeMillis() - buchberger_Lex; //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG); //PolynomialList<ModInteger> GLL = new PolynomialList<ModInteger>(L.ring, GL); IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG); //IdealObjectLex = new GroebnerBaseAbstract<ModInteger>(GLL); long tconv = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG); tconv = System.currentTimeMillis() - tconv; OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG); OrderedPolynomialList<ModInteger> o2 = new OrderedPolynomialList<ModInteger>(resultFGLM.get(0).ring, resultFGLM); List<GenPolynomial<ModInteger>> resultBuchberger = GL; OrderedPolynomialList<ModInteger> o3 = new OrderedPolynomialList<ModInteger>( resultBuchberger.get(0).ring, resultBuchberger); int grad_numberOfElements = GG.size(); int lex_numberOfElements = resultFGLM.size(); long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB(); long lex_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GL); //IdealObjectLex.maxDegreeOfGB(); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2); System.out.println("Groebnerbase Buchberger (INVLEX) " + o3); String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |" + lex_numberOfElements + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv + " |" + buchberger_Lex; //assertEquals(o2, o3); if (! o2.equals(o3) ) { throw new RuntimeException("FGLM != GB: " + o2 + " != " + o3); } return erg; } @SuppressWarnings("unchecked") public String modGrad(String order, String polynomials, Integer m) { //GroebnerBaseFGLM<ModInteger> IdealObjectFGLM; ModIntegerRing ring = new ModIntegerRing(m); GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring); String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<ModInteger> G = null; try { G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("G= " + G); //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG); //IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG); OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG); int grad_numberOfElements = GG.size(); long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB(); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |" + grad_maxPolyGrad + " |" + buchberger_Grad; return erg; } @SuppressWarnings("unchecked") public String modfglm(String order, String polynomials, Integer m) { GroebnerBaseFGLM<ModInteger> IdealObjectFGLM; //GroebnerBaseAbstract<ModInteger> IdealObjectLex; ModIntegerRing ring = new ModIntegerRing(m); GroebnerBase<ModInteger> gb = GBFactory.getImplementation(ring); String polynomials_Grad = "Mod " + ring.modul + " " + order + " G " + polynomials; Reader sourceG = new StringReader(polynomials_Grad); GenPolynomialTokenizer parserG = new GenPolynomialTokenizer(sourceG); PolynomialList<ModInteger> G = null; try { G = (PolynomialList<ModInteger>) parserG.nextPolynomialSet(); } catch (IOException e) { e.printStackTrace(); return "fail"; } System.out.println("G= " + G); //Computation of the Groebnerbase with Buchberger w.r.t GRADLEX (Total degree + INVLEX) long buchberger_Grad = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> GG = gb.GB(G.list); buchberger_Grad = System.currentTimeMillis() - buchberger_Grad; //PolynomialList<ModInteger> GGG = new PolynomialList<ModInteger>(G.ring, GG); IdealObjectFGLM = new GroebnerBaseFGLM<ModInteger>(); //GGG); long tconv = System.currentTimeMillis(); List<GenPolynomial<ModInteger>> resultFGLM = IdealObjectFGLM.convGroebnerToLex(GG); tconv = System.currentTimeMillis() - tconv; //PolynomialList<ModInteger> LLL = new PolynomialList<ModInteger>(G.ring, resultFGLM); //IdealObjectLex = new GroebnerBaseAbstract<ModInteger>(LLL); OrderedPolynomialList<ModInteger> o1 = new OrderedPolynomialList<ModInteger>(GG.get(0).ring, GG); OrderedPolynomialList<ModInteger> o2 = new OrderedPolynomialList<ModInteger>(resultFGLM.get(0).ring, resultFGLM); int grad_numberOfElements = GG.size(); int lex_numberOfElements = resultFGLM.size(); long grad_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(GG); //IdealObjectFGLM.maxDegreeOfGB(); long lex_maxPolyGrad = PolyUtil.<ModInteger> totalDegreeLeadingTerm(resultFGLM); //IdealObjectLex.maxDegreeOfGB(); System.out.println("Order of Variables: " + order); System.out.println("Groebnerbases: "); System.out.println("Groebnerbase Buchberger (IGRLEX) " + o1); System.out.println("Groebnerbase FGML (INVLEX) computed from Buchberger (IGRLEX) " + o2); String erg = "Mod " + m + " |" + order + " |" + grad_numberOfElements + " |" + lex_numberOfElements + " |" + grad_maxPolyGrad + " |" + lex_maxPolyGrad + " |" + buchberger_Grad + " |" + tconv; return erg; } /** * Method shuffle returns a random permutation of a string of variables. */ public String shuffle(String[] tempOrder) { Collections.shuffle(Arrays.asList(tempOrder)); StringBuffer ret = new StringBuffer("("); ret.append(ExpVector.varsToString(tempOrder)); ret.append(")"); return ret.toString(); } /** * Method bitHeight returns the bitlength of the greatest number * occurring during the computation of a Groebner base. */ public int bitHeight(List<GenPolynomial<BigRational>> list) { BigInteger denom = BigInteger.ONE; BigInteger num = BigInteger.ONE; for (GenPolynomial<BigRational> g : list) { for (Monomial<BigRational> m : g) { BigRational bi = m.coefficient(); BigInteger i = bi.denominator().abs(); BigInteger j = bi.numerator().abs(); if (i.compareTo(denom) > 0) denom = i; if (j.compareTo(num) > 0) num = j; } } int erg; if (denom.compareTo(num) > 0) { erg = denom.bitLength(); } else { erg = num.bitLength(); } return erg; } }
Java
/* * Animation plugin for compiz/beryl * * animation.c * * Copyright : (C) 2006 Erkin Bahceci * E-mail : erkinbah@gmail.com * * Based on Wobbly and Minimize plugins by * : David Reveman * E-mail : davidr@novell.com> * * Particle system added by : (C) 2006 Dennis Kasprzyk * E-mail : onestone@beryl-project.org * * Beam-Up added by : Florencio Guimaraes * E-mail : florencio@nexcorp.com.br * * Hexagon tessellator added by : Mike Slegeir * E-mail : mikeslegeir@mail.utexas.edu> * * 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 "private.h" // ===================== Effect: Leaf Spread ========================= const float LeafSpreadAnim::kDurationFactor = 1.67; LeafSpreadAnim::LeafSpreadAnim (CompWindow *w, WindowEvent curWindowEvent, float duration, const AnimEffect info, const CompRect &icon) : Animation::Animation (w, curWindowEvent, kDurationFactor * duration, info, icon), PolygonAnim::PolygonAnim (w, curWindowEvent, kDurationFactor * duration, info, icon) { mDoDepthTest = true; mDoLighting = true; mCorrectPerspective = CorrectPerspectivePolygon; } void LeafSpreadAnim::init () { if (!tessellateIntoRectangles (20, 14, 15.0f)) return; CompRect outRect (mAWindow->savedRectsValid () ? mAWindow->savedOutRect () : mWindow->outputRect ()); float fadeDuration = 0.26; float life = 0.4; float spreadFac = 3.5; float randYMax = 0.07; float winFacX = outRect.width () / 800.0; float winFacY = outRect.height () / 800.0; float winFacZ = (outRect.height () + outRect.width ()) / 2.0 / 800.0; float screenSizeFactor = (0.8 * DEFAULT_Z_CAMERA * ::screen->width ()); foreach (PolygonObject *p, mPolygons) { p->rotAxis.set (RAND_FLOAT (), RAND_FLOAT (), RAND_FLOAT ()); float speed = screenSizeFactor / 10 * (0.2 + RAND_FLOAT ()); float xx = 2 * (p->centerRelPos.x () - 0.5); float yy = 2 * (p->centerRelPos.y () - 0.5); float x = speed * winFacX * spreadFac * (xx + 0.5 * (RAND_FLOAT () - 0.5)); float y = speed * winFacY * spreadFac * (yy + 0.5 * (RAND_FLOAT () - 0.5)); float z = speed * winFacZ * 7 * ((RAND_FLOAT () - 0.5) / 0.5); p->finalRelPos.set (x, y, z); p->moveStartTime = p->centerRelPos.y () * (1 - fadeDuration - randYMax) + randYMax * RAND_FLOAT (); p->moveDuration = 1; p->fadeStartTime = p->moveStartTime + life; if (p->fadeStartTime > 1 - fadeDuration) p->fadeStartTime = 1 - fadeDuration; p->fadeDuration = fadeDuration; p->finalRotAng = 150; } }
Java
/**************** * Applications * ****************/ /* used by gnome-font-viewer and sushi */ SushiFontWidget { padding: 6px 12px; } /************ * nautilus * ************/ .nautilus-canvas-item { border-radius: 0; } .nautilus-desktop.nautilus-canvas-item { color: white; text-shadow: 1px 2px 3px alpha(@dark_shadow, 0.9) } .nautilus-desktop.nautilus-canvas-item:active { color: @theme_fg_color; } .nautilus-desktop.nautilus-canvas-item:selected { color: @theme_selected_fg_color; } .nautilus-canvas-item:selected:backdrop { background-color: shade(@bg_color,0.7); } .nautilus-desktop.nautilus-canvas-item:active, .nautilus-desktop.nautilus-canvas-item:prelight, .nautilus-desktop.nautilus-canvas-item:selected { text-shadow: none; } NautilusWindow .toolbar { border-width: 0 0 1px; border-style: solid; border-color: shade(@toolbar_bg_color, 0.7); } NautilusWindow .sidebar .frame { border-style: none; } NautilusWindow .sidebar row:hover { background-color: shade (@theme_bg_color, 0.95); } NautilusWindow * { -GtkPaned-handle-size: 1px; } NautilusWindow .pane-separator { background-image: url("../assets/null.png"); } NautilusWindow .button.sidebar-button:hover, NautilusWindow .button.sidebar-button:hover:active { border: 1px solid @borders; background-image: linear-gradient(to bottom, shade(shade(@theme_bg_color, 1.02), 1.12), shade(shade(@theme_bg_color, 1.02), 0.96) ); } NautilusWindow > GtkGrid > .pane-separator, NautilusWindow > GtkGrid > .pane-separator:hover { border-width: 0 1px 0 0; border-style: solid; border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 1.08); color: shade (@theme_bg_color, 0.9); } NautilusNotebook.notebook { border-right-width: 1px; border-left-width: 1px; border-bottom-width: 1px; } NautilusNotebook .frame, NautilusWindow .sidebar .frame { border-width: 0; border-image: none; } NautilusQueryEditor .search-bar.toolbar { border-top-width: 0; border-bottom-width: 0; } NautilusQueryEditor .toolbar { padding-top: 4px; padding-bottom: 2px; border-width: 1px 0 0 0; border-style: solid; border-color: shade(@toolbar_bg_color, 0.8); background-image: none; } NautilusQueryEditor .toolbar:first-child { padding-top: 4px; padding-bottom: 2px; } NautilusQueryEditor .toolbar:last-child, NautilusQueryEditor .search-bar.toolbar:only-child { padding-top: 4px; padding-bottom: 2px; border-bottom-width: 1px; border-bottom-color: shade(@toolbar_bg_color, 0.8); background-image: none; } NautilusListView GtkTreeView { border-color: @borders; /*Temp fix*/ } NautilusListView .view { border-bottom: 1px solid @theme_bg_color; } /****************** * gnome terminal * ******************/ TerminalWindow.background { background-color: transparent; } TerminalWindow GtkNotebook.notebook { border-right-width: 0; border-left-width: 0; border-bottom-width: 0; } /* no transparent background for gnome terminal scrollbars : remove this section if you have installed a patched version of gnome-terminal with transparency enabled */ TerminalWindow .scrollbars-junction,TerminalWindow .scrollbar.trough, TerminalWindow .scrollbars-junction.frame, TerminalWindow .frame.scrollbar.trough { border-color: @borders; background-color: @theme_bg_color; } TerminalWindow .scrollbars-junction:backdrop,TerminalWindow .scrollbar.trough:backdrop, TerminalWindow .scrollbars-junction.frame:backdrop, TerminalWindow .frame.scrollbar.trough:backdrop { border-color: @borders; background-color: @theme_bg_color; } TerminalWindow .scrollbar.vertical .slider { margin-left: 3px; } TerminalWindow .scrollbar.trough { border-width: 0; } /********* * gedit * *********/ GeditWindow * { -GtkPaned-handle-size: 1; } GeditWindow .pane-separator, GeditWindow .pane-separator:hover { border-width: 0 1px 1px 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 0.8); background-image: url("../assets/null.png"); color: shade(@theme_bg_color, 1.0); } GeditPanel.title GtkLabel { padding: 4px 0; } GeditPanel.vertical .title { padding: 4px 0 4px 3px; border-style: none; } GeditPanel .toolbar { border-style: none; background-color: transparent; } GeditDocumentsPanel .view { background-color: @theme_bg_color; } GeditStatusComboBox .button, GeditStatusComboBox .button:hover, GeditStatusComboBox .button:active, GeditStatusComboBox .button:active:hover { padding: 1px 6px 2px 4px; border-style: solid; border-width: 0 1px; border-radius: 0; } GeditStatusComboBox .button:hover, GeditStatusComboBox .button:active, GeditStatusComboBox .button:active:hover { border-color: shade(@theme_bg_color, 0.8); } GeditViewFrame .gedit-search-slider { padding: 4px; border-radius: 0 0 3px 3px; border-width: 0 1px 1px 1px; border-style: solid; border-color: shade(@theme_base_color, 0.7); background-color: @theme_base_color; } GeditViewFrame .gedit-search-slider .not-found { background-color: #D94141; background-image: none; color: white; } GeditViewFrame .gedit-search-slider .not-found:selected { background-color: @theme_selected_bg_color; color: @selected_foreground; } GeditFileBrowserWidget .primary-toolbar.toolbar { padding: 4px 8px; border-top: none; background-color: @theme_bg_color; background-image: none; } .gedit-search-entry-occurrences-tag { color: @theme_text_color; border: 0px none @borders; margin: 1px; padding: 4px; } GeditStatusbar { border-top: 1px solid @borders; background-color: @theme_bg_color; } /************* * gucharmap * *************/ GucharmapChartable { background-color: @theme_base_color; } GucharmapChartable:active, GucharmapChartable:focus, GucharmapChartable:selected { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } /************* * evolution * *************/ EPreviewPane { background-color: @base_color; color: @fg_color; } /*********** * gtkhtml * ***********/ GtkHTML { background-color: @base_color; color: @fg_color; } /* needed for webkit/GtkStyle/Evolution compatibility */ GtkHTML:active, GtkHTML:active:backdrop, .entry:active, .entry:active:backdrop { background-color: @base_color; color: @fg_color; } /****************** * gnome calendar * ******************/ .calendar-view { background-color: shade(@theme_base_color, 0.95); color: @theme_text_color; } /****************** * Gnome Contacts * ******************/ /* Border on the right in the left menu toolbar */ .contacts-left-header-bar:dir(ltr) { border-right-width: 1px; } .contacts-left-header-bar:dir(rtl) { border-left-width: 1px; } .contacts-left-header-bar:dir(ltr), .contacts-right-header-bar:dir(rtl) { border-top-right-radius: 0; } .contacts-right-header-bar:dir(ltr), .contacts-left-header-bar:dir(rtl) { border-top-left-radius: 0; } /* * Evince */ EvWindow.background > GtkBox.vertical > GtkPaned.horizontal > GtkBox.vertical > GtkScrolledWindow.frame { border-width: 0; border-radius: 0; } EvWindow.background EvSidebar.vertical .frame { border-width: 1px 0; border-radius: 0; } EvWindow.background EvSidebar.vertical .notebook { border-width: 1px 0; } EvWindow.background EvSidebarAnnotations.vertical GtkToolPalette > GtkToolItemGroup > .button { padding: 4px; border-image: none; border-radius: 0; border-style: solid; border-width: 0 0 1px; border-color: shade(@theme_bg_color, 0.8); } EvWindow.background EvSidebar.vertical .notebook .frame { border-width: 0; } EvWindow .pane-separator, EvWindow .pane-separator:hover { border-width: 0 1px; border-style: solid; border-color: shade(@theme_base_color, 0.9); background-color: transparent; color: shade(@theme_base_color, 0.7); } EvWindow.background EggFindBar.toolbar { border-width: 1px 0 0; border-style: solid; border-color: shade(@theme_base_color, 0.9); } EvWindow.background EvSidebar.vertical .notebook { border-color: shade(@theme_base_color, 0.7); background-color: @theme_base_color; border-radius: 0; } EvWindow.background EvSidebar.vertical .notebook.header { background-color: @theme_bg_color; box-shadow: none; background-image: none; border-width: 0px; } EvWindow.background EvSidebar.vertical .notebook tab.top:active { background-color: @theme_base_color; background-image: none; } EvWindow.background EvSidebar.vertical .notebook tab.top { border-color: transparent; border-width: 0px; background-image: none; background-color: transparent; } EvWindow.background EvSidebar.vertical .notebook tab GtkLabel { color: alpha(@toolbar_fg_color, 0.5); } EvWindow.background EvSidebar.vertical .notebook .prelight-page, EvWindow.background EvSidebar.vertical .notebook .prelight-page GtkLabel { color: @theme_fg_color; } EvWindow.background EvSidebar.vertical .notebook .active-page, EvWindow.background EvSidebar.vertical .notebook tab .active-page GtkLabel { color: alpha(@toolbar_fg_color, 1.0); } /* used by Documents and Evince */ .content-view.document-page { border-style: solid; border-width: 3px 3px 6px 4px; border-image: url("../assets/thumbnail-frame.png") 3 3 6 4; } /* * File-roller */ FrWindow.background GtkPaned.horizontal { -GtkPaned-handle-size: 1; } FrWindow > GtkGrid > .pane-separator, FrWindow > GtkGrid > .pane-separator:hover { border-width: 0 1px 0 0; border-style: solid; border-color: @borders; } FrWindow.background GtkBox.vertical GtkTreeView.view { background-color: @sidebar_bg; } /* * Totem */ /*TotemGrilo.vertical .content-view { border-width: 0; }*/ TotemMainToolbar.header-bar { border-width: 0; } TotemGrilo.vertical .search-bar { border-width: 1px 0 0 0; } GtkApplicationWindow.background GtkStack GtkVBox.vertical GtkOverlay GtkRevealer.top { background-color: @borders; } /* Transmission */ .tr-workarea .undershoot, .tr-workarea .overshoot { border-color: transparent; /* Remove black border on over- and undershoot */ } /************** * Tweak Tool * **************/ .tweak:hover{ color: @text_color; } .tweak-categories .list-row.button:hover { background-color: @selected_bg_color; color: @selected_fg_color; } .tweak-categories { background-color: @sidebar_bg_color; background-image: linear-gradient(to bottom,@sidebar_bg_color,@sidebar_bg_color); }
Java
<?php /** * Sets the body-tag class attribute. * * Adds 'sidebar-left', 'sidebar-right' or 'sidebars' classes as needed. */ function phptemplate_body_class($left, $right) { if ($left != '' && $right != '') { $class = 'sidebars'; } else { if ($left != '') { $class = 'sidebar-left'; } if ($right != '') { $class = 'sidebar-right'; } } if (isset($class)) { print ' class="'. $class .'"'; } } /** * Return a themed breadcrumb trail. * * @param $breadcrumb * An array containing the breadcrumb links. * @return a string containing the breadcrumb output. */ function phptemplate_breadcrumb($breadcrumb) { if (!empty($breadcrumb)) { return '<div class="breadcrumb">'. implode(' › ', $breadcrumb) .'</div>'; } } /** * Override or insert PHPTemplate variables into the templates. */ function phptemplate_preprocess_page(&$vars) { $vars['tabs2'] = menu_secondary_local_tasks(); // Hook into color.module if (module_exists('color')) { _color_page_alter($vars); } } /** * Add a "Comments" heading above comments except on forum pages. */ function tiki_preprocess_comment_wrapper(&$vars) { if ($vars['content'] && $vars['node']->type != 'forum') { $vars['content'] = '<h2 class="comments">'. t('Comments') .'</h2>'. $vars['content']; } } /** * Returns the rendered local tasks. The default implementation renders * them as tabs. Overridden to split the secondary tasks. * * @ingroup themeable */ function phptemplate_menu_local_tasks() { return menu_primary_local_tasks(); } /** * Returns the themed submitted-by string for the comment. */ function phptemplate_comment_submitted($comment) { return t('!datetime — !username', array( '!username' => theme('username', $comment), '!datetime' => format_date($comment->timestamp) )); } /** * Returns the themed submitted-by string for the node. */ function phptemplate_node_submitted($node) { return t('!datetime — !username', array( '!username' => theme('username', $node), '!datetime' => format_date($node->created), )); } /** * Generates IE CSS links for LTR and RTL languages. */ function phptemplate_get_ie_styles() { global $language; $iecss = '<link type="text/css" rel="stylesheet" media="all" href="'. base_path() . path_to_theme() .'/fix-ie.css" />'; if ($language->direction == LANGUAGE_RTL) { $iecss .= '<style type="text/css" media="all">@import "'. base_path() . path_to_theme() .'/fix-ie-rtl.css";</style>'; } return $iecss; }
Java
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_FRAME_HOST_NAVIGATION_CONTROLLER_DELEGATE_H_ #define CONTENT_BROWSER_FRAME_HOST_NAVIGATION_CONTROLLER_DELEGATE_H_ #include <string> #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_details.h" namespace content { struct LoadCommittedDetails; struct LoadNotificationDetails; struct NativeWebKeyboardEvent; class InterstitialPage; class InterstitialPageImpl; class RenderViewHost; class SiteInstance; class WebContents; class WebContentsDelegate; class NavigationControllerDelegate { public: virtual ~NavigationControllerDelegate() {} virtual RenderViewHost* GetRenderViewHost() const = 0; virtual InterstitialPage* GetInterstitialPage() const = 0; virtual const std::string& GetContentsMimeType() const = 0; virtual void NotifyNavigationStateChanged(unsigned changed_flags) = 0; virtual void Stop() = 0; virtual SiteInstance* GetSiteInstance() const = 0; virtual SiteInstance* GetPendingSiteInstance() const = 0; virtual int32 GetMaxPageID() = 0; virtual int32 GetMaxPageIDForSiteInstance(SiteInstance* site_instance) = 0; virtual bool IsLoading() const = 0; virtual void NotifyBeforeFormRepostWarningShow() = 0; virtual void NotifyNavigationEntryCommitted( const LoadCommittedDetails& load_details) = 0; virtual bool NavigateToPendingEntry( NavigationController::ReloadType reload_type) = 0; virtual void SetHistoryLengthAndPrune( const SiteInstance* site_instance, int merge_history_length, int32 minimum_page_id) = 0; virtual void CopyMaxPageIDsFrom(WebContents* web_contents) = 0; virtual void UpdateMaxPageID(int32 page_id) = 0; virtual void UpdateMaxPageIDForSiteInstance(SiteInstance* site_instance, int32 page_id) = 0; virtual void ActivateAndShowRepostFormWarningDialog() = 0; virtual WebContents* GetWebContents() = 0; virtual bool IsHidden() = 0; virtual void RenderViewForInterstitialPageCreated( RenderViewHost* render_view_host) = 0; virtual void AttachInterstitialPage( InterstitialPageImpl* interstitial_page) = 0; virtual void DetachInterstitialPage() = 0; virtual void SetIsLoading(RenderViewHost* render_view_host, bool is_loading, LoadNotificationDetails* details) = 0; }; } #endif
Java
/* * TrxFormController.java * * Created on Jan 9, 2010 8:22:32 PM * * Copyright (c) 2002 - 2010 : Swayam Inc. * * P R O P R I E T A R Y & C O N F I D E N T I A L * * The copyright of this document is vested in Swayam Inc. without * whose prior written permission its contents must not be published, * adapted or reproduced in any form or disclosed or * issued to any third party. */ package com.swayam.ims.webapp.controller.trx; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * * @author paawak */ public abstract class TrxFormController implements Controller { final TrxModeIndicator modeIndicator; private String formView; public TrxFormController(TrxModeIndicator modeIndicator) { this.modeIndicator = modeIndicator; } public final void setFormView(String formView) { this.formView = formView; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView modelNView = new ModelAndView(formView); modelNView.addObject("isPurchaseMode", modeIndicator.isPurchaseMode()); return modelNView; } }
Java
<?php if ( !defined( 'ABSPATH' ) ) { exit; } $rowWidth = 0; foreach ( $cells as $cell ) { $rowWidth += (int)$cell['width']; } if ( $rows ) { ?> <table class="mscrm-listview table"> <thead> <tr> <?php foreach ( current( $rows ) as $cellName => $cell ) { $cellWidth = $cells[$cellName]['width']; ?> <th style="width:<?php echo round( ( $cellWidth / $rowWidth * 100 ), 3 ); ?>%;"><?php echo $cell["head"]; ?></th> <?php } ?> </tr> </thead> <tbody> <?php foreach ( $rows as $row ) { ?> <tr> <?php foreach ( $row as $key => $cell ) : ?> <td><?php wordpresscrm_view_field( $cell ); ?></td> <?php endforeach; ?> </tr> <?php } ?> </tbody> <?php if ( array_key_exists( 'count', $attributes ) && (int)$attributes['count'] > 0 ) { $currentPage = 1; if ( array_key_exists( 'viewPage', $_GET ) && (int)$_GET['viewPage'] > 0 ) { $currentPage = (int)$_GET['viewPage']; } ?><tfoot> <tr> <td colspan="<?php echo esc_attr( count( $cells ) ); ?>"> <?php if ( $currentPage > 1 ) { $queryParams = ACRM()->request->query->all(); unset( $queryParams['viewPage'] ); if ( $currentPage > 2 ) { $queryParams[ 'viewPage'] = $currentPage - 1; } $url = \Symfony\Component\HttpFoundation\Request::create( ACRM()->request->getPathInfo(), 'GET', $queryParams ); ?><a href="<?php echo esc_attr( $url->getRequestUri() ); ?>" class="btn btn-outline-primary"><?php _e( '&larr; Previous', 'integration-dynamics' ); ?></a> <?php /* the prepended space is purposeful */ } if ( $entities->MoreRecords ) { $url = \Symfony\Component\HttpFoundation\Request::create( ACRM()->request->getPathInfo(), 'GET', array_merge( ACRM()->request->query->all(), [ 'viewPage' => $currentPage + 1 ] ) ); ?><a href="<?php echo esc_attr( $url->getRequestUri() ); ?>" class="btn btn-outline-primary"><?php _e( 'Next &rarr;', 'integration-dynamics' ); ?></a><?php } ?> </td> </tr> </tfoot> <?php } ?> </table> <?php } else { echo apply_filters( "wordpresscrm_no_results_view", __( "<p>No results</p>", 'integration-dynamics' ), $attributes["entity"], $attributes["name"] ); } ?>
Java
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2017 UniPro <ugene@unipro.ru> * http://ugene.net * * 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. */ #ifndef _U2_DOCUMENT_MODEL_TESTS_H_ #define _U2_DOCUMENT_MODEL_TESTS_H_ #include <U2Test/XMLTestUtils.h> #include <U2Core/IOAdapter.h> #include <QDomElement> namespace U2 { class Document; class GObject; class LoadDocumentTask; class SaveDocumentTask; class DocumentProviderTask; class GTest_LoadDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_LoadDocument, "load-document"); ReportResult report(); void prepare(); virtual void cleanup(); private: QString docContextName; LoadDocumentTask* loadTask; bool contextAdded; bool tempFile; QString url; GTestLogHelper logHelper; QString expectedLogMessage; QString expectedLogMessage2; QString unexpectedLogMessage; bool needVerifyLog; }; class GTest_SaveDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_SaveDocument, "save-document"); void prepare(); private: QString url; IOAdapterFactory* iof; QString docContextName; SaveDocumentTask* saveTask; }; class GTest_LoadBrokenDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_LoadBrokenDocument, "load-broken-document", TaskFlags(TaskFlag_NoRun)| TaskFlag_FailOnSubtaskCancel); Document* getDocument() const; ReportResult report(); void cleanup(); private: LoadDocumentTask* loadTask; QString url; bool tempFile; QString message; }; class GTest_ImportDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_ImportDocument, "import-document"); ReportResult report(); void prepare(); virtual void cleanup(); private: QString docContextName; DocumentProviderTask* importTask; bool contextAdded; bool tempFile; QString url; QString destUrl; GTestLogHelper logHelper; QString expectedLogMessage; QString expectedLogMessage2; QString unexpectedLogMessage; bool needVerifyLog; }; class GTest_ImportBrokenDocument : public GTest { Q_OBJECT public: SIMPLE_XML_TEST_BODY_WITH_FACTORY_EXT(GTest_ImportBrokenDocument, "import-broken-document", TaskFlags(TaskFlag_NoRun)| TaskFlag_FailOnSubtaskCancel); Document* getDocument() const; ReportResult report(); void cleanup(); private: DocumentProviderTask* importTask; QString url; QString destUrl; bool tempFile; QString message; }; class GTest_DocumentNumObjects : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_DocumentNumObjects, "check-num-objects"); ReportResult report(); QString docContextName; int numObjs; }; class GTest_DocumentFormat : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_DocumentFormat, "check-document-format"); ReportResult report(); QString docUrl; QString docFormat; }; class GTest_DocumentObjectNames : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_DocumentObjectNames, "check-document-object-names"); ReportResult report(); QString docContextName; QStringList names; }; class GTest_DocumentObjectTypes : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_DocumentObjectTypes, "check-document-object-types"); ReportResult report(); QString docContextName; QList<GObjectType> types; }; class DocumentModelTests { public: static QList<XMLTestFactory*> createTestFactories(); }; class GTest_FindGObjectByName : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_FindGObjectByName, "find-object-by-name"); ReportResult report(); void cleanup(); private: QString docContextName; QString objContextName; QString objName; GObjectType type; GObject* result; }; class GTest_CompareFiles : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_CompareFiles, "compare-docs"); ReportResult report(); private: void compareMixed(); QByteArray getLine(IOAdapter* io); IOAdapter* createIoAdapter(const QString& filePath); QString doc1Path; QString doc2Path; bool byLines; QStringList commentsStartWith; bool line_num_only; bool mixed_lines; int first_n_lines; }; class GTest_Compare_VCF_Files : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_Compare_VCF_Files, "compare-vcf-docs"); ReportResult report(); private: IOAdapter* createIoAdapter(const QString& filePath); QString getLine(IOAdapter* io); QString doc1Path; QString doc2Path; static const QByteArray COMMENT_MARKER; }; class GTest_Compare_PDF_Files : public GTest { Q_OBJECT SIMPLE_XML_TEST_BODY_WITH_FACTORY(GTest_Compare_PDF_Files, "compare-pdf-docs"); ReportResult report(); private: QString doc1Path; QString doc2Path; bool byLines; }; }//namespace #endif
Java
<?php /** * Options for the bibtex plugin * * @author Till Biskup <till@till-biskup> */ $meta['_basic'] = array('fieldset'); $meta['sqlite'] = array('onoff'); $meta['citetype'] = array('multichoice','_choices' => array('alpha','apa','authordate','numeric')); $meta['file'] = array('string'); $meta['pdfdir'] = array('string'); $meta['sort'] = array('onoff'); $meta['_formatstrings'] = array('fieldset'); $meta['fmtstr_article'] = array('string'); $meta['fmtstr_book'] = array('string'); $meta['fmtstr_booklet'] = array('string'); $meta['fmtstr_conference'] = array('string'); $meta['fmtstr_inbook'] = array('string'); $meta['fmtstr_incollection'] = array('string'); $meta['fmtstr_inproceedings'] = array('string'); $meta['fmtstr_manual'] = array('string'); $meta['fmtstr_mastersthesis'] = array('string'); $meta['fmtstr_misc'] = array('string'); $meta['fmtstr_phdthesis'] = array('string'); $meta['fmtstr_proceedings'] = array('string'); $meta['fmtstr_techreport'] = array('string'); $meta['fmtstr_unpublished'] = array('string');
Java
/* This file is part of ffmpeg-php Copyright (C) 2004-2008 Todd Kirby (ffmpeg.php 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. 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 In addition, as a special exception, the copyright holders of ffmpeg-php give you permission to combine ffmpeg-php with code included in the standard release of PHP under the PHP license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU GPL for ffmpeg-php and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU GPL requires distribution of source code. You must obey the GNU General Public License in all respects for all of the code used other than standard release of PHP. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif //#include <php.h> #include "ffmpeg_tools.h" #if LIBAVCODEC_VERSION_MAJOR >= 52 #include <swscale.h> /* {{{ ffmpeg_img_convert() * wrapper around ffmpeg image conversion routines */ int img_convert(AVPicture *dst, int dst_pix_fmt, AVPicture *src, int src_pix_fmt, int src_width, int src_height) { struct SwsContext *sws_ctx = NULL; // TODO: Try to get cached sws_context first sws_ctx = sws_getContext(src_width, src_height, 0, src_width, src_height, dst_pix_fmt, SWS_BICUBIC, NULL, NULL, NULL); if (sws_ctx == NULL){ return 2; } sws_scale(sws_ctx, src->data, src->linesize, 0, src_height, dst->data, dst->linesize); sws_freeContext(sws_ctx); return 0; } /* }}} */ void img_resample(ImgReSampleContext * context, AVPicture * pxOut, const AVPicture * pxIn) { if (context != NULL && context->context != NULL) { AVPicture shiftedInput; // = {0}; shiftedInput.data[0] = pxIn->data[0] + pxIn->linesize[0] * context->bandTop + context->bandLeft; shiftedInput.data[1] = pxIn->data[1] + (pxIn->linesize[1] * (context->bandTop / 2)) + (context->bandLeft+1) / 2; shiftedInput.data[2] = pxIn->data[2] + (pxIn->linesize[2] * (context->bandTop / 2)) + (context->bandLeft+1) / 2; shiftedInput.linesize[0] = pxIn->linesize[0]; shiftedInput.linesize[1] = pxIn->linesize[1]; shiftedInput.linesize[2] = pxIn->linesize[2]; sws_scale(context->context, (uint8_t**)shiftedInput.data, (int*)shiftedInput.linesize, 0, context->height - context->bandBottom - context->bandTop, pxOut->data, pxOut->linesize); } } ImgReSampleContext * img_resample_full_init (int owidth, int oheight, int iwidth, int iheight, int topBand, int bottomBand, int leftBand, int rightBand, int padtop, int padbottom, int padleft, int padright) { ImgReSampleContext * s = (ImgReSampleContext *)av_malloc(sizeof(ImgReSampleContext)); if (s == NULL) { return NULL; } int srcSurface = (iwidth - rightBand - leftBand)* (iheight - topBand - bottomBand); // We use bilinear when the source surface is big, and bicubic when the number of pixels to handle is less than 1 MPixels s->context = sws_getContext(iwidth - rightBand - leftBand, iheight - topBand - bottomBand, PIX_FMT_YUV420P, owidth, oheight, PIX_FMT_YUV420P, srcSurface > 1024000 ? SWS_FAST_BILINEAR : SWS_BICUBIC, NULL, NULL, NULL); if (s->context == NULL) { av_free(s); return NULL; } s->bandLeft = leftBand; s->bandRight = rightBand; s->bandTop = topBand; s->bandBottom = bottomBand; s->padLeft = padleft; s->padRight = padright; s->padTop = padtop; s->padBottom = padbottom; s->width = iwidth; s->height = iheight; s->outWidth = owidth; s->outHeight = oheight; return s; } ImgReSampleContext * img_resample_init (int owidth, int oheight, int iwidth, int iheight) { return img_resample_full_init(owidth, oheight, iwidth, iheight, 0, 0, 0, 0, 0, 0, 0, 0); } void img_resample_close(ImgReSampleContext * s) { if (s == NULL) return; sws_freeContext(s->context); av_free(s); } #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 * vim<600: noet sw=4 ts=4 */
Java
<?php /** * Suomi.fi authentication module. * * PHP version 7 * * Copyright (C) The National Library of Finland 2019. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package Authentication * @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Page */ namespace Finna\Auth; use VuFind\Exception\Auth as AuthException; /** * Suomi.fi authentication module. * * @category VuFind * @package Authentication * @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Page */ class Suomifi extends Shibboleth { /** * Set configuration. * * @param \Zend\Config\Config $config Configuration to set * * @return void */ public function setConfig($config) { // Replace Shibboleth config section with Shibboleth_suomifi $data = $config->toArray(); $data['Shibboleth'] = $data['Shibboleth_suomifi']; $config = new \Zend\Config\Config($data); parent::setConfig($config); } /** * Get the URL to establish a session (needed when the internal VuFind login * form is inadequate). Returns false when no session initiator is needed. * * @param string $target Full URL where external authentication method should * send user after login (some drivers may override this). * * @return bool|string */ public function getSessionInitiator($target) { $url = parent::getSessionInitiator($target); if (!$url) { return $url; } // Set 'auth_method' to Suomifi $url = str_replace( 'auth_method%3DShibboleth', 'auth_method%3DSuomifi', $url ); return $url; } /** * Get a server parameter taking into account any environment variables * redirected by Apache mod_rewrite. * * @param \Zend\Http\PhpEnvironment\Request $request Request object containing * account credentials. * @param string $param Parameter name * * @throws AuthException * @return mixed */ protected function getServerParam($request, $param) { $val = parent::getServerParam($request, $param); $config = $this->getConfig()->Shibboleth; if ($param === $config->username && ((bool)$config->hash_username ?? false) ) { $secret = $config->hash_secret ?? null; if (empty($secret)) { throw new AuthException('hash_secret not configured'); } $val = hash_hmac('sha256', $val, $secret, false); } return $val; } }
Java
/* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains macros and a little bit of code that is common to ** all of the platform-specific files (os_*.c) and is #included into those ** files. ** ** This file should be #included by the os_*.c files only. It is not a ** general purpose header file. */ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG ** macro to SQLITE_DEBUG and some older makefiles have not yet made the ** switch. The following code should catch this problem at compile-time. */ #ifdef MEMORY_DEBUG # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." #endif /* * When testing, this global variable stores the location of the * pending-byte in the database file. */ #ifdef SQLITE_TEST unsigned int sqlite3_pending_byte = 0x40000000; #endif #ifdef SQLITE_DEBUG int sqlite3_os_trace = 0; #define OSTRACE1(X) if( sqlite3_os_trace ) sqlite3DebugPrintf(X) #define OSTRACE2(X,Y) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y) #define OSTRACE3(X,Y,Z) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z) #define OSTRACE4(X,Y,Z,A) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A) #define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B) #define OSTRACE6(X,Y,Z,A,B,C) \ if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C) #define OSTRACE7(X,Y,Z,A,B,C,D) \ if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D) #else #define OSTRACE1(X) #define OSTRACE2(X,Y) #define OSTRACE3(X,Y,Z) #define OSTRACE4(X,Y,Z,A) #define OSTRACE5(X,Y,Z,A,B) #define OSTRACE6(X,Y,Z,A,B,C) #define OSTRACE7(X,Y,Z,A,B,C,D) #endif /* ** Macros for performance tracing. Normally turned off. Only works ** on i486 hardware. */ #ifdef SQLITE_PERFORMANCE_TRACE __inline__ unsigned long long int hwtime(void){ unsigned long long int x; __asm__("rdtsc\n\t" "mov %%edx, %%ecx\n\t" :"=A" (x)); return x; } static unsigned long long int g_start; static unsigned int elapse; #define TIMER_START g_start=hwtime() #define TIMER_END elapse=hwtime()-g_start #define TIMER_ELAPSED elapse #else #define TIMER_START #define TIMER_END #define TIMER_ELAPSED 0 #endif /* ** If we compile with the SQLITE_TEST macro set, then the following block ** of code will give us the ability to simulate a disk I/O error. This ** is used for testing the I/O recovery logic. */ #ifdef SQLITE_TEST int sqlite3_io_error_hit = 0; int sqlite3_io_error_pending = 0; int sqlite3_io_error_persist = 0; int sqlite3_diskfull_pending = 0; int sqlite3_diskfull = 0; #define SimulateIOError(CODE) \ if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \ if( sqlite3_io_error_pending-- == 1 \ || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); sqlite3_io_error_hit = 1; } #define SimulateDiskfullError(CODE) \ if( sqlite3_diskfull_pending ){ \ if( sqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ sqlite3_diskfull = 1; \ sqlite3_io_error_hit = 1; \ CODE; \ }else{ \ sqlite3_diskfull_pending--; \ } \ } #else #define SimulateIOError(A) #define SimulateDiskfullError(A) #endif /* ** When testing, keep a count of the number of open files. */ #ifdef SQLITE_TEST int sqlite3_open_file_count = 0; #define OpenCounter(X) sqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* ** sqlite3GenericMalloc ** sqlite3GenericRealloc ** sqlite3GenericOsFree ** sqlite3GenericAllocationSize ** ** Implementation of the os level dynamic memory allocation interface in terms ** of the standard malloc(), realloc() and free() found in many operating ** systems. No rocket science here. ** ** There are two versions of these four functions here. The version ** implemented here is only used if memory-management or memory-debugging is ** enabled. This version allocates an extra 8-bytes at the beginning of each ** block and stores the size of the allocation there. ** ** If neither memory-management or debugging is enabled, the second ** set of implementations is used instead. */ #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG) void *sqlite3GenericMalloc(int n){ char *p = (char *)malloc(n+8); assert(n>0); assert(sizeof(int)<=8); if( p ){ *(int *)p = n; p += 8; } return (void *)p; } void *sqlite3GenericRealloc(void *p, int n){ char *p2 = ((char *)p - 8); assert(n>0); p2 = (char*)realloc(p2, n+8); if( p2 ){ *(int *)p2 = n; p2 += 8; } return (void *)p2; } void sqlite3GenericFree(void *p){ assert(p); free((void *)((char *)p - 8)); } int sqlite3GenericAllocationSize(void *p){ return p ? *(int *)((char *)p - 8) : 0; } #else void *sqlite3GenericMalloc(int n){ char *p = (char *)malloc(n); return (void *)p; } void *sqlite3GenericRealloc(void *p, int n){ assert(n>0); p = realloc(p, n); return p; } void sqlite3GenericFree(void *p){ assert(p); free(p); } /* Never actually used, but needed for the linker */ int sqlite3GenericAllocationSize(void *p){ return 0; } #endif /* ** The default size of a disk sector */ #ifndef PAGER_SECTOR_SIZE # define PAGER_SECTOR_SIZE 512 #endif
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> <!-- HTML file produced from file: UserManual.tex -- -- using Hyperlatex v 2.3.1 (c) Otfried Cheong-- -- on Emacs 21.1 (patch 4) "Arches" XEmacs Lucid, Sun Apr 30 20:50:10 2000 --> <HEAD> <TITLE>Tao User Manual -- Using pitches - pitches.tao</TITLE> <link rel=stylesheet href="../../taomanual.css" type="text/css"> </HEAD><BODY BACKGROUND="bg.gif"> <table width="500" border="0" align="left" cellspacing="2" cellpadding="2"><tr><td class="nav" valign="top"><!-- top panel --><A HREF="UserManual_102.html"><IMG ALT="Up" ALIGN=BOTTOM BORDER=0 SRC="up.gif"></A> <BR><A HREF="UserManual_102.html">Tutorial</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td><td class="nav" valign="top"><A HREF="UserManual_140.html"><IMG ALT="Back" ALIGN=BOTTOM BORDER=0 SRC="back.gif"></A> <BR><A HREF="UserManual_140.html">Using the Output device - outputs.tao</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td><td class="nav" valign="top"><A HREF="UserManual_142.html"><IMG ALT="Forward" ALIGN=BOTTOM BORDER=0 SRC="forward.gif"></A> <BR><A HREF="UserManual_142.html">Creating a rectangular sheet</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td></tr><!-- end top panel --><tr><td colspan="3" class="main"><!-- main text --><br><br> <H2>Using pitches - pitches.tao</H2> This script illustrates the various pitch formats which are supported by <B>Tao</B>. These include <EM>oct</EM><A NAME="1">,</A> <EM>cps</EM><A NAME="2">,</A> <EM>Hz</EM><A NAME="3"> and</A> <EM>note name</EM><A NAME="4"> formats</A> (see sections <A HREF="UserManual_34.html">*</A> and <A HREF="UserManual_52.html">*</A>). <P><PRE> Audio rate: 44100; String array1[]= { (200 Hz, 20 secs), (220 Hz, 20 secs), (240 Hz, 20 secs), (260 Hz, 20 secs) }; String array2[]= { (8.00 pch, 20 secs), (8.04 pch, 20 secs), (8.06 pch, 20 secs), (8.08 pch, 20 secs) }; String array3[]= { (8.0 oct, 20 secs), (8.2 oct, 20 secs), (8.4 oct, 20 secs), (8.6 oct, 20 secs) }; Counter n; Init: For n = 0 to 3: array1[n].lockEnds(); array2[n].lockEnds(); array3[n].lockEnds(); ... ... Score 5 secs: Label(array1[0], 1.0, 0.0, 0.0, "LABEL", 0); At start for 0.1 msecs: For n = 0 to 3: array1[n](0.1).applyForce(1.0); array2[n](0.1).applyForce(1.0); array3[n](0.1).applyForce(1.0); ... ... ... </PRE> <P> <BR></td></tr><!-- end main text --><tr><td class="nav" align="left" valign="top"><!-- bottom matter --><A HREF="UserManual_102.html"><IMG ALT="Up" ALIGN=BOTTOM BORDER=0 SRC="up.gif"></A> <BR><A HREF="UserManual_102.html">Tutorial</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td><td class="nav" align="left" valign="top"><A HREF="UserManual_140.html"><IMG ALT="Back" ALIGN=BOTTOM BORDER=0 SRC="back.gif"></A> <BR><A HREF="UserManual_140.html">Using the Output device - outputs.tao</A><BR><IMG width="167" height="1" SRC="trans1x1.gif"> </td><td class="nav" align="left" valign="top"><!-- bottom matter --><A HREF="UserManual_142.html"><IMG ALT="Forward" ALIGN=BOTTOM BORDER=0 SRC="forward.gif"></A> <BR><A HREF="UserManual_142.html">Creating a rectangular sheet</A> <IMG width="167" height="1" SRC="trans1x1.gif"> </td></tr><!-- end bottom matter --> <tr><td colspan="3" class="addr"><!-- bottom panel --><ADDRESS><FONT SIZE=-1>&#169;1999,2000 Mark Pearson <A HREF="mailto:m.pearson@ukonline.co.uk">m.pearson@ukonline.co.uk</A> April 30, 2000</ADDRESS><BR></td></tr><!-- end bottom panel --></table></BODY></HTML>
Java
// clang-format off /* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing authors: Jim Shepherd (GA Tech) added SGI SCSL support Axel Kohlmeyer (Temple U) added support for FFTW3, KISS FFT, Dfti/MKL, and ACML Phil Blood (PSC) added single precision FFTs Paul Coffman (IBM) added MPI collectives remap ------------------------------------------------------------------------- */ #include "fft3d.h" #include "remap.h" #include <cstdlib> #include <cmath> #if defined(_OPENMP) #include <omp.h> #endif #ifdef FFT_KISS /* include kissfft implementation */ #include "kissfft.h" #endif #define MIN(A,B) ((A) < (B) ? (A) : (B)) #define MAX(A,B) ((A) > (B) ? (A) : (B)) /* ---------------------------------------------------------------------- Data layout for 3d FFTs: data set of Nfast x Nmid x Nslow elements is owned by P procs on input, each proc owns a subsection of the elements on output, each proc will own a (possibly different) subsection my subsection must not overlap with any other proc's subsection, i.e. the union of all proc's input (or output) subsections must exactly tile the global Nfast x Nmid x Nslow data set when called from C, all subsection indices are C-style from 0 to N-1 where N = Nfast or Nmid or Nslow when called from F77, all subsection indices are F77-style from 1 to N where N = Nfast or Nmid or Nslow a proc can own 0 elements on input or output by specifying hi index < lo index on both input and output, data is stored contiguously on a processor with a fast-varying, mid-varying, and slow-varying index ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Perform 3d FFT Arguments: in starting address of input data on this proc out starting address of where output data for this proc will be placed (can be same as in) flag 1 for forward FFT, -1 for backward FFT plan plan returned by previous call to fft_3d_create_plan ------------------------------------------------------------------------- */ void fft_3d(FFT_DATA *in, FFT_DATA *out, int flag, struct fft_plan_3d *plan) { FFT_SCALAR norm; #if defined(FFT_FFTW3) FFT_SCALAR *out_ptr; #endif FFT_DATA *data,*copy; // system specific constants #if defined(FFT_FFTW3) FFTW_API(plan) theplan; #else // nothing to do for other FFTs #endif // pre-remap to prepare for 1st FFTs if needed // copy = loc for remap result if (plan->pre_plan) { if (plan->pre_target == 0) copy = out; else copy = plan->copy; remap_3d((FFT_SCALAR *) in, (FFT_SCALAR *) copy, (FFT_SCALAR *) plan->scratch, plan->pre_plan); data = copy; } else data = in; // 1d FFTs along fast axis #if defined(FFT_MKL) if (flag == 1) DftiComputeForward(plan->handle_fast,data); else DftiComputeBackward(plan->handle_fast,data); #elif defined(FFT_FFTW3) if (flag == 1) theplan=plan->plan_fast_forward; else theplan=plan->plan_fast_backward; FFTW_API(execute_dft)(theplan,data,data); #else int total = plan->total1; int length = plan->length1; if (flag == 1) for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_fast_forward,&data[offset],&data[offset]); else for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_fast_backward,&data[offset],&data[offset]); #endif // 1st mid-remap to prepare for 2nd FFTs // copy = loc for remap result if (plan->mid1_target == 0) copy = out; else copy = plan->copy; remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) copy, (FFT_SCALAR *) plan->scratch, plan->mid1_plan); data = copy; // 1d FFTs along mid axis #if defined(FFT_MKL) if (flag == 1) DftiComputeForward(plan->handle_mid,data); else DftiComputeBackward(plan->handle_mid,data); #elif defined(FFT_FFTW3) if (flag == 1) theplan=plan->plan_mid_forward; else theplan=plan->plan_mid_backward; FFTW_API(execute_dft)(theplan,data,data); #else total = plan->total2; length = plan->length2; if (flag == 1) for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_mid_forward,&data[offset],&data[offset]); else for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_mid_backward,&data[offset],&data[offset]); #endif // 2nd mid-remap to prepare for 3rd FFTs // copy = loc for remap result if (plan->mid2_target == 0) copy = out; else copy = plan->copy; remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) copy, (FFT_SCALAR *) plan->scratch, plan->mid2_plan); data = copy; // 1d FFTs along slow axis #if defined(FFT_MKL) if (flag == 1) DftiComputeForward(plan->handle_slow,data); else DftiComputeBackward(plan->handle_slow,data); #elif defined(FFT_FFTW3) if (flag == 1) theplan=plan->plan_slow_forward; else theplan=plan->plan_slow_backward; FFTW_API(execute_dft)(theplan,data,data); #else total = plan->total3; length = plan->length3; if (flag == 1) for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_slow_forward,&data[offset],&data[offset]); else for (int offset = 0; offset < total; offset += length) kiss_fft(plan->cfg_slow_backward,&data[offset],&data[offset]); #endif // post-remap to put data in output format if needed // destination is always out if (plan->post_plan) remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) out, (FFT_SCALAR *) plan->scratch, plan->post_plan); // scaling if required if (flag == -1 && plan->scaled) { norm = plan->norm; const int num = plan->normnum; #if defined(FFT_FFTW3) out_ptr = (FFT_SCALAR *)out; #endif for (int i = 0; i < num; i++) { #if defined(FFT_FFTW3) *(out_ptr++) *= norm; *(out_ptr++) *= norm; #elif defined(FFT_MKL) out[i] *= norm; #else /* FFT_KISS */ out[i].re *= norm; out[i].im *= norm; #endif } } } /* ---------------------------------------------------------------------- Create plan for performing a 3d FFT Arguments: comm MPI communicator for the P procs which own the data nfast,nmid,nslow size of global 3d matrix in_ilo,in_ihi input bounds of data I own in fast index in_jlo,in_jhi input bounds of data I own in mid index in_klo,in_khi input bounds of data I own in slow index out_ilo,out_ihi output bounds of data I own in fast index out_jlo,out_jhi output bounds of data I own in mid index out_klo,out_khi output bounds of data I own in slow index scaled 0 = no scaling of result, 1 = scaling permute permutation in storage order of indices on output 0 = no permutation 1 = permute once = mid->fast, slow->mid, fast->slow 2 = permute twice = slow->fast, fast->mid, mid->slow nbuf returns size of internal storage buffers used by FFT usecollective use collective MPI operations for remapping data ------------------------------------------------------------------------- */ struct fft_plan_3d *fft_3d_create_plan( MPI_Comm comm, int nfast, int nmid, int nslow, int in_ilo, int in_ihi, int in_jlo, int in_jhi, int in_klo, int in_khi, int out_ilo, int out_ihi, int out_jlo, int out_jhi, int out_klo, int out_khi, int scaled, int permute, int *nbuf, int usecollective) { struct fft_plan_3d *plan; int me,nprocs,nthreads; int flag,remapflag; int first_ilo,first_ihi,first_jlo,first_jhi,first_klo,first_khi; int second_ilo,second_ihi,second_jlo,second_jhi,second_klo,second_khi; int third_ilo,third_ihi,third_jlo,third_jhi,third_klo,third_khi; int out_size,first_size,second_size,third_size,copy_size,scratch_size; int np1,np2,ip1,ip2; // query MPI info MPI_Comm_rank(comm,&me); MPI_Comm_size(comm,&nprocs); #if defined(_OPENMP) // query OpenMP info. // should have been initialized systemwide in Comm class constructor nthreads = omp_get_max_threads(); #else nthreads = 1; #endif // compute division of procs in 2 dimensions not on-processor bifactor(nprocs,&np1,&np2); ip1 = me % np1; ip2 = me/np1; // allocate memory for plan data struct plan = (struct fft_plan_3d *) malloc(sizeof(struct fft_plan_3d)); if (plan == nullptr) return nullptr; // remap from initial distribution to layout needed for 1st set of 1d FFTs // not needed if all procs own entire fast axis initially // first indices = distribution after 1st set of FFTs if (in_ilo == 0 && in_ihi == nfast-1) flag = 0; else flag = 1; MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm); if (remapflag == 0) { first_ilo = in_ilo; first_ihi = in_ihi; first_jlo = in_jlo; first_jhi = in_jhi; first_klo = in_klo; first_khi = in_khi; plan->pre_plan = nullptr; } else { first_ilo = 0; first_ihi = nfast - 1; first_jlo = ip1*nmid/np1; first_jhi = (ip1+1)*nmid/np1 - 1; first_klo = ip2*nslow/np2; first_khi = (ip2+1)*nslow/np2 - 1; plan->pre_plan = remap_3d_create_plan(comm,in_ilo,in_ihi,in_jlo,in_jhi,in_klo,in_khi, first_ilo,first_ihi,first_jlo,first_jhi, first_klo,first_khi,2,0,0,FFT_PRECISION,0); if (plan->pre_plan == nullptr) return nullptr; } // 1d FFTs along fast axis plan->length1 = nfast; plan->total1 = nfast * (first_jhi-first_jlo+1) * (first_khi-first_klo+1); // remap from 1st to 2nd FFT // choose which axis is split over np1 vs np2 to minimize communication // second indices = distribution after 2nd set of FFTs second_ilo = ip1*nfast/np1; second_ihi = (ip1+1)*nfast/np1 - 1; second_jlo = 0; second_jhi = nmid - 1; second_klo = ip2*nslow/np2; second_khi = (ip2+1)*nslow/np2 - 1; plan->mid1_plan = remap_3d_create_plan(comm, first_ilo,first_ihi,first_jlo,first_jhi, first_klo,first_khi, second_ilo,second_ihi,second_jlo,second_jhi, second_klo,second_khi,2,1,0,FFT_PRECISION, usecollective); if (plan->mid1_plan == nullptr) return nullptr; // 1d FFTs along mid axis plan->length2 = nmid; plan->total2 = (second_ihi-second_ilo+1) * nmid * (second_khi-second_klo+1); // remap from 2nd to 3rd FFT // if final distribution is permute=2 with all procs owning entire slow axis // then this remapping goes directly to final distribution // third indices = distribution after 3rd set of FFTs if (permute == 2 && out_klo == 0 && out_khi == nslow-1) flag = 0; else flag = 1; MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm); if (remapflag == 0) { third_ilo = out_ilo; third_ihi = out_ihi; third_jlo = out_jlo; third_jhi = out_jhi; third_klo = out_klo; third_khi = out_khi; } else { third_ilo = ip1*nfast/np1; third_ihi = (ip1+1)*nfast/np1 - 1; third_jlo = ip2*nmid/np2; third_jhi = (ip2+1)*nmid/np2 - 1; third_klo = 0; third_khi = nslow - 1; } plan->mid2_plan = remap_3d_create_plan(comm, second_jlo,second_jhi,second_klo,second_khi, second_ilo,second_ihi, third_jlo,third_jhi,third_klo,third_khi, third_ilo,third_ihi,2,1,0,FFT_PRECISION,usecollective); if (plan->mid2_plan == nullptr) return nullptr; // 1d FFTs along slow axis plan->length3 = nslow; plan->total3 = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) * nslow; // remap from 3rd FFT to final distribution // not needed if permute = 2 and third indices = out indices on all procs if (permute == 2 && out_ilo == third_ilo && out_ihi == third_ihi && out_jlo == third_jlo && out_jhi == third_jhi && out_klo == third_klo && out_khi == third_khi) flag = 0; else flag = 1; MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm); if (remapflag == 0) plan->post_plan = nullptr; else { plan->post_plan = remap_3d_create_plan(comm, third_klo,third_khi,third_ilo,third_ihi, third_jlo,third_jhi, out_klo,out_khi,out_ilo,out_ihi, out_jlo,out_jhi,2,(permute+1)%3,0,FFT_PRECISION,0); if (plan->post_plan == nullptr) return nullptr; } // configure plan memory pointers and allocate work space // out_size = amount of memory given to FFT by user // first/second/third_size = // amount of memory needed after pre,mid1,mid2 remaps // copy_size = amount needed internally for extra copy of data // scratch_size = amount needed internally for remap scratch space // for each remap: // out space used for result if big enough, else require copy buffer // accumulate largest required remap scratch space out_size = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) * (out_khi-out_klo+1); first_size = (first_ihi-first_ilo+1) * (first_jhi-first_jlo+1) * (first_khi-first_klo+1); second_size = (second_ihi-second_ilo+1) * (second_jhi-second_jlo+1) * (second_khi-second_klo+1); third_size = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) * (third_khi-third_klo+1); copy_size = 0; scratch_size = 0; if (plan->pre_plan) { if (first_size <= out_size) plan->pre_target = 0; else { plan->pre_target = 1; copy_size = MAX(copy_size,first_size); } scratch_size = MAX(scratch_size,first_size); } if (plan->mid1_plan) { if (second_size <= out_size) plan->mid1_target = 0; else { plan->mid1_target = 1; copy_size = MAX(copy_size,second_size); } scratch_size = MAX(scratch_size,second_size); } if (plan->mid2_plan) { if (third_size <= out_size) plan->mid2_target = 0; else { plan->mid2_target = 1; copy_size = MAX(copy_size,third_size); } scratch_size = MAX(scratch_size,third_size); } if (plan->post_plan) scratch_size = MAX(scratch_size,out_size); *nbuf = copy_size + scratch_size; if (copy_size) { plan->copy = (FFT_DATA *) malloc(copy_size*sizeof(FFT_DATA)); if (plan->copy == nullptr) return nullptr; } else plan->copy = nullptr; if (scratch_size) { plan->scratch = (FFT_DATA *) malloc(scratch_size*sizeof(FFT_DATA)); if (plan->scratch == nullptr) return nullptr; } else plan->scratch = nullptr; // system specific pre-computation of 1d FFT coeffs // and scaling normalization #if defined(FFT_MKL) DftiCreateDescriptor( &(plan->handle_fast), FFT_MKL_PREC, DFTI_COMPLEX, 1, (MKL_LONG)nfast); DftiSetValue(plan->handle_fast, DFTI_NUMBER_OF_TRANSFORMS, (MKL_LONG)plan->total1/nfast); DftiSetValue(plan->handle_fast, DFTI_PLACEMENT,DFTI_INPLACE); DftiSetValue(plan->handle_fast, DFTI_INPUT_DISTANCE, (MKL_LONG)nfast); DftiSetValue(plan->handle_fast, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nfast); #if defined(FFT_MKL_THREADS) DftiSetValue(plan->handle_fast, DFTI_NUMBER_OF_USER_THREADS, nthreads); #endif DftiCommitDescriptor(plan->handle_fast); DftiCreateDescriptor( &(plan->handle_mid), FFT_MKL_PREC, DFTI_COMPLEX, 1, (MKL_LONG)nmid); DftiSetValue(plan->handle_mid, DFTI_NUMBER_OF_TRANSFORMS, (MKL_LONG)plan->total2/nmid); DftiSetValue(plan->handle_mid, DFTI_PLACEMENT,DFTI_INPLACE); DftiSetValue(plan->handle_mid, DFTI_INPUT_DISTANCE, (MKL_LONG)nmid); DftiSetValue(plan->handle_mid, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nmid); #if defined(FFT_MKL_THREADS) DftiSetValue(plan->handle_mid, DFTI_NUMBER_OF_USER_THREADS, nthreads); #endif DftiCommitDescriptor(plan->handle_mid); DftiCreateDescriptor( &(plan->handle_slow), FFT_MKL_PREC, DFTI_COMPLEX, 1, (MKL_LONG)nslow); DftiSetValue(plan->handle_slow, DFTI_NUMBER_OF_TRANSFORMS, (MKL_LONG)plan->total3/nslow); DftiSetValue(plan->handle_slow, DFTI_PLACEMENT,DFTI_INPLACE); DftiSetValue(plan->handle_slow, DFTI_INPUT_DISTANCE, (MKL_LONG)nslow); DftiSetValue(plan->handle_slow, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nslow); #if defined(FFT_MKL_THREADS) DftiSetValue(plan->handle_slow, DFTI_NUMBER_OF_USER_THREADS, nthreads); #endif DftiCommitDescriptor(plan->handle_slow); #elif defined(FFT_FFTW3) #if defined(FFT_FFTW_THREADS) if (nthreads > 1) { FFTW_API(init_threads)(); FFTW_API(plan_with_nthreads)(nthreads); } #endif plan->plan_fast_forward = FFTW_API(plan_many_dft)(1, &nfast,plan->total1/plan->length1, nullptr,&nfast,1,plan->length1, nullptr,&nfast,1,plan->length1, FFTW_FORWARD,FFTW_ESTIMATE); plan->plan_fast_backward = FFTW_API(plan_many_dft)(1, &nfast,plan->total1/plan->length1, nullptr,&nfast,1,plan->length1, nullptr,&nfast,1,plan->length1, FFTW_BACKWARD,FFTW_ESTIMATE); plan->plan_mid_forward = FFTW_API(plan_many_dft)(1, &nmid,plan->total2/plan->length2, nullptr,&nmid,1,plan->length2, nullptr,&nmid,1,plan->length2, FFTW_FORWARD,FFTW_ESTIMATE); plan->plan_mid_backward = FFTW_API(plan_many_dft)(1, &nmid,plan->total2/plan->length2, nullptr,&nmid,1,plan->length2, nullptr,&nmid,1,plan->length2, FFTW_BACKWARD,FFTW_ESTIMATE); plan->plan_slow_forward = FFTW_API(plan_many_dft)(1, &nslow,plan->total3/plan->length3, nullptr,&nslow,1,plan->length3, nullptr,&nslow,1,plan->length3, FFTW_FORWARD,FFTW_ESTIMATE); plan->plan_slow_backward = FFTW_API(plan_many_dft)(1, &nslow,plan->total3/plan->length3, nullptr,&nslow,1,plan->length3, nullptr,&nslow,1,plan->length3, FFTW_BACKWARD,FFTW_ESTIMATE); #else /* FFT_KISS */ plan->cfg_fast_forward = kiss_fft_alloc(nfast,0,nullptr,nullptr); plan->cfg_fast_backward = kiss_fft_alloc(nfast,1,nullptr,nullptr); if (nmid == nfast) { plan->cfg_mid_forward = plan->cfg_fast_forward; plan->cfg_mid_backward = plan->cfg_fast_backward; } else { plan->cfg_mid_forward = kiss_fft_alloc(nmid,0,nullptr,nullptr); plan->cfg_mid_backward = kiss_fft_alloc(nmid,1,nullptr,nullptr); } if (nslow == nfast) { plan->cfg_slow_forward = plan->cfg_fast_forward; plan->cfg_slow_backward = plan->cfg_fast_backward; } else if (nslow == nmid) { plan->cfg_slow_forward = plan->cfg_mid_forward; plan->cfg_slow_backward = plan->cfg_mid_backward; } else { plan->cfg_slow_forward = kiss_fft_alloc(nslow,0,nullptr,nullptr); plan->cfg_slow_backward = kiss_fft_alloc(nslow,1,nullptr,nullptr); } #endif if (scaled == 0) plan->scaled = 0; else { plan->scaled = 1; plan->norm = 1.0/(nfast*nmid*nslow); plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) * (out_khi-out_klo+1); } return plan; } /* ---------------------------------------------------------------------- Destroy a 3d fft plan ------------------------------------------------------------------------- */ void fft_3d_destroy_plan(struct fft_plan_3d *plan) { if (plan->pre_plan) remap_3d_destroy_plan(plan->pre_plan); if (plan->mid1_plan) remap_3d_destroy_plan(plan->mid1_plan); if (plan->mid2_plan) remap_3d_destroy_plan(plan->mid2_plan); if (plan->post_plan) remap_3d_destroy_plan(plan->post_plan); if (plan->copy) free(plan->copy); if (plan->scratch) free(plan->scratch); #if defined(FFT_MKL) DftiFreeDescriptor(&(plan->handle_fast)); DftiFreeDescriptor(&(plan->handle_mid)); DftiFreeDescriptor(&(plan->handle_slow)); #elif defined(FFT_FFTW3) FFTW_API(destroy_plan)(plan->plan_slow_forward); FFTW_API(destroy_plan)(plan->plan_slow_backward); FFTW_API(destroy_plan)(plan->plan_mid_forward); FFTW_API(destroy_plan)(plan->plan_mid_backward); FFTW_API(destroy_plan)(plan->plan_fast_forward); FFTW_API(destroy_plan)(plan->plan_fast_backward); #if defined(FFT_FFTW_THREADS) FFTW_API(cleanup_threads)(); #endif #else if (plan->cfg_slow_forward != plan->cfg_fast_forward && plan->cfg_slow_forward != plan->cfg_mid_forward) { free(plan->cfg_slow_forward); free(plan->cfg_slow_backward); } if (plan->cfg_mid_forward != plan->cfg_fast_forward) { free(plan->cfg_mid_forward); free(plan->cfg_mid_backward); } free(plan->cfg_fast_forward); free(plan->cfg_fast_backward); #endif free(plan); } /* ---------------------------------------------------------------------- recursively divide n into small factors, return them in list ------------------------------------------------------------------------- */ void factor(int n, int *num, int *list) { if (n == 1) { return; } else if (n % 2 == 0) { *list = 2; (*num)++; factor(n/2,num,list+1); } else if (n % 3 == 0) { *list = 3; (*num)++; factor(n/3,num,list+1); } else if (n % 5 == 0) { *list = 5; (*num)++; factor(n/5,num,list+1); } else if (n % 7 == 0) { *list = 7; (*num)++; factor(n/7,num,list+1); } else if (n % 11 == 0) { *list = 11; (*num)++; factor(n/11,num,list+1); } else if (n % 13 == 0) { *list = 13; (*num)++; factor(n/13,num,list+1); } else { *list = n; (*num)++; return; } } /* ---------------------------------------------------------------------- divide n into 2 factors of as equal size as possible ------------------------------------------------------------------------- */ void bifactor(int n, int *factor1, int *factor2) { int n1,n2,facmax; facmax = static_cast<int> (sqrt((double) n)); for (n1 = facmax; n1 > 0; n1--) { n2 = n/n1; if (n1*n2 == n) { *factor1 = n1; *factor2 = n2; return; } } } /* ---------------------------------------------------------------------- perform just the 1d FFTs needed by a 3d FFT, no data movement used for timing purposes Arguments: in starting address of input data on this proc, all set to 0.0 nsize size of in flag 1 for forward FFT, -1 for backward FFT plan plan returned by previous call to fft_3d_create_plan ------------------------------------------------------------------------- */ void fft_1d_only(FFT_DATA *data, int nsize, int flag, struct fft_plan_3d *plan) { int i,num; FFT_SCALAR norm; #if defined(FFT_FFTW3) FFT_SCALAR *data_ptr; #endif // total = size of data needed in each dim // length = length of 1d FFT in each dim // total/length = # of 1d FFTs in each dim // if total > nsize, limit # of 1d FFTs to available size of data int total1 = plan->total1; int length1 = plan->length1; int total2 = plan->total2; int length2 = plan->length2; int total3 = plan->total3; int length3 = plan->length3; // fftw3 and Dfti in MKL encode the number of transforms // into the plan, so we cannot operate on a smaller data set #if defined(FFT_MKL) || defined(FFT_FFTW3) if ((total1 > nsize) || (total2 > nsize) || (total3 > nsize)) return; #endif if (total1 > nsize) total1 = (nsize/length1) * length1; if (total2 > nsize) total2 = (nsize/length2) * length2; if (total3 > nsize) total3 = (nsize/length3) * length3; // perform 1d FFTs in each of 3 dimensions // data is just an array of 0.0 #if defined(FFT_MKL) if (flag == 1) { DftiComputeForward(plan->handle_fast,data); DftiComputeForward(plan->handle_mid,data); DftiComputeForward(plan->handle_slow,data); } else { DftiComputeBackward(plan->handle_fast,data); DftiComputeBackward(plan->handle_mid,data); DftiComputeBackward(plan->handle_slow,data); } #elif defined(FFT_FFTW3) FFTW_API(plan) theplan; if (flag == 1) theplan=plan->plan_fast_forward; else theplan=plan->plan_fast_backward; FFTW_API(execute_dft)(theplan,data,data); if (flag == 1) theplan=plan->plan_mid_forward; else theplan=plan->plan_mid_backward; FFTW_API(execute_dft)(theplan,data,data); if (flag == 1) theplan=plan->plan_slow_forward; else theplan=plan->plan_slow_backward; FFTW_API(execute_dft)(theplan,data,data); #else if (flag == 1) { for (int offset = 0; offset < total1; offset += length1) kiss_fft(plan->cfg_fast_forward,&data[offset],&data[offset]); for (int offset = 0; offset < total2; offset += length2) kiss_fft(plan->cfg_mid_forward,&data[offset],&data[offset]); for (int offset = 0; offset < total3; offset += length3) kiss_fft(plan->cfg_slow_forward,&data[offset],&data[offset]); } else { for (int offset = 0; offset < total1; offset += length1) kiss_fft(plan->cfg_fast_backward,&data[offset],&data[offset]); for (int offset = 0; offset < total2; offset += length2) kiss_fft(plan->cfg_mid_backward,&data[offset],&data[offset]); for (int offset = 0; offset < total3; offset += length3) kiss_fft(plan->cfg_slow_backward,&data[offset],&data[offset]); } #endif // scaling if required // limit num to size of data if (flag == -1 && plan->scaled) { norm = plan->norm; num = MIN(plan->normnum,nsize); #if defined(FFT_FFTW3) data_ptr = (FFT_SCALAR *)data; #endif for (i = 0; i < num; i++) { #if defined(FFT_FFTW3) *(data_ptr++) *= norm; *(data_ptr++) *= norm; #elif defined(FFT_MKL) data[i] *= norm; #else data[i].re *= norm; data[i].im *= norm; #endif } } }
Java
/* Copyright (C) 2007 Volker Berlin This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; using java.awt.peer; using java.awt.@event; namespace ikvm.awt { internal class WindowsRobot : RobotPeer { Screen screen; internal WindowsRobot(java.awt.GraphicsDevice device) { screen = ((NetGraphicsDevice)device).screen; } public void dispose() { } public int getRGBPixel(int x, int y) { Bitmap bitmap = new Bitmap(1, 1); Graphics g = Graphics.FromImage(bitmap); g.CopyFromScreen( x, y, 0, 0, new Size(1,1)); g.Dispose(); Color color = bitmap.GetPixel(0,0); bitmap.Dispose(); return color.ToArgb(); } public int[] getRGBPixels(java.awt.Rectangle r) { int width = r.width; int height = r.height; Bitmap bitmap = new Bitmap(width, height); Graphics g = Graphics.FromImage(bitmap); g.CopyFromScreen(r.x, r.y, 0, 0, new Size(width, height)); g.Dispose(); int[] pixels = new int[width * height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixels[i+j*width] = bitmap.GetPixel(i, j).ToArgb(); } } bitmap.Dispose(); return pixels; } private byte MapKeyCode(int keyCode) { //TODO there need a keymap for some special chars //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/UserInput/VirtualKeyCodes.asp switch (keyCode) { case KeyEvent.VK_DELETE: return VK_DELETE; default: return (byte)keyCode; } } public void keyPress(int keycode) { keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYDOWN, IntPtr.Zero); } public void keyRelease(int keycode) { keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYUP, IntPtr.Zero); } public void mouseMove(int x, int y) { Cursor.Position = new Point(x,y); } public void mousePress(int button) { int dwFlags = 0; switch (button) { case InputEvent.BUTTON1_MASK: dwFlags |= MOUSEEVENTF_LEFTDOWN; break; case InputEvent.BUTTON2_MASK: dwFlags |= MOUSEEVENTF_MIDDLEDOWN; break; case InputEvent.BUTTON3_MASK: dwFlags |= MOUSEEVENTF_RIGHTDOWN; break; } mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero); } public void mouseRelease(int button) { int dwFlags = 0; switch (button) { case InputEvent.BUTTON1_MASK: dwFlags |= MOUSEEVENTF_LEFTUP; break; case InputEvent.BUTTON2_MASK: dwFlags |= MOUSEEVENTF_MIDDLEUP; break; case InputEvent.BUTTON3_MASK: dwFlags |= MOUSEEVENTF_RIGHTUP; break; } mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero); } public void mouseWheel(int wheel) { mouse_event(0, 0, 0, wheel, IntPtr.Zero); } [DllImport("user32.dll")] private static extern void keybd_event(byte vk, byte scan, int flags, IntPtr extrainfo); private const int KEYEVENTF_KEYDOWN = 0x0000; private const int KEYEVENTF_KEYUP = 0x0002; [DllImport("user32.dll")] private static extern void mouse_event( int dwFlags, // motion and click options int dx, // horizontal position or change int dy, // vertical position or change int dwData, // wheel movement IntPtr dwExtraInfo // application-defined information ); private const int MOUSEEVENTF_LEFTDOWN = 0x0002; private const int MOUSEEVENTF_LEFTUP = 0x0004; private const int MOUSEEVENTF_RIGHTDOWN = 0x0008; private const int MOUSEEVENTF_RIGHTUP = 0x0010; private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; private const int MOUSEEVENTF_MIDDLEUP = 0x0040; private const int VK_BACK = 0x08; private const int VK_TAB = 0x09; /* * 0x0A - 0x0B : reserved */ private const int VK_CLEAR = 0x0C; private const int VK_RETURN = 0x0D; private const int VK_SHIFT = 0x10; private const int VK_CONTROL = 0x11; private const int VK_MENU = 0x12; private const int VK_PAUSE = 0x13; private const int VK_CAPITAL = 0x14; private const int VK_KANA = 0x15; private const int VK_HANGEUL = 0x15; /* old name - should be here for compatibility */ private const int VK_HANGUL = 0x15; private const int VK_JUNJA = 0x17; private const int VK_FINAL = 0x18; private const int VK_HANJA = 0x19; private const int VK_KANJI = 0x19; private const int VK_ESCAPE = 0x1B; private const int VK_CONVERT = 0x1C; private const int VK_NONCONVERT = 0x1D; private const int VK_ACCEPT = 0x1E; private const int VK_MODECHANGE = 0x1F; private const int VK_SPACE = 0x20; private const int VK_PRIOR = 0x21; private const int VK_NEXT = 0x22; private const int VK_END = 0x23; private const int VK_HOME = 0x24; private const int VK_LEFT = 0x25; private const int VK_UP = 0x26; private const int VK_RIGHT = 0x27; private const int VK_DOWN = 0x28; private const int VK_SELECT = 0x29; private const int VK_PRINT = 0x2A; private const int VK_EXECUTE = 0x2B; private const int VK_SNAPSHOT = 0x2C; private const int VK_INSERT = 0x2D; private const int VK_DELETE = 0x2E; private const int VK_HELP = 0x2F; /* * VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39) * 0x40 : unassigned * VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) */ private const int VK_LWIN = 0x5B; private const int VK_RWIN = 0x5C; private const int VK_APPS = 0x5D; /* * 0x5E : reserved */ private const int VK_SLEEP = 0x5F; private const int VK_NUMPAD0 = 0x60; private const int VK_NUMPAD1 = 0x61; private const int VK_NUMPAD2 = 0x62; private const int VK_NUMPAD3 = 0x63; private const int VK_NUMPAD4 = 0x64; private const int VK_NUMPAD5 = 0x65; private const int VK_NUMPAD6 = 0x66; private const int VK_NUMPAD7 = 0x67; private const int VK_NUMPAD8 = 0x68; private const int VK_NUMPAD9 = 0x69; private const int VK_MULTIPLY = 0x6A; private const int VK_ADD = 0x6B; private const int VK_SEPARATOR = 0x6C; private const int VK_SUBTRACT = 0x6D; private const int VK_DECIMAL = 0x6E; private const int VK_DIVIDE = 0x6F; private const int VK_F1 = 0x70; private const int VK_F2 = 0x71; private const int VK_F3 = 0x72; private const int VK_F4 = 0x73; private const int VK_F5 = 0x74; private const int VK_F6 = 0x75; private const int VK_F7 = 0x76; private const int VK_F8 = 0x77; private const int VK_F9 = 0x78; private const int VK_F10 = 0x79; private const int VK_F11 = 0x7A; private const int VK_F12 = 0x7B; private const int VK_F13 = 0x7C; private const int VK_F14 = 0x7D; private const int VK_F15 = 0x7E; private const int VK_F16 = 0x7F; private const int VK_F17 = 0x80; private const int VK_F18 = 0x81; private const int VK_F19 = 0x82; private const int VK_F20 = 0x83; private const int VK_F21 = 0x84; private const int VK_F22 = 0x85; private const int VK_F23 = 0x86; private const int VK_F24 = 0x87; /* * 0x88 - 0x8F : unassigned */ private const int VK_NUMLOCK = 0x90; private const int VK_SCROLL = 0x91; /* * NEC PC-9800 kbd definitions */ private const int VK_OEM_NEC_EQUAL = 0x92; // '=' key on numpad /* * Fujitsu/OASYS kbd definitions */ private const int VK_OEM_FJ_JISHO = 0x92; // 'Dictionary' key private const int VK_OEM_FJ_MASSHOU= 0x93; // 'Unregister word' key private const int VK_OEM_FJ_TOUROKU= 0x94; // 'Register word' key private const int VK_OEM_FJ_LOYA = 0x95; // 'Left OYAYUBI' key private const int VK_OEM_FJ_ROYA = 0x96; // 'Right OYAYUBI' key /* * 0x97 - 0x9F : unassigned */ /* * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys. * Used only as parameters to GetAsyncKeyState() and GetKeyState(). * No other API or message will distinguish left and right keys in this way. */ private const int VK_LSHIFT = 0xA0; private const int VK_RSHIFT = 0xA1; private const int VK_LCONTROL = 0xA2; private const int VK_RCONTROL = 0xA3; private const int VK_LMENU = 0xA4; private const int VK_RMENU = 0xA5; private const int VK_BROWSER_BACK = 0xA6; private const int VK_BROWSER_FORWARD = 0xA7; private const int VK_BROWSER_REFRESH = 0xA8; private const int VK_BROWSER_STOP = 0xA9; private const int VK_BROWSER_SEARCH = 0xAA; private const int VK_BROWSER_FAVORITES = 0xAB; private const int VK_BROWSER_HOME = 0xAC; private const int VK_VOLUME_MUTE = 0xAD; private const int VK_VOLUME_DOWN = 0xAE; private const int VK_VOLUME_UP = 0xAF; private const int VK_MEDIA_NEXT_TRACK = 0xB0; private const int VK_MEDIA_PREV_TRACK = 0xB1; private const int VK_MEDIA_STOP = 0xB2; private const int VK_MEDIA_PLAY_PAUSE = 0xB3; private const int VK_LAUNCH_MAIL = 0xB4; private const int VK_LAUNCH_MEDIA_SELECT= 0xB5; private const int VK_LAUNCH_APP1 = 0xB6; private const int VK_LAUNCH_APP2 = 0xB7; /* * 0xB8 - 0xB9 : reserved */ private const int VK_OEM_1 = 0xBA; // ';:' for US private const int VK_OEM_PLUS = 0xBB; // '+' any country private const int VK_OEM_COMMA = 0xBC; // ',' any country private const int VK_OEM_MINUS = 0xBD; // '-' any country private const int VK_OEM_PERIOD = 0xBE; // '.' any country private const int VK_OEM_2 = 0xBF; // '/?' for US private const int VK_OEM_3 = 0xC0; // '`~' for US /* * 0xC1 - 0xD7 : reserved */ /* * 0xD8 - 0xDA : unassigned */ private const int VK_OEM_4 = 0xDB; // '[{' for US private const int VK_OEM_5 = 0xDC; // '\|' for US private const int VK_OEM_6 = 0xDD; // ']}' for US private const int VK_OEM_7 = 0xDE; // ''"' for US private const int VK_OEM_8 = 0xDF; /* * 0xE0 : reserved */ /* * Various extended or enhanced keyboards */ private const int VK_OEM_AX = 0xE1; // 'AX' key on Japanese AX kbd private const int VK_OEM_102 = 0xE2; // "<>" or "\|" on RT 102-key kbd. private const int VK_ICO_HELP = 0xE3; // Help key on ICO private const int VK_ICO_00 = 0xE4; // 00 key on ICO /* * 0xE8 : unassigned */ /* * Nokia/Ericsson definitions */ private const int VK_OEM_RESET = 0xE9; private const int VK_OEM_JUMP = 0xEA; private const int VK_OEM_PA1 = 0xEB; private const int VK_OEM_PA2 = 0xEC; private const int VK_OEM_PA3 = 0xED; private const int VK_OEM_WSCTRL = 0xEE; private const int VK_OEM_CUSEL = 0xEF; private const int VK_OEM_ATTN = 0xF0; private const int VK_OEM_FINISH = 0xF1; private const int VK_OEM_COPY = 0xF2; private const int VK_OEM_AUTO = 0xF3; private const int VK_OEM_ENLW = 0xF4; private const int VK_OEM_BACKTAB = 0xF5; private const int VK_ATTN = 0xF6; private const int VK_CRSEL = 0xF7; private const int VK_EXSEL = 0xF8; private const int VK_EREOF = 0xF9; private const int VK_PLAY = 0xFA; private const int VK_ZOOM = 0xFB; private const int VK_NONAME = 0xFC; private const int VK_PA1 = 0xFD; private const int VK_OEM_CLEAR = 0xFE; } }
Java
# vertx-microsrv-poc This is yet another study project # Implementation notes ## Multiple instances of a listing Verticle When deploying multiple time a Vertice listing to a TCP socket (ie. more than 1 instances), vert.x will implement a (non-strict) round robin among your verticles. https://groups.google.com/d/msg/vertx/IzyurInyaRE/InYHPs3UBwAJ
Java
# - Try to find the GLIB2 libraries # Once done this will define # # GLIB2_FOUND - system has glib2 # GLIB2_INCLUDE_DIR - the glib2 include directory # GLIB2_LIBRARIES - glib2 library # Copyright (c) 2008 Laurent Montel, <montel@kde.org> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. if(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES) # Already in cache, be silent set(GLIB2_FIND_QUIETLY TRUE) endif(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES) if (NOT WIN32) find_package(PkgConfig REQUIRED) pkg_check_modules(PKG_GLIB REQUIRED glib-2.0) endif(NOT WIN32) find_path(GLIB2_MAIN_INCLUDE_DIR glib.h PATH_SUFFIXES glib-2.0 PATHS ${PKG_GLIB_INCLUDE_DIRS} ) # search the glibconfig.h include dir under the same root where the library is found find_library(GLIB2_LIBRARIES NAMES glib-2.0 PATHS ${PKG_GLIB_LIBRARY_DIRS} ) find_path(GLIB2_INTERNAL_INCLUDE_DIR glibconfig.h PATH_SUFFIXES glib-2.0/include ../lib/glib-2.0/include PATHS ${PKG_GLIB_INCLUDE_DIRS} ${PKG_GLIB_LIBRARIES} ${CMAKE_SYSTEM_LIBRARY_PATH}) set(GLIB2_INCLUDE_DIR ${GLIB2_MAIN_INCLUDE_DIR}) # not sure if this include dir is optional or required # for now it is optional if(GLIB2_INTERNAL_INCLUDE_DIR) set(GLIB2_INCLUDE_DIR ${GLIB2_INCLUDE_DIR} ${GLIB2_INTERNAL_INCLUDE_DIR}) endif(GLIB2_INTERNAL_INCLUDE_DIR) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GLIB2 DEFAULT_MSG GLIB2_LIBRARIES GLIB2_MAIN_INCLUDE_DIR) mark_as_advanced(GLIB2_INCLUDE_DIR GLIB2_LIBRARIES)
Java
<?php class WCML_sensei{ function __construct(){ global $sitepress; add_action( 'manage_edit-lesson_columns', array( $sitepress, 'add_posts_management_column' ) ); add_action( 'manage_edit-course_columns', array( $sitepress, 'add_posts_management_column' ) ); add_action( 'save_post', array( $this, 'save_post_actions' ), 100, 2 ); add_action( 'sensei_log_activity_after', array( $this, 'log_activity_after' ), 10, 3 ); add_filter( 'sensei_bought_product_id', array( $this, 'filter_bought_product_id' ), 10, 2 ); add_action( 'delete_comment', array( $this, 'delete_user_activity' ) ); add_action( 'pre_get_comments', array( $this, 'pre_get_comments') ); } function save_post_actions( $post_id, $post ){ global $sitepress; // skip not related post types if ( !in_array( $post->post_type , array( 'lesson', 'course', 'quiz' ) ) ) { return; } // skip auto-drafts if ( $post->post_status == 'auto-draft' ) { return; } // skip autosave if ( isset( $_POST[ 'autosave' ] ) ) { return; } if( $post->post_type == 'quiz' && isset( $_POST[ 'ID' ] ) ){ $this->save_post_actions( $_POST[ 'ID' ], get_post( $_POST[ 'ID' ] ) ); } // sync fields from original $trid = $sitepress->get_element_trid( $post_id, 'post_' . $post->post_type ); $translations = $sitepress->get_element_translations( $trid, 'post_' . $post->post_type ); if ( !empty( $translations ) ) { $original_post_id = false; foreach ( $translations as $t ) { if ( $t->original ) { $original_post_id = $t->element_id; break; } } if ( $post_id != $original_post_id ) { $this->sync_custom_fields( $original_post_id, $post_id, $post->post_type ); } else { foreach ( $translations as $t ) { if ( $original_post_id != $t->element_id ) { $this->sync_custom_fields( $original_post_id, $t->element_id, $post->post_type ); } } } } } function sync_custom_fields ( $original_post_id, $post_id, $post_type ){ global $sitepress; $language = $sitepress->get_language_for_element( $post_id, 'post_'.$post_type ); if( $post_type == 'quiz' ){ //sync quiz lesson $lesson_id = get_post_meta( $original_post_id, '_quiz_lesson', true ); if( $lesson_id ){ $tr_lesson_id = apply_filters( 'translate_object_id', $lesson_id, 'post_lesson', false, $language ); if( !is_null( $tr_lesson_id ) ){ update_post_meta( $post_id, '_quiz_lesson', $tr_lesson_id ); } }else{ delete_post_meta( $post_id, '_quiz_lesson' ); } } elseif( $post_type == 'lesson' ){ //sync lesson course $course_id = get_post_meta( $original_post_id, '_lesson_course', true ); if( $course_id ){ $tr_course_id = apply_filters( 'translate_object_id', $course_id, 'post_course', false, $language ); if( !is_null( $tr_course_id ) ){ update_post_meta( $post_id, '_lesson_course', $tr_course_id ); } }else{ delete_post_meta( $post_id, '_lesson_course' ); } //sync lesson prerequisite $lesson_id = get_post_meta( $original_post_id, '_lesson_prerequisite', true ); if( $lesson_id ){ $tr_lesson_id = apply_filters( 'translate_object_id', $lesson_id, 'post_lesson', false, $language ); if( !is_null( $tr_lesson_id ) ){ update_post_meta( $post_id, '_lesson_prerequisite', $tr_lesson_id ); } }else{ delete_post_meta( $post_id, '_lesson_prerequisite' ); } }else{ //sync course woocommerce_product $product_id = get_post_meta( $original_post_id, '_course_woocommerce_product', true ); if( $product_id ){ $tr_product_id = apply_filters( 'translate_object_id', $product_id, 'post_product', false, $language ); if( !is_null( $tr_product_id ) ){ update_post_meta( $post_id, '_course_woocommerce_product', $tr_product_id ); } }else{ delete_post_meta( $post_id, '_course_woocommerce_product' ); } //sync course prerequisite $course_id = get_post_meta( $original_post_id, '_course_prerequisite', true ); if( $course_id ){ $tr_course_id = apply_filters( 'translate_object_id', $course_id, 'post_course', false, $language ); if( !is_null( $tr_course_id ) ){ update_post_meta( $post_id, '_course_prerequisite', $tr_course_id ); } }else{ delete_post_meta( $post_id, '_course_prerequisite' ); } } } function log_activity_after ( $args, $data, $comment_id ){ global $sitepress; $comment_post_id = $data['comment_post_ID']; $trid = $sitepress->get_element_trid( $comment_post_id, 'post_'.get_post_type( $comment_post_id ) ); $translations = $sitepress->get_element_translations( $trid, 'post_'.get_post_type( $comment_post_id ) ); foreach($translations as $translation){ if( $comment_post_id != $translation->element_id ){ $data['comment_post_ID'] = $translation->element_id; $trid = $sitepress->get_element_trid( $comment_id, 'comment' ); $tr_comment_id = apply_filters( 'translate_object_id', $comment_id, 'comment', false, $translation->language_code ); if ( isset( $args['action'] ) && 'update' == $args['action'] && !is_null( $tr_comment_id ) && get_comment( $tr_comment_id ) ) { $data['comment_ID'] = $tr_comment_id; $tr_comment_id = wp_update_comment( $data ); }else{ $tr_comment_id = wp_insert_comment( $data ); $sitepress->set_element_language_details( $tr_comment_id, 'comment', $trid, $translation->language_code ); } } } } function filter_bought_product_id( $product_id, $order ){ $order_language = get_post_meta( $order->id, 'wpml_language', true ); $tr_product_id = apply_filters( 'translate_object_id', $product_id, 'post_'.get_post_type( $product_id ), false, $order_language ); if( !is_null( $tr_product_id ) ){ return $tr_product_id; }else{ return $product_id; } } function delete_user_activity ( $comment_id ){ global $sitepress; $comment_type = get_comment_type( $comment_id ); if( strstr( $comment_type, "sensei" ) ){ $trid = $sitepress->get_element_trid( $comment_id, 'comment' ); $translations = $sitepress->get_element_translations( $trid, 'comment' ); remove_action( 'delete_comment', array ( $this, 'delete_user_activity' ) ); foreach ( $translations as $translation ){ if( $comment_id != $translation->element_id ){ wp_delete_comment( $translation->element_id, true ); } } } } function pre_get_comments($obj){ global $sitepress; if( $obj->query_vars[ 'type' ] == 'sensei_course_start' ){ remove_filter( 'comments_clauses', array( $sitepress, 'comments_clauses' ), 10, 2 ); } } }
Java