The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    ArrowInvalid
Message:      JSON parse error: Missing a closing quotation mark in string. in row 160
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 145, in _generate_tables
                  dataset = json.load(f)
                File "/usr/local/lib/python3.9/json/__init__.py", line 293, in load
                  return loads(fp.read(),
                File "/usr/local/lib/python3.9/json/__init__.py", line 346, in loads
                  return _default_decoder.decode(s)
                File "/usr/local/lib/python3.9/json/decoder.py", line 340, in decode
                  raise JSONDecodeError("Extra data", s, end)
              json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2274)
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1995, in _prepare_split_single
                  for _, table in generator:
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 148, in _generate_tables
                  raise e
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 122, in _generate_tables
                  pa_table = paj.read_json(
                File "pyarrow/_json.pyx", line 308, in pyarrow._json.read_json
                File "pyarrow/error.pxi", line 154, in pyarrow.lib.pyarrow_internal_check_status
                File "pyarrow/error.pxi", line 91, in pyarrow.lib.check_status
              pyarrow.lib.ArrowInvalid: JSON parse error: Missing a closing quotation mark in string. in row 160
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

text
string
meta
dict
<ion-view class="profile-likes" view-title="สนทนา" cache-view="false"> <ion-nav-buttons side="right"> <!--<a class="button button-icon" ui-sref="app.shop.cart"> <i class="icon ion-ios-cart"><span class="badge badge-assertive badge-cart">{{countProduct.getCountProduct()}}</span></i> </a>--> </ion-nav-buttons> <ion-content> <ion-list ng-if="user"> <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats | filter: { users : { _id : user._id } }" type="item-text-wrap" ui-sref="app.shop.cart-chatdetail({chatId: chat._id})"> <img ng-repeat="user in chat.users | filter: { _id : '!' + user._id}" ng-src="{{user.profileImageURL}}"> <h2 ng-repeat="user in chat.users | filter: { _id : '!' + user._id}">{{user.displayName}}</h2> <p>{{chat.lastText}}</p> <i class="icon ion-chevron-right icon-accessory"></i> <!--<ion-option-button class="button-assertive" ng-click="remove(chat)"> Delete </ion-option-button>--> </ion-item> </ion-list> </ion-content> <!--<ion-footer-bar> <i class="icon ion-android-person-add" style="font-size: 30px;" ui-sref="app.listfriend"></i> </ion-footer-bar>--> </ion-view>
{ "content_hash": "e8054ee1113ecb82112f1d807f68e13b", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 144, "avg_line_length": 53.72, "alnum_prop": 0.5606850335070737, "repo_name": "secretmoo35/ThamApp", "id": "0790a254dbf7d6b32629055c2467fc8cfe0cc33c", "size": "1353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/views/app/shop/cart-chat.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "638" }, { "name": "C#", "bytes": "155126" }, { "name": "C++", "bytes": "266969" }, { "name": "CSS", "bytes": "916274" }, { "name": "HTML", "bytes": "164838" }, { "name": "Java", "bytes": "469045" }, { "name": "JavaScript", "bytes": "7425708" }, { "name": "Objective-C", "bytes": "483228" }, { "name": "QML", "bytes": "2765" }, { "name": "Shell", "bytes": "64" } ] }
namespace foundation { class Dictionary; } namespace foundation { class DictionaryArray; } namespace renderer { class EnvironmentEDF; } namespace renderer { class ParamArray; } namespace renderer { // // OSL environment EDF factory. // class APPLESEED_DLLSYMBOL OSLEnvironmentEDFFactory : public IEnvironmentEDFFactory { public: // Return a string identifying this environment EDF model. virtual const char* get_model() const APPLESEED_OVERRIDE; // Return metadata for this environment EDF model. virtual foundation::Dictionary get_model_metadata() const APPLESEED_OVERRIDE; // Return metadata for the inputs of this environment EDF model. virtual foundation::DictionaryArray get_input_metadata() const APPLESEED_OVERRIDE; // Create a new environment EDF instance. virtual foundation::auto_release_ptr<EnvironmentEDF> create( const char* name, const ParamArray& params) const APPLESEED_OVERRIDE; // Static variant of the create() method above. static foundation::auto_release_ptr<EnvironmentEDF> static_create( const char* name, const ParamArray& params); }; } // namespace renderer #endif // !APPLESEED_RENDERER_MODELING_ENVIRONMENTEDF_OSLENVIRONMENTEDF_H
{ "content_hash": "6b1ad840c4d42561eee020ad8a7a9d5d", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 86, "avg_line_length": 32.97435897435897, "alnum_prop": 0.7192846034214619, "repo_name": "aiivashchenko/appleseed", "id": "ea7934fd67a193dccfcb316ecc678e66aa7fbbb8", "size": "3068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/appleseed/renderer/modeling/environmentedf/oslenvironmentedf.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "211" }, { "name": "C", "bytes": "1395946" }, { "name": "C++", "bytes": "9111244" }, { "name": "CMake", "bytes": "226630" }, { "name": "HTML", "bytes": "38058" }, { "name": "Makefile", "bytes": "717" }, { "name": "Objective-C", "bytes": "6087" }, { "name": "Python", "bytes": "312469" }, { "name": "Shell", "bytes": "2798" } ] }
<?php /** * @class messageAdminController * @author NAVER (developers@xpressengine.com) * @brief admin controller class of message module */ class messageAdminController extends message { /** * @brief Initialization */ function init() { } /** * @brief Configuration */ function procMessageAdminInsertConfig() { // Get information $args = Context::gets('skin', 'mskin', 'colorset', 'mcolorset'); // Create a module Controller object $oModuleController = getController('module'); $output = $oModuleController->insertModuleConfig('message',$args); if(!$output->toBool()) return $output; $this->setMessage('success_updated'); $returnUrl = Context::get('success_return_url') ? Context::get('success_return_url') : getNotEncodedUrl('', 'module', 'admin', 'act', 'dispMessageAdminConfig'); $this->setRedirectUrl($returnUrl); } } /* End of file message.admin.controller.php */ /* Location: ./modules/message/message.admin.controller.php */
{ "content_hash": "baeba9f746d930a97cf7fe83b7ea60d7", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 162, "avg_line_length": 27.083333333333332, "alnum_prop": 0.6964102564102564, "repo_name": "talkwithraon/XE4KAIST", "id": "169da556c462f689171f673c63e8048e8ba7be2e", "size": "1027", "binary": false, "copies": "38", "ref": "refs/heads/master", "path": "xe4kaist/modules/message/message.admin.controller.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "2358" }, { "name": "CSS", "bytes": "728319" }, { "name": "HTML", "bytes": "1286170" }, { "name": "JavaScript", "bytes": "2354460" }, { "name": "PHP", "bytes": "4750065" } ] }
require 'spec_helper' describe Spree::Payment do let(:order) { Spree::Order.create } let(:gateway) do gateway = Spree::Gateway::Bogus.new(:environment => 'test', :active => true) gateway.stub :source_required => true gateway end let(:card) do mock_model(Spree::CreditCard, :number => "4111111111111111", :has_payment_profile? => true) end let(:payment) do payment = Spree::Payment.new payment.source = card payment.order = order payment.payment_method = gateway payment end let(:amount_in_cents) { (payment.amount * 100).round } let!(:success_response) do double('success_response', :success? => true, :authorization => '123', :avs_result => { 'code' => 'avs-code' }, :cvv_result => { 'code' => 'cvv-code', 'message' => "CVV Result"}) end let(:failed_response) { double('gateway_response', :success? => false) } before(:each) do # So it doesn't create log entries every time a processing method is called payment.log_entries.stub(:create!) end context '#uncaptured_amount' do it "sets uncaptured amount on save" do expect(payment.uncaptured_amount).to eq(0) payment.save expect(payment.uncaptured_amount).to eq(payment.amount) end end context 'validations' do it "returns useful error messages when source is invalid" do payment.source = Spree::CreditCard.new payment.should_not be_valid cc_errors = payment.errors['Credit Card'] cc_errors.should include("Number can't be blank") cc_errors.should include("Month is not a number") cc_errors.should include("Year is not a number") cc_errors.should include("Verification Value can't be blank") end end # Regression test for https://github.com/spree/spree/pull/2224 context 'failure' do it 'should transition to failed from pending state' do payment.state = 'pending' payment.failure payment.state.should eql('failed') end it 'should transition to failed from processing state' do payment.state = 'processing' payment.failure payment.state.should eql('failed') end end context 'invalidate' do it 'should transition from checkout to invalid' do payment.state = 'checkout' payment.invalidate payment.state.should eq('invalid') end end context "processing" do before do payment.stub(:update_order) payment.stub(:create_payment_profile) end describe "#process!" do it "should purchase if with auto_capture" do payment.payment_method.should_receive(:auto_capture?).and_return(true) payment.should_receive(:purchase!) payment.process! end it "should authorize without auto_capture" do payment.payment_method.should_receive(:auto_capture?).and_return(false) payment.should_receive(:authorize!) payment.process! end it "should make the state 'processing'" do payment.should_receive(:started_processing!) payment.process! end it "should invalidate if payment method doesnt support source" do payment.payment_method.should_receive(:supports?).with(payment.source).and_return(false) expect { payment.process!}.to raise_error(Spree::Core::GatewayError) payment.state.should eq('invalid') end end describe "#authorize!" do it "should call authorize on the gateway with the payment amount" do payment.payment_method.should_receive(:authorize).with(amount_in_cents, card, anything).and_return(success_response) payment.authorize! end it "should call authorize on the gateway with the currency code" do payment.stub :currency => 'GBP' payment.payment_method.should_receive(:authorize).with(amount_in_cents, card, hash_including({:currency => "GBP"})).and_return(success_response) payment.authorize! end it "should log the response" do payment.log_entries.should_receive(:create!).with(:details => anything) payment.authorize! end context "when gateway does not match the environment" do it "should raise an exception" do gateway.stub :environment => "foo" expect { payment.authorize! }.to raise_error(Spree::Core::GatewayError) end end context "if successful" do before do payment.payment_method.should_receive(:authorize).with(amount_in_cents, card, anything).and_return(success_response) end it "should store the response_code, avs_response and cvv_response fields" do payment.authorize! payment.response_code.should == '123' payment.avs_response.should == 'avs-code' payment.cvv_response_code.should == 'cvv-code' payment.cvv_response_message.should == 'CVV Result' end it "should make payment pending" do payment.should_receive(:pend!) payment.authorize! end end context "if unsuccessful" do it "should mark payment as failed" do gateway.stub(:authorize).and_return(failed_response) payment.should_receive(:failure) payment.should_not_receive(:pend) lambda { payment.authorize! }.should raise_error(Spree::Core::GatewayError) end end end describe "#purchase!" do it "should call purchase on the gateway with the payment amount" do gateway.should_receive(:purchase).with(amount_in_cents, card, anything).and_return(success_response) payment.purchase! end it "should log the response" do payment.log_entries.should_receive(:create!).with(:details => anything) payment.purchase! end context "when gateway does not match the environment" do it "should raise an exception" do gateway.stub :environment => "foo" expect { payment.purchase! }.to raise_error(Spree::Core::GatewayError) end end context "if successful" do before do payment.payment_method.should_receive(:purchase).with(amount_in_cents, card, anything).and_return(success_response) end it "should store the response_code and avs_response" do payment.purchase! payment.response_code.should == '123' payment.avs_response.should == 'avs-code' end it "should make payment complete" do payment.should_receive(:complete!) payment.purchase! end it "should log a capture event" do payment.purchase! expect(payment.capture_events.count).to eq(1) expect(payment.capture_events.first.amount).to eq(payment.amount) end it "should set the uncaptured amount to 0" do payment.purchase! expect(payment.uncaptured_amount).to eq(0) end end context "if unsuccessful" do before do gateway.stub(:purchase).and_return(failed_response) payment.should_receive(:failure) payment.should_not_receive(:pend) end it "should make payment failed" do expect { payment.purchase! }.to raise_error(Spree::Core::GatewayError) end it "should not log a capture event" do expect { payment.purchase! }.to raise_error(Spree::Core::GatewayError) expect(payment.capture_events.count).to eq(0) end end end describe "#capture!" do context "when payment is pending" do before do payment.amount = 100 payment.state = 'pending' payment.response_code = '12345' end context "if successful" do before do payment.payment_method.should_receive(:capture).with(payment.money.money.cents, payment.response_code, anything).and_return(success_response) end it "should make payment complete" do payment.should_receive(:complete!) payment.capture! end it "logs capture events" do payment.capture! expect(payment.capture_events.count).to eq(1) expect(payment.capture_events.first.amount).to eq(payment.amount) end end context "capturing a partial amount" do it "logs capture events" do payment.capture!(5000) expect(payment.capture_events.count).to eq(1) expect(payment.capture_events.first.amount).to eq(50) end it "stores the uncaptured amount on the payment" do payment.capture!(6000) expect(payment.uncaptured_amount).to eq(40) # 100 - 60 = 40 end end context "if unsuccessful" do it "should not make payment complete" do gateway.stub :capture => failed_response payment.should_receive(:failure) payment.should_not_receive(:complete) expect { payment.capture! }.to raise_error(Spree::Core::GatewayError) end end end # Regression test for #2119 context "when payment is completed" do before do payment.state = 'completed' end it "should do nothing" do payment.should_not_receive(:complete) payment.payment_method.should_not_receive(:capture) payment.log_entries.should_not_receive(:create!) payment.capture! end end end describe "#void_transaction!" do before do payment.response_code = '123' payment.state = 'pending' end context "when profiles are supported" do it "should call payment_gateway.void with the payment's response_code" do gateway.stub :payment_profiles_supported? => true gateway.should_receive(:void).with('123', card, anything).and_return(success_response) payment.void_transaction! end end context "when profiles are not supported" do it "should call payment_gateway.void with the payment's response_code" do gateway.stub :payment_profiles_supported? => false gateway.should_receive(:void).with('123', anything).and_return(success_response) payment.void_transaction! end end it "should log the response" do payment.log_entries.should_receive(:create!).with(:details => anything) payment.void_transaction! end context "when gateway does not match the environment" do it "should raise an exception" do gateway.stub :environment => "foo" expect { payment.void_transaction! }.to raise_error(Spree::Core::GatewayError) end end context "if successful" do it "should update the response_code with the authorization from the gateway" do # Change it to something different payment.response_code = 'abc' payment.void_transaction! payment.response_code.should == '12345' end end context "if unsuccessful" do it "should not void the payment" do gateway.stub :void => failed_response payment.should_not_receive(:void) expect { payment.void_transaction! }.to raise_error(Spree::Core::GatewayError) end end # Regression test for #2119 context "if payment is already voided" do before do payment.state = 'void' end it "should not void the payment" do payment.payment_method.should_not_receive(:void) payment.void_transaction! end end end describe "#credit!" do before do payment.state = 'completed' payment.response_code = '123' end context "when outstanding_balance is less than payment amount" do before do payment.order.stub :outstanding_balance => 10 payment.stub :credit_allowed => 1000 end it "should call credit on the gateway with the credit amount and response_code" do gateway.should_receive(:credit).with(1000, card, '123', anything).and_return(success_response) payment.credit! end end context "when outstanding_balance is equal to payment amount" do before do payment.order.stub :outstanding_balance => payment.amount end it "should call credit on the gateway with the credit amount and response_code" do gateway.should_receive(:credit).with(amount_in_cents, card, '123', anything).and_return(success_response) payment.credit! end end context "when outstanding_balance is greater than payment amount" do before do payment.order.stub :outstanding_balance => 101 end it "should call credit on the gateway with the original payment amount and response_code" do gateway.should_receive(:credit).with(amount_in_cents.to_f, card, '123', anything).and_return(success_response) payment.credit! end end it "should log the response" do payment.log_entries.should_receive(:create!).with(:details => anything) payment.credit! end context "when gateway does not match the environment" do it "should raise an exception" do gateway.stub :environment => "foo" lambda { payment.credit! }.should raise_error(Spree::Core::GatewayError) end end context "when response is successful" do it "should create an offsetting payment" do Spree::Payment.should_receive(:create!) payment.credit! end it "resulting payment should have correct values" do payment.order.stub :outstanding_balance => 100 payment.stub :credit_allowed => 10 offsetting_payment = payment.credit! offsetting_payment.amount.to_f.should == -10 offsetting_payment.should be_completed offsetting_payment.response_code.should == '12345' offsetting_payment.source.should == payment end end end end context "when response is unsuccessful" do it "should not create a payment" do gateway.stub :credit => failed_response Spree::Payment.should_not_receive(:create) expect { payment.credit! }.to raise_error(Spree::Core::GatewayError) end end context "when already processing" do it "should return nil without trying to process the source" do payment.state = 'processing' payment.should_not_receive(:authorize!) payment.should_not_receive(:purchase!) payment.process!.should be_nil end end context "with source required" do context "raises an error if no source is specified" do before do payment.source = nil end specify do expect { payment.process! }.to raise_error(Spree::Core::GatewayError, Spree.t(:payment_processing_failed)) end end end context "with source optional" do context "raises no error if source is not specified" do before do payment.source = nil payment.payment_method.stub(:source_required? => false) end specify do expect { payment.process! }.not_to raise_error end end end describe "#credit_allowed" do # Regression test for #4403 & #4407 it "is the difference between offsets total and payment amount" do payment.amount = 100 payment.stub(:offsets_total).and_return(0) payment.credit_allowed.should == 100 payment.stub(:offsets_total).and_return(-80) payment.credit_allowed.should == 20 end end describe "#can_credit?" do it "is true if credit_allowed > 0" do payment.stub(:credit_allowed).and_return(100) payment.can_credit?.should be_true end it "is false if credit_allowed is 0" do payment.stub(:credit_allowed).and_return(0) payment.can_credit?.should be_false end end describe "#credit!" do context "when amount <= credit_allowed" do it "makes the state processing" do payment.state = 'completed' payment.stub(:credit_allowed).and_return(10) payment.partial_credit(10) payment.should be_processing end it "calls credit on the source with the payment and amount" do payment.state = 'completed' payment.stub(:credit_allowed).and_return(10) payment.should_receive(:credit!).with(10) payment.partial_credit(10) end end context "when amount > credit_allowed" do it "should not call credit on the source" do payment.state = 'completed' payment.stub(:credit_allowed).and_return(10) payment.partial_credit(20) payment.should be_completed end end end describe "#save" do it "should call order#update!" do payment = Spree::Payment.create(:amount => 100, :order => order) order.should_receive(:update!) payment.save end context "when profiles are supported" do before do gateway.stub :payment_profiles_supported? => true payment.source.stub :has_payment_profile? => false end context "when there is an error connecting to the gateway" do it "should call gateway_error " do gateway.should_receive(:create_profile).and_raise(ActiveMerchant::ConnectionError) lambda do Spree::Payment.create( :amount => 100, :order => order, :source => card, :payment_method => gateway ) end.should raise_error(Spree::Core::GatewayError) end end context "when successfully connecting to the gateway" do it "should create a payment profile" do payment.payment_method.should_receive :create_profile payment = Spree::Payment.create( :amount => 100, :order => order, :source => card, :payment_method => gateway ) end end end context "when profiles are not supported" do before { gateway.stub :payment_profiles_supported? => false } it "should not create a payment profile" do gateway.should_not_receive :create_profile payment = Spree::Payment.create( :amount => 100, :order => order, :source => card, :payment_method => gateway ) end end end describe "#build_source" do let(:params) do { :amount => 100, :payment_method => gateway, :source_attributes => { :expiry =>"1 / 99", :number => '1234567890123', :verification_value => '123', :name => 'Spree Commerce' } } end it "should build the payment's source" do payment = Spree::Payment.new(params) payment.should be_valid payment.source.should_not be_nil end it "assigns user and gateway to payment source" do order = create(:order) source = order.payments.new(params).source expect(source.user_id).to eq order.user_id expect(source.payment_method_id).to eq gateway.id end it "errors when payment source not valid" do params = { :amount => 100, :payment_method => gateway, :source_attributes => {:expiry => "1 / 12" }} payment = Spree::Payment.new(params) payment.should_not be_valid payment.source.should_not be_nil payment.source.should have(1).error_on(:number) payment.source.should have(1).error_on(:verification_value) end it "does not build a new source when duplicating the model with source_attributes set" do payment = create(:payment) payment.source_attributes = params[:source_attributes] expect { payment.dup }.to_not change { payment.source } end end describe "#currency" do before { order.stub(:currency) { "ABC" } } it "returns the order currency" do payment.currency.should == "ABC" end end describe "#display_amount" do it "returns a Spree::Money for this amount" do payment.display_amount.should == Spree::Money.new(payment.amount) end end # Regression test for #2216 describe "#gateway_options" do before { order.stub(:last_ip_address => "192.168.1.1") } it "contains an IP" do payment.gateway_options[:ip].should == order.last_ip_address end end describe "#set_unique_identifier" do # Regression test for #1998 it "sets a unique identifier on create" do payment.run_callbacks(:create) payment.identifier.should_not be_blank payment.identifier.size.should == 8 payment.identifier.should be_a(String) end # Regression test for #3733 it "does not regenerate the identifier on re-save" do payment.save old_identifier = payment.identifier payment.save payment.identifier.should == old_identifier end context "other payment exists" do let(:other_payment) { payment = Spree::Payment.new payment.source = card payment.order = order payment.payment_method = gateway payment } before { other_payment.save! } it "doesn't set duplicate identifier" do payment.should_receive(:generate_identifier).and_return(other_payment.identifier) payment.should_receive(:generate_identifier).and_call_original payment.run_callbacks(:create) payment.identifier.should_not be_blank payment.identifier.should_not == other_payment.identifier end end end describe "#amount=" do before do subject.amount = amount end context "when the amount is a string" do context "amount is a decimal" do let(:amount) { '2.99' } its(:amount) { should eql(BigDecimal('2.99')) } end context "amount is an integer" do let(:amount) { '2' } its(:amount) { should eql(BigDecimal('2.0')) } end context "amount contains a dollar sign" do let(:amount) { '$2.99' } its(:amount) { should eql(BigDecimal('2.99')) } end context "amount contains a comma" do let(:amount) { '$2,999.99' } its(:amount) { should eql(BigDecimal('2999.99')) } end context "amount contains a negative sign" do let(:amount) { '-2.99' } its(:amount) { should eql(BigDecimal('-2.99')) } end context "amount is invalid" do let(:amount) { 'invalid' } # this is a strange default for ActiveRecord its(:amount) { should eql(BigDecimal('0')) } end context "amount is an empty string" do let(:amount) { '' } its(:amount) { should be_nil } end end context "when the amount is a number" do let(:amount) { 1.55 } its(:amount) { should eql(BigDecimal('1.55')) } end context "when the amount is nil" do let(:amount) { nil } its(:amount) { should be_nil } end end describe "is_avs_risky?" do it "returns false if avs_response == 'D'" do payment.update_attribute(:avs_response, "D") payment.is_avs_risky?.should == false end it "returns false if avs_response == nil" do payment.update_attribute(:avs_response, nil) payment.is_avs_risky?.should == false end it "returns true if avs_response == A-Z, omitting D" do # should use avs_response_code helper ('A'..'Z').reject{ |x| x == 'D' }.to_a.each do |char| payment.update_attribute(:avs_response, char) payment.is_avs_risky?.should == true end end end describe "is_cvv_risky?" do it "returns false if cvv_response_code == 'M'" do payment.update_attribute(:cvv_response_code, "M") payment.is_cvv_risky?.should == false end it "returns false if cvv_response_code == nil" do payment.update_attribute(:cvv_response_code, nil) payment.is_cvv_risky?.should == false end it "returns false if cvv_response_message == ''" do payment.update_attribute(:cvv_response_message, '') payment.is_cvv_risky?.should == false end it "returns true if cvv_response_code == [A-Z], omitting D" do # should use cvv_response_code helper (%w{N P S U} << "").each do |char| payment.update_attribute(:cvv_response_code, char) payment.is_cvv_risky?.should == true end end end # Regression test for #4072 (kinda) # The need for this was discovered in the research for #4072 context "state changes" do it "are logged to the database" do payment.state_changes.should be_empty expect(payment.process!).to be_true payment.state_changes.count.should == 2 changes = payment.state_changes.map { |change| { change.previous_state => change.next_state} } expect(changes).to eq([ {"checkout" => "processing"}, { "processing" => "pending"} ]) end end end
{ "content_hash": "c7d7062e4467fbea0f37cdb9b44273e7", "timestamp": "", "source": "github", "line_count": 821, "max_line_length": 153, "avg_line_length": 31.37880633373934, "alnum_prop": 0.6072121729679373, "repo_name": "thanhjamin/z_spree", "id": "d87d59cd2d2da9f43ff51b84b61fad7dd666db88", "size": "25762", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/spec/models/spree/payment_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "103487" }, { "name": "CoffeeScript", "bytes": "31735" }, { "name": "JavaScript", "bytes": "55318" }, { "name": "Ruby", "bytes": "1546153" }, { "name": "Shell", "bytes": "1463" } ] }
local CLASS = require('Class') local FsmCtl = require("FsmController") local Entity = require("Entity") require("Util") -- abstract local State = CLASS() -- Lv0 local RootState = CLASS(State) -- Lv1 local PatrolState = CLASS(State) local FleeState = CLASS(State) local PassiveState = CLASS(State) -- Lv2 local NavigationState = CLASS(State) -- Lv3 local RunState = CLASS(State) local JumpState = CLASS(State) local ClimbState = CLASS(State) -- debug prupose local WanderState = CLASS(State) -- ************************************************* -- * abstract state * -- ************************************************* State.name = "basic" State.parentMachine = nil State.childrenMachine = {} State.agent = nil State.entity = nil -- action when entering a state, should be override function State:enter() assert(self.parentMachine) assert(self.agent) assert(self.entity) self.childrenMachine = {} end -- routine of a state, should be override function State:execute(dt) end -- action when exiting a state, should be cascade exiting -- should be override if needed, but must call the base class exit in the end function State:exit() for _,child in ipairs(self.childrenMachine) do child:exitState() end end -- ************************************************* -- * root state Lv0 * -- ************************************************* RootState.name = "root" RootState.actionFsm = nil RootState.holes = nil RootState.passive = false -- ******************** override ******************* function RootState:enter() State.enter(self) self.actionFsm = FsmCtl.new() self.actionFsm:attach(self) table.insert(self.childrenMachine, self.actionFsm) if self.entity.wander then local wanderState = WanderState.new({entity = self.entity}) self.actionFsm:changeState(wanderState) end end function RootState:execute(dt) if self.entity.wander then self.actionFsm:update(dt) return end -- what to do next? -- passive -> wait if self.passive and self.actionFsm.currState and self.actionFsm.currState.name == "passive" then return end if self.passive and (not self.actionFsm.currState or self.actionFsm.currState.name ~= "passive") then local passiveState = PassiveState.new({entity = self.entity}) self.actionFsm:changeState(passiveState) return end -- on air -> wait local onground = self.entity:isOnGround() if not ( onground ) and (not self.actionFsm.currState or self.actionFsm.currState.name ~= "onair") then --self.entity:resetAnim() return end -- enemy too close -> flee -- should avoid jitter between flee and patrol local threatened = self.entity:isThreatened() if threatened and (not self.actionFsm.currState or self.actionFsm.currState.name ~= "flee") then local fleeState = FleeState.new({entity = self.entity}) self.actionFsm:changeState(fleeState) return end -- safe and on ground -> find holes -- sort the holes based on distance first if onground and (not threatened) and (not self.actionFsm.currState or self.actionFsm.currState.name ~= "patrol") then assert(self.holes) local indice = {} for i,h in ipairs(self.holes) do table.insert(indice,h) end local patrolState = PatrolState.new({entity = self.entity, nodeIndice = indice}) self.actionFsm:changeState(patrolState) end self.actionFsm:update(dt) end function RootState:exit() return State.exit(self) end -- ************************************************* -- * patrol state Lv1 * -- ************************************************* PatrolState.name = "patrol" PatrolState.nodeIndice = {} PatrolState.naviFsm = nil -- ******************** override ******************* function PatrolState:enter() State.enter(self) assert(self.nodeIndice and table.getn(self.nodeIndice)>=2) self:sortTarget() self.naviFsm = FsmCtl.new() self.naviFsm:attach(self) table.insert(self.childrenMachine, self.naviFsm) local naviState = NavigationState.new({entity = self.entity}) --naviState.start = self.nodeIndice[1] naviState.start = world.navgraph:nearestNode(self.entity.px, self.entity.py) naviState.goal = self.nodeIndice[1] self.naviFsm:changeState(naviState) end function PatrolState:execute(dt) if not self.naviFsm.currState.next then table.insert(self.nodeIndice, table.remove(self.nodeIndice, 1)) local naviState = NavigationState.new({entity = self.entity}) naviState.start = world.navgraph:nearestNode(self.entity.px, self.entity.py) naviState.goal = self.nodeIndice[1] self.naviFsm:changeState(naviState) end self.naviFsm:update(dt) end function PatrolState:exit() return State.exit(self) end function PatrolState:sortTarget() local function sort(a,b) local dista = {} for _,e in ipairs(Entity._all) do if e.class == "Hunter" then table.insert(dista, eudist(e.px, e.py, world.navgraph.nodes[a].x, world.navgraph.nodes[a].y)) end end table.sort(dista) local hunterdista = dista[1] local distb = {} for _,e in ipairs(Entity._all) do if e.class == "Hunter" then table.insert(distb, eudist(e.px, e.py, world.navgraph.nodes[b].x, world.navgraph.nodes[b].y)) end end table.sort(distb) local hunterdistb = distb[1] if hunterdista >= 1.5 * self.entity.threatBound and hunterdistb >= 1.5 * self.entity.threatBound then local entitydista = eudist(self.entity.px, self.entity.py, world.navgraph.nodes[a].x, world.navgraph.nodes[a].y) local entitydistb = eudist(self.entity.px, self.entity.py, world.navgraph.nodes[b].x, world.navgraph.nodes[b].y) return entitydista < entitydistb else return hunterdista < hunterdistb end end table.sort(self.nodeIndice,sort) end -- ************************************************* -- * flee state Lv1 * -- ************************************************* FleeState.name = "flee" FleeState.moveFsm = nil FleeState.current = nil FleeState.next = nil -- ******************** override ******************* function FleeState:enter() State.enter(self) self.entity.body:setLinearVelocity(0,0) self.moveFsm = FsmCtl.new() self.moveFsm:attach(self) table.insert(self.childrenMachine, self.moveFsm) -- first goto a node self.next = world.navgraph:nearestNode(self.entity.px, self.entity.py) local run = RunState.new({entity = self.entity, target = world.navgraph.nodes[self.next]}) self.moveFsm:changeState(run) end function FleeState:execute(dt) assert(self.next) local currPosx = self.entity.px local currPosy = self.entity.py if eudist(currPosx, currPosy, world.navgraph.nodes[self.next].x, world.navgraph.nodes[self.next].y) <= 5 then self.current = self.next -- simply navigate to the reverse direction local bestedge = self:calcEscapeRoute() assert(bestedge) self.next = bestedge.next if bestedge.type == "run" then local run = RunState.new({entity = self.entity, target = world.navgraph.nodes[self.next]}) self.moveFsm:changeState(run) elseif bestedge.type == "jump" then local jump = JumpState.new({entity = self.entity, target = world.navgraph.nodes[self.next]}) self.moveFsm:changeState(jump) elseif type == "climb" then local climb = ClimbState.new({entity = self.entity, target = world.navgraph.nodes[self.next]}) self.moveFsm:changeState(climb) end end self.moveFsm:update(dt) end function FleeState:exit() return State.exit(self) end function FleeState:calcEscapeRoute() local maxheur = 0, bestedge for k,edge in pairs(world.navgraph.nodes[self.current].neighbors) do local heur = self:fleeHeuristic(world.navgraph.nodes[edge.next]) if heur > maxheur then maxheur = heur bestedge = edge end end return bestedge end function FleeState:fleeHeuristic(node) local dist = {} for _,e in ipairs(Entity._all) do if e.class == "Hunter" then table.insert(dist, eudist(e.px, e.py, node.x, node.y)) end end table.sort(dist) return dist[1] end -- ************************************************* -- * passive state Lv1 * -- ************************************************* PassiveState.name = "passive" -- ******************** override ******************* function PassiveState:enter() State.enter(self) self.entity:resetAnim() self.entity.body:setType("kinematic") self.entity.body:setLinearVelocity(0,0) end function PassiveState:execute(dt) -- body end function PassiveState:exit() -- body self.entity.body:setType("dynamic") -- TODO: maybe fail to set it back? return State.exit(self) end -- ************************************************* -- * navigation state Lv2 * -- ************************************************* NavigationState.name = "navigation" NavigationState.start = nil NavigationState.goal = nil NavigationState.current = nil NavigationState.next = nil NavigationState.type = nil NavigationState.path = nil NavigationState.moveFsm = nil -- ******************** override ******************* function NavigationState:enter() State.enter(self) assert(self.start, "start is nil") assert(self.goal, "goal is nil") self.path = world.navgraph:findPath(self.start,self.goal) assert(self.path, "path is nil") self.entity.body:setLinearVelocity(0,0) if not self.path[self.start] then -- alrealy at goal return -- self.parentMachine:changeState(WanderState.new()) else self.current = nil self.next = self.start self.moveFsm = FsmCtl.new() self.moveFsm:attach(self) table.insert(self.childrenMachine, self.moveFsm) self.type = self.path[self.start].type local run = RunState.new({entity = self.entity, target = world.navgraph.nodes[self.next]}) self.moveFsm:changeState(run) end end function NavigationState:execute(dt) local currPosx = self.entity.px local currPosy = self.entity.py if self:endCondition() then -- arrived at next node self.current = self.next self.next = self.path[self.next] if not self.next then -- arrived at goal return else self.type = self.next.type self.next = self.next.idx -- next action is run if self.type == "run" then local run = RunState.new({entity = self.entity, target = world.navgraph.nodes[self.next]}) self.moveFsm:changeState(run) -- next action is jump elseif self.type == "jump" then local jump = JumpState.new({entity = self.entity, target = world.navgraph.nodes[self.next]}) self.moveFsm:changeState(jump) -- next action is climb elseif self.type == "climb" then local climb = ClimbState.new({entity = self.entity, target = world.navgraph.nodes[self.next]}) self.moveFsm:changeState(climb) end end end self.moveFsm:update(dt) end function NavigationState:exit() NavigationState.start = nil NavigationState.goal = nil NavigationState.next = nil NavigationState.path = nil return State.exit(self) end function NavigationState:endCondition() local currPosx = self.entity.px local currPosy = self.entity.py return eudist(currPosx, currPosy, world.navgraph.nodes[self.next].x, world.navgraph.nodes[self.next].y) <= 5 end -- ************************************************* -- * run state Lv3 * -- ************************************************* RunState.name = "run" RunState.target = nil RunState.maxSpeed = 200 -- ******************** override ******************* function RunState:enter() State.enter(self) assert(self.target) self.entity:resetAnim() end function RunState:execute(dt) local entity = self.entity local currPosx = entity.px local currPosy = entity.py local _, g = world.physics:getGravity() local angle = angle(currPosx, currPosy, self.target.x, self.target.y) local currVelox, currVeloy = entity.body:getLinearVelocity() if currVelox * currVelox + currVeloy * currVeloy <= self.maxSpeed * self.maxSpeed then entity.body:applyForce(math.cos(angle) * 200, math.sin(angle) * 200 - g) else entity.body:setLinearVelocity(math.cos(angle) * self.maxSpeed, math.sin(angle) * self.maxSpeed) end -- animation if currVelox >= 0 then self.entity:setAnimDirection("right") else self.entity:setAnimDirection("left") end end function RunState:exit() return State.exit(self) end -- ************************************************* -- * jump state Lv3 * -- ************************************************* JumpState.name = "jump" JumpState.target = nil function JumpState:enter() State.enter(self) assert(self.target) self.entity:resetAnim() --self.entity:playSound("jump") self.entity.body:setLinearVelocity(0,0) local entity = self.entity local currx = entity.px local curry = entity.py local _, g = world.physics:getGravity() local m = entity.body:getMass() local fx,fy = self:calcJump(currx, curry, self.target.x, self.target.y,25, m, g) entity.body:applyLinearImpulse(fx,fy) end function JumpState:execute(dt) local entity = self.entity local currPosx = entity.px local currPosy = entity.py local currVelox, currVeloy = entity.body:getLinearVelocity() -- animation if currVelox >= 0 and currVeloy <= 0 then self.entity:setAnimDirection("jumpupright") elseif currVelox >= 0 and currVeloy > 0 then self.entity:setAnimDirection("jumpdownright") elseif currVelox <0 and currVeloy <=0 then self.entity:setAnimDirection("jumpupleft") else self.entity:setAnimDirection("jumpdownleft") end -- don't do anything when on air local objBelowleft = world:castRay(currPosx - 16, currPosy, currPosx - 16, currPosy + 20) local objBelowright = world:castRay(currPosx + 16, currPosy, currPosx + 16, currPosy + 20) if table.getn(objBelowleft) == 0 and table.getn(objBelowright) == 0 then return end end function JumpState:exit() return State.exit(self) end function JumpState:calcJump(currx, curry, targetx, targety, peakdh, m, g) local peaky = math.min(curry, targety) - peakdh local y1, y2, t1, t2 local vx0, vy0 local fx, fy y1 = curry - peaky y2 = targety - peaky vy0 = math.sqrt(2 * g * y1) t1 = math.sqrt(2 * y1 / g) t2 = math.sqrt(2 * y2 / g) vx0 = (targetx - currx) / (t1 + t2) fx = getImpulseForce(m,0,vx0) fy = getImpulseForce(m,0,vy0) return fx, -fy end -- ************************************************* -- * climb state Lv3 * -- ************************************************* ClimbState.name = "climb" ClimbState.target = nil ClimbState.speed = 100 -- ******************** override ******************* function ClimbState:enter() State.enter(self) assert(self.target) self.entity:resetAnim() self.entity.body:setLinearVelocity(0,0) end function ClimbState:execute(dt) local entity = self.entity local currPosx = entity.px local currPosy = entity.py local angle = angle(currPosx, currPosy, self.target.x, self.target.y) --entity.body:setLinearVelocity(math.cos(angle) * self.speed, math.sin(angle) * self.speed) --entity.body:setLinearVelocity(0,-200) local _,g = world.physics:getGravity() local m = self.entity.body:getMass() entity.body:applyForce(0,-g * m * 30) if self.target.y <= self.entity.py then self.entity:setAnimDirection("climbup") else self.entity:setAnimDirection("climbdown") end end function ClimbState:exit() return State.exit(self) end -- ************************************************* -- * wander state (debug prupose) * -- ************************************************* WanderState.name = "wander" -- ******************** override ******************* function WanderState:enter() State.enter(self) self.entity.vx = clamp(self.entity.vx, -400, 200) self.entity.vy = clamp(self.entity.vy, -400, 200) end function WanderState:execute(dt) --here we are going to create some keyboard events if love.keyboard.isDown("right") then --press the right arrow key to push the ball to the right self.entity.body:applyForce(1000,0) elseif love.keyboard.isDown("left") then --press the left arrow key to push the ball to the left self.entity.body:applyForce(-1000,0) end if love.keyboard.isDown("up") then --press the up arrow key to fly self.entity.body:applyForce(0,-1000) elseif love.keyboard.isDown("down") then --press the left arrow key to push the ball to the left self.entity.body:applyForce(0,1000) end if love.keyboard.isDown("r") then self.entity:release("random") end if love.keyboard.isDown("c") then self.entity:setCarried() end if love.keyboard.isDown("h") then self.entity:setHooked() end self.entity.vx = clamp(self.entity.vx, -400, 200) self.entity.vy = clamp(self.entity.vy, -400, 200) self.entity.body:setLinearVelocity(self.entity.vx, self.entity.vy) end function WanderState:exit() return State.exit(self) end local states = { rootState = RootState, patrolState = PatrolState, passiveState = PassiveState, navigationState = NavigationState, wanderState = WanderState, } return states
{ "content_hash": "f07487ea974e27f10cd8bff352ff6442", "timestamp": "", "source": "github", "line_count": 576, "max_line_length": 124, "avg_line_length": 31.897569444444443, "alnum_prop": 0.6046372394274206, "repo_name": "MangoSister/Grabbit", "id": "13905773457a9af84e0d75e7cbb25b9b358563b2", "size": "18529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "State.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "228163" } ] }
"""Add a new patient to the xpacsdb.patient_info table Usage: add_patient.py [options] add_patient.py -h Options: -h, --help Show this screen -d, --debug Show some debug information -s <host> The MySQL server host IP address. -p <port> MySQL port. Default is 3306. -u <user> User name. --password=<password> User password. --db=<database> Database name. Default is xpacs. -f <csv_file> Read list of patients from a CSV file (see below) Batch addition of patients ^^^^^^^^^^^^^^^^^^^^^^^^^^ If -f option is given, then patients are added in from a CSV file in a batch mode. This file should have the following headers: 'patient_id', 'gender', 'cohort', 'ethnicity', 'primary_diagnosis If there are existing patient_ids in the database, then the existing rows will be updated. Author: Avan Suinesiaputra - University of Auckland (2017) """ # Docopt is a library for parsing command line arguments import docopt import getpass import mysql.connector import termutils as tu import sqlutils as su if __name__ == '__main__': try: # Parse arguments, use file docstring as a parameter definition arguments = docopt.docopt(__doc__) # Default values if not arguments['-s']: arguments['-s'] = '127.0.0.1' if not arguments['-p']: arguments['-p'] = 3306 if not arguments['--db']: arguments['--db'] = 'xpacs' # Check user & password if not arguments['-u']: arguments['-u'] = raw_input('Username: ') if arguments['--password'] is None: arguments['--password'] = getpass.getpass('Password: ') # print arguments for debug if arguments['--debug']: tu.debug(str(arguments)) # Handle invalid options except docopt.DocoptExit as e: tu.error(e.message) exit() # connecting print 'Connecting to mysql://' + arguments['-s'] + ':' + str(arguments['-p']) + ' ...' try: cnx = mysql.connector.connect(user=arguments['-u'], host=arguments['-s'], port=arguments['-p'], password=arguments['--password'], database=arguments['--db']) except mysql.connector.Error as err: print(err) exit() existing_patients = su.get_all_patient_ids(cnx) # it's either by CSV file or interactive if arguments['-f'] is None: # First question: who is the patient? patientID = raw_input('Patient ID: ') if patientID in existing_patients: tu.error("Patient " + patientID + " already exists.") exit() # Remaining questions cohort = raw_input('Cohort [press <enter> to skip]: ') ethnicity = raw_input('Ethnicity [press <enter> to skip]: ') gender = raw_input('Cohort [M/F/U=unknown (default)]: ') if str.lower(gender) == 'f': gender = 'female' elif str.lower(gender) == 'm': gender = 'male' else: gender = 'unknown' primary_diagnosis = raw_input('Primary diagnosis [press <enter> to skip]: ') query = su.insert_new_patient_info(cnx, { 'patient_id': patientID, 'cohort': cohort, 'ethnicity': ethnicity, 'gender': gender, 'primary_diagnosis': primary_diagnosis }) if arguments['--debug']: tu.debug(query) tu.ok("Patient " + patientID + " added to the database") # don't forget to close the connection cnx.close() else: try: for row in su.read_csv(arguments['-f']): # fix gender g = str.lower(row['gender']) if g == 'male' or g == 'm': row['gender'] = 'male' elif g == 'female' or g == 'f': row['gender'] = 'female' else: row['gender'] = 'unknown' # update or insert if row['patient_id'] in existing_patients: if arguments['--debug']: tu.warn('Updating ' + row['patient_id']) query = su.update_patient_info(cnx, row) else: if arguments['--debug']: tu.debug('Inserting ' + row['patient_id']) query = su.insert_new_patient_info(cnx, row) if arguments['--debug']: print query except Exception, e: tu.error(str(e)) exit() tu.ok("SUCCESS")
{ "content_hash": "2f2e3aa5f6e304d045d4a15052a73347", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 86, "avg_line_length": 29.48701298701299, "alnum_prop": 0.5463554283197534, "repo_name": "CardiacAtlasProject/CAPServer2.0", "id": "a99a3ece7c9f12ec8a34f174a147734dbb5907ca", "size": "4541", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dbase/utils/add_patient.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5036" }, { "name": "CSS", "bytes": "10248" }, { "name": "Gherkin", "bytes": "179" }, { "name": "HTML", "bytes": "182082" }, { "name": "Java", "bytes": "446416" }, { "name": "JavaScript", "bytes": "271433" }, { "name": "Python", "bytes": "13917" }, { "name": "Scala", "bytes": "20977" }, { "name": "Shell", "bytes": "9179" } ] }
class AddStationableToStations < ActiveRecord::Migration def change add_column :stations, :stationable_id, :integer add_column :stations, :stationable_type, :string end end
{ "content_hash": "80c0ff8c762470cc89cfc150ef5158a7", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 56, "avg_line_length": 30.833333333333332, "alnum_prop": 0.7567567567567568, "repo_name": "soarpatriot/price", "id": "c2249e0848aed18601535db37892c2ea428b524f", "size": "185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20150830064509_add_stationable_to_stations.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "26603" }, { "name": "HTML", "bytes": "90684" }, { "name": "JavaScript", "bytes": "65422" }, { "name": "Ruby", "bytes": "301736" } ] }
from feature_format import featureFormat, targetFeatureSplit import pickle from sklearn.naive_bayes import GaussianNB from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score from sklearn.pipeline import Pipeline from sklearn.feature_selection import SelectKBest from sklearn.grid_search import GridSearchCV import numpy as np # loading the enron data dictionary with open("final_project_dataset.pkl", "r") as data_file: data_dict = pickle.load(data_file) # removing 'TOTAL' outlier del data_dict['TOTAL'] # creating new features for name in data_dict: if data_dict[name]["total_payments"] != "NaN" and\ data_dict[name]["total_stock_value"] != "NaN": data_dict[name]["ttl_pay_stock"] = \ data_dict[name]["total_payments"] + \ data_dict[name]["total_stock_value"] else: data_dict[name]["ttl_pay_stock"] = 0.0 # list containing all labels and features except email feat_list = ['poi', 'salary', 'to_messages', 'deferral_payments', 'total_payments', 'exercised_stock_options', 'bonus', 'restricted_stock', 'shared_receipt_with_poi', 'restricted_stock_deferred', 'total_stock_value', 'expenses', 'loan_advances', 'from_messages', 'other', 'from_this_person_to_poi', 'director_fees', 'deferred_income', 'long_term_incentive', 'from_poi_to_this_person', 'ttl_pay_stock'] # Selecting the best features using GridSearchCV data = featureFormat(data_dict, feat_list, sort_keys = True) labels, features = targetFeatureSplit(data) pipe = Pipeline([('KBest', SelectKBest()), ('clf', GaussianNB())]) K = [1,2,3,4,5] param_grid = [{'KBest__k': K}] gs = GridSearchCV(estimator=pipe, param_grid=param_grid, scoring='f1') gs.fit(features, labels) kb = SelectKBest(k=gs.best_params_['KBest__k']) kb.fit(features, labels) best_feat = list(kb.get_support(indices=True)+1) print "Best f1 score:", gs.best_score_ print "No. of features used for the best f1 score:", gs.best_params_['KBest__k'] print "Names of features used:\n", [feat_list[i] for i in best_feat] final_feat_list = ['poi', 'salary', 'exercised_stock_options', 'bonus', 'total_stock_value'] # Computing evaluation metrics using the selected features final_data = featureFormat(data_dict, final_feat_list, sort_keys = True) final_labels, final_features = targetFeatureSplit(final_data) final_sss = StratifiedShuffleSplit(final_labels, 1000, random_state = 42) accuracy = [] precision = [] recall = [] f1 = [] for train_indices, test_indices in final_sss: features_train = [final_features[i] for i in train_indices] features_test = [final_features[j] for j in test_indices] labels_train = [final_labels[i] for i in train_indices] labels_test = [final_labels[j] for j in test_indices] clf = GaussianNB() clf.fit(features_train, labels_train) pred = clf.predict(features_test) accuracy.append(accuracy_score(labels_test, pred)) precision.append(precision_score(labels_test, pred)) recall.append(recall_score(labels_test, pred)) f1.append(f1_score(labels_test, pred)) print "Evaluation results of GaussianNB using best features:" print "Mean Accuracy:", np.mean(accuracy) print "Mean Precision:", np.mean(precision) print "Mean Recall:", np.mean(recall) print "Mean f1 score:", np.mean(f1)
{ "content_hash": "a24100f845e24b23ac5195d51edbcdfb", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 83, "avg_line_length": 34.570093457943926, "alnum_prop": 0.6455798864557989, "repo_name": "rjegankumar/enron_email_fraud_identification", "id": "a8a6242d389ca5b999f731ba8fcc8cd50ed1ed98", "size": "3699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nb_classifier.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "29136" } ] }
import sys, os.path sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src')) import skameyka skameyka.app.run(port=5001, debug=True)
{ "content_hash": "46e7e46b32bc29d3febdd5955ac83d41", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 66, "avg_line_length": 21.285714285714285, "alnum_prop": 0.697986577181208, "repo_name": "baverman/skameyka", "id": "063e358e784f1830e802c72c9208e82e93e7f679", "size": "172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "run.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "4845" } ] }
package beans; import java.io.Serializable; @SuppressWarnings("serial") public class CharacteristicBean implements Serializable{ public static final int DEPRECATED_COLOUR[] = {200, 200, 200}; public static final int EXPERIMENTAL_COLOUR[] = {238, 130, 238}; private String name; private String nameHoverText; private int numOccurrences; private double bits; private double inX; private String value; private int colour[]; public CharacteristicBean(){ name = ""; nameHoverText = ""; numOccurrences = 0; bits = 0; inX = 0; value = ""; colour = null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNameHoverText() { return nameHoverText; } public void setNameHoverText(String nameHoverText) { this.nameHoverText = nameHoverText; } public int getNumOccurrences() { return numOccurrences; } public void setNumOccurrences(int numOccurrences) { this.numOccurrences = numOccurrences; } public double getBits() { return bits; } public void setBits(double bits) { this.bits = bits; } public double getInX() { return inX; } public void setInX(double inX) { this.inX = inX; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int[] getColour() { return colour; } public void setColour(int[] colour) { this.colour = colour; } }
{ "content_hash": "8516c68aa53e59b7ffa880b709ec7293", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 65, "avg_line_length": 17.3855421686747, "alnum_prop": 0.6964656964656964, "repo_name": "qqTYXn7/browserprint", "id": "5686b6abee5a9fa5516845a87dd31a55963a32af", "size": "1443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/beans/CharacteristicBean.java", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "2748" }, { "name": "CSS", "bytes": "2021" }, { "name": "HTML", "bytes": "153" }, { "name": "Java", "bytes": "531770" }, { "name": "JavaScript", "bytes": "47809" } ] }
import java.util.HashMap; public class Alexandra { public String gameID; public Pubsub pubsub; public HashMap config; public Alexandra(String gameID) { this.gameID = gameID; String pubsubURL = System.getenv("ALEXANDRA_PUBSUB"); pubsub = new Pubsub(pubsubURL, "games-" + gameID); config = null; while (config == null) { config = pubsub.getCurrentMessage("game.json"); } } }
{ "content_hash": "37b78248190f8f0e743c8e163d1d75c6", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 54, "avg_line_length": 23.823529411764707, "alnum_prop": 0.6864197530864198, "repo_name": "douglassquirrel/alexandra", "id": "a3e05824c6f982e57a212374abd2ea0f73aab804", "size": "405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libraries/Alexandra.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "6828" }, { "name": "Python", "bytes": "67866" }, { "name": "Ruby", "bytes": "10592" } ] }
#!/usr/bin/env node /*eslint-env node */ /*eslint no-process-exit: 0 */ 'use strict'; var chalk = require('chalk'); var program = require('commander'); var fs = require('fs'); var glob = require('glob'); var bootlint = require('./bootlint.js'); var packageJson = require('./../package.json'); program .version(packageJson.version) .usage('[options] [files...]') .option('-d, --disable <IDs>', 'Comma-separated list of disabled lint problem IDs', function (val) { return val.split(','); }) .parse(process.argv); var disabledIds = program.disable === undefined ? [] : program.disable; var totalErrCount = 0; var totalFileCount = 0; program.args.forEach(function (pattern) { var filenames = glob.sync(pattern); filenames.forEach(function (filename) { var reporter = function (lint) { var lintId = (lint.id[0] === 'E') ? chalk.bgGreen.white(lint.id) : chalk.bgRed.white(lint.id); console.log(filename + ":", lintId, lint.message); totalErrCount++; }; var html = null; try { html = fs.readFileSync(filename, {encoding: 'utf8'}); } catch (err) { console.log(filename + ":", err); return; } bootlint.lintHtml(html, reporter, disabledIds); totalFileCount++; }); }); console.log(""); if (totalErrCount > 0) { console.log("For details, look up the lint problem IDs in the Bootlint wiki: https://github.com/twbs/bootlint/wiki"); } console.log("" + totalErrCount + " lint error(s) found across " + totalFileCount + " file(s)."); if (totalErrCount) { process.exit(1); }
{ "content_hash": "1cc436c9a398eff9157e386c78c2a690", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 121, "avg_line_length": 29.589285714285715, "alnum_prop": 0.6022933011466506, "repo_name": "mubassirhayat/bootlint", "id": "9eac89133e09bda69ea11608025811abe8012c3d", "size": "1657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cli.js", "mode": "33261", "license": "mit", "language": [] }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "0ad259eb7798be0cfac85244d170d7e2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "a12eefd49ba9f48729899594ec4ce4985692a387", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Potentilla/Potentilla hoelzli/README.md", "mode": "33188", "license": "apache-2.0", "language": [] }
package servicenowPrep; public class _031DeleteLL { static class ListNode{ int value; public ListNode(int value) { this.value=value; } ListNode next; } public static void main(String[] args) { ListNode ln = new ListNode(0); ln.next = new ListNode(1); ln.next.next = new ListNode(2); ln.next.next.next = new ListNode(3); ln.next.next.next.next = new ListNode(4); ln.next.next.next.next.next = new ListNode(5); ln.next.next.next.next.next.next = new ListNode(6); ln.next.next.next.next.next.next.next = new ListNode(7); ln.next.next.next.next.next.next.next.next = new ListNode(8); ln=deleteLL(ln); while(ln!=null) { System.out.println(ln.value);ln=ln.next; } } private static ListNode deleteLL(ListNode ln) { while(ln!=null) { ListNode temp=ln.next; ln=null; ln=temp; } return ln; } }
{ "content_hash": "2e7b5091b4994c7c3465bc4356fb6a27", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 69, "avg_line_length": 23.475, "alnum_prop": 0.6048988285410011, "repo_name": "darshanhs90/Java-Coding", "id": "1c99999f11b82cec02a5390eaab4c3684a73afc3", "size": "939", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/servicenowPrep/_031DeleteLL.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1895320" } ] }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "f63b8253d6b9557cc5eaa8a19731c0b3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "a5709c5f5b8cf2089167e7890182cf7f124e9751", "size": "190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Argocoffea/Argocoffea lemblini/README.md", "mode": "33188", "license": "apache-2.0", "language": [] }
using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using AvansApp.ViewModels; namespace AvansApp.Views { public sealed partial class ResultsPageDetailControl : UserControl { public ResultVM MasterMenuItem { get { return GetValue(MasterMenuItemProperty) as ResultVM; } set { SetValue(MasterMenuItemProperty, value); } } public static DependencyProperty MasterMenuItemProperty = DependencyProperty.Register("MasterMenuItem", typeof(ResultVM), typeof(ResultsPageDetailControl), new PropertyMetadata(null)); public ResultsPageDetailControl() { InitializeComponent(); } } }
{ "content_hash": "c2aca4787940d7c3cbbbcb595b5a0eed", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 192, "avg_line_length": 29.652173913043477, "alnum_prop": 0.6906158357771262, "repo_name": "Tostifrosti/AvansApp", "id": "6c9cd13e3724a4a07f4835aae0fd58b0747df745", "size": "684", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Views/ResultsPageDetailControl.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "312804" } ] }
using namespace std; namespace scivey { namespace goosepp { using namespace scivey::goosepp::contentExtraction; string extractBody(const string &htmlText) { auto url = "http://www.nonsense.com"; GooseExtractor extractor(url, htmlText); return extractor.getBody(); } } // goosepp } // scivey
{ "content_hash": "2d030c2bce6f79a3b869a21dbd8da9c7", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 51, "avg_line_length": 18.176470588235293, "alnum_prop": 0.7184466019417476, "repo_name": "scivey/goosepp", "id": "053b2f388a5c5284ec9d5796fb845974849b5220", "size": "711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/goosepp.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "69770" }, { "name": "CMake", "bytes": "7765" }, { "name": "Makefile", "bytes": "816" }, { "name": "Python", "bytes": "648" } ] }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <feed><tipo>Rua</tipo><logradouro>E</logradouro><bairro>Dezoito do Forte</bairro><cidade>Aracaju</cidade><uf>SE</uf><cep>49072029</cep></feed>
{ "content_hash": "f06e7e81949fb21659fc8495cf61074c", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 142, "avg_line_length": 99.5, "alnum_prop": 0.7135678391959799, "repo_name": "chesarex/webservice-cep", "id": "0dcf5069ffa3d0da41898d852a9b882f041cd1ae", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/ceps/49/072/029/cep.xml", "mode": "33188", "license": "apache-2.0", "language": [] }
var dbModules = require('./db'); exports.getList = function(res) { query = dbModules.queryDatabase("SELECT first_name, last_name, reserve_list FROM participants WHERE cancelled='false' AND timestamp>'2019-02-01 12:00:00' ORDER BY id;") .then(function (data) { res.render('list', { title: 'Deltagare', data: data }); }) .catch(function (error) { console.log("Database error: " + error); var err = new Error(error); res.status(500); res.render('error', { error: err }); }); };
{ "content_hash": "30644b272e97a4cfb914eefec00e5ad8", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 170, "avg_line_length": 37.42857142857143, "alnum_prop": 0.6240458015267175, "repo_name": "noletreni/nodefest", "id": "597624fbf2534cf8a080f77b8b659fda69147e97", "size": "525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/list.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2167" }, { "name": "HTML", "bytes": "5553" }, { "name": "JavaScript", "bytes": "9803" } ] }
<?php namespace FormHandler\Field; use FormHandler\Form; abstract class AbstractFormButton extends Element { /** * The form object where this image button is located in. * * @var Form */ protected Form $form; /** * Is this button disabled? * * @var bool */ protected bool $disabled = false; /** * The name of the button * * @var string */ protected string $name = ''; /** * The size of the button * * @var int|null */ protected ?int $size = null; /** * Return if this field is disabled * * @return bool */ public function isDisabled(): bool { return $this->disabled; } /** * Set if this field is disabled and return the ImageButton reference * * @param bool $disabled * * @return $this */ public function setDisabled(bool $disabled): self { $this->disabled = $disabled; return $this; } /** * Return the name of the ImageButton * * @return string */ public function getName(): string { return $this->name; } /** * Set the name of the field and return the ImageButton reference * * @param string $name * * @return $this */ public function setName(string $name): self { $this->name = $name; return $this; } /** * Return the size of the field * * @return int|null */ public function getSize(): ?int { return $this->size; } /** * Set the size of the field and return the ImageButton reference * * @param int $size * * @return $this */ public function setSize(int $size): self { $this->size = $size; return $this; } /** * Return string representation of this button * * @return string */ public function render(): string { return $this->getForm()->getRenderer()->render($this); } /** * Return the form instance of this field * * @return Form */ public function getForm(): Form { return $this->form; } }
{ "content_hash": "b2f3885d310ee449ccae5bf74c43745b", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 73, "avg_line_length": 17.4375, "alnum_prop": 0.517921146953405, "repo_name": "FormHandler/FormHandler", "id": "45343c532b825abe21f9f261a0043ea2818dec5e", "size": "2232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Field/AbstractFormButton.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "369912" } ] }
<?php /* TwigBundle:Exception:logs.html.twig */ class __TwigTemplate_94e492f92ba3ec55e1d4fb998d576f06a5a2e114d697c90222bddcbde287f4bd extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<ol class=\"traces logs\"> "; // line 2 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable((isset($context["logs"]) ? $context["logs"] : null)); foreach ($context['_seq'] as $context["_key"] => $context["log"]) { // line 3 echo " <li"; if (($this->getAttribute($context["log"], "priority", array()) >= 400)) { echo " class=\"error\""; } elseif (($this->getAttribute($context["log"], "priority", array()) >= 300)) { echo " class=\"warning\""; } echo "> "; // line 4 echo twig_escape_filter($this->env, $this->getAttribute($context["log"], "priorityName", array()), "html", null, true); echo " - "; echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->formatLogMessage($this->getAttribute($context["log"], "message", array()), $this->getAttribute($context["log"], "context", array())); echo " </li> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['log'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 7 echo "</ol> "; } public function getTemplateName() { return "TwigBundle:Exception:logs.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 46 => 7, 35 => 4, 26 => 3, 22 => 2, 19 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("", "TwigBundle:Exception:logs.html.twig", "/home/pi/www/vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/Resources/views/Exception/logs.html.twig"); } }
{ "content_hash": "d9c2d04e0d340819e1a9e1e6a24e1da9", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 223, "avg_line_length": 35.27272727272727, "alnum_prop": 0.5589101620029455, "repo_name": "themayna/crawler", "id": "58650f3c79eb7a68dbe0b4e150db360023c69168", "size": "2716", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "var/cache/prod/twig/16/161576f8e375354c9afa45d6add2ab4c06fcf1188a72e541ac4ed52c678025e7.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "286" }, { "name": "HTML", "bytes": "10841" }, { "name": "JavaScript", "bytes": "1107" }, { "name": "PHP", "bytes": "62896" } ] }
/* * ESTGF - Escola Superior de Tecnologia e Gestão de Felgueiras */ /* IPP - Instituto Politécnico do Porto */ /* LEI - Licenciatura em Engenharia Informática*/ /* Projeto Final 2013/2014 /* */ package model; import java.util.ArrayList; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import validation.Validator; /** * Esta classe tem como objectivo criar um sub Orçamento * * @author Luís Sousa - 8090228 */ public class SubOrcamento { private SimpleIntegerProperty id = new SimpleIntegerProperty(); private SimpleStringProperty nome = new SimpleStringProperty(); private SimpleIntegerProperty idOrcamento = new SimpleIntegerProperty(); private SimpleStringProperty data = new SimpleStringProperty(); public Integer getId() { return id.get(); } public String getNome() { return nome.get(); } public int getIdOrcamento() { return idOrcamento.get(); } public String getData() { return data.get(); } public void setId(int id) { this.id.set(id); } public void setNome(String nome) { this.nome.set(nome); } public void setIdOrcamento(int id) { this.idOrcamento.set(id); } public void setData(String data) { this.data.set(data); } /** * Método que devolve uma lista com os errors que provêm de campos que foram * mal introduzidos * * @return array com erros */ public ArrayList<String> validate() { ArrayList<String> errors = new ArrayList<>(); Validator validator = new Validator(); errors.clear(); if (!validator.nomeSubOrcamento(this.getNome())) { errors.add("nome"); } if (!validator.data(this.getData())) { errors.add("data"); } return errors; } /** * Método que devolve uma string com a informação de um Sub Orçamento * * @return informação de um Orçamento */ @Override public String toString() { return "" + nome.get(); } }
{ "content_hash": "d9f6ac732d859dc1621359452c616f6b", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 80, "avg_line_length": 24.113636363636363, "alnum_prop": 0.6258246936852027, "repo_name": "luis-sousa/GC-v1.1b", "id": "ad2d120cf6e6a3ed31ddf88fd4e709ef2e4c1fa7", "size": "2136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/model/SubOrcamento.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1780" }, { "name": "HTML", "bytes": "31770" }, { "name": "Java", "bytes": "694177" } ] }
An old portfolio built with Express, jQuery, handlebars, and page
{ "content_hash": "2cbcff9cc5741929bc5f9d43278fc1ae", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 65, "avg_line_length": 66, "alnum_prop": 0.803030303030303, "repo_name": "themarquisdesheric/portfolio-project", "id": "cd5bd103999f4e17cc30c45329fff989aa0b7bbe", "size": "87", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3242" }, { "name": "HTML", "bytes": "2822" }, { "name": "JavaScript", "bytes": "2739" } ] }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- Copyright 2014 Microsoft Open Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --><preferencesets version="2.5.0" default="windowsazure.com"> <preferenceset name="windowsazure.com" blob="http://${storage-service-name}.blob.core.windows.net" management="https://management.core.windows.net/${subscription-id}" portalURL="https://manage.windowsazure.com" publishsettings="http://go.microsoft.com/fwlink/?LinkId=296861"/> <preferenceset name="windowsazure.cn (China)" blob="http://${storage-service-name}.blob.core.chinacloudapi.cn" management="https://management.core.chinacloudapi.cn/${subscription-id}" portalURL="http://windowsazure.cn" publishsettings="https://manage.windowsazure.cn/publishsettings/index?schemaversion=1.0"/> </preferencesets>
{ "content_hash": "b0145d93d3ab1fd8e7aba574962a8b56", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 92, "avg_line_length": 44.46666666666667, "alnum_prop": 0.7593703148425787, "repo_name": "nandhanurrevanth/msopentech-tools-for-intellij", "id": "3ee5449616a45db3af52d5d748fe40e54f892574", "size": "1334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/preferencesets.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "5380" }, { "name": "HTML", "bytes": "83848" }, { "name": "Java", "bytes": "1317633" }, { "name": "JavaScript", "bytes": "254" } ] }
import tigre import numpy as np from tigre.utilities import sample_loader import tigre.algorithms as algs #%% Geometry geo = tigre.geometry_default(high_resolution=False) # Offsets ## #################################################################################### # Lets try simnple offset: The detector gets completelly displaced geo.offOrigin = np.array([0, 0, 0]) # Offset of image from origin (mm) geo.offDetector = np.array([200, 200]) # Offset of Detector (mm) ## #################################################################################### # Auxiliary geo.accuracy = 0.5 # Accuracy of FWD proj (vx/sample) ## Load data and generate projections # see previous demo for explanation angles = np.linspace(0, 2 * np.pi, 100) # Load thorax phatom data head = sample_loader.load_head_phantom(geo.nVoxel) projections = tigre.Ax(head, geo, angles) #%% lets see it tigre.plotproj(projections, angles) ## we will skip reconstruction of this tests because the image is outside the detector ## ##################################################################### #%% Second test: lets test variying offsets: geo.offDetector = np.vstack( [10 * np.sin(angles), 20 * np.cos(angles)] ).T # Offset of Detector (mm) projections2 = tigre.Ax(head, geo, angles) ## lets see it tigre.plotproj(projections2, angles) ## reconstruction res = algs.sart(projections2, geo, angles, 10) tigre.plotimg(res, dim="z") #%% Third test: lets vary everything # Lets make the image smaller geo.nVoxel = np.array([128, 128, 128]) # number of voxels (vx) geo.sVoxel = np.array([256, 256, 256]) / 2 # total size of the image (mm) geo.dVoxel = geo.sVoxel / geo.nVoxel # size of each voxel (mm) head = sample_loader.load_head_phantom(geo.nVoxel) geo.offDetector = np.vstack( [10 * np.sin(angles), 10 * np.cos(angles)] ).T # Offset of Detector (mm) geo.offOrigin = np.vstack( [40 * np.sin(angles), np.linspace(-30, 30, 100), 40 * np.cos(angles)] ).T # Offset of image from origin (mm) projections3 = tigre.Ax(head, geo, angles) ## lets see it tigre.plotproj(projections3, angles) ## reconstruction res = algs.sart(projections3, geo, angles, 10) tigre.plotimg(res, dim="z")
{ "content_hash": "fe2ae2f5642346af4245e7cb1ce54657", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 87, "avg_line_length": 32.78260869565217, "alnum_prop": 0.610079575596817, "repo_name": "CERN/TIGRE", "id": "f61ba7bcef144cb08d79cb8bfc6a99ff3faaadfd", "size": "3177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/demos/d14_Offsets.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "108432" }, { "name": "Cuda", "bytes": "453981" }, { "name": "Cython", "bytes": "28212" }, { "name": "MATLAB", "bytes": "636785" }, { "name": "Python", "bytes": "281064" }, { "name": "Shell", "bytes": "761" }, { "name": "TeX", "bytes": "32165" } ] }
package controller; public class PlayerObs implements ObsEntity { private String msg; @Override public void update(String msg) { this.msg = msg; } @Override public String getState() { String tmp = msg; msg = ""; return tmp; } }
{ "content_hash": "49ab7cb1913e8b146fca341bdfc1e632", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 45, "avg_line_length": 14.157894736842104, "alnum_prop": 0.620817843866171, "repo_name": "MustafaAlsaid2022/1dv607", "id": "2f6f5c33fe92b35594d4499b68682cd1a70f3137", "size": "269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "workshop3/grade2/src/main/java/controller/PlayerObs.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "91427" } ] }
BUILD_REFLECTION(willow::Animation); BUILD_ENUM_REFLECTION(willow::Animation::ClipMode) .Value("Stop", willow::Animation::ClipMode::Stop) .Value("Loop", willow::Animation::ClipMode::Loop) .Value("Ping_Pong", willow::Animation::ClipMode::Ping_Pong); namespace willow { //////////////////////// /// Constructors /// Animation::Animation(const Path& path) { BinaryData data{ path }; auto* cursor = data.get_data(); // Get the number of frames in this animation this->num_frames = *reinterpret_cast<uint32*>(cursor); cursor += sizeof(uint32); // Load x position frames bool hasXFrames = static_cast<bool>(*cursor); cursor += 1; if (hasXFrames) { this->pos_x_frames = Array<float>(reinterpret_cast<float*>(cursor), num_frames); cursor += sizeof(float) * num_frames; } // Load y position frames bool hasYFrames = static_cast<bool>(*cursor); cursor += 1; if (hasYFrames) { this->pos_y_frames = Array<float>(reinterpret_cast<float*>(cursor), num_frames); cursor += sizeof(float) * num_frames; } // Load z position frames bool hasZFrames = static_cast<bool>(*cursor); cursor += 1; if (hasZFrames) { this->pos_z_frames = Array<float>(reinterpret_cast<float*>(cursor), num_frames); cursor += sizeof(float) * num_frames; } } /////////////////// /// Methods /// uint32 Animation::clip_frame(int32 frame, ClipMode mode) const { switch (mode) { case ClipMode::Stop: return std::max<uint32>(0, std::min<uint32>(frame, num_frames)); case ClipMode::Loop: return frame % num_frames; case ClipMode::Ping_Pong: auto div = std::div(frame, num_frames); // Gives quotient and remainder int32 mult = (int32)std::pow(-1, div.quot); // Alternates between '1' and '-1' if (mult == -1) { return num_frames - div.rem - 1; } else { return div.rem; } } // Not sure how else to handle case where 'mode' isn't valid return 0; } Vec3 Animation::sample_pos(int32 frame, ClipMode clip) const { Vec3 result; auto clippedFrame = this->clip_frame(frame, clip); if (!this->pos_x_frames.IsEmpty()) { result.X = this->pos_x_frames[clippedFrame]; } if (!this->pos_y_frames.IsEmpty()) { result.Y = this->pos_y_frames[clippedFrame]; } if (!this->pos_z_frames.IsEmpty()) { result.Z = this->pos_z_frames[clippedFrame]; } return result; } Vec3 Animation::add_pos(int32 frame, ClipMode clip, const Vec3& pos) const { auto anim = this->sample_pos(frame, clip); return pos + anim; } Vec3 Animation::blend_pos(int32 frame, ClipMode clip, Vec3 pos, float influence) const { auto anim = this->sample_pos(frame, clip); influence = std::min(0.f, std::max(influence, 1.f)); // Calculate influence anim *= influence; pos *= 1.f - influence; return pos + anim; } Quat Animation::sample_rot(int32 frame, ClipMode clip) const { auto clippedFrame = this->clip_frame(frame, clip); if (!this->rot_frames.IsEmpty()) { return rot_frames[clippedFrame]; } else { return Quat(); } } Vec3 Animation::sample_scale(int32 frame, ClipMode clip) const { auto clippedFrame = this->clip_frame(frame, clip); Vec3 result; if (!this->scale_x_frames.IsEmpty()) { result.X = scale_x_frames[clippedFrame]; } if (!this->scale_y_frames.IsEmpty()) { result.Y = scale_y_frames[clippedFrame]; } if (!this->scale_z_frames.IsEmpty()) { result.Z = scale_z_frames[clippedFrame]; } return result; } }
{ "content_hash": "d1e758970ed16dc068397aff56323a53", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 87, "avg_line_length": 22.126582278481013, "alnum_prop": 0.6378718535469108, "repo_name": "willcassella/WillowEngine", "id": "711c1e851648538cf63ba9744033cc5b1339516e", "size": "3754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Modules/Engine/source/Resources/Animation.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2007" }, { "name": "C++", "bytes": "630071" }, { "name": "CMake", "bytes": "4806" }, { "name": "GLSL", "bytes": "1810" }, { "name": "Python", "bytes": "10567" }, { "name": "Shell", "bytes": "1464" } ] }
{-# LANGUAGE GADTs #-} -- | Bidirectional typechecking for higher-rank polymorphism -- Implementation of http://www.mpi-sws.org/~neelk/bidir.pdf module Type where import Control.Applicative import Control.Monad import Data.Maybe import Data.Monoid import qualified Data.Set as S import AST import Context import NameGen import Pretty -- | Algorithmic subtyping: -- subtype Γ A B = Δ <=> Γ |- A <: B -| Δ subtype :: Context -> Polytype -> Polytype -> NameGen Context subtype gamma typ1 typ2 = traceNS "subtype" (gamma, typ1, typ2) $ checkwftype gamma typ1 $ checkwftype gamma typ2 $ case (typ1, typ2) of -- <:Var (TVar alpha, TVar alpha') | alpha == alpha' -> return gamma -- <:Unit (TUnit, TUnit) -> return gamma -- <:Exvar (TExists alpha, TExists alpha') | alpha == alpha' && alpha `elem` existentials gamma -> return gamma -- <:-> (TFun a1 a2, TFun b1 b2) -> do theta <- subtype gamma b1 a1 subtype theta (apply theta a2) (apply theta b2) -- <:forallR (a, TForall alpha b) -> do -- Do alpha conversion to avoid clashes alpha' <- freshTVar dropMarker (CForall alpha') <$> subtype (gamma >: CForall alpha') a (typeSubst (TVar alpha') alpha b) -- <:forallL (TForall alpha a, b) -> do -- Do alpha conversion to avoid clashes alpha' <- freshTVar dropMarker (CMarker alpha') <$> subtype (gamma >++ [CMarker alpha', CExists alpha']) (typeSubst (TExists alpha') alpha a) b -- <:InstantiateL (TExists alpha, a) | alpha `elem` existentials gamma && alpha `S.notMember` freeTVars a -> instantiateL gamma alpha a -- <:InstantiateR (a, TExists alpha) | alpha `elem` existentials gamma && alpha `S.notMember` freeTVars a -> instantiateR gamma a alpha _ -> error $ "subtype, don't know what to do with: " ++ pretty (gamma, typ1, typ2) -- | Algorithmic instantiation (left): -- instantiateL Γ α A = Δ <=> Γ |- α^ :=< A -| Δ instantiateL :: Context -> TVar -> Polytype -> NameGen Context instantiateL gamma alpha a = traceNS "instantiateL" (gamma, alpha, a) $ checkwftype gamma a $ checkwftype gamma (TExists alpha) $ case solve gamma alpha =<< monotype a of -- InstLSolve Just gamma' -> return gamma' Nothing -> case a of -- InstLReach TExists beta | ordered gamma alpha beta -> return $ fromJust $ solve gamma beta (TExists alpha) | otherwise -> return $ fromJust $ solve gamma alpha (TExists beta) -- InstLArr TFun a1 a2 -> do alpha1 <- freshTVar alpha2 <- freshTVar theta <- instantiateR (insertAt gamma (CExists alpha) $ context [ CExists alpha2 , CExists alpha1 , CExistsSolved alpha $ TFun (TExists alpha1) (TExists alpha2) ]) a1 alpha1 instantiateL theta alpha2 (apply theta a2) -- InstLAIIR TForall beta b -> do -- Do alpha conversion to avoid clashes beta' <- freshTVar dropMarker (CForall beta') <$> instantiateL (gamma >++ [CForall beta']) alpha (typeSubst (TVar beta') beta b) _ -> error $ "The impossible happened! instantiateL: " ++ pretty (gamma, alpha, a) -- | Algorithmic instantiation (right): -- instantiateR Γ A α = Δ <=> Γ |- A =:< α -| Δ instantiateR :: Context -> Polytype -> TVar -> NameGen Context instantiateR gamma a alpha = traceNS "instantiateR" (gamma, a, alpha) $ checkwftype gamma a $ checkwftype gamma (TExists alpha) $ case solve gamma alpha =<< monotype a of Just gamma' -> return gamma' Nothing -> case a of -- InstRReach TExists beta | ordered gamma alpha beta -> return $ fromJust $ solve gamma beta (TExists alpha) | otherwise -> return $ fromJust $ solve gamma alpha (TExists beta) -- InstRArr TFun a1 a2 -> do alpha1 <- freshTVar alpha2 <- freshTVar theta <- instantiateL (insertAt gamma (CExists alpha) $ context [ CExists alpha2 , CExists alpha1 , CExistsSolved alpha $ TFun (TExists alpha1) (TExists alpha2) ]) alpha1 a1 instantiateR theta (apply theta a2) alpha2 -- InstRAIIL TForall beta b -> do -- Do alpha conversion to avoid clashes beta' <- freshTVar dropMarker (CMarker beta') <$> instantiateR (gamma >++ [CMarker beta', CExists beta']) (typeSubst (TExists beta') beta b) alpha _ -> error $ "The impossible happened! instantiateR: " ++ pretty (gamma, a, alpha) -- | Type checking: -- typecheck Γ e A = Δ <=> Γ |- e <= A -| Δ typecheck :: Context -> Expr -> Polytype -> NameGen Context typecheck gamma expr typ = traceNS "typecheck" (gamma, expr, typ) $ checkwftype gamma typ $ case (expr, typ) of -- 1I (EUnit, TUnit) -> return gamma -- ForallI (e, TForall alpha a) -> do -- Do alpha conversion to avoid clashes alpha' <- freshTVar dropMarker (CForall alpha') <$> typecheck (gamma >: CForall alpha') e (typeSubst (TVar alpha') alpha a) -- ->I (EAbs x e, TFun a b) -> do x' <- freshVar dropMarker (CVar x' a) <$> typecheck (gamma >: CVar x' a) (subst (EVar x') x e) b -- Sub (e, b) -> do (a, theta) <- typesynth gamma e subtype theta (apply theta a) (apply theta b) -- | Type synthesising: -- typesynth Γ e = (A, Δ) <=> Γ |- e => A -| Δ typesynth :: Context -> Expr -> NameGen (Polytype, Context) typesynth gamma expr = traceNS "typesynth" (gamma, expr) $ checkwf gamma $ case expr of -- Var EVar x -> return ( fromMaybe (error $ "typesynth: not in scope " ++ pretty (expr, gamma)) (findVarType gamma x) , gamma ) -- Anno EAnno e a -> do delta <- typecheck gamma e a return (a, delta) -- 1I=> EUnit -> return (TUnit, gamma) {- -- ->I=> Original rule EAbs x e -> do x' <- freshVar alpha <- freshTVar beta <- freshTVar delta <- dropMarker (CVar x' (TExists alpha)) <$> typecheck (gamma >++ [ CExists alpha , CExists beta , CVar x' (TExists alpha) ]) (subst (EVar x') x e) (TExists beta) return (TFun (TExists alpha) (TExists beta), delta) -- -} -- {- -- ->I=> Full Damas-Milner type inference EAbs x e -> do x' <- freshVar alpha <- freshTVar beta <- freshTVar (delta, delta') <- breakMarker (CMarker alpha) <$> typecheck (gamma >++ [ CMarker alpha , CExists alpha , CExists beta , CVar x' (TExists alpha) ]) (subst (EVar x') x e) (TExists beta) let tau = apply delta' (TFun (TExists alpha) (TExists beta)) let evars = unsolved delta' uvars <- replicateM (length evars) freshTVar return ( tforalls uvars $ typeSubsts (zip (map TVar uvars) evars) tau , delta) -- -} -- ->E EApp e1 e2 -> do (a, theta) <- typesynth gamma e1 typeapplysynth theta (apply theta a) e2 -- | Type application synthesising -- typeapplysynth Γ A e = (C, Δ) <=> Γ |- A . e =>> C -| Δ typeapplysynth :: Context -> Polytype -> Expr -> NameGen (Polytype, Context) typeapplysynth gamma typ e = traceNS "typeapplysynth" (gamma, typ, e) $ checkwftype gamma typ $ case typ of -- ForallApp TForall alpha a -> do -- Do alpha conversion to avoid clashes alpha' <- freshTVar typeapplysynth (gamma >: CExists alpha') (typeSubst (TExists alpha') alpha a) e -- alpha^App TExists alpha -> do alpha1 <- freshTVar alpha2 <- freshTVar delta <- typecheck (insertAt gamma (CExists alpha) $ context [ CExists alpha2 , CExists alpha1 , CExistsSolved alpha $ TFun (TExists alpha1) (TExists alpha2) ]) e (TExists alpha1) return (TExists alpha2, delta) -- ->App TFun a c -> do delta <- typecheck gamma e a return (c, delta) _ -> error $ "typeapplysynth: don't know what to do with: " ++ pretty (gamma, typ, e) typesynthClosed :: Expr -> (Polytype, Context) typesynthClosed e = let (a, gamma) = evalNameGen $ typesynth mempty e in (apply gamma a, gamma) -- Examples eid :: Expr -- (λx. x) : ∀ t. t → t eid = eabs "x" (var "x") -: tforall "t" (tvar "t" --> tvar "t") -- Impredicative, so doesn't typecheck ididunit :: Expr -- (λid. id id ()) ((λx. x) : ∀ t. t → t) ididunit = eabs "id" (((var "id" -: tforall "t" (tvar "t" --> tvar "t")) $$ var "id") $$ eunit) $$ eid idunit :: Expr -- (λid. id ()) ((λx. x) : ∀ t. t → t) idunit = eabs "id" (var "id" $$ eunit) $$ eid idid :: Expr -- id id idid = (eid $$ eid) -: tforall "t" (tvar "t" --> tvar "t")
{ "content_hash": "43f2debd4a7e4abec8e9ac0865b6767b", "timestamp": "", "source": "github", "line_count": 269, "max_line_length": 103, "avg_line_length": 36.605947955390334, "alnum_prop": 0.5242205747943536, "repo_name": "ollef/Bidirectional", "id": "9073e5ffb4ddf2508ebe23021e39e7e47d775280", "size": "9892", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Type.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "22658" } ] }
package org.apache.activemq.transport.udp; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * A default implementation of {@link SimpleBufferPool} which keeps a pool of direct * byte buffers. */ public class DefaultBufferPool extends SimpleBufferPool implements ByteBufferPool { private List<ByteBuffer> buffers = new ArrayList<ByteBuffer>(); private Object lock = new Object(); public DefaultBufferPool() { super(true); } public DefaultBufferPool(boolean useDirect) { super(useDirect); } @Override public synchronized ByteBuffer borrowBuffer() { synchronized (lock) { int size = buffers.size(); if (size > 0) { return buffers.remove(size - 1); } } return createBuffer(); } @Override public void returnBuffer(ByteBuffer buffer) { synchronized (lock) { buffers.add(buffer); } } @Override public void start() throws Exception { } @Override public void stop() throws Exception { synchronized (lock) { /* * for (Iterator iter = buffers.iterator(); iter.hasNext();) { * ByteBuffer buffer = (ByteBuffer) iter.next(); } */ buffers.clear(); } } }
{ "content_hash": "fc71225cc0726869de663cebb6c7b626", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 84, "avg_line_length": 23.80701754385965, "alnum_prop": 0.5902726602800294, "repo_name": "chirino/activemq", "id": "f4f6864bf0d331a574a5de2b024e8de70a8f5d30", "size": "2160", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "activemq-client/src/main/java/org/apache/activemq/transport/udp/DefaultBufferPool.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "17712" }, { "name": "C#", "bytes": "27536" }, { "name": "C++", "bytes": "17404" }, { "name": "CSS", "bytes": "34997" }, { "name": "HTML", "bytes": "158883" }, { "name": "Java", "bytes": "25304453" }, { "name": "JavaScript", "bytes": "438641" }, { "name": "PHP", "bytes": "3665" }, { "name": "Perl", "bytes": "4128" }, { "name": "Protocol Buffer", "bytes": "13867" }, { "name": "Python", "bytes": "14547" }, { "name": "Ruby", "bytes": "6594" }, { "name": "Scala", "bytes": "302023" }, { "name": "Shell", "bytes": "87001" } ] }
`pypostalcode` is a fork of Nathan Van Gheem's excellent `pyzipcode` package. The zipcode database has been replaced with Canadian cities and their postal codes. The general usage is the same. Canadian postal codes are six characters with this format: `A1A 1A1`, where `A` is a letter and `1` is a digit, with a space separating the third and fourth characters. The first three digits are the Forward Sortation Area (FSA), and the last three are the Local Delivery Unit (LDU). The FSA information is available from the report "Forward Sortation Area Boundary File, 2011 Census. Statistics Canada Catalogue no. 92-179-X" retrieved from http://www12.statcan.gc.ca/census-recensement/2011/geo/bound-limit/bound-limit-2011-eng.cfm This module only uses the FSA designator for location. There are over 800,000 FSA+LDU combinations, but the 1,645 unique FSA values provide coarse resolution for most applications. To install: ``` pip install pypostalcode ``` Basic usage: ```pycon >>> from pypostalcode import PostalCodeDatabase >>> pcdb = PostalCodeDatabase() >>> pc = 'V5K' >>> location = pcdb[pc] >>> location.postalcode 'V5K' >>> location.city 'Vancouver (North Hastings- Sunrise)' >>> location.province 'British Columbia' >>> location.longitude -123.0489 >>> location.latitude 49.293 >>> location.timezone -8.0 >>> location.dst 1 ``` Get a list of postal codes given a radius in kilometers: ```pycon >>> from pypostalcode import PostalCodeDatabase >>> pcdb = PostalCodeDatabase() >>> pc = 'T3Z' >>> radius = 25 >>> results = pcdb.get_postalcodes_around_radius(pc, radius) >>> for r in results: ... print(f'{r.postalcode}: {r.city}, {r.province}') ... T3B: Calgary (Montgomery / Bowness / Silver Springs / Greenwood), Alberta T3G: Calgary (Hawkwood / Arbour Lake / Royal Oak / Rocky Ridge), Alberta T3H: Calgary (Discovery Ridge / Signal Hill / Aspen Woods / Patterson / Cougar Ridge), Alberta T3L: Calgary (Tuscany / Scenic Acres), Alberta T3R: Calgary Northwest, Alberta T3Z: Redwood Meadows, Alberta T4C: Cochrane, Alberta ``` © This data includes information copied with permission from Canada Post Corporation This data includes data from [GeoNames](https://www.geonames.org/), which is distributed under a [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) license
{ "content_hash": "dbdf9289eebeac5efd13a96dfe9b4c66", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 441, "avg_line_length": 38.83050847457627, "alnum_prop": 0.7468354430379747, "repo_name": "inkjet/pypostalcode", "id": "796a0b98070f427de9c1276ff0dc1622c9b0427c", "size": "2310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "5940" } ] }
using System; using MicrosoftResearch.Infer; using MicrosoftResearch.Infer.Distributions; using MicrosoftResearch.Infer.Maths; using MicrosoftResearch.Infer.Models; namespace AVPTM { /// <summary> /// Latent Dirichlet Allocation (LDA) prediction model implemented in Infer.NET. /// Use this class for obtaining predictive distributions over words for /// documents with known topic distributions /// </summary> public class LDAPredictionModel { /// <summary> /// Size of vocabulary /// </summary> public int SizeVocab { get; protected set; } /// <summary> /// Number of Topics /// </summary> public int NumTopics { get; protected set; } /// <summary> /// Sparsity specification for predictive distributions over words /// </summary> public Sparsity PredictionSparsity { get; protected set; } /// <summary> /// Inference engine /// </summary> public InferenceEngine Engine { get; protected set; } /// <summary> /// A predicted word /// </summary> protected Variable<int> Word; /// <summary> /// Per document distribution over topics (to be inferred) /// </summary> protected Variable<Vector> Theta; /// <summary> /// Per topic distribution over words (to be inferred) /// </summary> protected VariableArray<Vector> Phi; /// <summary> /// Prior for <see cref="Theta"/> /// </summary> protected Variable<Dirichlet> ThetaPrior; /// <summary> /// Prior for <see cref="Phi"/> /// </summary> protected VariableArray<Dirichlet> PhiPrior; /// <summary> /// Constructs an LDA model /// </summary> /// <param name="sizeVocab">Size of vocabulary</param> /// <param name="numTopics">Number of topics</param> public LDAPredictionModel(int sizeVocab, int numTopics) { SizeVocab = sizeVocab; NumTopics = numTopics; PredictionSparsity = Sparsity.Sparse; //--------------------------------------------- // The model //--------------------------------------------- var W = new Range(SizeVocab).Named("W"); var T = new Range(NumTopics).Named("T"); ThetaPrior = Variable.New<Dirichlet>().Named("ThetaPrior"); PhiPrior = Variable.Array<Dirichlet>(T).Named("PhiPrior").Attrib(new ValueRange(W)); Theta = Variable.New<Vector>().Named("Theta"); Phi = Variable.Array<Vector>(T).Named("Phi"); Theta = Variable.Random<Vector, Dirichlet>(ThetaPrior); Phi[T] = Variable.Random<Vector, Dirichlet>(PhiPrior[T]); Word = Variable.New<int>().Named("Word"); Word.SetSparsity(PredictionSparsity); var topic = Variable.Discrete(Theta).Attrib(new ValueRange(T)).Named("topic"); using (Variable.Switch(topic)) { Word.SetTo(Variable.Discrete(Phi[topic])); } Engine = new InferenceEngine(new VariationalMessagePassing()); Engine.Compiler.ShowWarnings = false; } /// <summary> /// Gets the predictive distributions for a set of documents /// <para> /// Topic distributions per document (<see cref="Theta"/>) and word distributions /// per topic (<see cref="Phi"/>) are observed, document distributions over words /// are inferred. /// </para> /// </summary> /// <param name="postTheta">The posterior document topic distributions</param> /// <param name="postPhi">The posterior topic word distributions</param> /// <returns>The predictive distribution over words for each document</returns> public virtual Discrete[] Predict(Dirichlet[] postTheta, Dirichlet[] postPhi) { int numDocs = postTheta.Length; var result = new Discrete[numDocs]; bool showProgress = Engine.ShowProgress; Engine.ShowProgress = false; try { for (int i = 0; i < numDocs; i++) { ThetaPrior.ObservedValue = postTheta[i]; PhiPrior.ObservedValue = postPhi; result[i] = Engine.Infer<Discrete>(Word); if (showProgress) { if (i % 80 == 0) Console.WriteLine(""); Console.Write("."); } } } finally { Engine.ShowProgress = showProgress; } if (showProgress) { Console.WriteLine(); } return result; } } }
{ "content_hash": "0029552c614a72deaaf1271f96330270", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 96, "avg_line_length": 36.75373134328358, "alnum_prop": 0.5342131979695431, "repo_name": "IntelligentSystemsLaboratory/JGI-PURE-Challenge", "id": "749d17e5d47ffeaaf3963cce83f5ecda0b4445bb", "size": "4927", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AVPTM/LDAPredictionModel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "46056" }, { "name": "CSS", "bytes": "2347" }, { "name": "HTML", "bytes": "38674" }, { "name": "JavaScript", "bytes": "66601" }, { "name": "Jupyter Notebook", "bytes": "103549" }, { "name": "Python", "bytes": "1811" }, { "name": "Ruby", "bytes": "13" } ] }
@implementation JSZVCRResourceManager #pragma mark - Class File Path Helper Methods + (NSString *)pathForFile:(NSString *)fileName inBundleForClass:(Class)classInBundle { NSBundle *bundle = [NSBundle bundleForClass:classInBundle]; return [self pathForFile:fileName inBundle:bundle]; } + (NSString *)pathForFile:(NSString *)fileName inBundle:(NSBundle *)bundle { return [bundle pathForResource:fileName.stringByDeletingPathExtension ofType:fileName.pathExtension]; } + (NSString *)pathForFileMatchingTest:(XCTestCase *)testCase inBundle:(NSBundle *)bundle { NSString *currentTestCaseMethod = NSStringFromSelector(testCase.invocation.selector); NSString *filePath = [NSString stringWithFormat:@"%@.plist", currentTestCaseMethod]; return [self pathForFile:filePath inBundle:bundle]; } + (NSBundle *)bundleWithName:(NSString *)bundleName containingClass:(Class)classInBundle { NSBundle *classBundle = [NSBundle bundleForClass:classInBundle]; return [NSBundle bundleWithPath:[classBundle pathForResource:bundleName ofType:@"bundle"]]; } + (NSString *)pathForFileMatchingTest:(XCTestCase *)testCase { return [self pathForFileMatchingTest:testCase inBundle:[self bundleWithName:[self nameFromClass:testCase.class] containingClass:testCase.class]]; } + (NSArray *)networkResponsesForFilePath:(NSString *)filePath { NSParameterAssert(filePath); return [[NSArray alloc] initWithContentsOfFile:filePath]; } + (NSArray *)networkResponsesForTest:(XCTestCase *)testCase { NSParameterAssert(testCase); return [self networkResponsesForFilePath:[self pathForFileMatchingTest:testCase]]; } + (NSBundle *)bundleForTestInDocumentsDirectory:(XCTestCase *)testCase { NSParameterAssert(testCase); NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory NSString *bundleName = [NSString stringWithFormat:@"%@.bundle", [self nameFromClass:testCase.class]]; NSString *bundlePath = [documentsPath stringByAppendingPathComponent:bundleName]; BOOL isDir; if (![[NSFileManager defaultManager] fileExistsAtPath:bundlePath isDirectory:&isDir]) { NSError *bundleCreationError = nil; [[NSFileManager defaultManager] createDirectoryAtPath:bundlePath withIntermediateDirectories:YES attributes:nil error:&bundleCreationError]; NSLog(@"bundleCreationError: %@", bundleCreationError); } return [NSBundle bundleWithPath:bundlePath]; } // This is intended for differentiating between Swift and Objective-C // runtimes.In Swift, the class name is <Module Name>.<Class Name> whereas // in Objective-C the class name is <Class Name> + (NSString *)nameFromClass:(Class)cls { NSString *className = NSStringFromClass(cls); NSRange dotRange = [className rangeOfString:@"." options:NSBackwardsSearch]; if (dotRange.location == NSNotFound) { return className; } else { return [className substringFromIndex:(dotRange.location + 1)]; } } + (BOOL)saveToDisk:(JSZVCRRecorder *)recorder withFilePath:(NSString *)filePath { // should assert that documents directory isn't automatically appended! NSParameterAssert(filePath); NSAssert([filePath.pathExtension isEqualToString:@"plist"], @"filePath extension must be .plist not %@", filePath.pathExtension); NSLog(@"filePath = %@", filePath); NSArray *dumpArray = recorder.allRecordingsForPlist; return [dumpArray writeToFile:filePath atomically:YES]; } + (BOOL)saveToDisk:(JSZVCRRecorder *)recorder forTest:(XCTestCase *)testCase { NSBundle *documentsBundle = [self bundleForTestInDocumentsDirectory:testCase]; NSString *currentTestCaseMethod = NSStringFromSelector(testCase.invocation.selector); NSString *fileName = [NSString stringWithFormat:@"%@.plist", currentTestCaseMethod]; NSString *filePath = [documentsBundle.bundlePath stringByAppendingPathComponent:fileName]; return [self saveToDisk:recorder withFilePath:filePath]; } @end
{ "content_hash": "e57c777d7f6f790a830469387bc705f6", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 149, "avg_line_length": 48.01176470588236, "alnum_prop": 0.7608429306542515, "repo_name": "minddistrict/JSZVCR", "id": "c62003fec327bf060f552d5e10ba2ab54fc88170", "size": "4288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JSZVCR/Classes/Resources/JSZVCRResourceManager.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "110147" }, { "name": "Ruby", "bytes": "4675" } ] }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {DefaultUpdater, UpdateOptions} from '../default'; import {logger as defaultLogger, Logger} from '../../util/logger'; const INLINE_UPDATE_REGEX = /{x-version-update:([\w\-_]+):(current|released)}/; const BLOCK_START_REGEX = /{x-version-update-start:([\w\-_]+):(current|released)}/; const BLOCK_END_REGEX = /{x-version-update-end}/; const VERSION_REGEX = /\d+\.\d+\.\d+(-\w+(\.\d+)?)?(-SNAPSHOT)?/; interface JavaUpdateOptions extends UpdateOptions { isSnapshot?: boolean; } /** * Updates a file annotated with region markers. These region markers are * either denoted inline with `{x-version-update:<component-name>:current|released}` * or with a `{x-version-update-start:<component-name>}` and `{x-version-update-end}`. */ export class JavaUpdate extends DefaultUpdater { isSnapshot: boolean; constructor(options: JavaUpdateOptions) { super(options); this.isSnapshot = !!options.isSnapshot; } /** * Given initial file contents, return updated contents. * @param {string} content The initial content * @returns {string} The updated content */ updateContent(content: string, logger: Logger = defaultLogger): string { if (!this.versionsMap) { logger.warn('missing versions map'); return content; } const newLines: string[] = []; let blockPackageName: string | null = null; content.split(/\r?\n/).forEach(line => { let match = line.match(INLINE_UPDATE_REGEX); if (match && (!this.isSnapshot || match[2] === 'current')) { const newVersion = this.versionsMap!.get(match[1]); if (newVersion) { newLines.push(line.replace(VERSION_REGEX, newVersion.toString())); } else { newLines.push(line); } } else if (blockPackageName) { const newVersion = this.versionsMap!.get(blockPackageName); if (newVersion) { newLines.push(line.replace(VERSION_REGEX, newVersion.toString())); } else { newLines.push(line); } if (line.match(BLOCK_END_REGEX)) { blockPackageName = null; } } else { match = line.match(BLOCK_START_REGEX); if (match && (!this.isSnapshot || match[2] === 'current')) { blockPackageName = match[1]; } newLines.push(line); } }); return newLines.join('\n'); } }
{ "content_hash": "5b5d6167f07f1a405e4485aaed729ad7", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 86, "avg_line_length": 36.7125, "alnum_prop": 0.6475995914198162, "repo_name": "googleapis/release-please", "id": "b88bdda3d223de4d0438d8b9a3413533d7be3df4", "size": "2937", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/updaters/java/java-update.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Elixir", "bytes": "613" }, { "name": "Go", "bytes": "626" }, { "name": "HCL", "bytes": "856" }, { "name": "Handlebars", "bytes": "562" }, { "name": "Java", "bytes": "3207" }, { "name": "JavaScript", "bytes": "210854" }, { "name": "PHP", "bytes": "1722" }, { "name": "Python", "bytes": "4849" }, { "name": "Ruby", "bytes": "1350" }, { "name": "TypeScript", "bytes": "1192232" } ] }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://www.netbeans.org/ns/project/1"> <type>org.netbeans.modules.java.j2seproject</type> <configuration> <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> <name>AutumnCompiler</name> <source-roots> <root id="src.dir"/> </source-roots> <test-roots> <root id="test.src.dir"/> </test-roots> </data> <references xmlns="http://www.netbeans.org/ns/ant-project-references/1"/> <spellchecker-wordlist xmlns="http://www.netbeans.org/ns/spellchecker-wordlist/1"> <word>ArgumentStack</word> <word>bd</word> <word>bi</word> <word>BigInteger</word> <word>bool</word> <word>ConcreteFunctionalList</word> <word>CtorTester</word> <word>ds</word> <word>eq</word> <word>executionTime</word> <word>expectField</word> <word>expectMethod</word> <word>FallingSky</word> <word>filesOf</word> <word>FloatTypes</word> <word>getAnnotation</word> <word>getClass</word> <word>getCompareTo</word> <word>getDeclaredConstructors</word> <word>getEquals</word> <word>getHashCode</word> <word>getInterfaces</word> <word>getIterator</word> <word>getMethod</word> <word>getName</word> <word>getSimpleName</word> <word>getSuperclass</word> <word>getSuperinterfaces</word> <word>getToString</word> <word>InaccessibleClass</word> <word>incrementAndGet</word> <word>IntegerTypes</word> <word>intValue</word> <word>invoke</word> <word>isAnnotation</word> <word>isAnnotationPresent</word> <word>isAssignableFrom</word> <word>isClass</word> <word>isEnum</word> <word>isInterface</word> <word>isLocalClass</word> <word>listIterator</word> <word>Ljava</word> <word>MalformedTestException</word> <word>MethodCompareTo</word> <word>MethodEquals</word> <word>moduleAnnotationDefinitions</word> <word>moduleDesignDefinitions</word> <word>moduleExceptionDefinitions</word> <word>moduleFunctions</word> <word>ModuleInfo</word> <word>modulos</word> <word>newArray</word> <word>parameterTypes</word> <word>readBytes</word> <word>readLines</word> <word>readText</word> <word>ReflectionTester</word> <word>ReflectiveTester</word> <word>RetentionPolicy</word> <word>returnType</word> <word>shiftLeft</word> <word>SpecialMethods</word> <word>StaticFieldTester</word> <word>str</word> <word>superclasses</word> <word>TestCase</word> <word>ThisTypeDoesNotExist</word> <word>toMap</word> <word>TypedFunctor</word> <word>UnitTester</word> <word>valueOf</word> <word>writeBytes</word> <word>writeLines</word> <word>writeText</word> <word>XA</word> <word>XE</word> </spellchecker-wordlist> </configuration> </project>
{ "content_hash": "dcc6b9b8d521b7fd6c1ccb728132d4f3", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 90, "avg_line_length": 37.747368421052634, "alnum_prop": 0.5303959843837145, "repo_name": "Mackenzie-High/autumn", "id": "f4f305e7535afd5ece3193855b86ab0ba57433dd", "size": "3586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nbproject/project.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2604069" }, { "name": "Shell", "bytes": "1208" } ] }
Sample app to demonstrate dependency injection using AutoFac IoC container
{ "content_hash": "3f033be974f7397f571d26faf4891f3f", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 74, "avg_line_length": 75, "alnum_prop": 0.8666666666666667, "repo_name": "andygjp/DepInjAndInvOfContSample", "id": "83dbbb396e6f501ccd4ebc52de07109731f20d77", "size": "102", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "115" }, { "name": "C#", "bytes": "11514" }, { "name": "CSS", "bytes": "513" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "19979" } ] }
package es.npatarino.android.gotchallenge.chat.message.usecases; import es.npatarino.android.gotchallenge.base.detail.usecases.UseCase; import es.npatarino.android.gotchallenge.chat.conversation.model.Conversation; import es.npatarino.android.gotchallenge.chat.message.MessageDomain; import es.npatarino.android.gotchallenge.chat.message.model.Message; import rx.Observable; import rx.Scheduler; public class SubscribeToMessage extends UseCase<Message> { private MessageDomain.Repository repository; private Conversation conversation; public SubscribeToMessage(MessageDomain.Repository repository, Scheduler uiThread, Scheduler executorThread) { super(uiThread, executorThread); this.repository = repository; } public Observable<Message> execute(Conversation conversation) { this.conversation = conversation; return execute(); } @Override protected Observable<Message> buildUseCaseObservable() { return scheduleOn(repository.subscribeToMessages(conversation)); } }
{ "content_hash": "feb006d5446ca8d307411eb803a6706c", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 78, "avg_line_length": 34.354838709677416, "alnum_prop": 0.7671361502347418, "repo_name": "tonilopezmr/Game-of-Thrones", "id": "b37cdc0a4acb8f4da363642dc3902638c13c5b0e", "size": "1065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/es/npatarino/android/gotchallenge/chat/message/usecases/SubscribeToMessage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "271383" } ] }
import type { IRowWrapperRenderer } from '../../types'; import { DATAGRID_CHECK_SELECT_ATTR, SelectionType } from '../../constants'; import { normalizedCellRenderer } from '../normalizers'; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const rowWrapper: IRowWrapperRenderer = (node, options, state, index, columns) => { const el = document.createElement('ul'); el.className = 'list-group list-group-flush sf-table__collapsed sf-table__collapsable border-bottom'; const elHeader = document.createElement('li'); const elHeaderRow = document.createElement('div'); elHeaderRow.className = 'row'; elHeader.className = 'list-group-item bg-light sf-table__group'; node.appendChild(el); let col = 12; if (options.selectable) { col = 11; const td = document.createElement('div'); td.className = 'col-1'; const checkbox = document.createElement('input'); checkbox.setAttribute(DATAGRID_CHECK_SELECT_ATTR, ''); checkbox.type = options.selectable.type === SelectionType.MULTIPLE ? 'checkbox' : 'radio'; checkbox.value = state.data[index][options.selectable.id]; checkbox.checked = state.isSelected(checkbox.value); checkbox.addEventListener('change', () => { state.parent.toggleSelection(checkbox.value, checkbox.checked); }); td.classList.add('sf-table__select'); td.appendChild(checkbox); elHeaderRow.appendChild(td); } const data = state.data[index]; if (options.renderAsList) { const { summaryColumn } = options.renderAsList; const d = document.createElement('div'); d.className = `col-${col}`; const cI = columns.find((c) => c.id === summaryColumn)!; const cell = data[summaryColumn]; const renderer = normalizedCellRenderer((options.cells || {})[summaryColumn], true); const r = renderer.render(cell, data, cI, options, index, state); if (r) { if (typeof r === 'string') { d.innerHTML = r; } else { d.appendChild(r); } } elHeaderRow.appendChild(d); } elHeader.addEventListener('click', () => { el.classList.toggle('sf-table__collapsed'); }); elHeader.appendChild(elHeaderRow); el.appendChild(elHeader); return el; };
{ "content_hash": "a71608327f7b3ccca49bcedb0677c03b", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 103, "avg_line_length": 37.47457627118644, "alnum_prop": 0.6734509271822705, "repo_name": "spiral/toolkit", "id": "960ca356282df221b25554fce04f88c579ccb52a", "size": "2211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/datagrid/src/render/list/rowWrapper.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "400" }, { "name": "Hack", "bytes": "21252" }, { "name": "JavaScript", "bytes": "73222" }, { "name": "PHP", "bytes": "9011" }, { "name": "SCSS", "bytes": "22888" }, { "name": "TypeScript", "bytes": "299930" } ] }
/** * canvasInteractor.js (c) 2018 Stefan Goessner * @file interaction manager for html `canvas`. * @author Stefan Goessner * @license MIT License */ /* jshint -W014 */ // Managing multiple canvases per static interactor as singleton ... // .. using a single requestAnimationFrame loop ! const canvasInteractor = { create() { const o = Object.create(this.prototype); o.constructor.apply(o,arguments); return o; }, // global static tickTimer properties fps: '?', fpsOrigin: 0, frames: 0, rafid: 0, instances: [], // global static timer methods tick(time) { canvasInteractor.fpsCount(time); for (const instance of canvasInteractor.instances) { instance.notify('tick',{t:time,dt:(time-instance.t)/1000,dirty:instance.dirty}); // notify listeners .. instance.t = time; instance.dirty = false; } canvasInteractor.rafid = requestAnimationFrame(canvasInteractor.tick); // request next animation frame ... }, add(instance) { canvasInteractor.instances.push(instance); if (canvasInteractor.instances.length === 1) // first instance added ... canvasInteractor.tick(canvasInteractor.fpsOrigin = performance.now()); }, remove(instance) { canvasInteractor.instances.splice(canvasInteractor.instances.indexOf(instance),1); if (canvasInteractor.instances.length === 0) // last instance removed ... cancelAnimationFrame(canvasInteractor.rafid); }, fpsCount(time) { if (time - canvasInteractor.fpsOrigin > 1000) { // one second interval reached ... const fps = ~~(canvasInteractor.frames*1000/(time - canvasInteractor.fpsOrigin) + 0.5); // ~~ as Math.floor() if (fps !== canvasInteractor.fps) for (const instance of canvasInteractor.instances) instance.notify('fps',canvasInteractor.fps=fps); canvasInteractor.fpsOrigin = time; canvasInteractor.frames = 0; } canvasInteractor.frames++; }, prototype: { constructor(ctx, {x,y,scl,cartesian}) { // canvas interaction properties this.ctx = ctx; this.view = {x:x||0,y:y||0,scl:scl||1,cartesian:cartesian||false}; this.evt = { type: false, basetype: false, x: -2, y:-2, xi: 0, yi:0, dx: 0, dy: 0, btn: 0, xbtn: 0, ybtn: 0, xusr: -2, yusr: -2, dxusr: 0, dyusr: 0, delta: 0, inside: false, hit: false, // something hit by pointer ... dscl: 1, // for zooming ... eps: 5 // some pixel tolerance ... }; this.dirty = true; // event handler registration const canvas = ctx.canvas; canvas.addEventListener("pointermove", this, false); canvas.addEventListener("pointerdown", this, false); canvas.addEventListener("pointerup", this, false); canvas.addEventListener("pointerenter", this, false); canvas.addEventListener("pointerleave", this, false); canvas.addEventListener("wheel", this, false); canvas.addEventListener("pointercancel", this, false); }, deinit() { const canvas = this.ctx.canvas; canvas.removeEventListener("pointermove", this, false); canvas.removeEventListener("pointerdown", this, false); canvas.removeEventListener("pointerup", this, false); canvas.removeEventListener("pointerenter", this, false); canvas.removeEventListener("pointerleave", this, false); canvas.removeEventListener("wheel", this, false); canvas.removeEventListener("pointercancel", this, false); this.endTimer(); delete this.signals; delete this.evt; delete this.ctx; return this; }, // canvas interaction interface handleEvent(e) { if (e.type in this && (e.isPrimary || e.type === 'wheel')) { // can I handle events of type e.type .. ? const bbox = e.target.getBoundingClientRect && e.target.getBoundingClientRect() || {left:0, top:0}, x = e.clientX - Math.floor(bbox.left), y = e.clientY - Math.floor(bbox.top), btn = e.buttons !== undefined ? e.buttons : e.button || e.which; this.evt.type = e.type; this.evt.basetype = e.type; // obsolete now ... ? this.evt.xi = this.evt.x; // interim coordinates ... this.evt.yi = this.evt.y; // ... of previous event. this.evt.dx = this.evt.dy = 0; this.evt.x = x; this.evt.y = this.view.cartesian ? this.ctx.canvas.height - y : y; this.evt.xusr = (this.evt.x - this.view.x)/this.view.scl; this.evt.yusr = (this.evt.y - this.view.y)/this.view.scl; this.evt.dxusr = this.evt.dyusr = 0; this.evt.dbtn = btn - this.evt.btn; this.evt.btn = btn; this.evt.delta = Math.max(-1,Math.min(1,e.deltaY||e.wheelDelta)) || 0; if (this.isDefaultPreventer(e.type)) e.preventDefault(); this[e.type](); // handle specific event .. ! this.notify(this.evt.type,this.evt); // .. tell the world .. ! } else console.log(e) }, pointermove() { this.evt.dx = this.evt.x - this.evt.xi; this.evt.dy = this.evt.y - this.evt.yi; if (this.evt.btn === 1) { // pointerdown state ... this.evt.dxusr = this.evt.dx/this.view.scl; // correct usr coordinates ... this.evt.dyusr = this.evt.dy/this.view.scl; this.evt.xusr -= this.evt.dxusr; // correct usr coordinates ... this.evt.yusr -= this.evt.dyusr; if (!this.evt.hit) { // let outer app perform panning ... this.evt.type = 'pan'; } else this.evt.type = 'drag'; } // view, geometry or graphics might be modified ... this.dirty = true; }, pointerdown() { this.evt.xbtn = this.evt.x; this.evt.ybtn = this.evt.y; }, pointerup() { this.evt.type = this.evt.x===this.evt.xbtn && this.evt.y===this.evt.ybtn ? 'click' : 'pointerup'; this.evt.xbtn = this.evt.x; this.evt.ybtn = this.evt.y; }, pointerleave() { this.evt.inside = false; }, pointerenter() { this.evt.inside = true; }, wheel() { this.evt.dscl = this.evt.delta>0?8/10:10/8; this.evt.eps /= this.evt.dscl; this.dirty = true; }, isDefaultPreventer(type) { return ['pointermove','pointerdown','pointerup','wheel'].includes(type); }, pntToUsr: function(p) { let vw = this.view; p.x = (p.x - vw.x)/vw.scl; p.y = (p.y - vw.y)/vw.scl; return p; }, // tickTimer interface startTimer() { // shouldn't there be a global startTimer method ? canvasInteractor.add(this); this.notify('timerStart',this); // notify potential listeners .. return this; }, endTimer() { this.notify('timerEnd',this.t/1000); // notify potential listeners .. canvasInteractor.remove(this); return this; }, // observable interface notify(key,val) { if (this.signals && this.signals[key]) for (let hdl of this.signals[key]) hdl(val); return this; }, on(key,handler) { // support array of keys as first argument. if (Array.isArray(key)) for (let k of key) this.on(k,handler); else ((this.signals || (this.signals = {})) && this.signals[key] || (this.signals[key]=[])).push(handler); return this; }, remove(key,handler) { const idx = (this.signals && this.signals[key]) ? this.signals[key].indexOf(handler) : -1; if (idx >= 0) this.signals[key].splice(idx,1); } } };
{ "content_hash": "9b7510ace65db730bcb9301684e97068", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 121, "avg_line_length": 41.16355140186916, "alnum_prop": 0.5143603133159269, "repo_name": "goessner/g2", "id": "2c2787e5d0a1b893ba32d7c2883c7e12ce0928bd", "size": "8809", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/canvasInteractor.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "176680" } ] }
Imports DTIServerControls Imports System.Text.RegularExpressions ''' <summary> ''' control to navigate search of DTI-managed media objects. Sorted by relevancy, submitted, or rating ''' </summary> ''' <remarks></remarks> #If DEBUG Then Public Class MediaSearcher Inherits DTIServerControl #Else <ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never), ComponentModel.ToolboxItem(False)> _ Public Class MediaSearcher Inherits DTIServerControl #End If Public btnSearch As New HtmlInputButton Public tbSearch As New TextBox Friend tbSort As New TextBox Public btnNewest As New HtmlAnchor Public btnOldest As New HtmlAnchor Public btnRating As New HtmlAnchor Friend pnlButtons As New Panel Public commonWords As String() = {"the", "of", "to", "and", "a", "in", "is", "it"} Public commonWordsList As New ArrayList(commonWords) Protected TitleWeight As Double = 5 Protected DescWeight As Double = 4 Protected TagWeight As Double = 3 Protected ContentWeight As Double = 2 Private _words As String() Public ReadOnly Property SearchWords() As String() Get If _words Is Nothing Then _words = Regex.Split(tbSearch.Text, "\W+") Dim wordList As New List(Of String) For Each word As String In _words If word <> "" Then wordList.Add(word) End If Next _words = wordList.ToArray End If Return _words End Get End Property Private _word_soup As String() Public ReadOnly Property WordSoup() As String() Get If _word_soup Is Nothing Then Dim _wordSoupList As New List(Of String) For Each word As String In SearchWords If Not commonWordsList.Contains(word) Then _wordSoupList.Add("%" & word & "%") End If Next _word_soup = _wordSoupList.ToArray End If Return _word_soup End Get End Property Private _use_search_rank As Boolean = True Public Property UseSearchRank() As Boolean Get Return _use_search_rank End Get Set(ByVal value As Boolean) _use_search_rank = value pnlButtons.Visible = Not value End Set End Property Public Property UseSortButtons() As Boolean Get Return pnlButtons.Visible End Get Set(ByVal value As Boolean) pnlButtons.Visible = value _use_search_rank = Not value End Set End Property Public Property ShowRatingSortButton() As Boolean Get Return btnRating.Visible End Get Set(ByVal value As Boolean) If value Then UseSortButtons = value btnRating.Visible = value End Set End Property Public Property ShowNewestOldestSortButtons() As Boolean Get Return btnNewest.Visible End Get Set(ByVal value As Boolean) If value Then UseSortButtons = value btnNewest.Visible = value btnOldest.Visible = value End Set End Property Public ReadOnly Property SortButtons() As ControlCollection Get Return pnlButtons.Controls End Get End Property Public Property SearchOnClick() As String Get Return btnSearch.Attributes("onclick") End Get Set(ByVal value As String) btnSearch.Attributes("onclick") = value End Set End Property Public Property SearchText() As String Get Return tbSearch.Text End Get Set(ByVal value As String) tbSearch.Text = value End Set End Property Private _add_query As String = "" Public Property AdditionalQuery() As String Get Return _add_query End Get Set(ByVal value As String) _add_query = value End Set End Property Public ReadOnly Property QueryFilter() As String Get For Each mediaType As mediaSearchTable In mediaSearchTableEntries If Not Content_Types.Contains(mediaType.ContentType) Then Content_Types.Add(mediaType.ContentType) End If Next Dim returnStatement As String = " User_Id = '" & MainID & "' AND Published <> 0 and Removed <> 1 " & _ " and Component_Type = '" & Component_Type & "' and (" & _ comp_string("Content_Type", "=", Content_Types.ToArray) & ")" If UseSearchRank Then returnStatement &= " and (" & CountExecString & " > 0)" ElseIf UseSortButtons AndAlso tbSearch.Text <> "" Then returnStatement &= " and ((" & comp_string("Title", "like", WordSoup) & ") or (" & _ comp_string("Description", "like", WordSoup) & ") or Id in (select Content_Id from " & _ "DTI_Content_Tag_Pivot where Component_Type = '" & Component_Type & "' and Tag_Id in " & _ "(select Id from DTI_Content_Tags where " & comp_string("Tag_Name", "like", WordSoup) & "))" For Each mediaSearch As mediaSearchTable In mediaSearchTableEntries If Not mediaSearch.TableName Is Nothing Then returnStatement &= " or (Content_Type = '" & mediaSearch.ContentType & "' and Content_Id" & _ "in (select Id from " & mediaSearch.TableName & " where " & _ comp_string(mediaSearch.VarCharColumnName, "like", WordSoup) & "))" End If Next returnStatement &= ")" End If If AdditionalQuery <> "" Then returnStatement &= " and (" & AdditionalQuery & ")" End If '" and User_Id in (select Id from from Users where MaindId = " & MainId & ")" Return returnStatement End Get End Property '***fixme database specific Private ReadOnly Property CountExecString() As String Get Dim returnValue As String = "1" If tbSearch.Text <> "" AndAlso UseSearchRank Then Dim titleString As String = "0" Dim descString As String = "0" Dim tagString As String = "0" Dim mediaString As String = "0" For Each word As String In SearchWords If Not commonWordsList.Contains(word) Then titleString &= " + CountString(isnull(Title, ''), '" & word & "')" descString &= " + CountString(isnull(Description, ''), '" & word & "')" tagString &= " + HasTag(Id, '" & Component_Type & "', '" & word & "')" For Each mediaSearch As mediaSearchTable In mediaSearchTableEntries mediaString &= " + case when Content_Type = '" & mediaSearch.ContentType & _ "' then CountString((select CONVERT(varchar(8000), isnull(" & _ mediaSearch.VarCharColumnName & ",'')) from " & mediaSearch.TableName & _ " where Id = Content_Id), '" & word & "') else 0 end" Next End If Next titleString = "(" & titleString & ") * " & TitleWeight descString = "(" & descString & ") * " & DescWeight tagString = "(" & tagString & ") * " & TagWeight mediaString = "(" & mediaString & ") * " & ContentWeight returnValue = "isnull(Rating, 1) * (" & titleString & " + " & descString & " + " & tagString & _ " + " & mediaString & ")" End If Return returnValue End Get End Property Public Property Sort() As String Get If tbSort.Text = "" Then tbSort.Text = "Date_added Desc" End If If UseSearchRank Then Return CountExecString & " desc, " & tbSort.Text ElseIf UseSortButtons Then Return tbSort.Text Else Return tbSort.Text End If End Get Set(ByVal value As String) tbSort.Text = value End Set End Property Public ReadOnly Property SearchSelectStatement() As String Get Return "select " & SearchColumns & " from DTIMediaManager where " & QueryFilter & " order by " & Sort End Get End Property Public ReadOnly Property SearchColumns() As String Get Return "*" End Get End Property Public Class mediaSearchTable Public ContentType As String Public TableName As String Public VarCharColumnName As String Public Sub New(ByVal cont_type As String, ByVal table_name As String, ByVal var_char_col_name As String) ContentType = cont_type TableName = table_name VarCharColumnName = var_char_col_name End Sub End Class Public mediaSearchTableEntries As New List(Of mediaSearchTable) Private _cont_types As New List(Of String) Public ReadOnly Property Content_Types() As List(Of String) Get Return _cont_types End Get End Property Public ReadOnly Property comp_string(ByVal colName As String, ByVal op As String, ByVal values As String()) As String Get Dim retString As String = colName & " " & op & " '" Dim concatString As String = "' or " & colName & " " & op & " '" For Each comp As String In values retString &= comp & concatString Next If retString.LastIndexOf(concatString) > -1 Then Return retString.Substring(0, retString.LastIndexOf(" or")) Else Return "1=1" End If End Get End Property Private Sub MediaSearcher_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init UseSortButtons = False tbSort.Text = "Date_added Desc" End Sub Private Sub MediaSearcher_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load tbSearch.ID = "tbMediaSearch" tbSearch.CssClass = "MediaSearchTextBox" btnSearch.Attributes("class") = "MediaSearchButton" tbSort.ID = "tbMediaSort" tbSort.CssClass = "MediaSortTextBox" jQueryLibrary.jQueryInclude.RegisterJQuery(Me.Page) registerClientScriptBlock("queryInit", "$.query = { prefix: false };", True) registerClientScriptFile("JQQ", BaseClasses.Scripts.ScriptsURL(True) & "jQueryLibrary/jquery.query.js") If Page.Request.Params("SearchCompType") <> "" Then Component_Type = Page.Request.Params("SearchCompType") End If If Page.Request.Params("SearchContTypes") <> "" Then For Each contType As String In Page.Request.Params("SearchContTypes").Split("+") Content_Types.Add(contType) Next End If If Page.Request.Params("SearchQuery") <> "" Then For Each contType As String In Page.Request.Params("SearchQuery").Split("+") Content_Types.Add(contType) Next End If End Sub Private Sub MediaSearcher_LoadControls(ByVal modeChanged As Boolean) Handles Me.LoadControls Controls.Add(tbSearch) Controls.Add(btnSearch) Controls.Add(New LiteralControl("<br />")) Controls.Add(tbSort) pnlButtons.Controls.Add(btnNewest) pnlButtons.Controls.Add(btnOldest) pnlButtons.Controls.Add(btnRating) Controls.Add(pnlButtons) End Sub Private Sub MediaSearcher_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender tbSort.Style("display") = "none" btnSearch.Attributes.Add("value", "Search") btnNewest.Attributes.Add("href", "#") btnNewest.InnerHtml = "Newest" btnNewest.Style("padding-right") = "30px" btnNewest.Attributes.Add("onclick", "$('#" & tbSort.ClientID & "').val('Date_Added Desc');$('#" & btnSearch.ClientID & "').click();return false;") btnOldest.Attributes.Add("href", "#") btnOldest.InnerHtml = "Oldest" btnOldest.Style("padding-right") = "30px" btnOldest.Attributes.Add("onclick", "$('#" & tbSort.ClientID & "').val('Date_Added Asc');$('#" & btnSearch.ClientID & "').click();return false;") btnRating.Attributes.Add("href", "#") btnRating.InnerHtml = "Rating" btnRating.Attributes.Add("onclick", "if($('#" & tbSort.ClientID & "').val().indexOf('Rating D') > -1){$('#" & tbSort.ClientID & "').val('Rating Asc');} else{$('#" & tbSort.ClientID & "').val('Rating Desc');}$('#" & btnSearch.ClientID & "').click();return false;") 'Dim script As String = "$(function() { if($.query.load(window.location.href).get('" & Me.ClientID & _ ' "') != '') { $('#" & Me.ClientID & "').val($.query.load(window.location.href).get('" & Me.ClientID & _ ' "'));}});" 'Page.ClientScript.RegisterStartupScript(Me.GetType, "searcherInit_" & Me.ClientID, script, True) End Sub '***fixme database specific - Poss remove Public Shared Function getCreateSqlFunctionsScript() As Hashtable Dim script1 As String = "CREATE FUNCTION [HasTag] " & vbCrLf & _ "( @media_id INT, @comp_type VARCHAR(100), @tag_name VARCHAR(100) ) " & vbCrLf & _ "RETURNS INT " & vbCrLf & _ "BEGIN " & vbCrLf & _ " RETURN (select count(*) " & vbCrLf & _ " from DTI_Content_Tag_Pivot " & vbCrLf & _ " where Content_Id = @media_id and Component_Type = @comp_type and Tag_Id in " & vbCrLf & _ " (select Id from DTI_Content_Tags where Tag_Name like '%' + @tag_name + '%')) " & vbCrLf & _ "END " Dim script2 As String = "CREATE FUNCTION [CountString] " & vbCrLf & _ "( @pInput VARCHAR(8000), @pSearchString VARCHAR(100) ) " & vbCrLf & _ "RETURNS INT " & vbCrLf & _ "BEGIN " & vbCrLf & _ " RETURN (LEN(@pInput) - " & vbCrLf & _ " LEN(REPLACE(@pInput, @pSearchString, ''))) / " & vbCrLf & _ " LEN(@pSearchString) " & vbCrLf & _ "END " Dim ret As New Hashtable ret("HasTag") = script1 ret("CountString") = script2 Return ret End Function Public Sub createSqlFunctions() Dim hash As Hashtable = getCreateSqlFunctionsScript() For Each obj As String In hash.Keys Try If Not sqlhelper.checkDBObjectExists(obj) Then sqlhelper.ExecuteNonQuery(hash(obj)) End If Catch ex As Exception End Try Next End Sub Private Sub MediaSearcher_typeFirstInitialized(ByVal t As System.Type) Handles Me.typeFirstInitialized Try createSqlFunctions() Catch ex As Exception End Try End Sub End Class
{ "content_hash": "150e5f4dae6123728f9fde48502f26b8", "timestamp": "", "source": "github", "line_count": 393, "max_line_length": 275, "avg_line_length": 42.62086513994911, "alnum_prop": 0.5244776119402985, "repo_name": "Micmaz/DTIControls", "id": "b1a55f4493e63d08c783ff2e0e2a550b888e988a", "size": "16750", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DTIContentManagement/DTIMediaManager/MediaSearcher.vb", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "1111353" }, { "name": "Batchfile", "bytes": "2442" }, { "name": "C#", "bytes": "59872" }, { "name": "CSS", "bytes": "1689439" }, { "name": "HTML", "bytes": "19388303" }, { "name": "JavaScript", "bytes": "3417429" }, { "name": "Less", "bytes": "48637" }, { "name": "SCSS", "bytes": "24889" }, { "name": "Shell", "bytes": "2881" }, { "name": "VBScript", "bytes": "1265" }, { "name": "Visual Basic .NET", "bytes": "2738884" }, { "name": "XSLT", "bytes": "24694" } ] }
using System.Collections.Generic; using System.Linq; using NuGet.ProjectModel; namespace Microsoft.DotNet.ProjectModel.Graph { public class ExportFile { public static readonly string ExportFileName = "project.fragment.lock.json"; public int Version { get; } public string ExportFilePath { get; } public IList<LockFileTargetLibrary> Exports { get; } public ExportFile(string exportFilePath, int version, IList<LockFileTargetLibrary> exports) { ExportFilePath = exportFilePath; Version = version; Exports = exports.Any() ? exports : new List<LockFileTargetLibrary>(0); } } }
{ "content_hash": "a801a3d2386b8a971f4ec79ad4eca06a", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 99, "avg_line_length": 29.608695652173914, "alnum_prop": 0.6681350954478708, "repo_name": "naamunds/cli", "id": "226bd0d5f021c8378ede8fd5af47bca54c357906", "size": "683", "binary": false, "copies": "1", "ref": "refs/heads/rel/1.0.0", "path": "src/Microsoft.DotNet.ProjectModel/Graph/ExportFile.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1842" }, { "name": "C#", "bytes": "2842646" }, { "name": "CSS", "bytes": "827" }, { "name": "F#", "bytes": "2062" }, { "name": "Groovy", "bytes": "2391" }, { "name": "HTML", "bytes": "27944" }, { "name": "JavaScript", "bytes": "1179" }, { "name": "PowerShell", "bytes": "39627" }, { "name": "Python", "bytes": "9745" }, { "name": "Shell", "bytes": "49243" } ] }
package com.prowidesoftware.swift.model.field; import com.prowidesoftware.swift.model.Tag; import com.prowidesoftware.Generated; import com.prowidesoftware.deprecation.ProwideDeprecated; import com.prowidesoftware.deprecation.TargetYear; import java.io.Serializable; import java.util.Locale; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import com.prowidesoftware.swift.model.BIC; import com.prowidesoftware.swift.model.field.MultiLineField; import com.prowidesoftware.swift.model.field.BICContainer; import com.prowidesoftware.swift.model.field.BICResolver; import org.apache.commons.lang3.StringUtils; import com.prowidesoftware.swift.model.field.SwiftParseUtils; import com.prowidesoftware.swift.model.field.Field; import com.prowidesoftware.swift.model.*; import com.prowidesoftware.swift.utils.SwiftFormatUtils; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * SWIFT MT Field 51A. * <p> * Model and parser for field 51A of a SWIFT MT message. * * <p>Subfields (components) Data types * <ol> * <li><code>String</code></li> * <li><code>String</code></li> * <li><code>BIC</code></li> * </ol> * * <p>Structure definition * <ul> * <li>validation pattern: <code>[[/&lt;DC&gt;][/34x]$]&lt;BIC&gt;</code></li> * <li>parser pattern: <code>[[/c][/S]$]S</code></li> * <li>components pattern: <code>SSB</code></li> * </ul> * * <p> * This class complies with standard release <strong>SRU2022</strong> */ @SuppressWarnings("unused") @Generated public class Field51A extends OptionAPartyField implements Serializable, BICContainer, MultiLineField { /** * Constant identifying the SRU to which this class belongs to. */ public static final int SRU = 2022; private static final long serialVersionUID = 1L; /** * Constant with the field name 51A. */ public static final String NAME = "51A"; /** * Same as NAME, intended to be clear when using static imports. */ public static final String F_51A = "51A"; /** * Default constructor. Creates a new field setting all components to null. */ public Field51A() { super(); } /** * Creates a new field and initializes its components with content from the parameter value. * @param value complete field value including separators and CRLF */ public Field51A(final String value) { super(value); } /** * Creates a new field and initializes its components with content from the parameter tag. * The value is parsed with {@link #parse(String)} * @throws IllegalArgumentException if the parameter tag is null or its tagname does not match the field name * @since 7.8 */ public Field51A(final Tag tag) { this(); if (tag == null) { throw new IllegalArgumentException("tag cannot be null."); } if (!StringUtils.equals(tag.getName(), "51A")) { throw new IllegalArgumentException("cannot create field 51A from tag "+tag.getName()+", tagname must match the name of the field."); } parse(tag.getValue()); } /** * Copy constructor. * Initializes the components list with a deep copy of the source components list. * @param source a field instance to copy * @since 7.7 */ public static Field51A newInstance(Field51A source) { Field51A cp = new Field51A(); cp.setComponents(new ArrayList<>(source.getComponents())); return cp; } /** * Create a Tag with this field name and the given value. * Shorthand for <code>new Tag(NAME, value)</code> * @see #NAME * @since 7.5 */ public static Tag tag(final String value) { return new Tag(NAME, value); } /** * Create a Tag with this field name and an empty string as value. * Shorthand for <code>new Tag(NAME, "")</code> * @see #NAME * @since 7.5 */ public static Tag emptyTag() { return new Tag(NAME, ""); } /** * Returns the field validator pattern. */ @Override public final String validatorPattern() { return "[[/<DC>][/34x]$]<BIC>"; } /** * Set the component 1 (D/C Mark). * * @param component1 the D/C Mark to set * @return the field object to enable build pattern */ public Field51A setComponent1(String component1) { setComponent(1, component1); return this; } /** * Set the D/C Mark (component 1). * * @param component1 the D/C Mark to set * @return the field object to enable build pattern */ public Field51A setDCMark(String component1) { return setComponent1(component1); } /** * Set the component 2 (Account). * * @param component2 the Account to set * @return the field object to enable build pattern */ public Field51A setComponent2(String component2) { setComponent(2, component2); return this; } /** * Set the Account (component 2). * * @param component2 the Account to set * @return the field object to enable build pattern */ public Field51A setAccount(String component2) { return setComponent2(component2); } /** * Set the component 3 (Identifier Code). * * @param component3 the Identifier Code to set * @return the field object to enable build pattern */ public Field51A setComponent3(String component3) { setComponent(3, component3); return this; } /** * Set the component3 from a BIC object. * * @param component3 the BIC with the Identifier Code content to set * @return the field object to enable build pattern */ public Field51A setComponent3(com.prowidesoftware.swift.model.BIC component3) { setComponent(3, SwiftFormatUtils.getBIC(component3)); return this; } /** * Set the Identifier Code (component 3). * * @param component3 the Identifier Code to set * @return the field object to enable build pattern */ public Field51A setIdentifierCode(String component3) { return setComponent3(component3); } /** * Set the Identifier Code (component 3) from a BIC object. * * @see #setComponent3(com.prowidesoftware.swift.model.BIC) * * @param component3 BIC with the Identifier Code content to set * @return the field object to enable build pattern */ public Field51A setIdentifierCode(com.prowidesoftware.swift.model.BIC component3) { return setComponent3(component3); } /** * Alternative <em>DEPRECATED</em> method setter for field's Identifier Code * * @see #setIdentifierCode(String) * * @param component3 the Identifier Code to set * @return the field object to enable build pattern */ @Deprecated @ProwideDeprecated(phase3 = TargetYear.SRU2023) public Field51A setBIC(String component3) { return setIdentifierCode(component3); } /** * Alternative <em>DEPRECATED</em> method setter for field's Identifier Code from a BIC object. * * @see #setComponent3(com.prowidesoftware.swift.model.BIC) * * @param component3 BIC with the Identifier Code content to set * @return the field object to enable build pattern */ @Deprecated @ProwideDeprecated(phase3 = TargetYear.SRU2023) public Field51A setBIC(com.prowidesoftware.swift.model.BIC component3) { return setIdentifierCode(component3); } public List<BIC> bics() { return BICResolver.bics(this); } public List<String> bicStrings () { return BICResolver.bicStrings(this); } /** * Returns the field's name composed by the field number and the letter option (if any). * @return the static value of Field51A.NAME */ @Override public String getName() { return NAME; } /** * Gets the first occurrence form the tag list or null if not found. * @return null if not found o block is null or empty * @param block may be null or empty */ public static Field51A get(final SwiftTagListBlock block) { if (block == null || block.isEmpty()) { return null; } final Tag t = block.getTagByName(NAME); if (t == null) { return null; } return new Field51A(t); } /** * Gets the first instance of Field51A in the given message. * @param msg may be empty or null * @return null if not found or msg is empty or null * @see #get(SwiftTagListBlock) */ public static Field51A get(final SwiftMessage msg) { if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) { return null; } return get(msg.getBlock4()); } /** * Gets a list of all occurrences of the field Field51A in the given message * an empty list is returned if none found. * @param msg may be empty or null in which case an empty list is returned * @see #getAll(SwiftTagListBlock) */ public static List<Field51A> getAll(final SwiftMessage msg) { if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) { return java.util.Collections.emptyList(); } return getAll(msg.getBlock4()); } /** * Gets a list of all occurrences of the field Field51A from the given block * an empty list is returned if none found. * * @param block may be empty or null in which case an empty list is returned */ public static List<Field51A> getAll(final SwiftTagListBlock block) { final List<Field51A> result = new ArrayList<>(); if (block == null || block.isEmpty()) { return result; } final Tag[] arr = block.getTagsByName(NAME); if (arr != null && arr.length > 0) { for (final Tag f : arr) { result.add(new Field51A(f)); } } return result; } /** * Returns a specific line from the field's value. * * @see MultiLineField#getLine(int) * @param line a reference to a specific line in the field, first line being 1 * @return line content or null if not present or if line number is above the expected * @since 7.7 */ public String getLine(int line) { return getLine(line, 0); } /** * Returns a specific line from the field's value. * * @see MultiLineField#getLine(int, int) * @param line a reference to a specific line in the field, first line being 1 * @param offset an optional component number used as offset when counting lines * @return line content or null if not present or if line number is above the expected * @since 7.7 */ public String getLine(int line, int offset) { Field51A cp = newInstance(this); return getLine(cp, line, null, offset); } /** * Returns the field value split into lines. * * @see MultiLineField#getLines() * @return lines content or empty list if field's value is empty * @since 7.7 */ public List<String> getLines() { return SwiftParseUtils.getLines(getValue()); } /** * Returns the field value starting at the offset component, split into lines. * * @see MultiLineField#getLines(int) * @param offset an optional component number used as offset when counting lines * @return found lines or empty list if lines are not present or the offset is invalid * @since 7.7 */ public List<String> getLines(int offset) { Field51A cp = newInstance(this); return SwiftParseUtils.getLines(getLine(cp, null, null, offset)); } /** * Returns a specific subset of lines from the field's value, given a range. * * @see MultiLineField#getLinesBetween(int, int ) * @param start a reference to a specific line in the field, first line being 1 * @param end a reference to a specific line in the field, must be greater than start * @return found lines or empty list if value is empty * @since 7.7 */ public List<String> getLinesBetween(int start, int end) { return getLinesBetween(start, end, 0); } /** * Returns a specific subset of lines from the field's value, starting at the offset component. * * @see MultiLineField#getLinesBetween(int start, int end, int offset) * @param start a reference to a specific line in the field, first line being 1 * @param end a reference to a specific line in the field, must be greater than start * @param offset an optional component number used as offset when counting lines * @return found lines or empty list if lines are not present or the offset is invalid * @since 7.7 */ public List<String> getLinesBetween(int start, int end, int offset) { Field51A cp = newInstance(this); return SwiftParseUtils.getLines(getLine(cp, start, end, offset)); } /** * This method deserializes the JSON data into a Field51A object. * @param json JSON structure including tuples with label and value for all field components * @return a new field instance with the JSON data parsed into field components or an empty field id the JSON is invalid * @since 7.10.3 * @see Field#fromJson(String) */ public static Field51A fromJson(final String json) { final Field51A field = new Field51A(); final JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject(); // **** COMPONENT 1 - D/C Mark if (jsonObject.get("dCMark") != null) { field.setComponent1(jsonObject.get("dCMark").getAsString()); } // **** COMPONENT 2 - Account if (jsonObject.get("account") != null) { field.setComponent2(jsonObject.get("account").getAsString()); } // **** COMPONENT 3 - Identifier Code // first try using alias's names (including deprecated ones, if any) if (jsonObject.get("bIC") != null) { field.setComponent3(jsonObject.get("bIC").getAsString()); } // last try using the official component's name (overwrites alternatives and DEPRECATED) if (jsonObject.get("identifierCode") != null) { field.setComponent3(jsonObject.get("identifierCode").getAsString()); } return field; } }
{ "content_hash": "473c8af21c5d0417ded9e42b7e77897a", "timestamp": "", "source": "github", "line_count": 458, "max_line_length": 144, "avg_line_length": 31.87117903930131, "alnum_prop": 0.6375282592313489, "repo_name": "prowide/prowide-core", "id": "c7cc08903884ac41091d54e5d028b189ee29b351", "size": "15192", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/generated/java/com/prowidesoftware/swift/model/field/Field51A.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "43156" }, { "name": "Java", "bytes": "25397388" } ] }
namespace SparkDotNet { public class XAPIStatusResultAudio : WebexObject { public int Volume { get; set; } } }
{ "content_hash": "33837c2c0c11d666cd58f02a7e727708", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 52, "avg_line_length": 16.375, "alnum_prop": 0.6412213740458015, "repo_name": "darrenparkinson/SparkDotNet", "id": "69138ce2631dda841214baaaa08bbf1a51b0f479", "size": "131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Models/XAPIStatusResultAudio.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "378169" } ] }
const path = require('../../../shared/lib/path'); const dispatcher = require('../../lib/dispatcher').dispatcher; const errors = require('../errors'); const err = require('../errors').errors; const Iterator = require('../tokenizer/TokenIterator').Iterator; const t = require('../tokenizer/tokenizer'); const ProjectResources = require('../resources/ProjectResources').ProjectResources; const FormResource = require('../resources/FormResource').FormResource; const Defines = require('./Defines').Defines; const MetaCompiler = require('./MetaCompiler'); const Tokenizer = t.Tokenizer; const removePadding = function(s) { return s.substr(1, s.length - 2); }; exports.PreProcessor = class PreProcessor { constructor(opts) { this._projectPath = path.getPathAndFilename(opts.projectFilename || '').path; this._documentPath = opts.documentPath || ''; this._projectFilename = opts.projectFilename; this._linter = opts.linter; this._onGetFileData = opts.onGetFileData; this._onGetFileDataError = opts.onGetFileDataError; this._onGetEditorFileData = opts.onGetEditorFileData; this._onError = opts.onError; this._onFinished = opts.onFinished; this._filesDone = {}; this._fileCount = 0; this._sortedFiles = null; this._error = false; this._defines = new Defines({globalDefines: opts.globalDefines || {}}); this._lineCount = 0; this._includeRoot = { filename: '' }; this._resources = new ProjectResources({ projectFilename: this._projectFilename, onGetEditorFileData: this._onGetEditorFileData, onGetFileData: this._onGetFileData }); } compileInclude(iterator, token, tokenFilename, includes) { token.done = true; token = iterator.skipWhiteSpace().next(); token.done = true; if (token.cls !== t.TOKEN_STRING) { token.filename = tokenFilename; throw errors.createError(err.FILENAME_EXPECTED, token, 'Filename expected.'); } let filename = removePadding(token.lexeme); includes.push({filename: filename, token: token}); if (this._onError) { try { MetaCompiler.checkRestTokens(iterator, 'include'); } catch (error) { this._onError({ type: 'Error', message: '<i class="error">Invalid tokens after include.</i>', tolen: token }); } } else { MetaCompiler.checkRestTokens(iterator, 'include'); } } processIncludes(fileItem, data) { let tokenizer = new Tokenizer(); let tokens = tokenizer.tokenize(data).getTokens(); let includes = []; let token = true; let iterator = new Iterator({tokens: tokens, compiler: this}); let metaCompiler = new MetaCompiler.MetaCompiler({ defines: this._defines, resources: this._resources, linter: this._linter }); this._tokens = tokens; this._lineCount += tokenizer.getLineNum(); if (this._linter) { this._linter.addTokens(tokens); } while (token) { token = iterator.skipWhiteSpace().next(); if (!token) { break; } switch (token.cls) { case t.TOKEN_META: switch (token.lexeme) { case t.LEXEME_META_INCLUDE: this.compileInclude(iterator, token, fileItem.filename, includes); break; case t.LEXEME_META_IFDEF: metaCompiler.compileIfdef(iterator, token, this._defines); break; case t.LEXEME_META_DEFINE: metaCompiler.compileDefine(iterator, token, fileItem.filename); break; case t.LEXEME_META_IMAGE: metaCompiler.compileImage(iterator, token, fileItem.filename); break; case t.LEXEME_META_TEXT: metaCompiler.compileText(iterator, token, fileItem.filename); break; case t.LEXEME_META_RESOURCE: metaCompiler.compileResource(iterator, token, fileItem.filename); break; } break; } } fileItem.tokens = tokens; fileItem.includes = includes; } processFile(includeItem, includeNode) { if (!includeNode) { includeNode = this._includeRoot; includeNode.filename = includeItem.filename; } let filesDone = this._filesDone; let filename = this.getBaseFilename(includeItem.filename); if (filename in filesDone) { return; } this._fileCount++; let fileItem = { tokens: null, projectPath: this._projectPath, filename: filename }; filesDone[filename] = fileItem; this._onGetFileData( filename, includeItem.token, this.onFileData.bind(this, fileItem, includeNode) ); } processResources() { let filesDone = this._filesDone; let resources = this._resources.getResources(); let projectPath = this._projectPath; let index = 0; let loadResource = () => { let resource = resources[index++]; if (resource) { if (resource.neededBeforeCompile()) { resource .setProjectPath(projectPath) .getData(loadResource); } else { loadResource(); } } else { this.getSortedFiles(); this._onFinished(filesDone, this._error); } }; loadResource(); } onFileData(fileItem, includeNode, data) { if (data === null) { this._onGetFileDataError && this._onGetFileDataError(fileItem); return; } this._fileCount--; if (fileItem.tokens === null) { this.processIncludes(fileItem, data); } let filesDone = this._filesDone; let includes = fileItem.includes; includes.forEach((include) => { if (include in filesDone) { return; } let newNode = {filename: include.filename}; if (!includeNode.includes) { includeNode.includes = []; } includeNode.includes.push(newNode); this.processFile(include, newNode); }); if (this._fileCount === 0) { this.processResources(this._onFinished); } } getDepth() { return 0; } getBaseFilename(filename) { let documentPath = this._documentPath; let projectPath = this._projectPath; if ((documentPath === '') && (projectPath === '')) { return filename; } if ((documentPath !== '') && filename.indexOf(documentPath) === 0) { return filename.substr(documentPath.length + 1 - filename.length); } if (filename.indexOf('/') === -1) { filename = path.join(projectPath.substr(documentPath.length + 1 - projectPath.length), filename); } return filename; } getTokens() { return this._tokens; } getLineCount() { return this._lineCount; } /** * Build an include file tree and return the depth of the file relative to the root of the project... **/ getDepthByFilename() { let projectPath = this._projectPath; let includesByFilename = {}; let includeByFilename = {}; // To check for circular includes... let depthByFilename = {}; const makeNodeByFilename = (node) => { if (node.includes) { includesByFilename[node.filename] = node.includes; node.includes.forEach((node) => { makeNodeByFilename(node); }); } }; const makeIncludes = (node) => { if (this._error) { return; } if (node.includes) { node.includes.forEach((includeNode) => { let filename1 = path.removePath(projectPath, node.filename); let filename2 = includeNode.filename; let index1 = filename1 + '!' + filename2; let index2 = filename2 + '!' + filename1; if ((index1 in includeByFilename) || (index2 in includeByFilename)) { if (!this._error) { if (this._onError) { this._onError({ type: 'Error', message: 'Circular include in ' + '<i class="error">"' + filename1 + '"</i> and ' + '<i class="error">' + filename2 + '"</i>.' }); } this._error = true; } return; } includeByFilename[index1] = true; makeIncludes(includeNode); }); } else if (node.filename in includesByFilename) { node.includes = includesByFilename[node.filename]; } }; const makeIncludeOrder = (node, depth) => { if (node.filename in depthByFilename) { depthByFilename[node.filename] = Math.max(depthByFilename[node.filename], depth); } else { depthByFilename[node.filename] = depth; } if (node.includes) { node.includes.forEach((node) => { makeIncludeOrder(node, depth + 1); }); } }; makeNodeByFilename(this._includeRoot); makeIncludes(this._includeRoot); if (!this._error) { makeIncludeOrder(this._includeRoot, 0); } return this._error ? null : depthByFilename; } getSortedFiles() { if (this._sortedFiles) { return this._sortedFiles; } let depthByFilename = this.getDepthByFilename(); let documentPath = this._documentPath; let projectPath = this._projectPath; let filesDone = this._filesDone; let files = []; if (!depthByFilename) { return []; } for (let i in filesDone) { let fileDone = filesDone[i]; fileDone.toString = function() { let depth = 0; let filename = this.filename; if (this.filename in depthByFilename) { depth = depthByFilename[filename]; } else { filename = path.removePath(projectPath, path.join(documentPath, filename)); if (filename in depthByFilename) { depth = depthByFilename[filename]; } } this.sortIndex = ('00000000' + (99999999 - depth)).substr(-8); return this.sortIndex; }; files.push(fileDone); } files.sort(); this._sortedFiles = files; return files; } getDefines() { return this._defines; } getDefinedOffsetTokens(tokens, offset, fileIndex) { if (!tokens) { return []; } let defines = this._defines; tokens.forEach((token) => { token.index += offset; if (token.cls === t.TOKEN_IDENTIFIER) { let value = defines.get(token.lexeme); if (value !== false) { if (!isNaN(parseInt(value, 10)) && (parseInt(value, 10) === value)) { token.value = parseInt(value, 10); token.cls = t.TOKEN_NUMBER; } else if (!isNaN(parseFloat(value))) { token.value = parseFloat(value); token.cls = t.TOKEN_NUMBER; } else { token.cls = t.TOKEN_STRING; } token.lexeme = value; } } token.fileIndex = fileIndex; }); return tokens; } getDefinedConcatTokens() { let tokens = []; let tokenOffset = 0; let files = this.getSortedFiles(); dispatcher.dispatch('PreProcessor.Database', {defines: this._defines, files: files}); files.forEach( function(file, fileIndex) { tokens = tokens.concat(this.getDefinedOffsetTokens(file.tokens || [], tokenOffset, fileIndex)); tokenOffset += file.tokens ? file.tokens.length : 0; }, this ); return tokens; } getResources() { return this._resources; } getFormResources() { let result = []; this._resources.getResources().forEach((resource) => { if (resource instanceof FormResource) { result.push(resource); } }); return result; } };
{ "content_hash": "98a29e190c60c4766a9bef6fe00290f0", "timestamp": "", "source": "github", "line_count": 382, "max_line_length": 111, "avg_line_length": 37.774869109947645, "alnum_prop": 0.47574497574497576, "repo_name": "ArnoVanDerVegt/wheel", "id": "e1dfb0e2a65b94973a222ea022aee81e380ece8e", "size": "14585", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "js/frontend/compiler/preprocessor/PreProcessor.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "113289" }, { "name": "CSS", "bytes": "526894" }, { "name": "HTML", "bytes": "1657447" }, { "name": "JavaScript", "bytes": "4667529" }, { "name": "Rich Text Format", "bytes": "496" } ] }
End of preview.